返回 CodeWhale
tests.rs
根目录 / crates / engine / src / tools / registry / tests.rs
1 use std::collections::HashMap;
2 use std::sync::Arc;
3
4 use serde_json::{Value, json};
5 use tempfile::tempdir;
6
7 use crate::tools::ToolRegistryBuilder;
8 use crate::tools::shell::BashTool;
9 use crate::tools::spec::{
10 ApprovalRequirement, ToolAuthorityEnvelope, ToolCapability, ToolContext, ToolError,
11 ToolMutationAuthority, ToolResult, ToolSpec, required_str,
12 };
13 use codewhale_runtime::config::ToolOverride;
14
15 use super::{
16 MCP_IMAGE_TEXT_PLACEHOLDER, ToolRegistry, enforce_tool_authority,
17 mcp_result_to_bounded_rich_tool_result, mcp_tool_adapter_for_test, readonly_evidence_tool,
18 };
19
20 #[tokio::test]
21 async fn shell_denial_reaches_registry_and_direct_delegation_sinks() {
22 use crate::tools::run_tool::RunTool;
23 use crate::tools::tasks::TasksTool;
24 use crate::tools::terminal_session::{TerminalResetTool, TerminalRunTool, TerminalSendTool};
25 use crate::tools::test_runner::RunTestsTool;
26 use crate::tools::verifier::RunVerifiersTool;
27 let tmp = tempdir().unwrap();
28 let mut context = ToolContext::new(tmp.path());
29 context.auto_approve = true;
30 context.disallowed_tools = vec!["Bash".into()];
31 let command = "printf forbidden > denial-canary.txt";
32 let cases: Vec<(Arc<dyn ToolSpec>, Value)> = vec![
33 (Arc::new(BashTool::new("Bash")), json!({"command":command})),
34 (
35 Arc::new(BashTool::alias("exec_interact", "interact")),
36 json!({"task_id":"missing", "stdin":command, "action":"wait"}),
37 ),
38 (
39 Arc::new(TasksTool::new("tasks")),
40 json!({"action":"gate_run", "gate":"custom", "command":command}),
41 ),
42 (Arc::new(TerminalRunTool), json!({"command":command})),
43 (
44 Arc::new(TerminalSendTool),
45 json!({"session":"missing", "text":command}),
46 ),
47 (Arc::new(TerminalResetTool), json!({"session":"missing"})),
48 (Arc::new(RunTool::new("Run")), json!({"action":"verifiers"})),
49 (
50 Arc::new(RunTestsTool),
51 json!({"args":"--config build.rustc=malicious"}),
52 ),
53 (Arc::new(RunVerifiersTool), json!({})),
54 ];
55 for (tool, input) in cases {
56 let mut registry = ToolRegistry::new(context.clone());
57 registry.register(tool.clone());
58 for result in [
59 registry.execute_full(tool.name(), input.clone()).await,
60 tool.execute(input, &context).await,
61 ] {
62 let error = result.expect_err(tool.name());
63 assert!(
64 error.to_string().contains("disallowed-tools"),
65 "{}: {error}",
66 tool.name()
67 );
68 assert!(!tmp.path().join("denial-canary.txt").exists());
69 }
70 }
71 }
72
73 #[test]
74 fn shell_denial_keeps_the_existing_bounded_child_read_only_exception() {
75 use crate::tools::execution_envelope::enforce_tool_denial;
76 use codewhale_agent_contract::worker_profile::ShellPolicy;
77 let tmp = tempdir().unwrap();
78 let mut context = ToolContext::new(tmp.path()).with_shell_policy(ShellPolicy::ReadOnly);
79 context.disallowed_tools = vec!["Bash".into()];
80 assert!(enforce_tool_denial(&context, "bash", &json!({"command":"pwd"})).is_err());
81 context = context.with_owner_agent("fixture-child", "fixture");
82 assert!(enforce_tool_denial(&context, "bash", &json!({"command":"pwd"})).is_ok());
83 for (name, input) in [
84 ("Bash", json!({"command":"pwd"})),
85 ("bash", json!({"command":"printf bad > denied"})),
86 ("bash", json!({"command":"pwd", "background":true})),
87 ("task_shell_start", json!({"command":"pwd"})),
88 (
89 "terminal_send",
90 json!({"session":"existing", "text":"pwd\n"}),
91 ),
92 (
93 "terminal/send",
94 json!({"session":"existing", "text":"pwd\n"}),
95 ),
96 ] {
97 assert!(
98 enforce_tool_denial(&context, name, &input).is_err(),
99 "{name}: {input}"
100 );
101 }
102 }
103
104 #[test]
105 fn mcp_iserror_result_maps_to_tool_error_preserving_text() {
106 // #5123-class: MCP servers report tool failure via isError on an
107 // otherwise successful response; the model must see a failure, not a
108 // success carrying an error message body.
109 let error_payload = json!({
110 "content": [
111 {"type": "text", "text": "delete failed: permission denied"}
112 ],
113 "isError": true
114 });
115 let result = mcp_result_to_bounded_rich_tool_result(error_payload).result;
116 assert!(!result.success, "isError must not be reported as success");
117 assert_eq!(result.content, "delete failed: permission denied");
118
119 let ok_payload = json!({
120 "content": [{"type": "text", "text": "wrote 3 rows"}]
121 });
122 let result = mcp_result_to_bounded_rich_tool_result(ok_payload).result;
123 assert!(result.success);
124 assert!(result.content.contains("wrote 3 rows"));
125
126 // isError without text content falls back to the serialized payload.
127 let bare_error = json!({"isError": true, "content": []});
128 let result = mcp_result_to_bounded_rich_tool_result(bare_error).result;
129 assert!(!result.success);
130 assert!(result.content.contains("isError"));
131 }
132
133 #[test]
134 fn mcp_image_result_uses_typed_block_without_base64_in_text() {
135 let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
136 let payload = json!({
137 "content": [
138 {"type": "text", "text": "screenshot captured"},
139 {"type": "image", "data": image_data, "mimeType": "image/png"}
140 ],
141 "structuredContent": {"page": "https://example.com"},
142 "isError": false
143 });
144
145 let rich = mcp_result_to_bounded_rich_tool_result(payload);
146
147 assert!(rich.result.success);
148 let sanitized: Value = serde_json::from_str(&rich.result.content).expect("sanitized MCP JSON");
149 assert_eq!(sanitized["content"][0]["text"], "screenshot captured");
150 assert_eq!(sanitized["content"][1]["data"], MCP_IMAGE_TEXT_PLACEHOLDER);
151 assert_eq!(
152 sanitized["structuredContent"],
153 json!({"page": "https://example.com"})
154 );
155 assert_eq!(sanitized["isError"], false);
156 assert!(!rich.result.content.contains(image_data));
157 assert_eq!(
158 rich.content_blocks,
159 vec![codewhale_tools::ToolResultContentBlock::Image {
160 mime_type: "image/png".to_string(),
161 data: image_data.to_string(),
162 }]
163 );
164 }
165
166 #[test]
167 fn mcp_transport_metadata_is_dropped_from_the_result() {
168 let icon = format!("data:image/png;base64,{}", "A".repeat(2_048));
169 let payload = json!({
170 "_meta": {"io.modelcontextprotocol/serverInfo": {"name": "github-mcp-server", "icons": [{"src": icon}]}},
171 "resultType": "complete",
172 "content": [{"type": "text", "text": "{\"total_count\":1}", "_meta": {"icon": icon}}]
173 });
174
175 let rich = mcp_result_to_bounded_rich_tool_result(payload);
176
177 assert!(rich.result.success);
178 assert!(
179 !rich.result.content.contains("base64"),
180 "{}",
181 rich.result.content
182 );
183 let sanitized: Value = serde_json::from_str(&rich.result.content).expect("MCP JSON");
184 assert_eq!(
185 sanitized,
186 json!({"content": [{"type": "text", "text": "{\"total_count\":1}"}]})
187 );
188 }
189
190 #[test]
191 fn mcp_invalid_image_is_removed_with_a_visible_receipt() {
192 let payload = json!({
193 "content": [
194 {"type": "image", "data": "not base64", "mimeType": "image/png"}
195 ]
196 });
197
198 let rich = mcp_result_to_bounded_rich_tool_result(payload);
199
200 assert!(rich.content_blocks.is_empty());
201 assert!(rich.result.content.contains("MCP image payload removed"));
202 assert!(
203 rich.result
204 .content
205 .contains("1 tool-result image block(s) omitted")
206 );
207 assert!(!rich.result.content.contains("not base64"));
208 }
209
210 #[test]
211 fn mcp_malformed_images_are_removed_with_a_visible_receipt() {
212 let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
213 let payload = json!({
214 "content": [
215 {"type": "image", "data": image_data},
216 {"type": "image", "data": {"nested": image_data}, "mimeType": "image/png"}
217 ]
218 });
219
220 let rich = mcp_result_to_bounded_rich_tool_result(payload);
221
222 assert!(rich.content_blocks.is_empty());
223 assert!(rich.result.content.contains("MCP image payload removed"));
224 assert!(
225 rich.result
226 .content
227 .contains("2 tool-result image block(s) omitted")
228 );
229 assert!(!rich.result.content.contains(image_data));
230 }
231
232 #[test]
233 fn mcp_image_limits_keep_one_valid_block_and_report_the_rest() {
234 let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
235 let oversized = "A".repeat(crate::image_attach::MAX_IMAGE_BYTES.div_ceil(3) * 4 + 4);
236 let payload = json!({
237 "content": [
238 {"type": "image", "data": oversized, "mimeType": "image/png"},
239 {"type": "image", "data": image_data, "mimeType": "image/png"},
240 {"type": "image", "data": image_data, "mimeType": "image/png"}
241 ]
242 });
243
244 let rich = mcp_result_to_bounded_rich_tool_result(payload);
245
246 assert_eq!(
247 rich.content_blocks,
248 vec![codewhale_tools::ToolResultContentBlock::Image {
249 mime_type: "image/png".to_string(),
250 data: image_data.to_string(),
251 }]
252 );
253 assert!(
254 rich.result
255 .content
256 .contains("2 tool-result image block(s) omitted")
257 );
258 assert!(!rich.result.content.contains(&oversized));
259 }
260
261 #[test]
262 fn mcp_error_text_and_typed_image_are_both_preserved() {
263 let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
264 let payload = json!({
265 "content": [
266 {"type": "text", "text": "capture failed after partial screenshot"},
267 {"type": "image", "data": image_data, "mimeType": "image/png"}
268 ],
269 "structuredContent": {"retryable": true},
270 "isError": true
271 });
272
273 let rich = mcp_result_to_bounded_rich_tool_result(payload);
274
275 assert!(!rich.result.success);
276 assert_eq!(
277 rich.result.content,
278 "capture failed after partial screenshot"
279 );
280 assert_eq!(
281 rich.content_blocks,
282 vec![codewhale_tools::ToolResultContentBlock::Image {
283 mime_type: "image/png".to_string(),
284 data: image_data.to_string(),
285 }]
286 );
287 }
288
289 /// A simple test tool for unit testing
290 struct TestTool {
291 name: String,
292 description: String,
293 }
294
295 #[async_trait::async_trait]
296 impl ToolSpec for TestTool {
297 fn name(&self) -> &str {
298 &self.name
299 }
300
301 fn description(&self) -> &str {
302 &self.description
303 }
304
305 fn input_schema(&self) -> Value {
306 json!({
307 "type": "object",
308 "properties": {
309 "message": { "type": "string" }
310 },
311 "required": ["message"]
312 })
313 }
314
315 fn capabilities(&self) -> Vec<ToolCapability> {
316 vec![ToolCapability::ReadOnly]
317 }
318
319 async fn execute(&self, input: Value, _context: &ToolContext) -> Result<ToolResult, ToolError> {
320 let message = required_str(&input, "message")?;
321 Ok(ToolResult::success(format!("Echo: {message}")))
322 }
323 }
324
325 fn make_test_tool(name: &str) -> Arc<TestTool> {
326 Arc::new(TestTool {
327 name: name.to_string(),
328 description: "A test tool".to_string(),
329 })
330 }
331
332 #[test]
333 fn mcp_read_helpers_remain_auto_and_eagerly_loaded() {
334 for name in [
335 "list_mcp_resources",
336 "list_mcp_resource_templates",
337 "mcp_read_resource",
338 "read_mcp_resource",
339 "mcp_get_prompt",
340 ] {
341 let adapter = mcp_tool_adapter_for_test(name);
342 assert_eq!(
343 adapter.approval_requirement(),
344 ApprovalRequirement::Auto,
345 "{name} should remain an automatic read helper"
346 );
347 assert!(adapter.is_read_only(), "{name} should remain read-only");
348 assert!(!adapter.defer_loading(), "{name} should remain loaded");
349 }
350 }
351
352 #[test]
353 fn mcp_actions_require_approval_with_exact_helper_matching() {
354 for name in [
355 "mcp_github_create_pull_request",
356 "mcp_github_list_mcp_resources_export",
357 "read_mcp_resource_and_delete",
358 ] {
359 let adapter = mcp_tool_adapter_for_test(name);
360 assert_eq!(
361 adapter.approval_requirement(),
362 ApprovalRequirement::Required,
363 "{name} must not inherit read-helper approval"
364 );
365 assert!(
366 adapter
367 .capabilities()
368 .contains(&ToolCapability::RequiresApproval),
369 "{name} should advertise approval gating"
370 );
371 assert!(adapter.defer_loading(), "{name} should remain deferred");
372 }
373 }
374
375 #[test]
376 fn test_registry_register_and_get() {
377 let tmp = tempdir().expect("tempdir");
378 let ctx = ToolContext::new(tmp.path().to_path_buf());
379 let mut registry = ToolRegistry::new(ctx);
380
381 let tool = make_test_tool("test_tool");
382 registry.register(tool);
383
384 assert!(registry.contains("test_tool"));
385 assert!(!registry.contains("nonexistent"));
386 assert_eq!(registry.all().len(), 1);
387 }
388
389 #[test]
390 fn resolve_exact_match_is_ascii_case_insensitive() {
391 let tmp = tempdir().expect("tempdir");
392 let ctx = ToolContext::new(tmp.path().to_path_buf());
393 let mut registry = ToolRegistry::new(ctx);
394
395 registry.register(make_test_tool("read_file"));
396
397 assert_eq!(registry.resolve("READ_FILE"), Some("read_file"));
398 }
399
400 #[test]
401 fn resolve_never_executes_a_fuzzy_prefix_guess() {
402 // #5123-class: a hallucinated name that merely shares a prefix with a
403 // real tool must NOT resolve — executing a prefix guess dispatched an
404 // arbitrary sibling tool ("agents" -> "agents/interrupt"). Exact and
405 // lossless normalizations still resolve; guesses return None so the
406 // caller can surface "unknown tool, did you mean: …".
407 let tmp = tempdir().expect("tempdir");
408 let ctx = ToolContext::new(tmp.path().to_path_buf());
409 let mut registry = ToolRegistry::new(ctx);
410
411 registry.register(make_test_tool("agents/interrupt"));
412 registry.register(make_test_tool("read_file"));
413
414 // Prefix guesses in both directions are rejected.
415 assert_eq!(registry.resolve("agents"), None);
416 assert_eq!(registry.resolve("agents/int"), None);
417 assert_eq!(registry.resolve("read"), None);
418 assert_eq!(registry.resolve("read_file_extra"), None);
419
420 // Lossless normalizations still resolve.
421 let mut hyphen_registry = ToolRegistry::new(ToolContext::new(tmp.path().to_path_buf()));
422 hyphen_registry.register(make_test_tool("read_file"));
423 assert_eq!(hyphen_registry.resolve("read-file"), Some("read_file"));
424 assert_eq!(hyphen_registry.resolve("ReadFile"), Some("read_file"));
425 assert_eq!(hyphen_registry.resolve("read_file_tool"), Some("read_file"));
426 }
427
428 #[test]
429 fn rlm_is_the_only_registered_session_surface() {
430 let tmp = tempdir().expect("tempdir");
431 let ctx = ToolContext::new(tmp.path().to_path_buf());
432 let registry = ToolRegistryBuilder::new().with_rlm_tool().build(ctx);
433
434 assert!(registry.contains("rlm"));
435 assert!(!registry.contains("harness"));
436 for retired in [
437 "rlm_session_objects",
438 "rlm_open",
439 "rlm_eval",
440 "rlm_configure",
441 "rlm_close",
442 ] {
443 assert!(
444 !registry.contains(retired),
445 "{retired} must no longer be callable"
446 );
447 }
448 }
449
450 /// The names an engine treats as built in: whatever is registered before the
451 /// plugin directory loads (see `configure_plugin_tools`).
452 fn builtin_names(registry: &ToolRegistry) -> std::collections::HashSet<String> {
453 registry.names().into_iter().map(str::to_string).collect()
454 }
455
456 #[test]
457 fn apply_overrides_removes_original_when_replacement_is_missing() {
458 let tmp = tempdir().expect("tempdir");
459 let ctx = ToolContext::new(tmp.path().to_path_buf());
460 let mut registry = ToolRegistryBuilder::new().with_file_tools().build(ctx);
461 let builtins = builtin_names(&registry);
462 std::fs::write(
463 tmp.path().join("reader.sh"),
464 "# name: custom-reader\n# description: drop-in reader\n",
465 )
466 .unwrap();
467 registry.load_plugins(tmp.path());
468 assert!(registry.contains("custom-reader"));
469
470 let mut overrides = HashMap::new();
471 overrides.insert(
472 "custom-reader".to_string(),
473 ToolOverride::Script {
474 path: "missing-wrapper.sh".to_string(),
475 args: None,
476 },
477 );
478
479 registry.apply_overrides(&overrides, tmp.path(), &builtins);
480
481 assert!(!registry.contains("custom-reader"));
482 assert!(registry.contains("read_file"));
483 }
484
485 /// D4 (CURRENT_DECISIONS §26): a `[tools.overrides]` script or command cannot
486 /// replace a built-in. The entry is refused loudly, naming the config key and
487 /// the built-in, and the built-in stays active; `disabled` and overrides under
488 /// a new name keep working.
489 #[test]
490 fn script_and_command_overrides_cannot_replace_builtins() {
491 let tmp = tempdir().unwrap();
492 let mut registry = ToolRegistryBuilder::new()
493 .with_file_tools()
494 .with_patch_tools()
495 .build(ToolContext::new(tmp.path()));
496 let builtins = builtin_names(&registry);
497 let file = registry.get("read_file").unwrap();
498 let patch = registry.get("apply_patch").unwrap();
499 std::fs::write(
500 tmp.path().join("wrapper.sh"),
501 "# name: wrapper\n# description: audit wrapper\n",
502 )
503 .unwrap();
504 let script = || ToolOverride::Script {
505 path: "wrapper.sh".to_string(),
506 args: None,
507 };
508 let command = || ToolOverride::Command {
509 command: "my-patcher".to_string(),
510 args: None,
511 };
512 let overrides = HashMap::from([
513 ("read_file".to_string(), script()),
514 ("apply_patch".to_string(), command()),
515 ("audited_file".to_string(), script()),
516 ("my_patcher".to_string(), command()),
517 ]);
518
519 let mut refused = Vec::new();
520 let errors = capture_registration_warnings(|| {
521 refused = registry.apply_overrides(&overrides, tmp.path(), &builtins);
522 });
523
524 assert!(Arc::ptr_eq(&registry.get("read_file").unwrap(), &file));
525 assert!(Arc::ptr_eq(&registry.get("apply_patch").unwrap(), &patch));
526 // The refusals are returned for the engine's status line and logged.
527 refused.sort();
528 assert_eq!(refused, ["apply_patch", "read_file"]);
529 for name in ["apply_patch", "read_file"] {
530 assert!(
531 errors.contains(&super::override_refusal_notice(name)),
532 "{errors}"
533 );
534 }
535 assert_eq!(
536 registry.get("audited_file").unwrap().description(),
537 "audit wrapper"
538 );
539 assert!(registry.contains("my_patcher"));
540
541 let disable = HashMap::from([("read_file".to_string(), ToolOverride::Disabled)]);
542 registry.apply_overrides(&disable, tmp.path(), &builtins);
543 assert!(!registry.contains("read_file"));
544 }
545
546 #[test]
547 fn creator_tool_names_are_reserved_against_scripts_and_overrides_even_before_registration() {
548 let tmp = tempdir().unwrap();
549 let tools_dir = tmp.path().join("tools");
550 std::fs::create_dir(&tools_dir).unwrap();
551 for (file, name) in [
552 ("plugin_manager.sh", "plugin_manager"),
553 ("plugin_manager_upper.sh", "PLUGIN_MANAGER"),
554 ("cordis_inspect_list.sh", "cordis_inspect_list"),
555 ("cordis_inspect_query.sh", "cordis_inspect_query"),
556 ("safe_extra.sh", "safe_extra"),
557 ] {
558 std::fs::write(
559 tools_dir.join(file),
560 format!("# name: {name}\n# description: {name}\n"),
561 )
562 .unwrap();
563 }
564 std::fs::write(
565 tools_dir.join("wrapper.sh"),
566 "# name: wrapper\n# description: override wrapper\n",
567 )
568 .unwrap();
569
570 let mut registry = ToolRegistryBuilder::new()
571 .with_file_tools()
572 .build(ToolContext::new(tmp.path()));
573 let builtins = builtin_names(&registry);
574
575 let load_errors = capture_registration_warnings(|| registry.load_plugins(&tools_dir));
576 assert!(registry.contains("safe_extra"));
577 for reserved in [
578 "plugin_manager",
579 "PLUGIN_MANAGER",
580 "cordis_inspect_list",
581 "cordis_inspect_query",
582 ] {
583 assert!(!registry.contains(reserved), "{reserved}");
584 assert!(
585 load_errors.contains(&format!(
586 "Cannot load plugin tool '{reserved}': name is already registered"
587 )),
588 "{reserved}: {load_errors}"
589 );
590 }
591
592 let overrides = HashMap::from([
593 (
594 "plugin_manager".to_string(),
595 ToolOverride::Script {
596 path: "wrapper.sh".to_string(),
597 args: None,
598 },
599 ),
600 (
601 "PLUGIN_MANAGER".to_string(),
602 ToolOverride::Command {
603 command: "hijack-pm".to_string(),
604 args: None,
605 },
606 ),
607 (
608 "cordis_inspect_list".to_string(),
609 ToolOverride::Script {
610 path: "wrapper.sh".to_string(),
611 args: None,
612 },
613 ),
614 (
615 "cordis_inspect_query".to_string(),
616 ToolOverride::Command {
617 command: "hijack-inspect".to_string(),
618 args: None,
619 },
620 ),
621 ]);
622 let mut refused = Vec::new();
623 let override_errors = capture_registration_warnings(|| {
624 refused = registry.apply_overrides(&overrides, &tools_dir, &builtins);
625 });
626 refused.sort();
627 assert_eq!(
628 refused,
629 [
630 "PLUGIN_MANAGER",
631 "cordis_inspect_list",
632 "cordis_inspect_query",
633 "plugin_manager",
634 ]
635 );
636 for reserved in [
637 "plugin_manager",
638 "PLUGIN_MANAGER",
639 "cordis_inspect_list",
640 "cordis_inspect_query",
641 ] {
642 assert!(!registry.contains(reserved), "{reserved}");
643 assert!(
644 override_errors.contains(&super::override_refusal_notice(reserved)),
645 "{reserved}: {override_errors}"
646 );
647 }
648
649 for disable_key in ["plugin_manager", "PLUGIN_MANAGER"] {
650 let mut reg = ToolRegistryBuilder::new()
651 .with_file_tools()
652 .build(ToolContext::new(tmp.path()));
653 reg.register(Arc::new(TestTool {
654 name: "plugin_manager".to_string(),
655 description: "built-in creator".to_string(),
656 }));
657 let reg_builtins = builtin_names(&reg);
658 let disable = HashMap::from([(disable_key.to_string(), ToolOverride::Disabled)]);
659 let disable_refused = reg.apply_overrides(&disable, &tools_dir, &reg_builtins);
660 assert!(
661 disable_refused.is_empty(),
662 "{disable_key}: {disable_refused:?}"
663 );
664 assert!(!reg.contains("plugin_manager"), "{disable_key}");
665 reg.load_plugins(&tools_dir);
666 assert!(!reg.contains("plugin_manager"), "{disable_key}");
667 }
668 }
669
670 /// D4 (CURRENT_DECISIONS §26): a script cannot approve itself. `approval: auto`
671 /// gets the default a script without the line gets, and the loader says so.
672 #[test]
673 fn script_tool_auto_approval_is_ignored_and_reported() {
674 let tmp = tempdir().unwrap();
675 let mut registry = ToolRegistryBuilder::new()
676 .with_file_tools()
677 .build(ToolContext::new(tmp.path()));
678 let builtins = builtin_names(&registry);
679 let plugin_dir = tmp.path().join("tools");
680 std::fs::create_dir(&plugin_dir).unwrap();
681 std::fs::write(
682 plugin_dir.join("greet.sh"),
683 "# name: greet\n# description: Say hello\n# approval: auto\n",
684 )
685 .unwrap();
686 std::fs::write(
687 tmp.path().join("audit.sh"),
688 "# name: ignored\n# description: audit\n# approval: auto\n",
689 )
690 .unwrap();
691 let overrides = HashMap::from([(
692 "audited".to_string(),
693 ToolOverride::Script {
694 path: tmp.path().join("audit.sh").to_string_lossy().into_owned(),
695 args: None,
696 },
697 )]);
698
699 let warnings = capture_registration_warnings(|| {
700 registry.load_plugins(&plugin_dir);
701 registry.apply_overrides(&overrides, &plugin_dir, &builtins);
702 });
703
704 for name in ["greet", "audited"] {
705 assert_eq!(
706 registry.get(name).unwrap().approval_requirement(),
707 ApprovalRequirement::Suggest,
708 "{name}"
709 );
710 assert!(
711 warnings.contains(&format!(
712 "Script tool '{name}': `approval: auto` is no longer supported for script tools"
713 )),
714 "{warnings}"
715 );
716 }
717 }
718
719 #[test]
720 fn builder_registers_speech_without_the_tts_alias() {
721 let tmp = tempdir().expect("tempdir");
722 let ctx = ToolContext::new(tmp.path().to_path_buf());
723 let registry = ToolRegistryBuilder::new()
724 .with_speech_tools(None, None)
725 .build(ctx);
726
727 assert!(registry.contains("speech"));
728 assert!(!registry.contains("tts"));
729 }
730
731 #[test]
732 fn agent_runtime_surface_skips_speech_without_a_client() {
733 use super::AgentToolSurfaceOptions;
734 use codewhale_agent_contract::worker_profile::ShellPolicy;
735 let tmp = tempdir().expect("tempdir");
736 let ctx = ToolContext::new(tmp.path().to_path_buf());
737 let registry = ToolRegistryBuilder::new()
738 .with_agent_runtime_surface(
739 None,
740 "test-model".to_string(),
741 AgentToolSurfaceOptions::new(ShellPolicy::Full),
742 crate::tools::todo::new_shared_todo_list(),
743 )
744 .build(ctx);
745 assert!(!registry.contains("speech"));
746 }
747
748 #[test]
749 fn model_visible_tool_descriptions_name_no_vendor() {
750 use super::AgentToolSurfaceOptions;
751 use codewhale_agent_contract::worker_profile::ShellPolicy;
752 let tmp = tempdir().expect("tempdir");
753 let ctx = ToolContext::new(tmp.path().to_path_buf());
754 let mut options = AgentToolSurfaceOptions::new(ShellPolicy::Full);
755 options.web_search_enabled = true;
756 let registry = ToolRegistryBuilder::new()
757 .with_agent_runtime_surface(
758 None,
759 "test-model".to_string(),
760 options,
761 crate::tools::todo::new_shared_todo_list(),
762 )
763 .with_speech_tools(None, None)
764 .build(ctx);
765 let vendors = [
766 "xiaomi",
767 "mimo",
768 "claude",
769 "anthropic",
770 "openai",
771 "gpt-",
772 "deepseek",
773 "gemini",
774 "kimi",
775 "qwen",
776 "grok",
777 "mistral",
778 ];
779 for tool in registry.to_api_tools() {
780 let description = tool.description.to_ascii_lowercase();
781 for vendor in vendors {
782 assert!(
783 !description.contains(vendor),
784 "tool {} names a vendor ({vendor}) in its model-facing description",
785 tool.name
786 );
787 }
788 }
789 }
790
791 #[test]
792 fn test_registry_names() {
793 let tmp = tempdir().expect("tempdir");
794 let ctx = ToolContext::new(tmp.path().to_path_buf());
795 let mut registry = ToolRegistry::new(ctx);
796
797 registry.register(make_test_tool("tool_a"));
798 registry.register(make_test_tool("tool_b"));
799
800 let names = registry.names();
801 assert_eq!(names.len(), 2);
802 assert!(names.contains(&"tool_a"));
803 assert!(names.contains(&"tool_b"));
804 }
805
806 #[test]
807 fn test_registry_to_api_tools() {
808 let tmp = tempdir().expect("tempdir");
809 let ctx = ToolContext::new(tmp.path().to_path_buf());
810 let mut registry = ToolRegistry::new(ctx);
811
812 registry.register(make_test_tool("my_tool"));
813
814 let api_tools = registry.to_api_tools();
815 assert_eq!(api_tools.len(), 1);
816 assert_eq!(api_tools[0].name, "my_tool");
817 assert_eq!(api_tools[0].description, "A test tool");
818 }
819
820 #[test]
821 fn api_tools_with_cache_marks_last_tool_ephemeral() {
822 let tmp = tempdir().expect("tempdir");
823 let ctx = ToolContext::new(tmp.path().to_path_buf());
824 let mut registry = ToolRegistry::new(ctx);
825
826 registry.register(make_test_tool("tool_a"));
827 registry.register(make_test_tool("tool_b"));
828
829 let api_tools = registry.to_api_tools_with_cache(true);
830 assert_eq!(api_tools.len(), 2);
831 assert!(api_tools[0].cache_control.is_none());
832 assert_eq!(
833 api_tools[1]
834 .cache_control
835 .as_ref()
836 .map(|c| c.cache_type.as_str()),
837 Some("ephemeral")
838 );
839 }
840
841 /// Tool whose `description()` advances through a script of pre-built
842 /// strings, one per call. Used to demonstrate that the api-tools cache
843 /// pins the description bytes on first read instead of re-sampling them
844 /// each turn (#263 follow-up; mirrors reference-cc's `getToolSchemaCache`).
845 struct VaryingDescriptionTool {
846 name: String,
847 descriptions: Vec<String>,
848 next: std::sync::atomic::AtomicUsize,
849 }
850
851 impl VaryingDescriptionTool {
852 fn new(name: &str, descriptions: &[&str]) -> Self {
853 Self {
854 name: name.to_string(),
855 descriptions: descriptions.iter().map(|s| (*s).to_string()).collect(),
856 next: std::sync::atomic::AtomicUsize::new(0),
857 }
858 }
859 }
860
861 #[async_trait::async_trait]
862 impl ToolSpec for VaryingDescriptionTool {
863 fn name(&self) -> &str {
864 &self.name
865 }
866
867 fn description(&self) -> &str {
868 let idx = self
869 .next
870 .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
871 .min(self.descriptions.len() - 1);
872 &self.descriptions[idx]
873 }
874
875 fn input_schema(&self) -> Value {
876 json!({"type": "object", "properties": {}, "required": []})
877 }
878
879 fn capabilities(&self) -> Vec<ToolCapability> {
880 vec![ToolCapability::ReadOnly]
881 }
882
883 async fn execute(
884 &self,
885 _input: Value,
886 _context: &ToolContext,
887 ) -> Result<ToolResult, ToolError> {
888 Ok(ToolResult::success("ok".to_string()))
889 }
890 }
891
892 #[test]
893 fn to_api_tools_pins_description_bytes_across_calls() {
894 // Regression for the cache-stability follow-up: an MCP adapter that
895 // returns a different `description()` on reconnect (or any other
896 // tool whose description isn't a `&'static str`) would otherwise
897 // rewrite the catalog bytes mid-session and miss the prefix cache.
898 // The registry pins the first call's value until it's mutated.
899 let tmp = tempdir().expect("tempdir");
900 let ctx = ToolContext::new(tmp.path().to_path_buf());
901 let mut registry = ToolRegistry::new(ctx);
902 registry.register(Arc::new(VaryingDescriptionTool::new(
903 "varying",
904 &["first description", "second description"],
905 )));
906
907 let first = registry.to_api_tools();
908 let second = registry.to_api_tools();
909
910 assert_eq!(first.len(), 1);
911 assert_eq!(first[0].description, "first description");
912 assert_eq!(
913 first, second,
914 "api-tools catalog must be byte-identical across reads with no mutation in between"
915 );
916 }
917
918 #[test]
919 fn register_invalidates_api_tools_cache() {
920 // Counter-test: when a real change happens (a new tool registers,
921 // an existing one is removed, or `clear` is called), the cache must
922 // be discarded so the next read reflects the live registry.
923 let tmp = tempdir().expect("tempdir");
924 let ctx = ToolContext::new(tmp.path().to_path_buf());
925 let mut registry = ToolRegistry::new(ctx);
926 registry.register(Arc::new(VaryingDescriptionTool::new(
927 "varying",
928 &["first description", "second description"],
929 )));
930
931 let before = registry.to_api_tools();
932 assert_eq!(before.len(), 1);
933
934 registry.register(make_test_tool("late_arrival"));
935
936 let after = registry.to_api_tools();
937 assert_eq!(after.len(), 2, "cache must rebuild after register");
938 assert!(after.iter().any(|t| t.name == "varying"));
939 assert!(after.iter().any(|t| t.name == "late_arrival"));
940 // The varying tool's description advances on cache rebuild — the
941 // first read above sampled `first description`; this rebuild samples
942 // `second description`. The point is just that the bytes *can*
943 // change after a real mutation, not that they always do.
944 let varying_after = after
945 .iter()
946 .find(|t| t.name == "varying")
947 .expect("varying tool present");
948 assert_eq!(varying_after.description, "second description");
949 }
950
951 #[test]
952 fn remove_tool_invalidates_api_tools_cache() {
953 let tmp = tempdir().expect("tempdir");
954 let ctx = ToolContext::new(tmp.path().to_path_buf());
955 let mut registry = ToolRegistry::new(ctx);
956 registry.register(make_test_tool("alpha"));
957 registry.register(make_test_tool("beta"));
958
959 let before = registry.to_api_tools();
960 assert_eq!(before.len(), 2);
961
962 assert!(registry.remove_tool("alpha"));
963 let after_remove = registry.to_api_tools();
964 assert_eq!(after_remove.len(), 1);
965 assert_eq!(after_remove[0].name, "beta");
966 }
967
968 #[test]
969 fn to_api_tools_emits_alphabetical_order_regardless_of_registration_order() {
970 // Regression for #263: HashMap iteration is non-deterministic across
971 // process launches, which busts DeepSeek's KV prefix cache for every
972 // cross-session resume. `to_api_tools` must emit by name regardless
973 // of registration order so two consecutive calls (and two distinct
974 // launches) produce byte-identical output.
975 let tmp = tempdir().expect("tempdir");
976 let ctx = ToolContext::new(tmp.path().to_path_buf());
977
978 let order_a = {
979 let mut registry = ToolRegistry::new(ctx.clone());
980 registry.register(make_test_tool("zebra"));
981 registry.register(make_test_tool("alpha"));
982 registry.register(make_test_tool("mango"));
983 registry
984 .to_api_tools()
985 .iter()
986 .map(|t| t.name.clone())
987 .collect::<Vec<_>>()
988 };
989
990 let order_b = {
991 let mut registry = ToolRegistry::new(ctx.clone());
992 registry.register(make_test_tool("alpha"));
993 registry.register(make_test_tool("mango"));
994 registry.register(make_test_tool("zebra"));
995 registry
996 .to_api_tools()
997 .iter()
998 .map(|t| t.name.clone())
999 .collect::<Vec<_>>()
1000 };
1001
1002 assert_eq!(order_a, vec!["alpha", "mango", "zebra"]);
1003 assert_eq!(order_a, order_b);
1004 }
1005
1006 fn scoped_context(workspace: &std::path::Path) -> ToolContext {
1007 ToolContext::new(workspace.to_path_buf())
1008 .with_tool_authority(
1009 ToolAuthorityEnvelope {
1010 schema_version: 1,
1011 owner: "fleet-worker-1".to_string(),
1012 authority: ToolMutationAuthority::ScopedWrite,
1013 network_access: None,
1014 shell: crate::tools::spec::ToolShellAuthority::None,
1015 verification: crate::tools::spec::ToolVerificationAuthority::None,
1016 writable_roots: vec!["src".to_string()],
1017 writable_files: Vec::new(),
1018 coordination_contracts: Vec::new(),
1019 }
1020 .normalized()
1021 .expect("test authority"),
1022 )
1023 .expect("test context authority")
1024 }
1025
1026 fn readonly_scout_context(workspace: &std::path::Path, network_access: bool) -> ToolContext {
1027 ToolContext::new(workspace.to_path_buf())
1028 .with_tool_authority(ToolAuthorityEnvelope {
1029 schema_version: 1,
1030 owner: "scout-1".to_string(),
1031 authority: ToolMutationAuthority::ReadOnly,
1032 network_access: Some(network_access),
1033 shell: crate::tools::spec::ToolShellAuthority::ReadOnly,
1034 verification: crate::tools::spec::ToolVerificationAuthority::None,
1035 writable_roots: Vec::new(),
1036 writable_files: Vec::new(),
1037 coordination_contracts: Vec::new(),
1038 })
1039 .expect("read-only Scout authority")
1040 }
1041
1042 fn readonly_verifier_context(workspace: &std::path::Path) -> ToolContext {
1043 ToolContext::new(workspace.to_path_buf())
1044 .with_tool_authority(ToolAuthorityEnvelope {
1045 schema_version: 1,
1046 owner: "verifier-1".to_string(),
1047 authority: ToolMutationAuthority::ReadOnly,
1048 network_access: Some(true),
1049 shell: crate::tools::spec::ToolShellAuthority::None,
1050 verification: crate::tools::spec::ToolVerificationAuthority::Bounded,
1051 writable_roots: Vec::new(),
1052 writable_files: Vec::new(),
1053 coordination_contracts: Vec::new(),
1054 })
1055 .expect("bounded verifier authority")
1056 }
1057
1058 #[test]
1059 fn machine_verifier_catalog_and_dispatch_add_only_bounded_run() {
1060 let tmp = tempdir().expect("tempdir");
1061 let registry = ToolRegistryBuilder::new()
1062 .with_agent_tools_policy(
1063 codewhale_agent_contract::worker_profile::ShellPolicy::None,
1064 crate::tools::user_input::UserInputLimits::default(),
1065 )
1066 .with_web_tools()
1067 .with_todo_tool(crate::tools::todo::new_shared_todo_list())
1068 .build(readonly_verifier_context(tmp.path()));
1069 let tools = registry.to_api_tools();
1070 let names = tools
1071 .iter()
1072 .map(|tool| tool.name.as_str())
1073 .collect::<Vec<_>>();
1074 assert_eq!(names, {
1075 let mut expected = vec![
1076 "Run",
1077 "Web",
1078 "context_archive_search",
1079 "file_search",
1080 "grep_files",
1081 "handle_read",
1082 "list_dir",
1083 "load_skill",
1084 "lsp",
1085 "present",
1086 "read",
1087 "read_media",
1088 "request_user_input",
1089 "retrieve_tool_result",
1090 "show_data",
1091 "todo_write",
1092 "tui_help",
1093 "validate_data",
1094 "web.run",
1095 ];
1096 if crate::tools::image_ocr::ocr_available() {
1097 expected.push("image_ocr");
1098 expected.sort_unstable();
1099 }
1100 expected
1101 });
1102 let run = registry.get("Run").expect("bounded Run registered");
1103 enforce_tool_authority(
1104 "Run",
1105 &json!({"action": "tests", "args": "-p codewhale-tui ordinary_scout"}),
1106 run.as_ref(),
1107 registry.context(),
1108 )
1109 .expect("pure test selection fits bounded verifier authority");
1110 let error = enforce_tool_authority(
1111 "Run",
1112 &json!({"action": "tests", "args": "--manifest-path ../other/Cargo.toml"}),
1113 run.as_ref(),
1114 registry.context(),
1115 )
1116 .expect_err("unbounded verification must remain refused")
1117 .to_string();
1118 assert!(error.contains("unbounded verification"), "{error}");
1119 assert!(!registry.contains("bash"), "Verifier never gains raw shell");
1120 assert!(!registry.contains("Bash"), "Verifier never gains raw shell");
1121 }
1122
1123 #[tokio::test]
1124 async fn fleet_authority_allows_scoped_file_writes_and_rejects_outside_paths() {
1125 let tmp = tempdir().expect("tempdir");
1126 std::fs::create_dir(tmp.path().join("src")).expect("src");
1127 std::fs::create_dir(tmp.path().join("docs")).expect("docs");
1128 let registry = ToolRegistryBuilder::new()
1129 .with_file_tools()
1130 .with_patch_tools()
1131 .build(scoped_context(tmp.path()));
1132
1133 registry
1134 .execute_full(
1135 "write_file",
1136 json!({"path": "src/ok.txt", "content": "ok\n"}),
1137 )
1138 .await
1139 .expect("scoped write");
1140 assert_eq!(
1141 std::fs::read_to_string(tmp.path().join("src/ok.txt")).expect("written file"),
1142 "ok\n"
1143 );
1144
1145 let error = registry
1146 .execute_full(
1147 "write_file",
1148 json!({"path": "docs/no.txt", "content": "no\n"}),
1149 )
1150 .await
1151 .expect_err("out-of-scope write")
1152 .to_string();
1153 assert!(error.contains("outside its machine-readable"), "{error}");
1154 assert!(!tmp.path().join("docs/no.txt").exists());
1155 }
1156
1157 #[tokio::test]
1158 async fn fleet_authority_allows_only_classifier_proven_readonly_bash() {
1159 let tmp = tempdir().expect("tempdir");
1160 std::fs::create_dir(tmp.path().join("src")).expect("src");
1161 std::fs::write(
1162 tmp.path().join("src/evidence.txt"),
1163 "first\nsecond\nthird\n",
1164 )
1165 .expect("inspection fixture");
1166 let registry = ToolRegistryBuilder::new()
1167 .with_shell_tools()
1168 .build(readonly_scout_context(tmp.path(), true));
1169
1170 let shell = crate::tools::shell::LowercaseBashTool;
1171 for command in [
1172 "pwd",
1173 "git status --short",
1174 "rg needle src",
1175 "gh issue list --limit 10",
1176 "gh issue view 5287 --json title,state",
1177 "sed -n '2,3p' src/evidence.txt",
1178 // #6015: durable workers accept the same grammar as in-session
1179 // agents — pipelines, chains, find, git -C and a leading cd.
1180 "rg -n foo src | head -5",
1181 "find . -name '*.rs'",
1182 "git -C . log --oneline -3",
1183 "cd src && git diff",
1184 "git diff HEAD && echo '=== FILES ===' && ls -la",
1185 "rg -n foo src 2>/dev/null",
1186 "sed -n '2p' src/evidence.txt | head -n 1",
1187 "sed -n '2p' src/evidence.txt | gh issue list",
1188 "gh issue list | sed -n '2p'",
1189 "find src -name '*.rs'",
1190 ] {
1191 enforce_tool_authority(
1192 "bash",
1193 &json!({"command": command}),
1194 &shell,
1195 registry.context(),
1196 )
1197 .unwrap_or_else(|error| panic!("{command} should fit read-only Scout authority: {error}"));
1198 }
1199
1200 let result = registry
1201 .execute_full("bash", json!({"command": "pwd"}))
1202 .await
1203 .expect("bounded read-only bash survives machine authority");
1204 assert!(result.success, "{}", result.content);
1205
1206 #[cfg(unix)]
1207 {
1208 let result = registry
1209 .execute_full("bash", json!({"command": "sed -n '2,3p' src/evidence.txt"}))
1210 .await
1211 .expect("numeric sed inspection survives machine authority");
1212 assert!(result.success, "{}", result.content);
1213 assert!(
1214 result.content.contains("second\nthird"),
1215 "{}",
1216 result.content
1217 );
1218 assert_eq!(
1219 std::fs::read_to_string(tmp.path().join("src/evidence.txt")).expect("fixture"),
1220 "first\nsecond\nthird\n"
1221 );
1222 }
1223
1224 for command in [
1225 "touch src/no.txt",
1226 "git checkout -- src/lib.rs",
1227 "git push origin main",
1228 "gh issue close 5287",
1229 "gh issue edit 5287 --title changed",
1230 "gh issue create --title nope --body nope",
1231 "gh issue view 5287 > issue.txt",
1232 "gh issue view 5287 &",
1233 "bash -lc 'git status'",
1234 "sed -i -n '2p' src/evidence.txt",
1235 "sed -n '2p' src/evidence.txt -i",
1236 "sed -n '2p' src/evidence.txt -e 'w src/no.txt'",
1237 "sed -n '2p' src/evidence.txt -f src/evidence.txt",
1238 "sed -n 'w src/no.txt' src/evidence.txt",
1239 "sed -n 'e touch src/no.txt' src/evidence.txt",
1240 "sed -n 's/first/changed/w src/no.txt' src/evidence.txt",
1241 "sed -n '2p' $(touch src/no.txt)",
1242 "sed -n '2p' src/evidence.txt > src/no.txt",
1243 "sed -n '2p' src/evidence.txt && touch src/no.txt",
1244 "find src -delete",
1245 "awk '1' src/evidence.txt",
1246 "git commit -m x",
1247 "sort -o src/no.txt src/evidence.txt",
1248 "cd /etc; cat passwd",
1249 ] {
1250 let error = registry
1251 .execute_full("bash", json!({"command": command}))
1252 .await
1253 .expect_err("mutating bash remains outside machine authority")
1254 .to_string();
1255 // The refusal names the rule, from the same classifier every
1256 // read-only gate uses.
1257 assert!(error.contains("[shell.readonly.command]"), "{error}");
1258 assert!(error.contains("File tool"), "{error}");
1259 }
1260 assert!(!tmp.path().join("src/no.txt").exists());
1261
1262 let no_shell = scoped_context(tmp.path());
1263 let error = enforce_tool_authority("bash", &json!({"command": "pwd"}), &shell, &no_shell)
1264 .expect_err("mutation authority must not imply shell authority")
1265 .to_string();
1266 assert!(error.contains("does not grant read-only shell"), "{error}");
1267 }
1268
1269 #[test]
1270 fn fleet_authority_sed_inspection_preserves_policy_boundaries() {
1271 let tmp = tempdir().expect("tempdir");
1272 let context = readonly_scout_context(tmp.path(), false);
1273 let registry = ToolRegistryBuilder::new().with_shell_tools().build(context);
1274 let name = "bash";
1275 let shell = registry.get(name).expect("shell tool");
1276 let input = json!({"command": "sed -n '300,400p' src/lib.rs", "timeout": 10});
1277 enforce_tool_authority(name, &input, shell.as_ref(), registry.context())
1278 .expect("local numeric sed inspection needs no network grant");
1279 assert!(
1280 !shell.is_read_only_for(&input),
1281 "parent classification stays strict"
1282 );
1283 assert!(
1284 !shell.supports_parallel_for(&input),
1285 "parallel policy stays strict"
1286 );
1287 assert_eq!(
1288 shell.approval_requirement_for(&input),
1289 ApprovalRequirement::Required
1290 );
1291
1292 let mut denied = registry.context().clone();
1293 denied.disallowed_tools = vec!["Bash".into()];
1294 assert!(enforce_tool_authority(name, &input, shell.as_ref(), &denied).is_err());
1295 assert!(
1296 enforce_tool_authority(name, &input, shell.as_ref(), &scoped_context(tmp.path())).is_err(),
1297 "write authority does not grant shell authority"
1298 );
1299 assert!(
1300 enforce_tool_authority(
1301 name,
1302 &input,
1303 shell.as_ref(),
1304 &readonly_verifier_context(tmp.path())
1305 )
1306 .is_err(),
1307 "shell-less evidence authority stays shell-less"
1308 );
1309 for field in [
1310 json!({"background": true}),
1311 json!({"tty": true}),
1312 json!({"interactive": true}),
1313 json!({"stdin": ""}),
1314 json!({"action": "wait"}),
1315 json!({"action": "interact"}),
1316 json!({"action": "cancel"}),
1317 json!({"action": 3}),
1318 json!({"task_id": "shell_1"}),
1319 json!({"persist": true}),
1320 json!({"sandbox_permissions": "danger-full-access", "justification": "test"}),
1321 ] {
1322 let mut rejected = input.clone();
1323 rejected
1324 .as_object_mut()
1325 .unwrap()
1326 .extend(field.as_object().unwrap().clone());
1327 assert!(
1328 enforce_tool_authority(name, &rejected, shell.as_ref(), registry.context()).is_err(),
1329 "{name}: {rejected}"
1330 );
1331 }
1332 }
1333
1334 #[test]
1335 fn fleet_authority_intersects_readonly_github_bash_with_network_ceiling() {
1336 let tmp = tempdir().expect("tempdir");
1337 let shell = crate::tools::shell::LowercaseBashTool;
1338 let input = json!({"command": "gh issue view 5287"});
1339 let networked = ToolContext::new(tmp.path().to_path_buf())
1340 .with_tool_authority(ToolAuthorityEnvelope {
1341 schema_version: 1,
1342 owner: "scout".to_string(),
1343 authority: ToolMutationAuthority::ReadOnly,
1344 network_access: Some(true),
1345 shell: crate::tools::spec::ToolShellAuthority::ReadOnly,
1346 verification: crate::tools::spec::ToolVerificationAuthority::None,
1347 writable_roots: Vec::new(),
1348 writable_files: Vec::new(),
1349 coordination_contracts: Vec::new(),
1350 })
1351 .expect("networked scout");
1352 enforce_tool_authority("bash", &input, &shell, &networked)
1353 .expect("networked scout may inspect GitHub");
1354
1355 let offline = ToolContext::new(tmp.path().to_path_buf())
1356 .with_tool_authority(ToolAuthorityEnvelope {
1357 schema_version: 1,
1358 owner: "offline-scout".to_string(),
1359 authority: ToolMutationAuthority::ReadOnly,
1360 network_access: Some(false),
1361 shell: crate::tools::spec::ToolShellAuthority::ReadOnly,
1362 verification: crate::tools::spec::ToolVerificationAuthority::None,
1363 writable_roots: Vec::new(),
1364 writable_files: Vec::new(),
1365 coordination_contracts: Vec::new(),
1366 })
1367 .expect("offline scout");
1368 let error = enforce_tool_authority("bash", &input, &shell, &offline)
1369 .expect_err("network denial must win")
1370 .to_string();
1371 assert!(error.contains("does not grant network access"), "{error}");
1372
1373 // #6015: an admitted network read cannot hide inside a pipeline or chain.
1374 for command in [
1375 "gh pr view 1 | head",
1376 "ls && gh issue list",
1377 "cd . && gh pr view 1",
1378 ] {
1379 let input = json!({"command": command});
1380 enforce_tool_authority("bash", &input, &shell, &networked)
1381 .unwrap_or_else(|error| panic!("{command}: {error}"));
1382 let error = enforce_tool_authority("bash", &input, &shell, &offline)
1383 .expect_err("network denial must win inside compositions")
1384 .to_string();
1385 assert!(
1386 error.contains("does not grant network access"),
1387 "{command}: {error}"
1388 );
1389 }
1390 // Network access alone cannot authorize npm's configured destinations.
1391 for command in [
1392 "npm view x",
1393 "npm view @scope/pkg --json",
1394 "cd sub && npm view x",
1395 ] {
1396 let input = json!({"command": command});
1397 for context in [&networked, &offline] {
1398 let error = enforce_tool_authority("bash", &input, &shell, context)
1399 .expect_err("npm metadata reads require ordinary shell authority")
1400 .to_string();
1401 assert!(error.contains("configuration"), "{command}: {error}");
1402 }
1403 }
1404 }
1405
1406 #[tokio::test]
1407 async fn fleet_authority_denies_git_even_when_the_action_is_nominally_read_only() {
1408 let tmp = tempdir().expect("tempdir");
1409 std::fs::create_dir(tmp.path().join("src")).expect("src");
1410 let registry = ToolRegistryBuilder::new()
1411 .with_git_tools()
1412 .with_git_history_tools()
1413 .with_review_tool(None, "fixture-model".to_string())
1414 .build(scoped_context(tmp.path()));
1415
1416 for (name, input) in [
1417 ("Git", json!({"action": "status"})),
1418 ("Git", json!({"action": "diff"})),
1419 ("Git", json!({"action": "show", "revision": "HEAD"})),
1420 ("Git", json!({"action": "blame", "path": "src/lib.rs"})),
1421 ("review", json!({"target": "diff"})),
1422 ] {
1423 let error = registry
1424 .execute_full(name, input)
1425 .await
1426 .expect_err("Git subprocesses remain unprovable under Fleet authority")
1427 .to_string();
1428 assert!(error.contains("Git helpers"), "{name}: {error}");
1429 }
1430 }
1431
1432 #[tokio::test]
1433 async fn fleet_authority_rejects_fim_edit_outside_its_write_scope() {
1434 let tmp = tempdir().expect("tempdir");
1435 std::fs::create_dir(tmp.path().join("src")).expect("src");
1436 std::fs::create_dir(tmp.path().join("docs")).expect("docs");
1437 std::fs::write(tmp.path().join("docs/outside.txt"), "before\nafter\n").expect("fixture");
1438 let registry = ToolRegistryBuilder::new()
1439 .with_tool(Arc::new(crate::tools::fim::FimEditTool::new(
1440 None,
1441 "fixture-model".to_string(),
1442 )))
1443 .build(scoped_context(tmp.path()));
1444
1445 let error = registry
1446 .execute_full(
1447 "fim_edit",
1448 json!({
1449 "path": "docs/outside.txt",
1450 "prefix_anchor": "before\n",
1451 "suffix_anchor": "after\n"
1452 }),
1453 )
1454 .await
1455 .expect_err("FIM mutation must be checked before model execution")
1456 .to_string();
1457 assert!(error.contains("outside its machine-readable"), "{error}");
1458 assert_eq!(
1459 std::fs::read_to_string(tmp.path().join("docs/outside.txt")).unwrap(),
1460 "before\nafter\n"
1461 );
1462 }
1463
1464 struct MixedExecutionTool;
1465
1466 #[async_trait::async_trait]
1467 impl ToolSpec for MixedExecutionTool {
1468 fn name(&self) -> &str {
1469 "mixed_execution"
1470 }
1471
1472 fn description(&self) -> &str {
1473 "inspect or start a child"
1474 }
1475
1476 fn input_schema(&self) -> Value {
1477 json!({"type": "object"})
1478 }
1479
1480 fn capabilities(&self) -> Vec<ToolCapability> {
1481 vec![ToolCapability::ExecutesCode]
1482 }
1483
1484 fn is_read_only_for(&self, input: &Value) -> bool {
1485 input.get("action").and_then(Value::as_str) == Some("inspect")
1486 }
1487
1488 async fn execute(
1489 &self,
1490 _input: Value,
1491 _context: &ToolContext,
1492 ) -> Result<ToolResult, ToolError> {
1493 Ok(ToolResult::success("observed"))
1494 }
1495 }
1496
1497 #[tokio::test]
1498 async fn fleet_authority_allows_read_only_actions_but_denies_mixed_family_starts() {
1499 let tmp = tempdir().expect("tempdir");
1500 std::fs::create_dir(tmp.path().join("src")).expect("src");
1501 let registry = ToolRegistryBuilder::new()
1502 .with_tool(Arc::new(MixedExecutionTool))
1503 .build(scoped_context(tmp.path()));
1504
1505 registry
1506 .execute_full("mixed_execution", json!({"action": "inspect"}))
1507 .await
1508 .expect("read-only status/inspect actions remain usable");
1509 let error = registry
1510 .execute_full("mixed_execution", json!({"action": "start"}))
1511 .await
1512 .expect_err("child/code starts remain denied")
1513 .to_string();
1514 assert!(error.contains("child execution"), "{error}");
1515 }
1516
1517 struct UnscopedMutator;
1518
1519 #[async_trait::async_trait]
1520 impl ToolSpec for UnscopedMutator {
1521 fn name(&self) -> &str {
1522 "unscoped_mutator"
1523 }
1524
1525 fn description(&self) -> &str {
1526 "mutates state without a file target"
1527 }
1528
1529 fn input_schema(&self) -> Value {
1530 json!({"type": "object"})
1531 }
1532
1533 fn capabilities(&self) -> Vec<ToolCapability> {
1534 Vec::new()
1535 }
1536
1537 fn is_read_only_for(&self, _input: &Value) -> bool {
1538 false
1539 }
1540
1541 async fn execute(
1542 &self,
1543 _input: Value,
1544 _context: &ToolContext,
1545 ) -> Result<ToolResult, ToolError> {
1546 Ok(ToolResult::success("mutated"))
1547 }
1548 }
1549
1550 #[tokio::test]
1551 async fn fleet_authority_denies_every_unscoped_mutator_not_only_file_capabilities() {
1552 let tmp = tempdir().expect("tempdir");
1553 std::fs::create_dir(tmp.path().join("src")).expect("src");
1554 let registry = ToolRegistryBuilder::new()
1555 .with_tool(Arc::new(UnscopedMutator))
1556 .build(scoped_context(tmp.path()));
1557
1558 let error = registry
1559 .execute_full("unscoped_mutator", json!({}))
1560 .await
1561 .expect_err("unscoped mutation must fail closed")
1562 .to_string();
1563 assert!(error.contains("mutating tool"), "{error}");
1564 }
1565
1566 #[test]
1567 fn test_builder_basic() {
1568 let tmp = tempdir().expect("tempdir");
1569 let ctx = ToolContext::new(tmp.path().to_path_buf());
1570
1571 let registry = ToolRegistryBuilder::new()
1572 .with_tool(make_test_tool("custom"))
1573 .build(ctx);
1574
1575 assert!(registry.contains("custom"));
1576 }
1577
1578 #[test]
1579 fn test_builder_with_web_tools_registers_the_canonical_web_surface() {
1580 let tmp = tempdir().expect("tempdir");
1581 let ctx = ToolContext::new(tmp.path().to_path_buf());
1582
1583 let registry = ToolRegistryBuilder::new().with_web_tools().build(ctx);
1584
1585 // The model-facing web surface is the canonical action-dispatched tool.
1586 assert!(registry.contains("Web"));
1587 assert!(registry.contains("web.run"));
1588 for retired in ["web_search", "fetch_url", "wait_for_dev_server"] {
1589 assert!(!registry.contains(retired), "{retired} must stay removed");
1590 }
1591 }
1592
1593 #[test]
1594 fn canonical_runtime_tools_hide_compatibility_aliases() {
1595 let tmp = tempdir().expect("tempdir");
1596 let ctx = ToolContext::new(tmp.path().to_path_buf());
1597 let registry = ToolRegistryBuilder::new()
1598 .with_file_tools()
1599 .with_search_tools()
1600 .with_git_tools()
1601 .with_git_history_tools()
1602 .with_test_runner_tool()
1603 .with_web_tools()
1604 .with_patch_tools()
1605 .build(ctx);
1606
1607 let api_names = registry
1608 .to_api_tools()
1609 .into_iter()
1610 .map(|tool| tool.name)
1611 .collect::<Vec<_>>();
1612 for canonical in [
1613 "read",
1614 "write",
1615 "edit",
1616 "list_dir",
1617 "file_search",
1618 "grep_files",
1619 "Git",
1620 "Run",
1621 "Web",
1622 ] {
1623 assert!(api_names.iter().any(|name| name == canonical));
1624 }
1625 assert!(
1626 !registry.contains("File"),
1627 "the File action family is retired"
1628 );
1629 for hidden in ["read_file", "write_file", "edit_file"] {
1630 assert!(
1631 registry.contains(hidden),
1632 "{hidden} must stay callable by name"
1633 );
1634 assert!(
1635 api_names.iter().all(|name| name != hidden),
1636 "{hidden} must stay out of new model catalogs"
1637 );
1638 }
1639 for retired in [
1640 "git_status",
1641 "git_diff",
1642 "git_log",
1643 "git_show",
1644 "git_blame",
1645 "run_tests",
1646 "run_verifiers",
1647 "web_search",
1648 "fetch_url",
1649 "wait_for_dev_server",
1650 ] {
1651 assert!(!registry.contains(retired), "{retired} must stay removed");
1652 assert!(
1653 api_names.iter().all(|name| name != retired),
1654 "{retired} must not be advertised"
1655 );
1656 }
1657 // apply_patch remains searchable/deferred outside the Pi-small head.
1658 assert!(registry.contains("apply_patch"));
1659 assert!(api_names.iter().any(|name| name == "apply_patch"));
1660 }
1661
1662 #[tokio::test]
1663 async fn canonical_file_actions_share_read_before_edit_state() {
1664 let tmp = tempdir().expect("tempdir");
1665 std::fs::write(tmp.path().join("sample.txt"), "before\n").expect("fixture");
1666 let ctx = ToolContext::new(tmp.path().to_path_buf());
1667 let registry = ToolRegistryBuilder::new().with_file_tools().build(ctx);
1668
1669 registry
1670 .execute_full("read_file", json!({"path": "sample.txt"}))
1671 .await
1672 .expect("canonical read should execute");
1673 registry
1674 .execute_full(
1675 "edit_file",
1676 json!({
1677 "path": "sample.txt",
1678 "search": "before",
1679 "replace": "after"
1680 }),
1681 )
1682 .await
1683 .expect("canonical edit should execute after the read");
1684
1685 assert_eq!(
1686 std::fs::read_to_string(tmp.path().join("sample.txt")).expect("edited file"),
1687 "after\n"
1688 );
1689 }
1690
1691 #[test]
1692 fn read_only_file_surface_does_not_advertise_write_actions() {
1693 let tmp = tempdir().expect("tempdir");
1694 let ctx = ToolContext::new(tmp.path().to_path_buf());
1695 let registry = ToolRegistryBuilder::new()
1696 .with_read_only_file_tools()
1697 .with_search_tools()
1698 .build(ctx);
1699 let names = registry
1700 .to_api_tools()
1701 .into_iter()
1702 .map(|tool| tool.name)
1703 .collect::<Vec<_>>();
1704 assert!(names.iter().any(|name| name == "read"));
1705 for hidden_or_mutating in ["read_file", "write", "edit"] {
1706 assert!(
1707 names.iter().all(|name| name != hidden_or_mutating),
1708 "{hidden_or_mutating} must not be model-visible"
1709 );
1710 }
1711 assert!(registry.contains("read_file"));
1712 assert!(!registry.contains("write_file"));
1713 assert!(!registry.contains("edit_file"));
1714 }
1715
1716 #[test]
1717 fn agent_runtime_surface_gates_request_plugin_install_on_option() {
1718 use super::AgentToolSurfaceOptions;
1719 use codewhale_agent_contract::worker_profile::ShellPolicy;
1720
1721 // Policy rule 11: hosts without the TUI (exec, runtime API) and sessions
1722 // with contextual tips off get no plugin-offer tool in any mode.
1723 let build_surface = |enabled: bool| {
1724 let tmp = tempdir().expect("tempdir");
1725 let ctx = ToolContext::new(tmp.path().to_path_buf());
1726 let mut options = AgentToolSurfaceOptions::new(ShellPolicy::Full);
1727 options.request_plugin_install_enabled = enabled;
1728 ToolRegistryBuilder::new()
1729 .with_agent_runtime_surface(
1730 None,
1731 "test-model".to_string(),
1732 options,
1733 crate::tools::todo::new_shared_todo_list(),
1734 )
1735 .build(ctx)
1736 };
1737
1738 assert!(build_surface(true).contains("request_plugin_install"));
1739 assert!(!build_surface(false).contains("request_plugin_install"));
1740 }
1741
1742 #[test]
1743 fn agent_tools_with_shell_policy_none_excludes_shell_tools() {
1744 let tmp = tempdir().expect("tempdir");
1745 let ctx = ToolContext::new(tmp.path().to_path_buf());
1746
1747 let registry = ToolRegistryBuilder::new()
1748 .with_agent_tools_policy(
1749 codewhale_agent_contract::worker_profile::ShellPolicy::None,
1750 crate::tools::user_input::UserInputLimits::default(),
1751 )
1752 .build(ctx);
1753
1754 assert!(!registry.contains("bash"));
1755 assert!(!registry.contains("Bash"));
1756 assert!(
1757 !registry.contains("exec_shell"),
1758 "retired exec_shell must remain absent"
1759 );
1760 assert!(
1761 !registry.contains("task_shell_start"),
1762 "task_shell_start should be excluded when the shell policy is None"
1763 );
1764 assert!(
1765 !registry.contains("task_shell_wait"),
1766 "task_shell_wait should be excluded when the shell policy is None"
1767 );
1768 }
1769
1770 #[test]
1771 fn agent_tools_with_shell_policy_readonly_exposes_only_run_only_bash() {
1772 let tmp = tempdir().expect("tempdir");
1773 let ctx = ToolContext::new(tmp.path().to_path_buf());
1774
1775 let registry = ToolRegistryBuilder::new()
1776 .with_agent_tools_policy(
1777 codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly,
1778 crate::tools::user_input::UserInputLimits::default(),
1779 )
1780 .build(ctx);
1781
1782 assert!(registry.contains("bash"));
1783 assert!(!registry.contains("Bash"));
1784 assert!(!registry.contains("exec_shell"));
1785 assert!(!registry.contains("task_shell_start"));
1786 assert!(!registry.contains("task_shell_wait"));
1787 assert!(
1788 registry
1789 .names()
1790 .into_iter()
1791 .all(|name| !name.starts_with("terminal/") && !name.starts_with("terminal_"))
1792 );
1793 let bash = registry
1794 .to_api_tools()
1795 .into_iter()
1796 .find(|tool| tool.name == "bash")
1797 .expect("read-only lowercase bash catalog");
1798 assert_eq!(bash.input_schema["required"], json!(["command"]));
1799 assert_eq!(
1800 bash.input_schema["properties"]
1801 .as_object()
1802 .expect("bash properties")
1803 .keys()
1804 .cloned()
1805 .collect::<std::collections::BTreeSet<_>>(),
1806 [
1807 "command",
1808 "cwd",
1809 "description",
1810 "justification",
1811 "read_only",
1812 "sandbox_permissions",
1813 "timeout"
1814 ]
1815 .into_iter()
1816 .map(str::to_string)
1817 .collect()
1818 );
1819 for hidden in ["action", "background", "tty", "stdin", "task_id", "wait"] {
1820 assert!(bash.input_schema["properties"].get(hidden).is_none());
1821 }
1822 assert!(
1823 registry
1824 .to_api_tools()
1825 .iter()
1826 .all(|tool| tool.name != "Bash")
1827 );
1828 }
1829
1830 #[test]
1831 fn machine_readonly_catalog_is_exactly_the_evidence_profile() {
1832 let tmp = tempdir().expect("tempdir");
1833 let registry = ToolRegistryBuilder::new()
1834 .with_agent_tools_policy(
1835 codewhale_agent_contract::worker_profile::ShellPolicy::ReadOnly,
1836 crate::tools::user_input::UserInputLimits::default(),
1837 )
1838 .with_web_tools()
1839 .with_todo_tool(crate::tools::todo::new_shared_todo_list())
1840 .build(readonly_scout_context(tmp.path(), true));
1841 let tools = registry.to_api_tools();
1842 let names = tools
1843 .iter()
1844 .map(|tool| tool.name.as_str())
1845 .collect::<Vec<_>>();
1846 assert_eq!(names, {
1847 let mut expected = vec![
1848 "Web",
1849 "bash",
1850 "context_archive_search",
1851 "file_search",
1852 "grep_files",
1853 "handle_read",
1854 "list_dir",
1855 "load_skill",
1856 "lsp",
1857 "present",
1858 "read",
1859 "read_media",
1860 "request_user_input",
1861 "retrieve_tool_result",
1862 "show_data",
1863 "todo_write",
1864 "tui_help",
1865 "validate_data",
1866 "web.run",
1867 ];
1868 if crate::tools::image_ocr::ocr_available() {
1869 expected.push("image_ocr");
1870 expected.sort_unstable();
1871 }
1872 expected
1873 });
1874 assert!(!registry.contains("File"));
1875 assert!(!registry.contains("Bash"));
1876 assert!(tools.iter().all(|tool| tool.name != "File"));
1877 assert!(tools.iter().all(|tool| tool.name != "Bash"));
1878 let shell = tools.iter().find(|tool| tool.name == "bash").unwrap();
1879 assert!(shell.description.contains("`cd <dir> &&`"));
1880 assert!(shell.description.contains("git log"));
1881 assert!(shell.description.contains("cannot change its own role"));
1882 let bash = registry.get("bash").unwrap();
1883 enforce_tool_authority(
1884 "bash",
1885 &json!({"command": "cd src && git status"}),
1886 bash.as_ref(),
1887 registry.context(),
1888 )
1889 .expect("a leading cd moves into the working directory (#6015)");
1890 for command in ["git branch -a", "git rev-parse HEAD"] {
1891 let error = enforce_tool_authority(
1892 "bash",
1893 &json!({"command":command}),
1894 bash.as_ref(),
1895 registry.context(),
1896 )
1897 .unwrap_err()
1898 .to_string();
1899 assert!(
1900 error.contains("subcommand:") && error.contains("git log"),
1901 "{error}"
1902 );
1903 }
1904 let web = tools.iter().find(|tool| tool.name == "Web").unwrap();
1905 assert_eq!(
1906 web.input_schema["properties"]["action"]["enum"],
1907 json!(["search", "fetch"])
1908 );
1909 let lsp = registry
1910 .get("lsp")
1911 .expect("lsp is registered on the read-only evidence surface");
1912 enforce_tool_authority("lsp", &json!({}), lsp.as_ref(), registry.context())
1913 .expect("machine read-only dispatch uses the same positive profile as the catalog");
1914 let offline = ToolRegistryBuilder::new()
1915 .with_web_tools()
1916 .build(readonly_scout_context(tmp.path(), false));
1917 assert!(
1918 offline
1919 .to_api_tools()
1920 .iter()
1921 .all(|tool| !matches!(tool.name.as_str(), "Web" | "web.run"))
1922 );
1923 }
1924
1925 #[test]
1926 fn agent_tools_with_shell_policy_full_includes_shell_tools() {
1927 let tmp = tempdir().expect("tempdir");
1928 let ctx = ToolContext::new(tmp.path().to_path_buf());
1929
1930 let registry = ToolRegistryBuilder::new()
1931 .with_agent_tools_policy(
1932 codewhale_agent_contract::worker_profile::ShellPolicy::Full,
1933 crate::tools::user_input::UserInputLimits::default(),
1934 )
1935 .build(ctx);
1936
1937 assert!(registry.contains("bash"));
1938 assert!(!registry.contains("Bash"));
1939 assert!(!registry.contains("exec_shell"));
1940 assert!(
1941 !registry.contains("task_shell_start"),
1942 "task_shell_start is removed; background shell work goes through bash background=true"
1943 );
1944 assert!(
1945 registry.contains("task_shell_wait"),
1946 "task_shell_wait should be included when the shell policy is Full"
1947 );
1948 let api_names = registry
1949 .to_api_tools()
1950 .into_iter()
1951 .map(|tool| tool.name)
1952 .collect::<Vec<_>>();
1953 assert!(api_names.iter().any(|name| name == "bash"));
1954 assert!(api_names.iter().all(|name| name != "Bash"));
1955 }
1956
1957 /// v0.9.3 removes the per-action shell aliases entirely.
1958 #[test]
1959 fn shell_surface_exposes_lowercase_bash_and_hides_legacy_handler() {
1960 let tmp = tempdir().expect("tempdir");
1961 let ctx = ToolContext::new(tmp.path().to_path_buf());
1962 let registry = ToolRegistryBuilder::new().with_shell_tools().build(ctx);
1963
1964 for alias in [
1965 "exec_shell",
1966 "exec_wait",
1967 "exec_interact",
1968 "exec_shell_wait",
1969 "exec_shell_interact",
1970 "exec_shell_cancel",
1971 ] {
1972 assert!(!registry.contains(alias), "{alias} must be removed");
1973 }
1974
1975 let api_names: Vec<String> = registry
1976 .to_api_tools()
1977 .into_iter()
1978 .map(|tool| tool.name)
1979 .collect();
1980
1981 assert!(registry.contains("bash"));
1982 assert!(!registry.contains("Bash"));
1983
1984 // Only lowercase bash is model-visible.
1985 assert!(
1986 api_names.iter().any(|n| n == "bash"),
1987 "bash should be model-visible"
1988 );
1989 assert!(api_names.iter().all(|n| n != "Bash"));
1990
1991 // Removed names also cannot leak back into the model catalog.
1992 for alias in [
1993 "exec_shell",
1994 "exec_wait",
1995 "exec_interact",
1996 "exec_shell_wait",
1997 "exec_shell_interact",
1998 "exec_shell_cancel",
1999 ] {
2000 assert!(
2001 api_names.iter().all(|n| n != alias),
2002 "{alias} should be hidden from the model catalog"
2003 );
2004 }
2005 }
2006
2007 /// Each durable-work family exposes one canonical action tool; v0.9.3
2008 /// removes the per-action execution aliases.
2009 #[test]
2010 fn runtime_task_families_expose_only_canonical_tools() {
2011 let tmp = tempdir().expect("tempdir");
2012 let ctx = ToolContext::new(tmp.path().to_path_buf());
2013 let registry = ToolRegistryBuilder::new()
2014 .with_runtime_task_tools()
2015 .build(ctx);
2016
2017 let legacy_aliases = [
2018 "task_create",
2019 "task_list",
2020 "task_read",
2021 "task_cancel",
2022 "task_gate_run",
2023 "pr_attempt_record",
2024 "pr_attempt_list",
2025 "pr_attempt_read",
2026 "pr_attempt_preflight",
2027 "github_issue_context",
2028 "github_pr_context",
2029 "github_comment",
2030 "github_close_issue",
2031 "github_close_pr",
2032 "automation_create",
2033 "automation_list",
2034 "automation_read",
2035 "automation_update",
2036 "automation_pause",
2037 "automation_resume",
2038 "automation_delete",
2039 "automation_run",
2040 ];
2041 for alias in legacy_aliases {
2042 assert!(!registry.contains(alias), "{alias} must be removed");
2043 }
2044
2045 let api_names: Vec<String> = registry
2046 .to_api_tools()
2047 .into_iter()
2048 .map(|tool| tool.name)
2049 .collect();
2050
2051 // Only the canonical tools are model-visible.
2052 for canonical in ["tasks", "github", "automation"] {
2053 assert!(
2054 api_names.iter().any(|n| n == canonical),
2055 "{canonical} should be model-visible"
2056 );
2057 }
2058 // Removed aliases also cannot leak back into the model catalog.
2059 for alias in legacy_aliases {
2060 assert!(
2061 api_names.iter().all(|n| n != alias),
2062 "{alias} should be hidden from the model catalog"
2063 );
2064 }
2065 }
2066
2067 /// The Plan-mode read-only surface registers only the canonical families,
2068 /// restricted to their read actions.
2069 #[test]
2070 fn read_only_task_surface_contains_no_per_action_aliases() {
2071 let tmp = tempdir().expect("tempdir");
2072 let ctx = ToolContext::new(tmp.path().to_path_buf());
2073 let registry = ToolRegistryBuilder::new()
2074 .with_runtime_read_only_task_tools()
2075 .build(ctx);
2076
2077 for name in [
2078 "task_list",
2079 "task_read",
2080 "pr_attempt_list",
2081 "pr_attempt_read",
2082 "github_issue_context",
2083 "github_pr_context",
2084 "automation_list",
2085 "automation_read",
2086 "task_create",
2087 "task_cancel",
2088 "task_gate_run",
2089 "pr_attempt_record",
2090 "pr_attempt_preflight",
2091 "github_comment",
2092 "github_close_issue",
2093 "github_close_pr",
2094 "automation_create",
2095 "automation_update",
2096 "automation_pause",
2097 "automation_resume",
2098 "automation_delete",
2099 "automation_run",
2100 ] {
2101 assert!(!registry.contains(name), "{name} must be removed");
2102 }
2103
2104 let api_names: Vec<String> = registry
2105 .to_api_tools()
2106 .into_iter()
2107 .map(|tool| tool.name)
2108 .collect();
2109 assert_eq!(api_names.len(), 4);
2110 for canonical in ["tasks", "github", "automation", "send_later"] {
2111 assert!(
2112 api_names.iter().any(|n| n == canonical),
2113 "{canonical} should be model-visible on the read-only surface"
2114 );
2115 }
2116 // Every registered tool stays read-only (Plan-mode invariant).
2117 for tool in registry.all() {
2118 let caps = tool.capabilities();
2119 assert!(
2120 !caps.contains(&ToolCapability::WritesFiles)
2121 && !caps.contains(&ToolCapability::ExecutesCode),
2122 "read-only surface must not register write/exec tools: {}",
2123 tool.name()
2124 );
2125 }
2126 }
2127
2128 /// The action-shaped RLM family is registered only for compatibility.
2129 #[test]
2130 fn rlm_family_removes_legacy_aliases() {
2131 let tmp = tempdir().expect("tempdir");
2132 let ctx = ToolContext::new(tmp.path().to_path_buf());
2133 let registry = ToolRegistryBuilder::new().with_rlm_tool().build(ctx);
2134
2135 for alias in [
2136 "rlm_session_objects",
2137 "rlm_open",
2138 "rlm_eval",
2139 "rlm_configure",
2140 "rlm_close",
2141 ] {
2142 assert!(!registry.contains(alias), "{alias} must stay removed");
2143 }
2144
2145 let api_names: Vec<String> = registry
2146 .to_api_tools()
2147 .into_iter()
2148 .map(|tool| tool.name)
2149 .collect();
2150 assert!(
2151 api_names.iter().any(|n| n == "rlm"),
2152 "canonical rlm tool must be discoverable by new model turns"
2153 );
2154 for retired in [
2155 "rlm_session_objects",
2156 "rlm_open",
2157 "rlm_eval",
2158 "rlm_configure",
2159 "rlm_close",
2160 ] {
2161 assert!(
2162 api_names.iter().all(|n| n != retired),
2163 "{retired} must not be advertised"
2164 );
2165 }
2166 }
2167
2168 #[test]
2169 fn a_builder_upgrade_replaces_the_tool_instead_of_registering_it_twice() {
2170 let builder = ToolRegistryBuilder::new()
2171 .with_file_tools()
2172 .with_file_tools()
2173 .with_patch_tools();
2174 let read_tools = builder
2175 .tools
2176 .iter()
2177 .filter(|tool| tool.name() == "read")
2178 .count();
2179 assert_eq!(read_tools, 1, "one read tool after replacement");
2180 assert!(
2181 builder
2182 .tools
2183 .iter()
2184 .any(|tool| tool.name() == "apply_patch"),
2185 "the upgrade still adds apply_patch"
2186 );
2187 let tmp = tempdir().unwrap();
2188 let warnings = capture_registration_warnings(|| {
2189 let registry = builder.build(ToolContext::new(tmp.path()));
2190 assert!(registry.contains("read"));
2191 assert!(registry.contains("apply_patch"));
2192 });
2193 assert!(warnings.is_empty(), "normal file composition: {warnings}");
2194 }
2195
2196 fn capture_registration_warnings(action: impl FnOnce()) -> String {
2197 use std::io::{Read, Seek, SeekFrom};
2198 let mut output = tempfile::tempfile().unwrap();
2199 let subscriber = tracing_subscriber::fmt()
2200 .without_time()
2201 .with_ansi(false)
2202 .with_max_level(tracing::Level::WARN)
2203 .with_writer(std::sync::Mutex::new(output.try_clone().unwrap()))
2204 .finish();
2205 tracing::subscriber::with_default(subscriber, action);
2206 output.seek(SeekFrom::Start(0)).unwrap();
2207 let mut warnings = String::new();
2208 output.read_to_string(&mut warnings).unwrap();
2209 warnings
2210 }
2211
2212 #[test]
2213 fn runtime_surface_hardening_plugin_collisions_preserve_registered_tools() {
2214 let tmp = tempdir().unwrap();
2215 let mut registry = ToolRegistryBuilder::new()
2216 .with_file_tools()
2217 .build(ToolContext::new(tmp.path()));
2218 let original = registry.get("read").unwrap();
2219 let original_catalog = registry.to_api_tools();
2220 std::fs::write(
2221 tmp.path().join("tool.sh"),
2222 "# name: read\n# description: custom file tool\n",
2223 )
2224 .unwrap();
2225 let errors = capture_registration_warnings(|| registry.load_plugins(tmp.path()));
2226 assert!(
2227 errors.contains("Cannot load plugin tool 'read': name is already registered"),
2228 "{errors}"
2229 );
2230 assert!(errors.contains(&format!(
2231 "previous_origin={:?}",
2232 original.registration_origin()
2233 )));
2234 let plugin_origin = format!(
2235 "plugin script tool.sh ({})",
2236 codewhale_runtime::safe_label::SafeLabel::identifier(
2237 &tmp.path().join("tool.sh").to_string_lossy()
2238 )
2239 );
2240 assert!(errors.contains(&format!("plugin_origin={plugin_origin:?}")));
2241 assert!(!errors.contains(tmp.path().to_string_lossy().as_ref()));
2242 assert!(Arc::ptr_eq(&registry.get("read").unwrap(), &original));
2243 assert_eq!(
2244 serde_json::to_value(registry.to_api_tools()).unwrap(),
2245 serde_json::to_value(original_catalog).unwrap()
2246 );
2247
2248 std::fs::write(
2249 tmp.path().join("other.sh"),
2250 "# name: custom-reader\n# description: custom reader\n",
2251 )
2252 .unwrap();
2253 registry.load_plugins(tmp.path());
2254 assert!(registry.contains("custom-reader"));
2255
2256 // An explicit override still wins over a drop-in script of the same name;
2257 // it never replaces a built-in (see
2258 // `script_and_command_overrides_cannot_replace_builtins`).
2259 let builtins = std::collections::HashSet::from(["read".to_string()]);
2260 let overrides = std::collections::HashMap::from([(
2261 "custom-reader".to_string(),
2262 codewhale_runtime::config::ToolOverride::Command {
2263 command: "my-reader".to_string(),
2264 args: None,
2265 },
2266 )]);
2267 registry.apply_overrides(&overrides, tmp.path(), &builtins);
2268 assert!(
2269 registry
2270 .get("custom-reader")
2271 .unwrap()
2272 .description()
2273 .contains("my-reader")
2274 );
2275 assert!(Arc::ptr_eq(&registry.get("read").unwrap(), &original));
2276 }
2277
2278 #[test]
2279 fn registration_adapter_origins_are_bounded_and_exclude_execution_payloads() {
2280 use crate::tools::dynamic::RuntimeDynamicTool;
2281 use crate::tools::plugin::tool_from_override;
2282 use codewhale_app_server_protocol::runtime::DynamicToolSpec;
2283 let tmp = tempdir().unwrap();
2284 let hostile = format!(
2285 "\u{1b}[31m\nhttps://private.invalid/token?{}",
2286 "x".repeat(500)
2287 );
2288 let command = "do-not-log-command";
2289 let argument = "do-not-log-argument";
2290 let schema_payload = "do-not-log-schema";
2291 let cases: Vec<(Arc<dyn ToolSpec>, &str)> = vec![
2292 (
2293 Arc::new(RuntimeDynamicTool::new(DynamicToolSpec {
2294 name: hostile.clone(),
2295 namespace: Some(hostile.clone()),
2296 description: command.into(),
2297 input_schema: json!({"description":schema_payload}),
2298 defer_loading: false,
2299 })),
2300 "runtime dynamic namespace sha256:",
2301 ),
2302 (
2303 Arc::new(super::McpToolAdapter {
2304 delegated_read: None,
2305 name: hostile.clone(),
2306 server_name: Some("plugin-4-demo-server_with_underscores".into()),
2307 tool: crate::mcp::McpTool {
2308 name: hostile.clone(),
2309 description: Some(command.into()),
2310 input_schema: json!({"description":schema_payload}),
2311 annotations: None,
2312 },
2313 pool: Arc::new(tokio::sync::Mutex::new(crate::mcp::McpPool::new(
2314 codewhale_mcp::config::McpConfig::default(),
2315 ))),
2316 }),
2317 "MCP server plugin-4-demo-server_with_underscores, tool sha256:",
2318 ),
2319 (
2320 tool_from_override(
2321 &hostile,
2322 &ToolOverride::Command {
2323 command: command.into(),
2324 args: Some(vec![argument.into()]),
2325 },
2326 tmp.path(),
2327 )
2328 .unwrap(),
2329 "config [tools.overrides.sha256:",
2330 ),
2331 ];
2332 for (replacement, expected_origin) in cases {
2333 let mut registry = ToolRegistry::new(ToolContext::new(tmp.path()));
2334 registry.register(make_test_tool(&hostile));
2335 let warnings = capture_registration_warnings(|| registry.register(replacement.clone()));
2336 assert_eq!(warnings.lines().count(), 1, "{warnings}");
2337 assert!(
2338 warnings.contains("Overwriting existing tool: sha256:"),
2339 "{warnings}"
2340 );
2341 assert!(warnings.contains(expected_origin), "{warnings}");
2342 assert!(warnings.len() < 600, "{warnings}");
2343 for excluded in [
2344 &hostile,
2345 command,
2346 argument,
2347 schema_payload,
2348 "https://private.invalid",
2349 "\u{1b}",
2350 ] {
2351 assert!(
2352 !warnings.contains(excluded),
2353 "unexpected payload: {warnings}"
2354 );
2355 }
2356 assert!(Arc::ptr_eq(&registry.get(&hostile).unwrap(), &replacement));
2357 }
2358 }
2359
2360 /// Regression probe for the fleet-52663788 class of provider 400
2361 /// (`Invalid schema for function 'bash': null is not of type "array"`):
2362 /// a read-only Fleet worker (reviewer) projects its tool schemas before the
2363 /// wire; no projected schema may carry a JSON null, because strict
2364 /// OpenAI-compatible validators reject null where arrays/objects are typed.
2365 #[test]
2366 fn fleet_readonly_reviewer_wire_catalog_carries_no_null_schema_fields() {
2367 use crate::tools::spec::{
2368 ToolMutationAuthority, ToolShellAuthority, ToolVerificationAuthority,
2369 };
2370
2371 fn collect_null_paths(value: &Value, path: String, out: &mut Vec<String>) {
2372 match value {
2373 Value::Null => out.push(path),
2374 Value::Object(map) => {
2375 for (key, child) in map {
2376 collect_null_paths(child, format!("{path}.{key}"), out);
2377 }
2378 }
2379 Value::Array(items) => {
2380 for (index, child) in items.iter().enumerate() {
2381 collect_null_paths(child, format!("{path}[{index}]"), out);
2382 }
2383 }
2384 _ => {}
2385 }
2386 }
2387
2388 let tmp = tempdir().expect("tempdir");
2389 let reviewer_authority = ToolAuthorityEnvelope {
2390 schema_version: 1,
2391 owner: "reviewer".to_string(),
2392 authority: ToolMutationAuthority::ReadOnly,
2393 network_access: Some(false),
2394 shell: ToolShellAuthority::ReadOnly,
2395 verification: ToolVerificationAuthority::None,
2396 writable_roots: Vec::new(),
2397 writable_files: Vec::new(),
2398 coordination_contracts: Vec::new(),
2399 };
2400 let context = ToolContext::new(tmp.path().to_path_buf())
2401 .with_tool_authority(reviewer_authority)
2402 .expect("reviewer authority");
2403
2404 let registry = ToolRegistryBuilder::new()
2405 .with_file_tools()
2406 .with_foreground_shell_tools()
2407 .with_search_tools()
2408 .build(context);
2409 let tools = registry.to_api_tools();
2410 assert!(
2411 tools.iter().any(|tool| tool.name == "bash"),
2412 "reviewer keeps classifier-bounded bash"
2413 );
2414
2415 for tool in &tools {
2416 let mut nulls = Vec::new();
2417 collect_null_paths(&tool.input_schema, "$".to_string(), &mut nulls);
2418 assert!(
2419 nulls.is_empty(),
2420 "tool {} schema carries null at {nulls:?}: {}",
2421 tool.name,
2422 tool.input_schema
2423 );
2424 }
2425 }
2426
2427 #[test]
2428 fn read_media_is_not_offered_to_a_text_only_route() {
2429 use codewhale_config::route::CapabilityState;
2430 let tmp = tempdir().unwrap();
2431 for (state, offered) in [
2432 (CapabilityState::Unsupported, false),
2433 (CapabilityState::Unknown, true),
2434 (CapabilityState::Supported, true),
2435 ] {
2436 let mut context = ToolContext::new(tmp.path());
2437 context.route_capabilities.image_input = state;
2438 let registry = ToolRegistryBuilder::new()
2439 .with_read_media_tool()
2440 .build(context);
2441 assert_eq!(registry.get("read_media").is_some(), offered, "{state:?}");
2442 }
2443 }
2444
2445 /// #6559 D04-10: a client-supplied dynamic tool cannot take over a builtin
2446 /// handler (and its approval policy), and a second dynamic tool with the same
2447 /// model-facing name from another namespace cannot replace the first.
2448 #[test]
2449 fn dynamic_tools_never_replace_registered_tools() {
2450 use codewhale_app_server_protocol::runtime::DynamicToolSpec;
2451 let tmp = tempdir().unwrap();
2452 let spec = |namespace: &str, name: &str, description: &str| DynamicToolSpec {
2453 namespace: Some(namespace.to_string()),
2454 name: name.to_string(),
2455 description: description.to_string(),
2456 input_schema: json!({"type": "object"}),
2457 defer_loading: false,
2458 };
2459 let registry = ToolRegistryBuilder::new()
2460 .with_file_tools()
2461 .with_dynamic_tools(&[
2462 spec("client", "read", "client read"),
2463 spec("first", "lookup", "first lookup"),
2464 spec("second", "lookup", "second lookup"),
2465 ])
2466 .build(ToolContext::new(tmp.path()));
2467
2468 let read = registry.get("read").expect("builtin read");
2469 assert_ne!(read.description(), "client read");
2470 assert!(
2471 !read.registration_origin().contains("runtime dynamic"),
2472 "{}",
2473 read.registration_origin()
2474 );
2475 assert_eq!(
2476 registry
2477 .get("lookup")
2478 .expect("first dynamic tool")
2479 .description(),
2480 "first lookup"
2481 );
2482 }
2483
2484 #[cfg(unix)]
2485 #[tokio::test(flavor = "current_thread")]
2486 async fn scoped_worker_convert_output_is_judged_on_the_field_it_writes() {
2487 use std::os::unix::fs::PermissionsExt;
2488 let _env = crate::test_support::lock_test_env();
2489 let bin = tempdir().expect("bin");
2490 let stub = bin.path().join("pandoc");
2491 std::fs::write(
2492 &stub,
2493 "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo 'pandoc 3.1.9'; exit 0; fi\nsrc=\"$2\"\nout=\"\"\nwhile [ $# -gt 0 ]; do if [ \"$1\" = \"--output\" ]; then out=\"$2\"; fi; shift; done\nif [ -n \"$out\" ]; then cat \"$src\" > \"$out\"; else cat \"$src\"; fi\n",
2494 )
2495 .expect("stub");
2496 std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).expect("chmod");
2497 let search = std::env::join_paths(std::iter::once(bin.path().to_path_buf()).chain(
2498 std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()),
2499 ))
2500 .expect("path");
2501 let _path = crate::test_support::EnvVarGuard::set("PATH", search);
2502
2503 let tmp = tempdir().expect("tempdir");
2504 std::fs::create_dir(tmp.path().join("src")).expect("src");
2505 std::fs::create_dir(tmp.path().join("ops")).expect("ops");
2506 std::fs::write(tmp.path().join("src/in.md"), "PAYLOAD\n").expect("source");
2507 std::fs::write(tmp.path().join("ops/outside.txt"), "original\n").expect("fixture");
2508 let registry = ToolRegistryBuilder::new()
2509 .with_tool(Arc::new(crate::tools::pandoc::PandocConvertTool))
2510 .build(scoped_context(tmp.path()));
2511
2512 registry
2513 .execute_full(
2514 "pandoc_convert",
2515 json!({"source_path": "src/in.md", "target_format": "plain", "output_path": "src/out.txt"}),
2516 )
2517 .await
2518 .expect("an output inside the write scope");
2519 assert_eq!(
2520 std::fs::read_to_string(tmp.path().join("src/out.txt")).unwrap(),
2521 "PAYLOAD\n"
2522 );
2523
2524 for input in [
2525 json!({"source_path": "src/in.md", "target_format": "plain", "output_path": "ops/outside.txt"}),
2526 json!({
2527 "source_path": "src/in.md",
2528 "target_format": "plain",
2529 "output_path": "ops/outside.txt",
2530 "path": "src/unused.txt"
2531 }),
2532 ] {
2533 registry
2534 .execute_full("pandoc_convert", input)
2535 .await
2536 .expect_err("an output outside the write scope must be refused");
2537 assert_eq!(
2538 std::fs::read_to_string(tmp.path().join("ops/outside.txt")).unwrap(),
2539 "original\n"
2540 );
2541 }
2542 }
2543
2544 #[tokio::test]
2545 async fn subagent_mcp_tools_survive_a_busy_parent_pool() {
2546 let mut pool = crate::mcp::McpPool::new(codewhale_mcp::config::McpConfig::default());
2547 pool.insert_test_connection("linear", &["list_issues"], None);
2548 let pool = Arc::new(tokio::sync::Mutex::new(pool));
2549 let held = pool.lock().await;
2550 let build = tokio::spawn(ToolRegistryBuilder::new().with_mcp_tools(Arc::clone(&pool)));
2551 tokio::task::yield_now().await;
2552 assert!(!build.is_finished());
2553 drop(held);
2554 let tmp = tempdir().unwrap();
2555 let registry = build
2556 .await
2557 .expect("builder task")
2558 .build(ToolContext::new(tmp.path()));
2559 assert!(registry.contains("mcp_linear_list_issues"));
2560 }
2561
2562 #[test]
2563 fn evidence_profile_excludes_exactly_the_tools_that_start_workspace_programs() {
2564 let git = crate::tools::git_tool::GitTool::new("Git");
2565 let review = crate::tools::review::ReviewTool::new(None, "model".to_string());
2566 let lsp = crate::tools::lsp::LspTool;
2567 for tool in [&git as &dyn ToolSpec, &review] {
2568 assert!(
2569 tool.capabilities()
2570 .contains(&ToolCapability::StartsWorkspaceProgram),
2571 "{}",
2572 tool.name()
2573 );
2574 assert!(!readonly_evidence_tool(tool), "{}", tool.name());
2575 }
2576 assert!(readonly_evidence_tool(&lsp));
2577
2578 struct Starter;
2579 #[async_trait::async_trait]
2580 impl ToolSpec for Starter {
2581 fn name(&self) -> &'static str {
2582 "starter"
2583 }
2584 fn description(&self) -> &'static str {
2585 "test"
2586 }
2587 fn input_schema(&self) -> Value {
2588 json!({"type": "object"})
2589 }
2590 fn capabilities(&self) -> Vec<ToolCapability> {
2591 vec![
2592 ToolCapability::ReadOnly,
2593 ToolCapability::StartsWorkspaceProgram,
2594 ]
2595 }
2596 async fn execute(
2597 &self,
2598 _input: Value,
2599 _context: &ToolContext,
2600 ) -> Result<ToolResult, ToolError> {
2601 unreachable!()
2602 }
2603 }
2604 assert!(!readonly_evidence_tool(&Starter));
2605 }
2606
2606 lines RUST