返回 CodeWhale
tests.rs
根目录 / crates / engine / src / core / engine / tool_catalog / tests.rs
1 use super::prepare_tools_for_strict_mode;
2 use super::{
3 CODE_EXECUTION_DESCRIPTION, DEFAULT_ACTIVE_NATIVE_TOOLS, ToolMode,
4 allowlist_is_native_file_and_shell_only, apply_mcp_tool_deferral, apply_native_tool_deferral,
5 build_model_tool_catalog_with_surface, default_synthetic_catalog_tool_names,
6 ensure_advanced_tooling, execute_tool_search_with_cache, initial_active_tools,
7 is_synthetic_catalog_tool, remove_evicted_cache_activations, requested_tool_mode,
8 tool_matches_any_rule,
9 };
10 use crate::core::session::ToolActivationCache;
11 use codewhale_config::AppMode;
12 use codewhale_models::Tool;
13 use serde_json::json;
14 use std::collections::{BTreeSet, HashSet};
15
16 fn tool(name: &str) -> Tool {
17 Tool {
18 tool_type: None,
19 name: name.to_string(),
20 description: format!("{name} test tool"),
21 input_schema: json!({"type": "object", "properties": {}}),
22 allowed_callers: None,
23 defer_loading: None,
24 input_examples: None,
25 strict: None,
26 cache_control: None,
27 }
28 }
29
30 /// The shared launcher applies policy only where enforcement is available.
31 /// The model-facing description must not promise unconditional isolation.
32 #[test]
33 fn code_execution_description_does_not_claim_process_sandboxing() {
34 assert!(CODE_EXECUTION_DESCRIPTION.contains("local Python interpreter"));
35 assert!(!CODE_EXECUTION_DESCRIPTION.contains("sandbox"));
36 }
37
38 /// Python output must match our UTF-8 decoder even with non-UTF-8 parent stdio.
39 #[tokio::test]
40 async fn code_execution_returns_utf8_stdout_and_stderr() {
41 use crate::test_support::{EnvVarGuard, lock_test_env};
42 use codewhale_dependencies::ExternalTool as _;
43
44 let _env_lock = lock_test_env();
45 if !codewhale_dependencies::Python::available() {
46 return;
47 }
48 let _encoding = EnvVarGuard::set("PYTHONIOENCODING", "gbk");
49 let tmp = tempfile::tempdir().expect("tempdir");
50 let result = super::execute_code_execution_tool(
51 &json!({"code": r#"import sys; print("\u4e2d\u6587"); print("\u9519\u8bef", file=sys.stderr)"#}),
52 tmp.path(),
53 &crate::tools::spec::ToolContext::new(tmp.path()),
54 )
55 .await
56 .expect("code execution should run");
57 let payload = result.metadata.expect("payload");
58 assert_eq!(
59 (
60 payload["stdout"].as_str().map(str::trim_end),
61 payload["stderr"].as_str().map(str::trim_end),
62 ),
63 (Some("中文"), Some("错误")),
64 );
65 }
66
67 /// The published synthetic-name list and the predicate that classifies a
68 /// catalog entry as synthetic must agree. A name that appears in the list
69 /// but is not classified synthetic would let the request projection report
70 /// a provenance the engine itself disputes.
71 #[test]
72 fn published_synthetic_names_agree_with_the_synthetic_predicate() {
73 let names = default_synthetic_catalog_tool_names();
74 assert!(!names.is_empty());
75 for name in &names {
76 assert!(
77 is_synthetic_catalog_tool(name),
78 "'{name}' is published as synthetic but the predicate disagrees"
79 );
80 }
81 let mut sorted = names.clone();
82 sorted.sort();
83 sorted.dedup();
84 assert_eq!(names, sorted, "the list must be sorted and deduplicated");
85
86 // MCP names resolve through the real pool, so they are deliberately
87 // absent here even though the predicate accepts them.
88 assert!(!names.iter().any(|name| name.starts_with("mcp_")));
89
90 // `multi_tool_use.parallel` is a call name, never a catalog entry, so
91 // it has no catalog provenance and must not be published as synthetic.
92 assert!(!names.iter().any(|name| name == "multi_tool_use.parallel"));
93 }
94
95 #[test]
96 fn first_turn_surface_is_stable_across_plan_work_and_operate() {
97 assert_eq!(
98 DEFAULT_ACTIVE_NATIVE_TOOLS,
99 &[
100 "read",
101 "write",
102 "edit",
103 "list_dir",
104 "file_search",
105 "grep_files",
106 "bash",
107 "agent",
108 "todo_write",
109 "create_goal",
110 "present",
111 "load_skill"
112 ]
113 );
114 let expected = [
115 "agent",
116 "bash",
117 "create_goal",
118 "edit",
119 "file_search",
120 "grep_files",
121 "list_dir",
122 "load_skill",
123 "present",
124 "read",
125 "todo_write",
126 "tool_search",
127 "write",
128 ]
129 .into_iter()
130 .map(str::to_string)
131 .collect::<BTreeSet<_>>();
132 let mut expected_prefix = None;
133 for mode in [AppMode::Plan, AppMode::Agent] {
134 let mut catalog = [
135 "read",
136 "write",
137 "edit",
138 "list_dir",
139 "file_search",
140 "grep_files",
141 "bash",
142 "agent",
143 "workflow",
144 "todo_write",
145 "create_goal",
146 "get_goal",
147 "update_goal",
148 "task_shell_wait",
149 "present",
150 "Git",
151 "Run",
152 "tasks",
153 "load_skill",
154 ]
155 .into_iter()
156 .map(tool)
157 .collect::<Vec<_>>();
158 let always_load = HashSet::new();
159 apply_native_tool_deferral(&mut catalog, &always_load);
160 ensure_advanced_tooling(&mut catalog, mode, &always_load, ToolMode::Direct);
161 let active_names = initial_active_tools(&catalog);
162 let active = active_names.iter().cloned().collect::<BTreeSet<_>>();
163 assert_eq!(active, expected, "{mode:?}");
164 let prefix = serde_json::to_string(&super::active_tools_for_step(&catalog, &active_names))
165 .expect("serialize first-turn tool prefix");
166 if let Some(expected) = &expected_prefix {
167 assert_eq!(&prefix, expected, "{mode:?} must preserve schema bytes");
168 } else {
169 expected_prefix = Some(prefix);
170 }
171 }
172 }
173
174 #[test]
175 fn eager_workflow_still_respects_command_allow_and_deny_gates() {
176 for mode in [AppMode::Plan, AppMode::Agent] {
177 for (allow, deny, expected) in [
178 (None, None, true),
179 (Some("read"), None, false),
180 (Some("workflow"), None, true),
181 (None, Some("workflow"), false),
182 (Some("workflow"), Some("workflow"), false),
183 ] {
184 let always_load = HashSet::from(["workflow".to_string()]);
185 let catalog = build_model_tool_catalog_with_surface(
186 ["read", "agent", "workflow"]
187 .into_iter()
188 .map(tool)
189 .collect(),
190 Vec::new(),
191 mode,
192 &always_load,
193 crate::model_profile::ToolSurfaceBudget::Standard,
194 );
195 let policy = super::ToolSurfacePolicy::new(
196 crate::tools::ToolRegistry::new(crate::tools::ToolContext::for_empty_registry()),
197 Some(catalog),
198 mode,
199 &always_load,
200 false,
201 allow.map(|name| vec![name.to_string()]),
202 deny.map(|name| vec![name.to_string()]),
203 None,
204 ToolMode::Direct,
205 );
206 assert_eq!(policy.allows_tool("workflow"), expected);
207 assert_eq!(policy.active_names.contains("workflow"), expected);
208 assert_eq!(
209 policy.catalog.iter().any(|tool| tool.name == "workflow"),
210 expected
211 );
212 }
213 }
214 }
215
216 #[test]
217 fn mcp_tools_are_searchable_not_eager_in_every_mode() {
218 for mode in [AppMode::Plan, AppMode::Agent] {
219 let mut catalog = vec![tool("read_mcp_resource"), tool("mcp_acme_lookup")];
220 apply_mcp_tool_deferral(&mut catalog, mode, &HashSet::new());
221 assert!(
222 catalog
223 .iter()
224 .all(|definition| definition.defer_loading == Some(true)),
225 "{mode:?}: {catalog:?}"
226 );
227 }
228 }
229
230 #[test]
231 fn cache_eviction_does_not_hide_a_tool_that_became_eager() {
232 let mut catalog = vec![tool("promoted")];
233 catalog[0].defer_loading = Some(true);
234 let mut cache = ToolActivationCache::default();
235 cache.activate(&catalog, &["promoted".to_string()]);
236
237 catalog[0].defer_loading = Some(false);
238 let mut active = initial_active_tools(&catalog);
239 let evicted = cache.revalidate(&catalog);
240 remove_evicted_cache_activations(&catalog, &mut active, evicted);
241
242 assert!(active.contains("promoted"));
243 assert_eq!(cache.names().count(), 0);
244 }
245
246 #[test]
247 fn successful_cached_execution_updates_lru_without_granting_uncached_names() {
248 let max = crate::core::session::TOOL_ACTIVATION_CACHE_MAX_NAMES;
249 let catalog = (0..=max)
250 .map(|index| {
251 let mut definition = tool(&format!("deferred-{index}"));
252 definition.defer_loading = Some(true);
253 definition
254 })
255 .collect::<Vec<_>>();
256 let mut cache = ToolActivationCache::default().with_eviction(true);
257 let first = (0..max)
258 .map(|index| format!("deferred-{index}"))
259 .collect::<Vec<_>>();
260 let mut active = HashSet::new();
261 let delta = cache.activate(&catalog, &first);
262 active.extend(delta.admitted);
263
264 let oldest = format!("deferred-{}", max - 1);
265 let next_oldest = format!("deferred-{}", max - 2);
266 assert!(cache.record_use(&oldest));
267 let delta = cache.activate(&catalog, &[format!("deferred-{max}")]);
268 remove_evicted_cache_activations(&catalog, &mut active, delta.evicted);
269 active.extend(delta.admitted);
270 // The batch is ranked best-first; using its oldest retained match
271 // promotes it ahead of the next batch without granting an unseen tool.
272 assert!(cache.names().any(|name| name == oldest));
273 assert!(cache.names().any(|name| name == "deferred-0"));
274 assert!(!cache.names().any(|name| name == next_oldest));
275
276 assert!(!cache.record_use("never-activated"));
277 assert!(!active.contains("never-activated"));
278 }
279
280 #[test]
281 fn search_admissions_are_pinned_against_a_later_search_in_the_same_turn() {
282 let max = crate::core::session::TOOL_ACTIVATION_CACHE_MAX_NAMES;
283 let stale = (0..max - 4)
284 .map(|index| format!("stale_{index}"))
285 .collect::<Vec<_>>();
286 let group = |prefix: &str| (1..=4).map(|n| format!("{prefix}_{n}")).collect::<Vec<_>>();
287 let mut catalog = Vec::new();
288 for name in stale.iter().chain(&group("alpha")).chain(&group("beta")) {
289 let mut definition = tool(name);
290 definition.defer_loading = Some(true);
291 catalog.push(definition);
292 }
293 let mut active = initial_active_tools(&catalog);
294 let mut cache = ToolActivationCache::default().with_eviction(true);
295 cache.activate(&catalog, &stale);
296 for name in &stale {
297 cache.record_use(name);
298 }
299 cache.begin_turn();
300 cache.begin_turn();
301
302 for prefix in ["alpha", "beta"] {
303 execute_tool_search_with_cache(
304 codewhale_tools::names::TOOL_SEARCH_NAME,
305 &json!({"query": format!("^{prefix}_"), "match": "regex"}),
306 &catalog,
307 &mut active,
308 &mut cache,
309 )
310 .expect("tool search should succeed");
311 }
312
313 let retained = cache.names().collect::<HashSet<_>>();
314 for name in group("alpha") {
315 assert!(retained.contains(name.as_str()), "{name} was evicted");
316 }
317 for name in group("beta") {
318 assert!(retained.contains(name.as_str()), "{name} was not admitted");
319 }
320 }
321
322 #[test]
323 fn searching_for_an_eager_tool_is_not_reported_as_cache_rejected() {
324 let mut catalog = vec![tool("read")];
325 catalog[0].defer_loading = Some(false);
326 let mut active = initial_active_tools(&catalog);
327 let mut cache = ToolActivationCache::default();
328
329 let result = execute_tool_search_with_cache(
330 codewhale_tools::names::TOOL_SEARCH_NAME,
331 &json!({"query": "read"}),
332 &catalog,
333 &mut active,
334 &mut cache,
335 )
336 .expect("tool search should succeed");
337
338 let metadata = result.metadata.expect("search metadata");
339 assert_eq!(metadata["tool_references"], json!([]));
340 assert_eq!(metadata["unavailable_tool_references"], json!([]));
341 assert!(active.contains("read"));
342 assert_eq!(cache.names().count(), 0);
343 }
344
345 #[test]
346 fn regex_search_matches_displayed_tool_names_case_insensitively() {
347 let mut catalog = vec![tool("read"), tool("Web"), tool("automation")];
348 catalog[1].defer_loading = Some(true);
349 catalog[2].defer_loading = Some(true);
350 let mut active = initial_active_tools(&catalog);
351 let mut cache = ToolActivationCache::default();
352
353 let result = execute_tool_search_with_cache(
354 codewhale_tools::names::TOOL_SEARCH_NAME,
355 &json!({"query": "^(automation|Web)$", "match": "regex"}),
356 &catalog,
357 &mut active,
358 &mut cache,
359 )
360 .expect("tool search should succeed");
361
362 let metadata = result.metadata.expect("search metadata");
363 assert_eq!(metadata["tool_references"], json!(["Web", "automation"]));
364
365 let err = execute_tool_search_with_cache(
366 codewhale_tools::names::TOOL_SEARCH_NAME,
367 &json!({"query": "[unclosed", "match": "regex"}),
368 &catalog,
369 &mut active,
370 &mut cache,
371 )
372 .expect_err("invalid regex should fail")
373 .to_string();
374 assert!(err.contains("[unclosed"), "{err}");
375 assert!(!err.contains("(?i)"), "{err}");
376 }
377
378 #[test]
379 fn allow_and_deny_rules_cover_visible_and_hidden_compat_aliases_symmetrically() {
380 for family in [
381 &["read", "read_file"][..],
382 &["write", "write_file"][..],
383 &["edit", "edit_file"][..],
384 &["bash", "Bash", "exec_shell"][..],
385 ] {
386 for rule in family {
387 let rules = vec![(*rule).to_string()];
388 for tool_name in family {
389 assert!(
390 tool_matches_any_rule(&rules, tool_name),
391 "rule {rule:?} should cover alias {tool_name:?}"
392 );
393 }
394 }
395 }
396
397 assert!(tool_matches_any_rule(&["exec_shell*".to_string()], "bash"));
398 assert!(tool_matches_any_rule(
399 &["exec_shell*".to_string()],
400 "exec_shell_wait"
401 ));
402 for primitive in ["read", "write", "edit"] {
403 assert!(tool_matches_any_rule(&["File".to_string()], primitive));
404 }
405 assert!(!tool_matches_any_rule(&["read".to_string()], "write"));
406 }
407
408 #[test]
409 fn native_file_and_shell_allowlist_can_skip_mcp_startup() {
410 let native = ["bash", "read", "write", "edit"].map(str::to_string);
411 assert!(allowlist_is_native_file_and_shell_only(Some(&native)));
412 assert!(!allowlist_is_native_file_and_shell_only(None));
413 }
414
415 #[test]
416 fn unknown_and_wildcard_allowlists_keep_mcp_startup() {
417 for rule in ["mcp_github_list_prs", "mcp_*", "m*", "*", "other_tool"] {
418 assert!(
419 !allowlist_is_native_file_and_shell_only(Some(&[rule.to_string()])),
420 "{rule} may admit an MCP-backed tool"
421 );
422 }
423 }
424
425 #[test]
426 fn compact_surface_keeps_agent_eager_defers_workflow() {
427 let catalog = build_model_tool_catalog_with_surface(
428 [
429 "read",
430 "write",
431 "edit",
432 "bash",
433 "agent",
434 "workflow",
435 "todo_write",
436 ]
437 .into_iter()
438 .map(tool)
439 .collect(),
440 Vec::new(),
441 AppMode::Agent,
442 &HashSet::new(),
443 crate::model_profile::ToolSurfaceBudget::Compact,
444 );
445
446 for (name, deferred) in [("agent", false), ("workflow", true)] {
447 assert_eq!(
448 catalog
449 .iter()
450 .find(|definition| definition.name == name)
451 .and_then(|definition| definition.defer_loading),
452 Some(deferred),
453 "{name}"
454 );
455 }
456 }
457
458 /// The per-tool Registry paragraph is gone; the catalog builder must leave the
459 /// shell tool's description exactly as the registry produced it, so the KV
460 /// prefix stays byte-stable and there is one Registry authority (the prompt).
461 #[test]
462 fn catalog_build_does_not_append_registry_guidance_to_the_shell_tool() {
463 let described = tool("bash");
464 let catalog = build_model_tool_catalog_with_surface(
465 vec![described.clone()],
466 Vec::new(),
467 AppMode::Agent,
468 &HashSet::new(),
469 crate::model_profile::ToolSurfaceBudget::Standard,
470 );
471
472 let shell = catalog
473 .iter()
474 .find(|definition| definition.name == "bash")
475 .expect("shell tool");
476 assert_eq!(shell.description, described.description);
477 assert!(!shell.description.contains("registry_sync"));
478 }
479
480 #[test]
481 fn requested_tool_mode_prefers_model_hint_then_flag_then_direct() {
482 use codewhale_runtime::features::{Feature, Features};
483
484 // #6562: code mode is the default; `[features] code_mode = false` is the
485 // escape hatch back to Direct.
486 let on = Features::with_defaults();
487 assert_eq!(requested_tool_mode(None, &on), ToolMode::CodeMode);
488
489 let mut off = Features::with_defaults();
490 off.disable(Feature::CodeMode);
491 assert_eq!(requested_tool_mode(None, &off), ToolMode::Direct);
492
493 // Model metadata wins over config, in both directions (Codex parity).
494 assert_eq!(
495 requested_tool_mode(Some(ToolMode::Direct), &on),
496 ToolMode::Direct
497 );
498 assert_eq!(
499 requested_tool_mode(Some(ToolMode::CodeMode), &off),
500 ToolMode::CodeMode
501 );
502 }
503
504 #[test]
505 fn tool_search_is_offered_only_where_execute_tools_is_not_eager() {
506 let surface = |mode: AppMode, tool_mode: ToolMode, allowed: Option<Vec<String>>| {
507 let mut catalog = vec![tool("read"), tool("write")];
508 apply_native_tool_deferral(&mut catalog, &HashSet::new());
509 crate::tools::registry::apply_tool_cache_breakpoint(&mut catalog);
510 super::ToolSurfacePolicy::new(
511 crate::tools::ToolRegistry::new(crate::tools::ToolContext::for_empty_registry()),
512 Some(catalog),
513 mode,
514 &HashSet::new(),
515 false,
516 allowed,
517 None,
518 None,
519 tool_mode,
520 )
521 };
522 let allow = Some(vec!["execute_tools".to_string(), "read".to_string()]);
523 for (mode, tool_mode, allowed, searches) in [
524 (AppMode::Agent, ToolMode::CodeMode, None, false),
525 (AppMode::Agent, ToolMode::CodeMode, allow, false),
526 (AppMode::Agent, ToolMode::Direct, None, true),
527 (AppMode::Plan, ToolMode::CodeMode, None, false),
528 (AppMode::Plan, ToolMode::Direct, None, true),
529 ] {
530 let policy = surface(mode, tool_mode, allowed);
531 let label = format!("{mode:?} {tool_mode:?}");
532 assert_eq!(
533 policy.catalog.iter().any(|t| t.name == "tool_search"),
534 searches,
535 "{label}"
536 );
537 assert!(
538 policy.catalog.iter().any(|t| t.name == "execute_tools"),
539 "{label}"
540 );
541 let active = policy.active.expect("tools field");
542 assert_eq!(
543 active.iter().any(|t| t.name == "tool_search"),
544 searches,
545 "{label}"
546 );
547 assert_eq!(
548 active.iter().filter(|t| t.cache_control.is_some()).count(),
549 1,
550 "{label}"
551 );
552 }
553 }
554
555 /// A timed-out or cancelled `code_execution` kills the interpreter and what the
556 /// script started; a bare `output()` left both running.
557 #[cfg(unix)]
558 #[tokio::test]
559 async fn dropped_code_execution_kills_the_interpreter_tree() {
560 if codewhale_dependencies::resolve_python_interpreter().is_none() {
561 return;
562 }
563 let tmp = tempfile::tempdir().expect("tempdir");
564 let pid_file = tmp.path().join("grandchild.pid");
565 let code = format!(
566 "import subprocess\np = subprocess.Popen(['sleep', '300'])\nopen({:?}, 'w').write(str(p.pid))\np.wait()\n",
567 pid_file.display().to_string()
568 );
569 let input = json!({ "code": code });
570 let context = crate::tools::spec::ToolContext::new(tmp.path());
571 let run = super::execute_code_execution_tool(&input, tmp.path(), &context);
572 let grandchild = codewhale_runtime::process_tree::drop_once_pid_written(run, &pid_file).await;
573 assert!(
574 codewhale_runtime::process_tree::wait_for_pid_exit(
575 grandchild,
576 std::time::Duration::from_secs(5)
577 ),
578 "a process the script started outlived the dropped code_execution call"
579 );
580 }
581
582 fn test_tool(name: &str, input_schema: serde_json::Value) -> Tool {
583 Tool {
584 input_schema,
585 ..tool(name)
586 }
587 }
588
589 #[test]
590 fn strict_mode_applies_per_tool_in_mixed_catalog() {
591 let mut tools = vec![
592 test_tool(
593 "lookup",
594 json!({
595 "type": "object",
596 "properties": {
597 "query": {"type": "string"}
598 },
599 "required": []
600 }),
601 ),
602 test_tool(
603 "either",
604 json!({
605 "type": "object",
606 "properties": {
607 "a": {"type": "string"},
608 "b": {"type": "string"}
609 },
610 "anyOf": [
611 {"required": ["a"]},
612 {"required": ["b"]}
613 ]
614 }),
615 ),
616 test_tool(
617 "nested",
618 json!({
619 "type": "object",
620 "properties": {
621 "value": {
622 "oneOf": [
623 {"type": "string"},
624 {"type": "integer"}
625 ]
626 }
627 }
628 }),
629 ),
630 ];
631
632 assert!(!prepare_tools_for_strict_mode(&mut tools));
633 assert_eq!(tools[0].strict, Some(true));
634 assert_eq!(tools[0].input_schema["required"], json!([]));
635 assert!(tools[0].input_schema.get("additionalProperties").is_none());
636 assert_eq!(tools[1].strict, None);
637 assert!(tools[1].input_schema.get("anyOf").is_some());
638 assert_eq!(tools[2].strict, None);
639 assert!(
640 tools[2].input_schema["properties"]["value"]
641 .get("oneOf")
642 .is_some()
643 );
644 }
645
646 #[test]
647 fn strict_mode_rejects_nested_unsupported_composition() {
648 let mut tools = vec![Tool {
649 tool_type: None,
650 name: "nested".to_string(),
651 description: "Nested oneOf".to_string(),
652 input_schema: json!({
653 "type": "object",
654 "properties": {
655 "value": {
656 "oneOf": [
657 {"type": "string"},
658 {"type": "integer"}
659 ]
660 }
661 }
662 }),
663 allowed_callers: None,
664 defer_loading: None,
665 input_examples: None,
666 strict: None,
667 cache_control: None,
668 }];
669
670 assert!(!prepare_tools_for_strict_mode(&mut tools));
671 assert_eq!(tools[0].strict, None);
672 }
673
674 #[test]
675 fn strict_mode_leaves_dependent_schema_tools_non_strict() {
676 let schema = json!({
677 "type": "object",
678 "properties": {
679 "action": {"type": "string"},
680 "message": {"type": "string"}
681 },
682 "dependentSchemas": {
683 "action": {
684 "properties": {"message": {}},
685 "required": ["message"]
686 }
687 }
688 });
689 let mut tools = vec![test_tool("agent", schema.clone())];
690
691 assert!(!prepare_tools_for_strict_mode(&mut tools));
692 assert_eq!(tools[0].strict, None);
693 assert_eq!(tools[0].input_schema, schema);
694 }
695
696 #[test]
697 fn strict_mode_marks_compatible_tools_strict() {
698 let mut tools = vec![Tool {
699 tool_type: None,
700 name: "lookup".to_string(),
701 description: "Lookup".to_string(),
702 input_schema: json!({
703 "type": "object",
704 "properties": {
705 "query": {"type": "string"}
706 },
707 "required": []
708 }),
709 allowed_callers: None,
710 defer_loading: None,
711 input_examples: None,
712 strict: None,
713 cache_control: None,
714 }];
715
716 assert!(prepare_tools_for_strict_mode(&mut tools));
717 assert_eq!(tools[0].strict, Some(true));
718 assert_eq!(tools[0].input_schema["required"], json!([]));
719 assert!(tools[0].input_schema.get("additionalProperties").is_none());
720 }
721
722 #[test]
723 fn deferred_toolbox_runtime_message_is_minimal_and_roundtrips_with_legacy_meta() {
724 let message = crate::runtime_handoff::deferred_toolbox_runtime_message(&["Git", "Web"]);
725 assert!(codewhale_models::turn_classify::is_runtime_owned_user_message(&message));
726 assert_eq!(message.content.len(), 2);
727 let meta = match &message.content[1] {
728 codewhale_models::ContentBlock::Text { text, .. } => text.as_str(),
729 other => panic!("expected text metadata block, got {other:?}"),
730 };
731 assert_eq!(
732 meta,
733 "<turn_meta>\nInput provenance: runtime (non-authoritative)\n</turn_meta>"
734 );
735 assert!(!meta.contains("Current local date:"));
736 assert!(!meta.contains("Repo Working Set"));
737 assert_eq!(
738 crate::runtime_handoff::deferred_toolbox_tools(&message),
739 Some(vec!["Git".to_string(), "Web".to_string()])
740 );
741
742 let legacy = codewhale_models::Message {
743 role: codewhale_models::Role::User,
744 content: vec![
745 codewhale_models::ContentBlock::Text {
746 text: r#"{"type":"current_deferred_toolbox","active_deferred_tools":["Run"]}"#
747 .to_string(),
748 cache_control: None,
749 },
750 codewhale_models::ContentBlock::Text {
751 text: "<turn_meta>\nCurrent local date: 2026-11-18\nInput provenance: runtime (non-authoritative)\n## Repo Working Set\n</turn_meta>".to_string(),
752 cache_control: None,
753 },
754 ],
755 };
756 assert_eq!(
757 crate::runtime_handoff::deferred_toolbox_tools(&legacy),
758 Some(vec!["Run".to_string()])
759 );
760 }
761
762 #[test]
763 fn eager_wire_tools_never_enter_tool_search_or_activation_cache() {
764 let mut catalog = vec![
765 tool("mcp_demo_authenticate"),
766 tool("mcp_demo_wait_for"),
767 tool("mcp_demo_eager_active"),
768 tool("mcp_demo_deferred_query"),
769 ];
770 let always_load = HashSet::from([
771 "mcp_demo_authenticate".to_string(),
772 "mcp_demo_wait*".to_string(),
773 ]);
774 apply_mcp_tool_deferral(&mut catalog, AppMode::Agent, &always_load);
775 assert_eq!(catalog[0].defer_loading, Some(false));
776 assert_eq!(catalog[1].defer_loading, Some(false));
777 assert_eq!(catalog[2].defer_loading, Some(true));
778 assert_eq!(catalog[3].defer_loading, Some(true));
779
780 let mut active = initial_active_tools(&catalog);
781 active.insert("mcp_demo_eager_active".to_string());
782 let mut cache = ToolActivationCache::default();
783
784 for query in ["authenticate", "wait", "eager_active", "mcp_demo"] {
785 let result = execute_tool_search_with_cache(
786 codewhale_tools::names::TOOL_SEARCH_NAME,
787 &json!({"query": query, "match": "bm25"}),
788 &catalog,
789 &mut active,
790 &mut cache,
791 )
792 .expect("search succeeds");
793 let refs = result.metadata.expect("metadata")["tool_references"].clone();
794 if query == "mcp_demo" {
795 assert_eq!(refs, json!(["mcp_demo_deferred_query"]));
796 } else {
797 assert_eq!(refs, json!([]), "query={query}");
798 }
799 }
800 assert_eq!(
801 cache.names().collect::<Vec<_>>(),
802 vec!["mcp_demo_deferred_query"]
803 );
804 }
805
806 #[test]
807 fn readmission_search_input_matches_exact_name_without_newline_leak() {
808 let input = super::readmission_search_input("web.run");
809 let query = input["query"].as_str().expect("query string");
810 assert_eq!(query, "^web\\.run$");
811 assert!(!query.contains('\n'));
812 assert!(!query.contains("\\n"));
813
814 let mut target = tool("web.run");
815 target.defer_loading = Some(true);
816 let mut prefix_collision = tool("web.run_extended");
817 prefix_collision.defer_loading = Some(true);
818 let mut desc_collision = tool("other_tool");
819 desc_collision.description = "wraps web.run internally".to_string();
820 desc_collision.defer_loading = Some(true);
821
822 let catalog = vec![prefix_collision, desc_collision, target];
823 let mut active = initial_active_tools(&catalog);
824 let mut cache = ToolActivationCache::default();
825 let result = execute_tool_search_with_cache(
826 codewhale_tools::names::TOOL_SEARCH_NAME,
827 &input,
828 &catalog,
829 &mut active,
830 &mut cache,
831 )
832 .expect("readmission search");
833 assert_eq!(
834 result.metadata.expect("metadata")["tool_references"],
835 json!(["web.run"])
836 );
837 }
838
839 #[test]
840 fn terminal_underscore_tools_are_visible_and_slash_aliases_are_not_registered() {
841 let tmp = tempfile::tempdir().expect("tempdir");
842 let registry = crate::tools::registry::ToolRegistryBuilder::new()
843 .with_terminal_tools()
844 .build(crate::tools::spec::ToolContext::new(tmp.path()));
845 let visible: BTreeSet<String> = registry
846 .to_api_tools()
847 .into_iter()
848 .map(|tool| tool.name)
849 .collect();
850 let canonical = [
851 "terminal_run",
852 "terminal_send",
853 "terminal_wait",
854 "terminal_cancel",
855 "terminal_reset",
856 ];
857 let legacy = [
858 "terminal/run",
859 "terminal/send",
860 "terminal/wait",
861 "terminal/cancel",
862 "terminal/reset",
863 ];
864 for (new_name, old_name) in canonical.iter().zip(legacy.iter()) {
865 assert!(
866 visible.contains(*new_name),
867 "{new_name} must be model-visible"
868 );
869 assert!(!registry.contains(old_name), "{old_name} is registered");
870 assert!(tool_matches_any_rule(&[(*old_name).to_string()], new_name));
871 assert!(tool_matches_any_rule(&[(*new_name).to_string()], old_name));
872 assert!(tool_matches_any_rule(&["terminal/*".to_string()], new_name));
873 assert!(tool_matches_any_rule(&["terminal_*".to_string()], old_name));
874 }
875 }
876
877 #[test]
878 fn deferred_schema_hydration_returns_error_with_field_details() {
879 let mut deferred = test_tool(
880 "update_goal",
881 json!({
882 "type": "object",
883 "properties": {
884 "status": {
885 "type": "string",
886 "enum": ["complete", "blocked", "yield"],
887 "description": "Terminal or yield transition for the active goal."
888 },
889 "verification": {
890 "type": "object",
891 "description": "Structured proof for completion.",
892 "required": ["status"],
893 "properties": {
894 "status": {"type": "string", "enum": ["passed", "not_applicable"]},
895 "check": {"type": "string"}
896 }
897 },
898 "tags": {
899 "type": "array",
900 "description": "Optional labels.",
901 "items": {"type": "string"}
902 }
903 },
904 "required": ["status"]
905 }),
906 );
907 deferred.defer_loading = Some(true);
908
909 let result = super::deferred_tool_schema_hydration_result(&deferred, &json!({}));
910 assert!(!result.success);
911 assert!(result.content.contains("status: string (complete | blocked | yield) required — Terminal or yield transition for the active goal."), "{}", result.content);
912 assert!(result.content.contains("verification: object {check: string, status: string (passed | not_applicable) required} — Structured proof for completion."), "{}", result.content);
913 assert!(
914 result
915 .content
916 .contains("tags: array<string> — Optional labels."),
917 "{}",
918 result.content
919 );
920 }
921
922 #[test]
923 fn goal_followup_tools_defer_by_default_and_auto_activate_together() {
924 let mut catalog = vec![tool("create_goal"), tool("get_goal"), tool("update_goal")];
925 apply_native_tool_deferral(&mut catalog, &HashSet::new());
926 assert_eq!(catalog[0].defer_loading, Some(false));
927 assert_eq!(catalog[1].defer_loading, Some(true));
928 assert_eq!(catalog[2].defer_loading, Some(true));
929
930 let mut active = initial_active_tools(&catalog);
931 assert!(active.contains("create_goal"));
932 assert!(!active.contains("get_goal"));
933 assert!(!active.contains("update_goal"));
934
935 let mut cache = ToolActivationCache::default();
936 let changed =
937 super::activate_goal_followup_tools(&catalog, &mut active, &mut cache, &mut |names| {
938 ToolActivationCache::test_measure(&catalog, names)
939 })
940 .expect("goal followup activation");
941 assert!(changed);
942 assert!(active.contains("get_goal"));
943 assert!(active.contains("update_goal"));
944
945 let changed_again =
946 super::activate_goal_followup_tools(&catalog, &mut active, &mut cache, &mut |_| {
947 panic!("already-active goal tools must not re-measure")
948 })
949 .expect("idempotent activation");
950 assert!(!changed_again);
951 }
952
953 #[test]
954 fn activate_result_dependencies_skips_when_already_active_or_eager() {
955 let mut retrieval = tool("retrieve_tool_result");
956 retrieval.defer_loading = Some(true);
957 let catalog = vec![retrieval];
958 let mut active = initial_active_tools(&catalog);
959 active.remove("retrieve_tool_result");
960 let mut cache = ToolActivationCache::default();
961 let spilled = crate::tools::spec::ToolResult::success("preview")
962 .with_metadata(json!({"evidence_available": true}));
963
964 let first = super::activate_result_dependencies(
965 &catalog,
966 &mut active,
967 &mut cache,
968 &spilled,
969 &mut |names| ToolActivationCache::test_measure(&catalog, names),
970 )
971 .expect("first spill activates retrieval");
972 assert!(first);
973 assert!(active.contains("retrieve_tool_result"));
974
975 let second = super::activate_result_dependencies(
976 &catalog,
977 &mut active,
978 &mut cache,
979 &spilled,
980 &mut |_| panic!("second spill must not re-measure or re-activate"),
981 )
982 .expect("second spill is a no-op");
983 assert!(!second);
984 }
985
986 #[test]
987 fn task_shell_wait_defers_by_default_and_auto_activates_on_background_shell_job() {
988 let mut catalog = vec![tool("bash"), tool("task_shell_wait")];
989 apply_native_tool_deferral(&mut catalog, &HashSet::new());
990 assert_eq!(catalog[0].defer_loading, Some(false));
991 assert_eq!(catalog[1].defer_loading, Some(true));
992
993 let mut active = initial_active_tools(&catalog);
994 assert!(active.contains("bash"));
995 assert!(!active.contains("task_shell_wait"));
996
997 let mut cache = ToolActivationCache::default();
998 let background_bash = crate::tools::spec::ToolResult::success("Background task started")
999 .with_metadata(json!({"status": "Running", "backgrounded": true, "task_id": "shell_1"}));
1000 let activated = super::activate_result_dependencies(
1001 &catalog,
1002 &mut active,
1003 &mut cache,
1004 &background_bash,
1005 &mut |names| ToolActivationCache::test_measure(&catalog, names),
1006 )
1007 .expect("background bash activates task_shell_wait");
1008 assert!(activated);
1009 assert!(active.contains("task_shell_wait"));
1010
1011 let repeated =
1012 super::activate_background_shell_tools(&catalog, &mut active, &mut cache, &mut |_| {
1013 panic!("already-active task_shell_wait must not re-measure")
1014 })
1015 .expect("idempotent activation");
1016 assert!(!repeated);
1017
1018 let mut active_exec = initial_active_tools(&catalog);
1019 let mut cache_exec = ToolActivationCache::default();
1020 let exec_running = crate::tools::spec::ToolResult::success("Background task started")
1021 .with_metadata(json!({"status": "Running", "task_id": "shell_2"}));
1022 let activated_exec = super::activate_result_dependencies(
1023 &catalog,
1024 &mut active_exec,
1025 &mut cache_exec,
1026 &exec_running,
1027 &mut |names| ToolActivationCache::test_measure(&catalog, names),
1028 )
1029 .expect("exec_shell running task activates task_shell_wait");
1030 assert!(activated_exec);
1031 assert!(active_exec.contains("task_shell_wait"));
1032 }
1033
1034 #[test]
1035 fn bm25_tool_search_expands_curated_synonyms_without_false_substring_hits() {
1036 let mut catalog = [
1037 "read_media",
1038 "Git",
1039 "Run",
1040 "terminal_run",
1041 "task_shell_wait",
1042 "agent",
1043 "workflow",
1044 "remember",
1045 "Web",
1046 "lsp",
1047 "todo_write",
1048 "tasks",
1049 "thread_status",
1050 "prune_cache",
1051 ]
1052 .into_iter()
1053 .map(|name| {
1054 let mut entry = tool(name);
1055 entry.description = format!("Tool {name}");
1056 entry.defer_loading = Some(true);
1057 entry
1058 })
1059 .collect::<Vec<_>>();
1060 catalog.push({
1061 let mut entry = tool("mcp_git_status");
1062 entry.description = "MCP repo status".to_string();
1063 entry.defer_loading = Some(true);
1064 entry
1065 });
1066
1067 let active = HashSet::new();
1068 let cases = [
1069 ("screenshot", "read_media"),
1070 ("pdf", "read_media"),
1071 ("image", "read_media"),
1072 ("branch", "Git"),
1073 ("diff", "Git"),
1074 ("commit", "Git"),
1075 ("lint", "Run"),
1076 ("build", "Run"),
1077 ("check", "Run"),
1078 ("pty", "terminal_run"),
1079 ("bg", "task_shell_wait"),
1080 ("background", "task_shell_wait"),
1081 ("subagent", "agent"),
1082 ("delegate", "agent"),
1083 ("worker", "agent"),
1084 ("spawn", "agent"),
1085 ("memory", "remember"),
1086 ("note", "remember"),
1087 ("http", "Web"),
1088 ("url", "Web"),
1089 ("definition", "lsp"),
1090 ("references", "lsp"),
1091 ("diagnostics", "lsp"),
1092 ("checklist", "todo_write"),
1093 ("plan", "todo_write"),
1094 ];
1095 for (query, expected) in cases {
1096 let matches = super::discover_tools_with_bm25_like(&catalog, query, 8, &active, None);
1097 assert!(
1098 matches.iter().any(|name| name == expected),
1099 "query {query:?} should find {expected:?}, got {matches:?}"
1100 );
1101 }
1102
1103 let pdf_matches = super::discover_tools_with_bm25_like(&catalog, "pdf", 8, &active, None);
1104 assert!(
1105 !pdf_matches.iter().any(|name| name == "thread_status"),
1106 "synonym expansion must not match substrings inside words: {pdf_matches:?}"
1107 );
1108 let lint_matches = super::discover_tools_with_bm25_like(&catalog, "lint", 8, &active, None);
1109 assert!(
1110 !lint_matches.iter().any(|name| name == "prune_cache"),
1111 "synonym expansion must not match substrings inside words: {lint_matches:?}"
1112 );
1113 let exact_git = super::discover_tools_with_bm25_like(&catalog, "git", 8, &active, None);
1114 assert_eq!(exact_git.first().map(String::as_str), Some("Git"));
1115 }
1116
1117 #[test]
1118 fn deferred_named_batch_keeps_execute_tools_schema_minimal() {
1119 let step_schema = json!({"type": "object", "properties": {
1120 "target": {"type": "string", "description": "x".repeat(400)},
1121 "find": {"type": "object", "properties": {"query": {"type": "string"}}}
1122 }});
1123 let mut batch = tool("mcp_cu_run_actions");
1124 batch.description = "Run several computer-use steps.".repeat(20);
1125 batch.defer_loading = Some(true);
1126 batch.input_schema = json!({
1127 "type": "object",
1128 "required": ["steps"],
1129 "properties": {"steps": {
1130 "type": "array", "minItems": 1, "maxItems": 8,
1131 "items": {"type": "object", "required": ["tool"], "properties": {
1132 "tool": {"type": "string", "enum": ["click", "drag"]},
1133 "arguments": {"type": "object", "oneOf": [step_schema.clone(), step_schema]}
1134 }}
1135 }}
1136 });
1137 let mut catalog = vec![
1138 crate::tools::codemode::execute_tools_tool_definition(),
1139 batch,
1140 ];
1141 let members = vec!["click".to_string(), "drag".to_string()];
1142 assert!(super::configure_composition_entry(
1143 &mut catalog,
1144 Some("mcp_cu_run_actions"),
1145 &members
1146 ));
1147 let offered = &catalog[0].input_schema["properties"]["batch"];
1148 let rendered = offered.to_string();
1149 assert!(!rendered.contains("xxxxxxxx"), "{rendered}");
1150 assert!(!rendered.contains("computer-use steps"), "{rendered}");
1151 assert!(rendered.contains("tools.describe"), "{rendered}");
1152 assert!(super::offered_batch_allows(
1153 &catalog,
1154 "mcp_cu_run_actions",
1155 &json!({"steps": [{"tool": "click", "arguments": {}}]})
1156 ));
1157 }
1158
1159 #[test]
1160 fn tool_search_ranks_first_party_names_above_mcp_description_hits() {
1161 let mut run = tool("Run");
1162 run.defer_loading = Some(true);
1163 let mut git = tool("Git");
1164 git.defer_loading = Some(true);
1165 let mut computer = tool("mcp_cu_run_actions");
1166 computer.description = "Run tests, run actions, run anything on the desktop.".to_string();
1167 computer.defer_loading = Some(true);
1168 let mut notebook = tool("mcp_db_run_notebook");
1169 notebook.description = "Run a notebook".to_string();
1170 notebook.defer_loading = Some(true);
1171 let catalog = vec![computer, notebook, run, git];
1172 let found = super::discover_tools_with_bm25_like(
1173 &catalog,
1174 "run tests cargo",
1175 super::TOOL_SEARCH_DEFAULT_MAX_RESULTS,
1176 &HashSet::new(),
1177 None,
1178 );
1179 assert_eq!(found.first().map(String::as_str), Some("Run"), "{found:?}");
1180 assert!(!found.iter().any(|name| name == "Git"), "{found:?}");
1181 assert!(found.len() <= 4, "{found:?}");
1182 }
1183
1184 #[test]
1185 fn program_discovery_resolves_one_name_and_reports_cuts_and_gaps() {
1186 let catalog: Vec<Tool> = [
1187 "agent",
1188 "dup_run",
1189 "execute_tools",
1190 "list_dir",
1191 "mcp_GitHub_list_issues",
1192 "mcp_dup_run",
1193 "todo_write",
1194 "tool_search",
1195 ]
1196 .into_iter()
1197 .map(tool)
1198 .collect();
1199 let discover = |input: serde_json::Value| {
1200 super::describe_tools_for_program(&input, &catalog).map(|result| {
1201 serde_json::from_str::<serde_json::Value>(&result.content).expect("discovery JSON")
1202 })
1203 };
1204 let resolve = |namespace: &str, op: &str| {
1205 discover(json!({"mode": "resolve", "namespace": namespace, "op": op}))
1206 };
1207 assert_eq!(resolve("todo", "write").unwrap()["name"], "todo_write");
1208 assert_eq!(
1209 resolve("github", "listIssues").unwrap()["name"],
1210 "mcp_GitHub_list_issues"
1211 );
1212 assert!(resolve("tool", "search").is_err());
1213 let unknown = resolve("todo", "wrte").unwrap_err().to_string();
1214 assert!(unknown.contains("todo_write("), "{unknown}");
1215 let ambiguous = resolve("dup", "run").unwrap_err().to_string();
1216 assert!(
1217 ambiguous.contains("mcp_dup_run(") && ambiguous.contains("more than one"),
1218 "{ambiguous}"
1219 );
1220
1221 let listed = discover(json!({"mode": "list", "max_results": 3})).unwrap();
1222 assert_eq!(listed["total"], 6);
1223 assert_eq!(listed["truncated"], true);
1224 assert_eq!(listed["tools"][0]["direct_only"], true, "{listed}");
1225 assert!(listed["tools"][0].get("signature").is_none(), "{listed}");
1226 assert!(listed["tools"][1]["namespace"].is_null(), "{listed}");
1227 assert!(listed["tools"][2]["namespace"].is_null(), "{listed}");
1228 let github = discover(json!({"mode": "list", "namespace": "github"})).unwrap();
1229 assert_eq!(github["tools"][0]["namespace"], "GitHub");
1230
1231 for namespace in ["tool", "execute"] {
1232 let found =
1233 discover(json!({"mode": "search", "query": "", "namespace": namespace})).unwrap();
1234 assert_eq!(found["tools"], json!([]), "{namespace}");
1235 }
1236
1237 let described =
1238 discover(json!({"mode": "describe", "names": ["nope", "list_dir", "list_dir"]})).unwrap();
1239 assert_eq!(described["tools"][0]["missing"], true, "{described}");
1240 assert_eq!(described["tools"][1]["name"], "list_dir");
1241 assert!(
1242 described["tools"][1]["signature"]
1243 .as_str()
1244 .is_some_and(|sig| sig.contains("list_dir(")),
1245 "{described}"
1246 );
1247 assert_eq!(described["tools"][2]["name"], "list_dir");
1248 }
1249
1250 #[test]
1251 fn codemode_suggestions_suppress_unrelated_filler_matches_and_keep_real_typos() {
1252 let catalog: Vec<Tool> = [
1253 "retrieve_tool_result",
1254 "notify",
1255 "mcp_linear_get_release_note",
1256 "mcp_linear_list_issues",
1257 "read_file",
1258 "grep_files",
1259 ]
1260 .into_iter()
1261 .map(tool)
1262 .collect();
1263
1264 assert_eq!(
1265 super::suggest_tools_for_codemode(&catalog, "definitely_not_a_tool", 3),
1266 Vec::<String>::new()
1267 );
1268 assert_eq!(
1269 super::suggest_tools_for_codemode(&catalog, "get_tool", 3),
1270 Vec::<String>::new()
1271 );
1272 assert_eq!(
1273 super::suggest_tools_for_codemode(&catalog, "xyzzy_nonexistent", 3),
1274 Vec::<String>::new()
1275 );
1276 assert_eq!(
1277 super::suggest_tools_for_codemode(&catalog, "read_fil", 3),
1278 vec!["read_file".to_string()]
1279 );
1280 assert_eq!(
1281 super::suggest_tools_for_codemode(&catalog, "linear_issue", 3),
1282 vec!["mcp_linear_list_issues".to_string()]
1283 );
1284 assert_eq!(
1285 super::suggest_tools_for_codemode(&catalog, "grep_file", 3),
1286 vec!["grep_files".to_string()]
1287 );
1288 }
1289
1289 lines RUST