| 1 | //! Side-effect-free preparation of concrete tool inputs. |
| 2 | //! |
| 3 | //! The turn loop remains the authority orchestrator. This module only makes |
| 4 | //! the input-specific policy decision inspectable and reusable, including a |
| 5 | //! mandatory second preparation after a hook rewrites input. |
| 6 | |
| 7 | use std::collections::BTreeSet; |
| 8 | use std::path::PathBuf; |
| 9 | |
| 10 | use serde_json::Value; |
| 11 | |
| 12 | use codewhale_execpolicy::ApprovalMode; |
| 13 | |
| 14 | use crate::mcp::McpPool; |
| 15 | use crate::tools::ToolRegistry; |
| 16 | use crate::tools::approval_cache::{computer_use_batch_hidden_gate, computer_use_user_gate}; |
| 17 | use crate::tools::spec::{ApprovalRequirement, PreparedToolCall, ResourceClaim, ToolError}; |
| 18 | |
| 19 | use super::dispatch::{ |
| 20 | mcp_tool_approval_description, mcp_tool_is_parallel_safe, mcp_tool_is_read_only, |
| 21 | }; |
| 22 | use super::tool_catalog::{CODE_EXECUTION_TOOL_NAME, EXECUTE_TOOLS_TOOL_NAME}; |
| 23 | use codewhale_tools::names::is_tool_search_tool; |
| 24 | |
| 25 | #[derive(Debug, Clone, PartialEq)] |
| 26 | pub(super) struct PreparedToolPolicy { |
| 27 | pub(super) call: PreparedToolCall, |
| 28 | pub(super) auto_approve: bool, |
| 29 | } |
| 30 | |
| 31 | impl PreparedToolPolicy { |
| 32 | pub(super) fn apply_mcp_always_allow(&mut self, pool: &McpPool) -> Option<u64> { |
| 33 | if self.call.approval != ApprovalRequirement::Suggest |
| 34 | || !McpPool::is_mcp_tool(&self.call.name) |
| 35 | { |
| 36 | return None; |
| 37 | } |
| 38 | let binding = pool.always_allow_binding(&self.call.name)?; |
| 39 | self.call.approval = ApprovalRequirement::Auto; |
| 40 | Some(binding) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | /// Prepare a concrete call without mutating external state. |
| 45 | pub(super) fn prepare_tool_call( |
| 46 | name: &str, |
| 47 | input: Value, |
| 48 | registry: Option<&ToolRegistry>, |
| 49 | session_auto_approve: bool, |
| 50 | ) -> Result<PreparedToolPolicy, ToolError> { |
| 51 | if McpPool::is_mcp_tool(name) { |
| 52 | // CW-11: a reviewed plugin's `readOnlyHint` makes its tool run like |
| 53 | // the built-in resource reads. A declared `destructiveHint` only |
| 54 | // withholds that relaxation and labels the card: Full Access still |
| 55 | // covers it (#3866), because a host that answers approvals from its |
| 56 | // own flag (`exec` with a Full Access `approval_policy`) would |
| 57 | // otherwise deny a call its posture already allows. |
| 58 | let read_only = mcp_tool_is_read_only(name) |
| 59 | || crate::mcp::mcp_tool_approval_hint(name) |
| 60 | == Some(crate::mcp::McpToolApprovalHint::TrustedReadOnly); |
| 61 | let delegated = registry |
| 62 | .filter(|tools| tools.context().child_host.is_some()) |
| 63 | .and_then(|tools| tools.delegated_mcp_read(name)); |
| 64 | let scoped_read = delegated.is_some(); |
| 65 | if let Some(grant) = delegated |
| 66 | && !grant.permits_arguments(&input) |
| 67 | { |
| 68 | return Err(ToolError::permission_denied( |
| 69 | "Delegated connector disclosure denied.", |
| 70 | )); |
| 71 | } |
| 72 | if !mcp_tool_is_read_only(name) |
| 73 | && !scoped_read |
| 74 | && let Some(authority) = |
| 75 | registry.and_then(|registry| registry.context().tool_authority.as_ref()) |
| 76 | { |
| 77 | return Err(ToolError::permission_denied(format!( |
| 78 | "worker '{}' cannot run mutating MCP tool {name}: it has no bounded file target under the machine-readable authority envelope", |
| 79 | authority.owner |
| 80 | ))); |
| 81 | } |
| 82 | // K1/K2 stopgap: Computer Use consent and `app_script` need a human |
| 83 | // decision. Never auto-approve them, and refuse them outright in a |
| 84 | // posture that has no person at the card (Auto-Review, Never). Full |
| 85 | // Access is not such a posture: it has a UI, so it asks. Denying there |
| 86 | // made the most permissive posture the one posture where Computer Use |
| 87 | // could never be authorized at all. |
| 88 | if let Some(inner) = computer_use_batch_hidden_gate(name, &input) { |
| 89 | return Err(ToolError::permission_denied(format!( |
| 90 | "Computer Use {inner} cannot run inside {name}: consent and scripts need their own approval card. Call it on its own so the user can decide." |
| 91 | ))); |
| 92 | } |
| 93 | if computer_use_user_gate(name, &input).is_some() { |
| 94 | let posture = registry.map(|registry| { |
| 95 | let context = registry.context(); |
| 96 | ( |
| 97 | context.auto_approve, |
| 98 | context.approval_mode, |
| 99 | context.owner_present, |
| 100 | ) |
| 101 | }); |
| 102 | let can_ask = posture.is_none_or(|(auto_approve, approval_mode, owner_present)| { |
| 103 | approval_mode.is_ask_family() |
| 104 | || auto_approve |
| 105 | || approval_mode == ApprovalMode::Bypass |
| 106 | || (approval_mode == ApprovalMode::Auto && owner_present) |
| 107 | }); |
| 108 | if !can_ask { |
| 109 | let label = posture.map_or("Full Access", |(auto_approve, approval_mode, _)| { |
| 110 | if auto_approve { |
| 111 | ApprovalMode::Bypass.permission_chip_label() |
| 112 | } else { |
| 113 | approval_mode.permission_chip_label() |
| 114 | } |
| 115 | }); |
| 116 | return Err(ToolError::permission_denied(format!( |
| 117 | "Computer Use call {name} needs your own approval, and the current {label} posture has no one to ask: consent and scripts cannot be granted by a model tool call. Switch to Ask or Full Access to review it." |
| 118 | ))); |
| 119 | } |
| 120 | return Ok(PreparedToolPolicy { |
| 121 | call: PreparedToolCall { |
| 122 | name: name.to_string(), |
| 123 | description: mcp_tool_approval_description(name, &input), |
| 124 | input, |
| 125 | read_only: false, |
| 126 | supports_parallel: false, |
| 127 | starts_detached: false, |
| 128 | approval: ApprovalRequirement::Required, |
| 129 | resources: vec![ResourceClaim::GlobalExclusive], |
| 130 | }, |
| 131 | auto_approve: false, |
| 132 | }); |
| 133 | } |
| 134 | return Ok(PreparedToolPolicy { |
| 135 | call: PreparedToolCall { |
| 136 | name: name.to_string(), |
| 137 | description: mcp_tool_approval_description(name, &input), |
| 138 | input, |
| 139 | read_only: read_only || scoped_read, |
| 140 | supports_parallel: mcp_tool_is_parallel_safe(name) || read_only, |
| 141 | starts_detached: false, |
| 142 | approval: if scoped_read { |
| 143 | ApprovalRequirement::Required |
| 144 | } else if read_only { |
| 145 | ApprovalRequirement::Auto |
| 146 | } else { |
| 147 | ApprovalRequirement::Suggest |
| 148 | }, |
| 149 | resources: if read_only { |
| 150 | vec![ResourceClaim::ReadOnly] |
| 151 | } else { |
| 152 | vec![ResourceClaim::GlobalExclusive] |
| 153 | }, |
| 154 | }, |
| 155 | auto_approve: session_auto_approve && !scoped_read, |
| 156 | }); |
| 157 | } |
| 158 | |
| 159 | if let Some(registry) = registry |
| 160 | && let Some(spec) = registry.get(name) |
| 161 | { |
| 162 | let mut call = spec.prepare(input, registry.context())?; |
| 163 | call.resources = registered_resource_claims( |
| 164 | name, |
| 165 | &call.input, |
| 166 | registry.context(), |
| 167 | call.read_only, |
| 168 | call.starts_detached, |
| 169 | )?; |
| 170 | return Ok(PreparedToolPolicy { |
| 171 | call, |
| 172 | auto_approve: registry.context().auto_approve, |
| 173 | }); |
| 174 | } |
| 175 | |
| 176 | if name == CODE_EXECUTION_TOOL_NAME { |
| 177 | reject_unbounded_execution_under_authority(name, registry)?; |
| 178 | return Ok(conservative_execution_policy( |
| 179 | name, |
| 180 | input, |
| 181 | "Run model-provided Python code with the current execution policy", |
| 182 | session_auto_approve, |
| 183 | )); |
| 184 | } |
| 185 | |
| 186 | if name == EXECUTE_TOOLS_TOOL_NAME { |
| 187 | reject_unbounded_execution_under_authority(name, registry)?; |
| 188 | let first_line = input |
| 189 | .get("code") |
| 190 | .and_then(Value::as_str) |
| 191 | .and_then(|code| code.lines().map(str::trim).find(|line| !line.is_empty())) |
| 192 | .unwrap_or("execute_tools program"); |
| 193 | let mut policy = conservative_execution_policy( |
| 194 | name, |
| 195 | input.clone(), |
| 196 | &format!("execute_tools: {first_line}"), |
| 197 | session_auto_approve, |
| 198 | ); |
| 199 | // #6562: every nested call is planned and approved through the same |
| 200 | // gate as a direct call (or, without an engine gate, limited to |
| 201 | // read-only auto-approved calls), so approving the program itself |
| 202 | // would grant nothing. It stays exclusive and non-read-only. |
| 203 | policy.call.approval = ApprovalRequirement::Auto; |
| 204 | return Ok(policy); |
| 205 | } |
| 206 | |
| 207 | if is_tool_search_tool(name) { |
| 208 | return Ok(PreparedToolPolicy { |
| 209 | call: PreparedToolCall { |
| 210 | name: name.to_string(), |
| 211 | input, |
| 212 | description: "Search tool catalog".to_string(), |
| 213 | read_only: true, |
| 214 | supports_parallel: true, |
| 215 | starts_detached: false, |
| 216 | approval: ApprovalRequirement::Auto, |
| 217 | resources: vec![ResourceClaim::ToolCatalogWrite], |
| 218 | }, |
| 219 | auto_approve: session_auto_approve, |
| 220 | }); |
| 221 | } |
| 222 | |
| 223 | Err(ToolError::not_available(format!( |
| 224 | "tool '{name}' has no preparation path" |
| 225 | ))) |
| 226 | } |
| 227 | |
| 228 | fn reject_unbounded_execution_under_authority( |
| 229 | name: &str, |
| 230 | registry: Option<&ToolRegistry>, |
| 231 | ) -> Result<(), ToolError> { |
| 232 | let Some(authority) = registry.and_then(|registry| registry.context().tool_authority.as_ref()) |
| 233 | else { |
| 234 | return Ok(()); |
| 235 | }; |
| 236 | Err(ToolError::permission_denied(format!( |
| 237 | "worker '{}' cannot run {name}: arbitrary code execution cannot prove a bounded file target under the machine-readable authority envelope", |
| 238 | authority.owner |
| 239 | ))) |
| 240 | } |
| 241 | |
| 242 | /// Re-run preparation from the rewritten input rather than patching any |
| 243 | /// previously derived field. |
| 244 | pub(super) fn reprepare_tool_call_after_hook( |
| 245 | name: &str, |
| 246 | updated_input: Value, |
| 247 | registry: Option<&ToolRegistry>, |
| 248 | session_auto_approve: bool, |
| 249 | ) -> Result<PreparedToolPolicy, ToolError> { |
| 250 | prepare_tool_call(name, updated_input, registry, session_auto_approve) |
| 251 | } |
| 252 | |
| 253 | fn conservative_execution_policy( |
| 254 | name: &str, |
| 255 | input: Value, |
| 256 | description: &str, |
| 257 | auto_approve: bool, |
| 258 | ) -> PreparedToolPolicy { |
| 259 | PreparedToolPolicy { |
| 260 | call: PreparedToolCall { |
| 261 | name: name.to_string(), |
| 262 | input, |
| 263 | description: description.to_string(), |
| 264 | read_only: false, |
| 265 | supports_parallel: false, |
| 266 | starts_detached: false, |
| 267 | approval: ApprovalRequirement::Suggest, |
| 268 | resources: vec![ResourceClaim::GlobalExclusive], |
| 269 | }, |
| 270 | auto_approve, |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | fn registered_resource_claims( |
| 275 | name: &str, |
| 276 | input: &Value, |
| 277 | context: &crate::tools::ToolContext, |
| 278 | read_only: bool, |
| 279 | starts_detached: bool, |
| 280 | ) -> Result<Vec<ResourceClaim>, ToolError> { |
| 281 | let canonical = codewhale_execpolicy::canonical_action::canonical_action_alias(name, input); |
| 282 | match canonical { |
| 283 | "read" | "read_file" | "read_media" | "image_ocr" => { |
| 284 | path_claim(input, "path", None, context, ResourceClaim::ReadPath) |
| 285 | } |
| 286 | "validate_data" => { |
| 287 | if input |
| 288 | .get("path") |
| 289 | .and_then(Value::as_str) |
| 290 | .map(str::trim) |
| 291 | .is_some_and(|path| !path.is_empty()) |
| 292 | { |
| 293 | path_claim(input, "path", None, context, ResourceClaim::ReadPath) |
| 294 | } else if read_only && !starts_detached { |
| 295 | Ok(vec![ResourceClaim::ReadOnly]) |
| 296 | } else { |
| 297 | Ok(global_exclusive_claim()) |
| 298 | } |
| 299 | } |
| 300 | "write" | "write_file" | "edit" | "edit_file" => { |
| 301 | path_claim(input, "path", None, context, ResourceClaim::WritePath) |
| 302 | } |
| 303 | "list_dir" | "grep_files" | "file_search" => { |
| 304 | path_claim(input, "path", Some("."), context, ResourceClaim::ReadTree) |
| 305 | } |
| 306 | "apply_patch" => apply_patch_resource_claims(input, context), |
| 307 | "terminal_run" => Ok(terminal_claim(input, "session", Some("term-1"))), |
| 308 | "terminal_send" | "terminal_wait" | "terminal_cancel" | "terminal_reset" => { |
| 309 | Ok(terminal_claim(input, "session", None)) |
| 310 | } |
| 311 | "exec_shell_wait" | "exec_wait" => Ok(terminal_task_claims(input)), |
| 312 | "task_shell_wait" => { |
| 313 | if read_only |
| 314 | && !starts_detached |
| 315 | && input.get("gate").is_none_or(Value::is_null) |
| 316 | && !crate::tools::tasks::task_shell_wait_requests_cancel(input) |
| 317 | { |
| 318 | Ok(terminal_task_claims(input)) |
| 319 | } else { |
| 320 | Ok(global_exclusive_claim()) |
| 321 | } |
| 322 | } |
| 323 | "exec_shell_interact" | "exec_interact" | "exec_shell_cancel" => { |
| 324 | Ok(terminal_claim(input, "task_id", None)) |
| 325 | } |
| 326 | "exec_shell" | "bash" | "git_status" | "git_diff" | "git_log" | "git_show" |
| 327 | | "git_blame" | "git_commit_plan" | "git_merge_tree" | "git_review_scope" | "lsp" => { |
| 328 | if read_only && !starts_detached { |
| 329 | Ok(vec![ResourceClaim::WorkspaceRead]) |
| 330 | } else { |
| 331 | Ok(global_exclusive_claim()) |
| 332 | } |
| 333 | } |
| 334 | "load_skill" |
| 335 | | "retrieve_tool_result" |
| 336 | | "session_search" |
| 337 | | "web_search" |
| 338 | | "fetch_url" |
| 339 | | "wait_for_dev_server" |
| 340 | | "agent" |
| 341 | | "agents/list" |
| 342 | | "agents_list" |
| 343 | | "task_list" |
| 344 | | "task_read" |
| 345 | | "pr_attempt_list" |
| 346 | | "pr_attempt_read" |
| 347 | | "tasks" |
| 348 | | "tui_help" |
| 349 | | "handle_read" |
| 350 | | "registry_sync" |
| 351 | | "get_goal" |
| 352 | | "memory_search" |
| 353 | | "context_archive_search" |
| 354 | | "automation_list" |
| 355 | | "automation_read" |
| 356 | | "github_issue_context" |
| 357 | | "github_pr_context" |
| 358 | | "github_report_read" |
| 359 | | "rlm_session_objects" |
| 360 | | "workflow" => { |
| 361 | if read_only && !starts_detached { |
| 362 | Ok(vec![ResourceClaim::ReadOnly]) |
| 363 | } else { |
| 364 | Ok(global_exclusive_claim()) |
| 365 | } |
| 366 | } |
| 367 | _ => Ok(global_exclusive_claim()), |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | fn path_claim( |
| 372 | input: &Value, |
| 373 | key: &str, |
| 374 | default: Option<&str>, |
| 375 | context: &crate::tools::ToolContext, |
| 376 | build: fn(PathBuf) -> ResourceClaim, |
| 377 | ) -> Result<Vec<ResourceClaim>, ToolError> { |
| 378 | let raw = input |
| 379 | .get(key) |
| 380 | .and_then(Value::as_str) |
| 381 | .map(str::trim) |
| 382 | .filter(|path| !path.is_empty()) |
| 383 | .or(default); |
| 384 | let Some(raw) = raw else { |
| 385 | return Ok(global_exclusive_claim()); |
| 386 | }; |
| 387 | Ok(context |
| 388 | .resolve_path(raw) |
| 389 | .map_or_else(|_| global_exclusive_claim(), |path| vec![build(path)])) |
| 390 | } |
| 391 | |
| 392 | fn apply_patch_resource_claims( |
| 393 | input: &Value, |
| 394 | context: &crate::tools::ToolContext, |
| 395 | ) -> Result<Vec<ResourceClaim>, ToolError> { |
| 396 | let Ok(preflight) = codewhale_tools::patch_preflight::preflight_apply_patch(input) else { |
| 397 | return Ok(global_exclusive_claim()); |
| 398 | }; |
| 399 | if preflight.touched_files.is_empty() { |
| 400 | return Ok(global_exclusive_claim()); |
| 401 | } |
| 402 | |
| 403 | let mut claims = BTreeSet::new(); |
| 404 | for path in preflight.touched_files { |
| 405 | let Ok(path) = context.resolve_path(&path) else { |
| 406 | return Ok(global_exclusive_claim()); |
| 407 | }; |
| 408 | claims.insert(ResourceClaim::WritePath(path)); |
| 409 | } |
| 410 | Ok(claims.into_iter().collect()) |
| 411 | } |
| 412 | |
| 413 | fn terminal_claim(input: &Value, key: &str, default: Option<&str>) -> Vec<ResourceClaim> { |
| 414 | input |
| 415 | .get(key) |
| 416 | .and_then(Value::as_str) |
| 417 | .map(str::trim) |
| 418 | .filter(|id| !id.is_empty()) |
| 419 | .or(default) |
| 420 | .map_or_else(global_exclusive_claim, |id| { |
| 421 | vec![ResourceClaim::Terminal(id.to_string())] |
| 422 | }) |
| 423 | } |
| 424 | |
| 425 | fn terminal_task_claims(input: &Value) -> Vec<ResourceClaim> { |
| 426 | let has_single = input.get("task_id").is_some_and(|v| !v.is_null()); |
| 427 | let has_many = input.get("task_ids").is_some_and(|v| !v.is_null()); |
| 428 | if has_single && has_many { |
| 429 | return global_exclusive_claim(); |
| 430 | } |
| 431 | if has_single { |
| 432 | return terminal_claim(input, "task_id", None); |
| 433 | } |
| 434 | if has_many { |
| 435 | let Some(items) = input.get("task_ids").and_then(Value::as_array) else { |
| 436 | return global_exclusive_claim(); |
| 437 | }; |
| 438 | if items.is_empty() { |
| 439 | return global_exclusive_claim(); |
| 440 | } |
| 441 | let mut claims = BTreeSet::new(); |
| 442 | for item in items { |
| 443 | let Some(id) = item.as_str().map(str::trim).filter(|id| !id.is_empty()) else { |
| 444 | return global_exclusive_claim(); |
| 445 | }; |
| 446 | claims.insert(ResourceClaim::Terminal(id.to_string())); |
| 447 | } |
| 448 | return claims.into_iter().collect(); |
| 449 | } |
| 450 | global_exclusive_claim() |
| 451 | } |
| 452 | |
| 453 | fn global_exclusive_claim() -> Vec<ResourceClaim> { |
| 454 | vec![ResourceClaim::GlobalExclusive] |
| 455 | } |
| 456 | |
| 457 | #[cfg(test)] |
| 458 | mod tests { |
| 459 | use std::sync::Arc; |
| 460 | |
| 461 | use async_trait::async_trait; |
| 462 | use serde_json::json; |
| 463 | use tempfile::tempdir; |
| 464 | |
| 465 | use crate::tools::spec::{ToolCapability, ToolContext, ToolResult, ToolSpec}; |
| 466 | |
| 467 | use super::*; |
| 468 | |
| 469 | struct InputDependentTool; |
| 470 | |
| 471 | #[async_trait] |
| 472 | impl ToolSpec for InputDependentTool { |
| 473 | fn name(&self) -> &str { |
| 474 | "input_dependent" |
| 475 | } |
| 476 | |
| 477 | fn description(&self) -> &str { |
| 478 | "characterization tool" |
| 479 | } |
| 480 | |
| 481 | fn input_schema(&self) -> Value { |
| 482 | json!({"type": "object"}) |
| 483 | } |
| 484 | |
| 485 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 486 | vec![ToolCapability::WritesFiles] |
| 487 | } |
| 488 | |
| 489 | fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement { |
| 490 | if input.get("safe").and_then(Value::as_bool) == Some(true) { |
| 491 | ApprovalRequirement::Auto |
| 492 | } else { |
| 493 | ApprovalRequirement::Required |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | fn is_read_only_for(&self, input: &Value) -> bool { |
| 498 | input.get("safe").and_then(Value::as_bool) == Some(true) |
| 499 | } |
| 500 | |
| 501 | fn supports_parallel_for(&self, input: &Value) -> bool { |
| 502 | self.is_read_only_for(input) |
| 503 | } |
| 504 | |
| 505 | fn starts_detached_for(&self, input: &Value) -> bool { |
| 506 | input.get("detached").and_then(Value::as_bool) == Some(true) |
| 507 | } |
| 508 | |
| 509 | async fn execute( |
| 510 | &self, |
| 511 | _input: Value, |
| 512 | _context: &ToolContext, |
| 513 | ) -> Result<ToolResult, ToolError> { |
| 514 | unreachable!("preparation must not execute the tool") |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | fn registry() -> (tempfile::TempDir, ToolRegistry) { |
| 519 | let root = tempdir().expect("tempdir"); |
| 520 | let mut context = ToolContext::new(root.path().to_path_buf()); |
| 521 | context.auto_approve = true; |
| 522 | let mut registry = ToolRegistry::new(context); |
| 523 | registry.register(Arc::new(InputDependentTool)); |
| 524 | (root, registry) |
| 525 | } |
| 526 | |
| 527 | #[test] |
| 528 | fn prepared_policy_matches_existing_input_specific_decisions() { |
| 529 | let (_root, registry) = registry(); |
| 530 | let spec = registry.get("input_dependent").expect("registered tool"); |
| 531 | |
| 532 | for input in [ |
| 533 | json!({"safe": true, "detached": false}), |
| 534 | json!({"safe": false, "detached": true}), |
| 535 | ] { |
| 536 | let prepared = |
| 537 | prepare_tool_call("input_dependent", input.clone(), Some(®istry), false) |
| 538 | .expect("prepare"); |
| 539 | |
| 540 | assert_eq!( |
| 541 | prepared.call.approval, |
| 542 | spec.approval_requirement_for(&input) |
| 543 | ); |
| 544 | assert_eq!(prepared.call.read_only, spec.is_read_only_for(&input)); |
| 545 | assert_eq!( |
| 546 | prepared.call.supports_parallel, |
| 547 | spec.supports_parallel_for(&input) |
| 548 | ); |
| 549 | assert_eq!( |
| 550 | prepared.call.starts_detached, |
| 551 | spec.starts_detached_for(&input) |
| 552 | ); |
| 553 | assert!(prepared.auto_approve); |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | #[test] |
| 558 | fn hook_rewrite_discards_every_original_prepared_decision() { |
| 559 | let (_root, registry) = registry(); |
| 560 | let original = prepare_tool_call( |
| 561 | "input_dependent", |
| 562 | json!({"safe": true, "detached": false}), |
| 563 | Some(®istry), |
| 564 | false, |
| 565 | ) |
| 566 | .expect("prepare original"); |
| 567 | let rewritten = reprepare_tool_call_after_hook( |
| 568 | "input_dependent", |
| 569 | json!({"safe": false, "detached": true}), |
| 570 | Some(®istry), |
| 571 | false, |
| 572 | ) |
| 573 | .expect("reprepare rewritten input"); |
| 574 | |
| 575 | assert_eq!(original.call.approval, ApprovalRequirement::Auto); |
| 576 | assert!(original.call.read_only); |
| 577 | assert!(original.call.supports_parallel); |
| 578 | assert!(!original.call.starts_detached); |
| 579 | |
| 580 | assert_eq!(rewritten.call.approval, ApprovalRequirement::Required); |
| 581 | assert!(!rewritten.call.read_only); |
| 582 | assert!(!rewritten.call.supports_parallel); |
| 583 | assert!(rewritten.call.starts_detached); |
| 584 | assert_eq!( |
| 585 | rewritten.call.input, |
| 586 | json!({"safe": false, "detached": true}) |
| 587 | ); |
| 588 | } |
| 589 | |
| 590 | #[test] |
| 591 | fn bypass_preparation_preserves_legacy_policy_table() { |
| 592 | struct Expected { |
| 593 | name: &'static str, |
| 594 | approval: ApprovalRequirement, |
| 595 | read_only: bool, |
| 596 | supports_parallel: bool, |
| 597 | global_exclusive: bool, |
| 598 | } |
| 599 | |
| 600 | for expected in [ |
| 601 | Expected { |
| 602 | name: "read_mcp_resource", |
| 603 | approval: ApprovalRequirement::Auto, |
| 604 | read_only: true, |
| 605 | supports_parallel: true, |
| 606 | global_exclusive: false, |
| 607 | }, |
| 608 | Expected { |
| 609 | name: "mcp_filesystem_write", |
| 610 | approval: ApprovalRequirement::Suggest, |
| 611 | read_only: false, |
| 612 | supports_parallel: false, |
| 613 | global_exclusive: true, |
| 614 | }, |
| 615 | Expected { |
| 616 | name: CODE_EXECUTION_TOOL_NAME, |
| 617 | approval: ApprovalRequirement::Suggest, |
| 618 | read_only: false, |
| 619 | supports_parallel: false, |
| 620 | global_exclusive: true, |
| 621 | }, |
| 622 | Expected { |
| 623 | name: "tool_search", |
| 624 | approval: ApprovalRequirement::Auto, |
| 625 | read_only: true, |
| 626 | supports_parallel: true, |
| 627 | global_exclusive: false, |
| 628 | }, |
| 629 | ] { |
| 630 | let prepared = prepare_tool_call(expected.name, json!({}), None, false) |
| 631 | .unwrap_or_else(|error| panic!("prepare {}: {error}", expected.name)); |
| 632 | assert_eq!( |
| 633 | prepared.call.approval, expected.approval, |
| 634 | "{}", |
| 635 | expected.name |
| 636 | ); |
| 637 | assert_eq!( |
| 638 | prepared.call.read_only, expected.read_only, |
| 639 | "{}", |
| 640 | expected.name |
| 641 | ); |
| 642 | assert_eq!( |
| 643 | prepared.call.supports_parallel, expected.supports_parallel, |
| 644 | "{}", |
| 645 | expected.name |
| 646 | ); |
| 647 | assert_eq!( |
| 648 | prepared.call.resources == vec![ResourceClaim::GlobalExclusive], |
| 649 | expected.global_exclusive, |
| 650 | "{}", |
| 651 | expected.name |
| 652 | ); |
| 653 | assert!(!prepared.call.starts_detached, "{}", expected.name); |
| 654 | assert!(!prepared.auto_approve, "{}", expected.name); |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | #[test] |
| 659 | fn mcp_annotation_hints_drive_approval() { |
| 660 | use crate::mcp::{McpToolApprovalHint, set_mcp_tool_approval_hint_for_test}; |
| 661 | |
| 662 | let read_only = "mcp_plugin-9-cw11test_page_snapshot"; |
| 663 | set_mcp_tool_approval_hint_for_test(read_only, Some(McpToolApprovalHint::TrustedReadOnly)); |
| 664 | let prepared = prepare_tool_call(read_only, json!({}), None, false) |
| 665 | .expect("prepare trusted read-only MCP tool"); |
| 666 | assert_eq!(prepared.call.approval, ApprovalRequirement::Auto); |
| 667 | assert!(prepared.call.read_only); |
| 668 | |
| 669 | // A bounded worker keeps the execution gate's rule: only the built-in |
| 670 | // resource reads, so preparation never admits a call execution refuses. |
| 671 | let workspace = tempfile::tempdir().expect("tempdir"); |
| 672 | let context = crate::tools::ToolContext::new(workspace.path().to_path_buf()) |
| 673 | .with_tool_authority(crate::tools::spec::ToolAuthorityEnvelope { |
| 674 | schema_version: 1, |
| 675 | owner: "cw11-worker".to_string(), |
| 676 | authority: crate::tools::spec::ToolMutationAuthority::ScopedWrite, |
| 677 | network_access: None, |
| 678 | shell: crate::tools::spec::ToolShellAuthority::None, |
| 679 | verification: crate::tools::spec::ToolVerificationAuthority::None, |
| 680 | writable_roots: Vec::new(), |
| 681 | writable_files: vec!["src/named.rs".to_string()], |
| 682 | coordination_contracts: Vec::new(), |
| 683 | }) |
| 684 | .expect("valid envelope"); |
| 685 | let registry = crate::tools::ToolRegistry::new(context); |
| 686 | let refused = prepare_tool_call(read_only, json!({}), Some(®istry), false) |
| 687 | .expect_err("a bounded worker cannot run a plugin-declared read"); |
| 688 | assert!(refused.to_string().contains("cw11-worker"), "{refused}"); |
| 689 | |
| 690 | let destructive = "mcp_cw11test_drop_table"; |
| 691 | set_mcp_tool_approval_hint_for_test(destructive, Some(McpToolApprovalHint::Destructive)); |
| 692 | let prepared = prepare_tool_call(destructive, json!({}), None, false) |
| 693 | .expect("prepare destructive MCP tool"); |
| 694 | assert_eq!(prepared.call.approval, ApprovalRequirement::Suggest); |
| 695 | assert!(!prepared.call.read_only); |
| 696 | assert!( |
| 697 | prepared.call.description.contains("destructive"), |
| 698 | "{}", |
| 699 | prepared.call.description |
| 700 | ); |
| 701 | // Full Access covers it like any other promptable tool (#3866): a |
| 702 | // host answering from its own flag must not deny what the posture |
| 703 | // allows. |
| 704 | let prepared = prepare_tool_call(destructive, json!({}), None, true) |
| 705 | .expect("prepare destructive MCP tool under Full Access"); |
| 706 | assert!(prepared.auto_approve); |
| 707 | |
| 708 | set_mcp_tool_approval_hint_for_test(read_only, None); |
| 709 | set_mcp_tool_approval_hint_for_test(destructive, None); |
| 710 | } |
| 711 | |
| 712 | #[test] |
| 713 | fn mcp_write_preparation_respects_session_auto_approval() { |
| 714 | let prepared = prepare_tool_call("mcp_filesystem_write", json!({}), None, true) |
| 715 | .expect("prepare MCP write tool with session auto-approval"); |
| 716 | |
| 717 | assert_eq!(prepared.call.approval, ApprovalRequirement::Suggest); |
| 718 | assert!(!prepared.call.read_only); |
| 719 | assert!(!prepared.call.supports_parallel); |
| 720 | assert_eq!( |
| 721 | prepared.call.resources, |
| 722 | vec![ResourceClaim::GlobalExclusive] |
| 723 | ); |
| 724 | assert!(prepared.auto_approve); |
| 725 | assert!(!super::super::turn_loop::registered_tool_approval_required( |
| 726 | &prepared.call.name, |
| 727 | prepared.call.approval, |
| 728 | prepared.auto_approve, |
| 729 | )); |
| 730 | } |
| 731 | |
| 732 | /// K1: the model cannot grant itself Computer Use consent. A posture with |
| 733 | /// no person at the card refuses at preparation; Ask and Full Access both |
| 734 | /// reach the card, always require approval, are never session |
| 735 | /// auto-approved, and a session grant for one app does not cover another. |
| 736 | #[test] |
| 737 | fn model_issued_computer_use_consent_never_auto_approves() { |
| 738 | let consent = "mcp_plugin-12-computer-use-computer_consent"; |
| 739 | let allow_safari = |
| 740 | json!({"action": "allow", "app": "Safari", "bundle_id": "com.apple.Safari"}); |
| 741 | let foreground = json!({"action": "allow", "scope": "foreground"}); |
| 742 | |
| 743 | // Postures with nobody at the card refuse before approval routing. |
| 744 | for (session_auto, context_auto, mode) in [ |
| 745 | (false, false, ApprovalMode::Auto), |
| 746 | (false, false, ApprovalMode::Never), |
| 747 | ] { |
| 748 | let root = tempdir().expect("tempdir"); |
| 749 | let mut context = ToolContext::new(root.path().to_path_buf()); |
| 750 | context.auto_approve = context_auto; |
| 751 | context.approval_mode = mode; |
| 752 | let registry = ToolRegistry::new(context); |
| 753 | for (name, input) in [ |
| 754 | (consent, allow_safari.clone()), |
| 755 | (consent, foreground.clone()), |
| 756 | ( |
| 757 | "mcp_codewhale-cu_consent_revoke", |
| 758 | json!({"app": "Terminal"}), |
| 759 | ), |
| 760 | ( |
| 761 | "mcp_plugin-12-computer-use-computer_app_script", |
| 762 | json!({"script": "do shell script \"id\""}), |
| 763 | ), |
| 764 | ] { |
| 765 | let error = prepare_tool_call(name, input.clone(), Some(®istry), session_auto) |
| 766 | .expect_err("model-issued consent must not run without a human"); |
| 767 | assert!( |
| 768 | matches!(error, ToolError::PermissionDenied { .. }), |
| 769 | "{name} {mode:?}: {error}" |
| 770 | ); |
| 771 | } |
| 772 | } |
| 773 | // Full Access shows the card instead of refusing it. The call still |
| 774 | // requires approval and is never auto-approved, so a posture cannot |
| 775 | // stand in for the person's answer. |
| 776 | for (session_auto, context_auto, mode) in [ |
| 777 | (true, false, ApprovalMode::Suggest), |
| 778 | (false, true, ApprovalMode::Suggest), |
| 779 | (false, false, ApprovalMode::Bypass), |
| 780 | ] { |
| 781 | let root = tempdir().expect("tempdir"); |
| 782 | let mut context = ToolContext::new(root.path().to_path_buf()); |
| 783 | context.auto_approve = context_auto; |
| 784 | context.approval_mode = mode; |
| 785 | let registry = ToolRegistry::new(context); |
| 786 | let prepared = |
| 787 | prepare_tool_call(consent, allow_safari.clone(), Some(®istry), session_auto) |
| 788 | .expect("Full Access reaches the consent card"); |
| 789 | assert_eq!(prepared.call.approval, ApprovalRequirement::Required); |
| 790 | assert!(!prepared.auto_approve, "{mode:?}"); |
| 791 | assert!(super::super::turn_loop::registered_tool_approval_required( |
| 792 | &prepared.call.name, |
| 793 | prepared.call.approval, |
| 794 | prepared.auto_approve, |
| 795 | )); |
| 796 | } |
| 797 | |
| 798 | // Ask posture: a Required card that names the app, bundle and scope. |
| 799 | let root = tempdir().expect("tempdir"); |
| 800 | let registry = ToolRegistry::new(ToolContext::new(root.path().to_path_buf())); |
| 801 | let prepared = prepare_tool_call(consent, allow_safari.clone(), Some(®istry), false) |
| 802 | .expect("Ask posture opens a card"); |
| 803 | assert_eq!(prepared.call.approval, ApprovalRequirement::Required); |
| 804 | assert!(!prepared.auto_approve); |
| 805 | assert!(!prepared.call.read_only); |
| 806 | assert!(super::super::turn_loop::registered_tool_approval_required( |
| 807 | &prepared.call.name, |
| 808 | prepared.call.approval, |
| 809 | prepared.auto_approve, |
| 810 | )); |
| 811 | let description = &prepared.call.description; |
| 812 | assert!(description.contains("Safari"), "{description}"); |
| 813 | assert!(description.contains("com.apple.Safari"), "{description}"); |
| 814 | assert!(description.contains("scope: app"), "{description}"); |
| 815 | let foreground_card = prepare_tool_call(consent, foreground, Some(®istry), false) |
| 816 | .expect("foreground card"); |
| 817 | assert!( |
| 818 | foreground_card |
| 819 | .call |
| 820 | .description |
| 821 | .contains("scope: foreground") |
| 822 | ); |
| 823 | // An irreversible-action confirm token is named as such, not as an |
| 824 | // "<unnamed app>" consent; a multi-line script says it is truncated. |
| 825 | let confirm_card = prepare_tool_call( |
| 826 | consent, |
| 827 | json!({"action": "allow", "confirm": "tok-1"}), |
| 828 | Some(®istry), |
| 829 | false, |
| 830 | ) |
| 831 | .expect("confirm card"); |
| 832 | assert_eq!(confirm_card.call.approval, ApprovalRequirement::Required); |
| 833 | assert!( |
| 834 | confirm_card |
| 835 | .call |
| 836 | .description |
| 837 | .contains("irreversible action"), |
| 838 | "{}", |
| 839 | confirm_card.call.description |
| 840 | ); |
| 841 | let script_card = prepare_tool_call( |
| 842 | "mcp_plugin-12-computer-use-computer_app_script", |
| 843 | json!({"script": "tell application \"Finder\" to activate\ndo shell script \"id\""}), |
| 844 | Some(®istry), |
| 845 | false, |
| 846 | ) |
| 847 | .expect("script card"); |
| 848 | assert!( |
| 849 | script_card.call.description.contains("first of 2 lines"), |
| 850 | "{}", |
| 851 | script_card.call.description |
| 852 | ); |
| 853 | |
| 854 | // After a session grant for Safari, a consent for Terminal still |
| 855 | // prompts: the grant key is the exact call, not the MCP kind. |
| 856 | let granted = |
| 857 | crate::tools::approval_cache::build_approval_grouping_key(consent, &allow_safari); |
| 858 | let terminal = crate::tools::approval_cache::build_approval_grouping_key( |
| 859 | consent, |
| 860 | &json!({"action": "allow", "app": "Terminal", "bundle_id": "com.apple.Terminal"}), |
| 861 | ); |
| 862 | assert_ne!(granted, terminal); |
| 863 | |
| 864 | // K1: run_actions cannot smuggle a consent grant or a script past |
| 865 | // the per-call card, in any posture (Ask included). |
| 866 | let batch = "mcp_plugin-12-computer-use-computer_run_actions"; |
| 867 | for (step, session_auto) in [ |
| 868 | ( |
| 869 | json!({"tool": "consent_allow", "arguments": {"app": "Terminal"}}), |
| 870 | false, |
| 871 | ), |
| 872 | ( |
| 873 | json!({"tool": "consent", "args": {"action": "allow", "scope": "foreground"}}), |
| 874 | false, |
| 875 | ), |
| 876 | ( |
| 877 | json!({"tool": "consent_revoke", "arguments": {"app": "Terminal"}}), |
| 878 | true, |
| 879 | ), |
| 880 | ( |
| 881 | json!({"tool": "app_script", "arguments": {"script": "do shell script \"id\""}}), |
| 882 | false, |
| 883 | ), |
| 884 | ] { |
| 885 | let input = json!({"steps": [{"tool": "click", "arguments": {"x": 1, "y": 1}}, step]}); |
| 886 | let error = prepare_tool_call(batch, input, Some(®istry), session_auto) |
| 887 | .expect_err("a batched consent or script must be refused"); |
| 888 | assert!( |
| 889 | matches!(error, ToolError::PermissionDenied { .. }), |
| 890 | "{error}" |
| 891 | ); |
| 892 | } |
| 893 | let plain_batch = json!({"steps": [ |
| 894 | {"tool": "click", "arguments": {"x": 1, "y": 1}}, |
| 895 | {"tool": "consent", "arguments": {"action": "status"}}, |
| 896 | ]}); |
| 897 | assert!(prepare_tool_call(batch, plain_batch, Some(®istry), false).is_ok()); |
| 898 | |
| 899 | // Reading the ledger is unaffected. |
| 900 | let status = prepare_tool_call(consent, json!({"action": "status"}), Some(®istry), true) |
| 901 | .expect("status is not gated"); |
| 902 | assert!(status.auto_approve); |
| 903 | } |
| 904 | |
| 905 | #[test] |
| 906 | fn hook_rewrite_reprepares_resource_claims_from_final_input() { |
| 907 | let root = tempdir().expect("tempdir"); |
| 908 | let context = ToolContext::new(root.path().to_path_buf()); |
| 909 | let original_path = context.resolve_path("before.rs").expect("original path"); |
| 910 | let rewritten_path = context.resolve_path("after.rs").expect("rewritten path"); |
| 911 | let mut registry = ToolRegistry::new(context); |
| 912 | registry.register(Arc::new(crate::tools::file::ReadFileTool)); |
| 913 | |
| 914 | let original = prepare_tool_call( |
| 915 | "read_file", |
| 916 | json!({"path": "before.rs"}), |
| 917 | Some(®istry), |
| 918 | false, |
| 919 | ) |
| 920 | .expect("prepare original read"); |
| 921 | let rewritten = reprepare_tool_call_after_hook( |
| 922 | "read_file", |
| 923 | json!({"path": "after.rs"}), |
| 924 | Some(®istry), |
| 925 | false, |
| 926 | ) |
| 927 | .expect("reprepare rewritten read"); |
| 928 | |
| 929 | assert_eq!( |
| 930 | original.call.resources, |
| 931 | vec![ResourceClaim::ReadPath(original_path)] |
| 932 | ); |
| 933 | assert_eq!( |
| 934 | rewritten.call.resources, |
| 935 | vec![ResourceClaim::ReadPath(rewritten_path)] |
| 936 | ); |
| 937 | } |
| 938 | |
| 939 | #[test] |
| 940 | fn registered_file_claims_are_canonical_and_input_specific() { |
| 941 | let root = tempdir().expect("tempdir"); |
| 942 | let context = ToolContext::new(root.path().to_path_buf()); |
| 943 | let exact = context.resolve_path("src/lib.rs").expect("exact path"); |
| 944 | let tree = context.resolve_path("src").expect("tree path"); |
| 945 | |
| 946 | assert_eq!( |
| 947 | registered_resource_claims( |
| 948 | "read_file", |
| 949 | &json!({"path": "src/lib.rs"}), |
| 950 | &context, |
| 951 | true, |
| 952 | false, |
| 953 | ) |
| 954 | .expect("read claim"), |
| 955 | vec![ResourceClaim::ReadPath(exact.clone())] |
| 956 | ); |
| 957 | assert_eq!( |
| 958 | registered_resource_claims( |
| 959 | "edit_file", |
| 960 | &json!({"path": "src/lib.rs"}), |
| 961 | &context, |
| 962 | false, |
| 963 | false, |
| 964 | ) |
| 965 | .expect("write claim"), |
| 966 | vec![ResourceClaim::WritePath(exact)] |
| 967 | ); |
| 968 | assert_eq!( |
| 969 | registered_resource_claims( |
| 970 | "grep_files", |
| 971 | &json!({"path": "src"}), |
| 972 | &context, |
| 973 | true, |
| 974 | false, |
| 975 | ) |
| 976 | .expect("tree claim"), |
| 977 | vec![ResourceClaim::ReadTree(tree)] |
| 978 | ); |
| 979 | assert_eq!( |
| 980 | registered_resource_claims( |
| 981 | "read_file", |
| 982 | &json!({"path": "../../outside"}), |
| 983 | &context, |
| 984 | true, |
| 985 | false, |
| 986 | ) |
| 987 | .expect("path escape must fall back conservatively"), |
| 988 | vec![ResourceClaim::GlobalExclusive] |
| 989 | ); |
| 990 | } |
| 991 | |
| 992 | #[cfg(unix)] |
| 993 | #[test] |
| 994 | fn symlink_aliases_resolve_to_the_same_file_claim() { |
| 995 | use std::os::unix::fs::symlink; |
| 996 | |
| 997 | let root = tempdir().expect("tempdir"); |
| 998 | let real_dir = root.path().join("real"); |
| 999 | std::fs::create_dir(&real_dir).expect("create real directory"); |
| 1000 | std::fs::write(real_dir.join("lib.rs"), "fn main() {}\n").expect("write real file"); |
| 1001 | symlink("real", root.path().join("alias")).expect("create directory symlink"); |
| 1002 | let context = ToolContext::new(root.path().to_path_buf()); |
| 1003 | let canonical_real = real_dir |
| 1004 | .join("lib.rs") |
| 1005 | .canonicalize() |
| 1006 | .expect("canonical file"); |
| 1007 | |
| 1008 | let read_alias = registered_resource_claims( |
| 1009 | "read_file", |
| 1010 | &json!({"path": "alias/lib.rs"}), |
| 1011 | &context, |
| 1012 | true, |
| 1013 | false, |
| 1014 | ) |
| 1015 | .expect("alias claim"); |
| 1016 | let write_real = registered_resource_claims( |
| 1017 | "write_file", |
| 1018 | &json!({"path": "real/lib.rs"}), |
| 1019 | &context, |
| 1020 | false, |
| 1021 | false, |
| 1022 | ) |
| 1023 | .expect("real claim"); |
| 1024 | |
| 1025 | assert_eq!(read_alias, vec![ResourceClaim::ReadPath(canonical_real)]); |
| 1026 | assert!(read_alias[0].conflicts_with(&write_real[0])); |
| 1027 | } |
| 1028 | |
| 1029 | #[test] |
| 1030 | fn apply_patch_claims_every_resolved_target_or_falls_back_global() { |
| 1031 | let root = tempdir().expect("tempdir"); |
| 1032 | let context = ToolContext::new(root.path().to_path_buf()); |
| 1033 | let a = context.resolve_path("a.rs").expect("a path"); |
| 1034 | let b = context.resolve_path("b.rs").expect("b path"); |
| 1035 | |
| 1036 | let claims = registered_resource_claims( |
| 1037 | "apply_patch", |
| 1038 | &json!({ |
| 1039 | "replace": [ |
| 1040 | {"path": "b.rs", "content": "b"}, |
| 1041 | {"path": "a.rs", "content": "a"} |
| 1042 | ] |
| 1043 | }), |
| 1044 | &context, |
| 1045 | false, |
| 1046 | false, |
| 1047 | ) |
| 1048 | .expect("patch claims"); |
| 1049 | assert_eq!( |
| 1050 | claims, |
| 1051 | vec![ResourceClaim::WritePath(a), ResourceClaim::WritePath(b)] |
| 1052 | ); |
| 1053 | |
| 1054 | assert_eq!( |
| 1055 | registered_resource_claims( |
| 1056 | "apply_patch", |
| 1057 | &json!({"patch": "not a unified diff"}), |
| 1058 | &context, |
| 1059 | false, |
| 1060 | false, |
| 1061 | ) |
| 1062 | .expect("fallback claim"), |
| 1063 | vec![ResourceClaim::GlobalExclusive] |
| 1064 | ); |
| 1065 | assert_eq!( |
| 1066 | registered_resource_claims( |
| 1067 | "apply_patch", |
| 1068 | &json!({"replace": [{"path": "../../outside", "content": "nope"}]}), |
| 1069 | &context, |
| 1070 | false, |
| 1071 | false, |
| 1072 | ) |
| 1073 | .expect("escaped target fallback"), |
| 1074 | vec![ResourceClaim::GlobalExclusive] |
| 1075 | ); |
| 1076 | } |
| 1077 | |
| 1078 | #[test] |
| 1079 | fn terminal_and_unknown_tools_keep_conservative_claims() { |
| 1080 | let root = tempdir().expect("tempdir"); |
| 1081 | let context = ToolContext::new(root.path().to_path_buf()); |
| 1082 | |
| 1083 | assert_eq!( |
| 1084 | registered_resource_claims("terminal_run", &json!({}), &context, false, false) |
| 1085 | .expect("default terminal"), |
| 1086 | vec![ResourceClaim::Terminal("term-1".to_string())] |
| 1087 | ); |
| 1088 | assert_eq!( |
| 1089 | registered_resource_claims( |
| 1090 | "terminal_wait", |
| 1091 | &json!({"session": "term-2"}), |
| 1092 | &context, |
| 1093 | false, |
| 1094 | false, |
| 1095 | ) |
| 1096 | .expect("terminal wait"), |
| 1097 | vec![ResourceClaim::Terminal("term-2".to_string())] |
| 1098 | ); |
| 1099 | assert_eq!( |
| 1100 | registered_resource_claims( |
| 1101 | "exec_shell_interact", |
| 1102 | &json!({"task_id": "task-7"}), |
| 1103 | &context, |
| 1104 | false, |
| 1105 | false, |
| 1106 | ) |
| 1107 | .expect("task terminal"), |
| 1108 | vec![ResourceClaim::Terminal("task-7".to_string())] |
| 1109 | ); |
| 1110 | assert_eq!( |
| 1111 | registered_resource_claims("plugin_tool", &json!({}), &context, true, false) |
| 1112 | .expect("unknown tool"), |
| 1113 | vec![ResourceClaim::GlobalExclusive] |
| 1114 | ); |
| 1115 | } |
| 1116 | |
| 1117 | fn plan_from_prepared( |
| 1118 | index: usize, |
| 1119 | prepared: PreparedToolPolicy, |
| 1120 | ) -> super::super::dispatch::ToolExecutionPlan { |
| 1121 | let approval_required = super::super::turn_loop::registered_tool_approval_required( |
| 1122 | &prepared.call.name, |
| 1123 | prepared.call.approval, |
| 1124 | prepared.auto_approve, |
| 1125 | ); |
| 1126 | super::super::dispatch::ToolExecutionPlan { |
| 1127 | index, |
| 1128 | id: format!("call-{index}"), |
| 1129 | model_call: None, |
| 1130 | name: prepared.call.name, |
| 1131 | input: prepared.call.input, |
| 1132 | caller: None, |
| 1133 | interactive: false, |
| 1134 | approval_required, |
| 1135 | approval_description: prepared.call.description, |
| 1136 | mcp_always_binding: None, |
| 1137 | approval_force_prompt: false, |
| 1138 | supports_parallel: prepared.call.supports_parallel, |
| 1139 | read_only: prepared.call.read_only, |
| 1140 | detached_start: prepared.call.starts_detached, |
| 1141 | resources: prepared.call.resources, |
| 1142 | blocked_error: None, |
| 1143 | guard_result: None, |
| 1144 | grants_outside_workspace_read: false, |
| 1145 | creator_gate: None, |
| 1146 | search_consent: false, |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | #[test] |
| 1151 | fn readonly_tools_and_tool_search_schedule_in_one_parallel_wave() { |
| 1152 | use super::super::dispatch::{ToolExecutionBatch, plan_tool_execution_batches}; |
| 1153 | use crate::mcp::{McpToolApprovalHint, set_mcp_tool_approval_hint_for_test}; |
| 1154 | |
| 1155 | let root = tempdir().expect("tempdir"); |
| 1156 | let mut context = ToolContext::new(root.path().to_path_buf()); |
| 1157 | context.auto_approve = true; |
| 1158 | let mut registry = ToolRegistry::new(context); |
| 1159 | registry.register(Arc::new(crate::tools::file_tool::ReadTool)); |
| 1160 | registry.register(Arc::new(crate::tools::file_tool::EditTool)); |
| 1161 | registry.register(Arc::new(crate::tools::git_tool::GitTool::new("Git"))); |
| 1162 | registry.register(Arc::new(crate::tools::skill::LoadSkillTool)); |
| 1163 | registry.register(Arc::new( |
| 1164 | crate::tools::tool_result_retrieval::RetrieveToolResultTool, |
| 1165 | )); |
| 1166 | registry.register(Arc::new(crate::tools::session::SessionSearchTool)); |
| 1167 | registry.register(Arc::new(crate::tools::web_tool::WebTool::new("Web"))); |
| 1168 | registry.register(Arc::new(crate::tools::shell::LowercaseBashTool)); |
| 1169 | registry.register(Arc::new(crate::tools::tasks::TasksTool::new("tasks"))); |
| 1170 | |
| 1171 | let trusted_mcp = "mcp_plugin-9-schedtest_lookup"; |
| 1172 | set_mcp_tool_approval_hint_for_test( |
| 1173 | trusted_mcp, |
| 1174 | Some(McpToolApprovalHint::TrustedReadOnly), |
| 1175 | ); |
| 1176 | |
| 1177 | let wave_calls = vec![ |
| 1178 | ("read", json!({"path": "src/lib.rs"})), |
| 1179 | ("Git", json!({"action": "status"})), |
| 1180 | ("load_skill", json!({"name": "list"})), |
| 1181 | ("retrieve_tool_result", json!({"ref": "art_1"})), |
| 1182 | ("session_search", json!({"query": "scheduler"})), |
| 1183 | ("Web", json!({"action": "search", "query": "codewhale"})), |
| 1184 | ("tasks", json!({"action": "list"})), |
| 1185 | ("tool_search", json!({"query": "git"})), |
| 1186 | ("bash", json!({"command": "ls -la", "read_only": true})), |
| 1187 | ( |
| 1188 | "read_mcp_resource", |
| 1189 | json!({"server": "docs", "uri": "mem://1"}), |
| 1190 | ), |
| 1191 | (trusted_mcp, json!({"id": 1})), |
| 1192 | ]; |
| 1193 | |
| 1194 | let plans: Vec<_> = wave_calls |
| 1195 | .into_iter() |
| 1196 | .enumerate() |
| 1197 | .map(|(idx, (name, input))| { |
| 1198 | let prepared = prepare_tool_call(name, input, Some(®istry), true) |
| 1199 | .unwrap_or_else(|e| panic!("prepare {name}: {e}")); |
| 1200 | assert!(prepared.call.read_only, "{name} should be read_only"); |
| 1201 | assert!( |
| 1202 | prepared.call.supports_parallel, |
| 1203 | "{name} should support parallel" |
| 1204 | ); |
| 1205 | assert_ne!( |
| 1206 | prepared.call.resources, |
| 1207 | vec![ResourceClaim::GlobalExclusive], |
| 1208 | "{name} must not claim GlobalExclusive" |
| 1209 | ); |
| 1210 | plan_from_prepared(idx, prepared) |
| 1211 | }) |
| 1212 | .collect(); |
| 1213 | |
| 1214 | let batches = plan_tool_execution_batches(plans); |
| 1215 | assert_eq!(batches.len(), 1); |
| 1216 | match &batches[0] { |
| 1217 | ToolExecutionBatch::Parallel(items) => { |
| 1218 | assert_eq!(items.len(), 11); |
| 1219 | } |
| 1220 | ToolExecutionBatch::Serial(_) => panic!("expected one parallel wave"), |
| 1221 | } |
| 1222 | |
| 1223 | let agent_list = registered_resource_claims( |
| 1224 | "agent", |
| 1225 | &json!({"action": "status"}), |
| 1226 | registry.context(), |
| 1227 | true, |
| 1228 | false, |
| 1229 | ) |
| 1230 | .expect("agent status"); |
| 1231 | assert_eq!(agent_list, vec![ResourceClaim::ReadOnly]); |
| 1232 | let agent_start = registered_resource_claims( |
| 1233 | "agent", |
| 1234 | &json!({"action": "start", "detached": true}), |
| 1235 | registry.context(), |
| 1236 | false, |
| 1237 | true, |
| 1238 | ) |
| 1239 | .expect("agent start"); |
| 1240 | assert_eq!(agent_start, vec![ResourceClaim::GlobalExclusive]); |
| 1241 | |
| 1242 | set_mcp_tool_approval_hint_for_test(trusted_mcp, None); |
| 1243 | } |
| 1244 | |
| 1245 | #[test] |
| 1246 | fn mutating_tools_preserve_barriers_and_tool_searches_share_a_batch() { |
| 1247 | use super::super::dispatch::{ToolExecutionBatch, plan_tool_execution_batches}; |
| 1248 | |
| 1249 | let root = tempdir().expect("tempdir"); |
| 1250 | let mut context = ToolContext::new(root.path().to_path_buf()); |
| 1251 | context.auto_approve = true; |
| 1252 | let mut registry = ToolRegistry::new(context); |
| 1253 | registry.register(Arc::new(crate::tools::file_tool::ReadTool)); |
| 1254 | registry.register(Arc::new(crate::tools::file_tool::EditTool)); |
| 1255 | registry.register(Arc::new(crate::tools::git_tool::GitTool::new("Git"))); |
| 1256 | registry.register(Arc::new(crate::tools::shell::LowercaseBashTool)); |
| 1257 | |
| 1258 | let git_status = |
| 1259 | prepare_tool_call("Git", json!({"action": "status"}), Some(®istry), true) |
| 1260 | .expect("git status"); |
| 1261 | let edit_file = prepare_tool_call( |
| 1262 | "edit", |
| 1263 | json!({"path": "src/lib.rs", "edits": []}), |
| 1264 | Some(®istry), |
| 1265 | true, |
| 1266 | ) |
| 1267 | .expect("edit"); |
| 1268 | let bash_mut = prepare_tool_call( |
| 1269 | "bash", |
| 1270 | json!({"command": "cargo build"}), |
| 1271 | Some(®istry), |
| 1272 | true, |
| 1273 | ) |
| 1274 | .expect("mutating bash"); |
| 1275 | let bash_bg = prepare_tool_call( |
| 1276 | "bash", |
| 1277 | json!({"command": "cargo check", "background": true}), |
| 1278 | Some(®istry), |
| 1279 | true, |
| 1280 | ) |
| 1281 | .expect("background bash"); |
| 1282 | let git_fetch = prepare_tool_call("Git", json!({"action": "fetch"}), Some(®istry), true) |
| 1283 | .expect("git fetch"); |
| 1284 | let mcp_mut = |
| 1285 | prepare_tool_call("mcp_github_create_issue", json!({}), Some(®istry), true) |
| 1286 | .expect("mutating mcp"); |
| 1287 | |
| 1288 | assert!(git_status.call.resources[0].conflicts_with(&edit_file.call.resources[0])); |
| 1289 | assert_eq!( |
| 1290 | bash_mut.call.resources, |
| 1291 | vec![ResourceClaim::GlobalExclusive] |
| 1292 | ); |
| 1293 | assert_eq!(bash_bg.call.resources, vec![ResourceClaim::GlobalExclusive]); |
| 1294 | assert_eq!( |
| 1295 | git_fetch.call.resources, |
| 1296 | vec![ResourceClaim::GlobalExclusive] |
| 1297 | ); |
| 1298 | assert_eq!(mcp_mut.call.resources, vec![ResourceClaim::GlobalExclusive]); |
| 1299 | |
| 1300 | let search_1 = |
| 1301 | prepare_tool_call("tool_search", json!({"query": "a"}), None, true).expect("search 1"); |
| 1302 | let read_1 = prepare_tool_call("read", json!({"path": "src/a.rs"}), Some(®istry), true) |
| 1303 | .expect("read 1"); |
| 1304 | let search_2 = |
| 1305 | prepare_tool_call("tool_search", json!({"query": "b"}), None, true).expect("search 2"); |
| 1306 | |
| 1307 | let batches = plan_tool_execution_batches(vec![ |
| 1308 | plan_from_prepared(0, git_status), |
| 1309 | plan_from_prepared(1, edit_file), |
| 1310 | plan_from_prepared(2, search_1), |
| 1311 | plan_from_prepared(3, read_1), |
| 1312 | plan_from_prepared(4, search_2), |
| 1313 | plan_from_prepared(5, git_fetch), |
| 1314 | plan_from_prepared(6, bash_mut), |
| 1315 | ]); |
| 1316 | assert_eq!(batches.len(), 5); |
| 1317 | assert!(matches!(&batches[0], ToolExecutionBatch::Parallel(items) if items.len() == 1)); |
| 1318 | assert!(matches!(&batches[1], ToolExecutionBatch::Serial(item) if item.index == 1)); |
| 1319 | assert!(matches!(&batches[2], ToolExecutionBatch::Parallel(items) if items.len() == 3)); |
| 1320 | assert!(matches!(&batches[3], ToolExecutionBatch::Serial(item) if item.index == 5)); |
| 1321 | assert!(matches!(&batches[4], ToolExecutionBatch::Serial(item) if item.index == 6)); |
| 1322 | } |
| 1323 | |
| 1324 | #[test] |
| 1325 | fn task_shell_wait_handles_single_multi_and_mutating_claims() { |
| 1326 | use super::super::dispatch::{ToolExecutionBatch, plan_tool_execution_batches}; |
| 1327 | |
| 1328 | let root = tempdir().expect("tempdir"); |
| 1329 | let mut context = ToolContext::new(root.path().to_path_buf()); |
| 1330 | context.auto_approve = true; |
| 1331 | let mut registry = ToolRegistry::new(context); |
| 1332 | registry.register(Arc::new(crate::tools::file_tool::ReadTool)); |
| 1333 | registry.register(Arc::new(crate::tools::tasks::TaskShellWaitTool)); |
| 1334 | |
| 1335 | let multi_ab = prepare_tool_call( |
| 1336 | "task_shell_wait", |
| 1337 | json!({"task_ids": ["bg-2", "bg-1"], "wait": true, "until": "any"}), |
| 1338 | Some(®istry), |
| 1339 | true, |
| 1340 | ) |
| 1341 | .expect("multi-task wait"); |
| 1342 | assert!(multi_ab.call.read_only); |
| 1343 | assert!(multi_ab.call.supports_parallel); |
| 1344 | assert_eq!( |
| 1345 | multi_ab.call.resources, |
| 1346 | vec![ |
| 1347 | ResourceClaim::Terminal("bg-1".to_string()), |
| 1348 | ResourceClaim::Terminal("bg-2".to_string()), |
| 1349 | ] |
| 1350 | ); |
| 1351 | |
| 1352 | let single_c = prepare_tool_call( |
| 1353 | "task_shell_wait", |
| 1354 | json!({"task_id": "bg-3"}), |
| 1355 | Some(®istry), |
| 1356 | true, |
| 1357 | ) |
| 1358 | .expect("single wait"); |
| 1359 | assert_eq!( |
| 1360 | single_c.call.resources, |
| 1361 | vec![ResourceClaim::Terminal("bg-3".to_string())] |
| 1362 | ); |
| 1363 | |
| 1364 | let overlapping_a = prepare_tool_call( |
| 1365 | "task_shell_wait", |
| 1366 | json!({"task_id": "bg-1"}), |
| 1367 | Some(®istry), |
| 1368 | true, |
| 1369 | ) |
| 1370 | .expect("overlapping wait"); |
| 1371 | |
| 1372 | let cancel_a = prepare_tool_call( |
| 1373 | "task_shell_wait", |
| 1374 | json!({"task_id": "bg-1", "cancel": true}), |
| 1375 | Some(®istry), |
| 1376 | true, |
| 1377 | ) |
| 1378 | .expect("cancel wait"); |
| 1379 | assert!(!cancel_a.call.read_only); |
| 1380 | assert!(!cancel_a.call.supports_parallel); |
| 1381 | assert_eq!( |
| 1382 | cancel_a.call.resources, |
| 1383 | vec![ResourceClaim::GlobalExclusive] |
| 1384 | ); |
| 1385 | |
| 1386 | let gate_a = prepare_tool_call( |
| 1387 | "task_shell_wait", |
| 1388 | json!({"task_id": "bg-1", "gate": "test"}), |
| 1389 | Some(®istry), |
| 1390 | true, |
| 1391 | ) |
| 1392 | .expect("gate wait"); |
| 1393 | assert!(!gate_a.call.read_only); |
| 1394 | assert!(!gate_a.call.supports_parallel); |
| 1395 | assert_eq!(gate_a.call.resources, vec![ResourceClaim::GlobalExclusive]); |
| 1396 | |
| 1397 | let invalid_both = prepare_tool_call( |
| 1398 | "task_shell_wait", |
| 1399 | json!({"task_id": "bg-1", "task_ids": ["bg-2"]}), |
| 1400 | Some(®istry), |
| 1401 | true, |
| 1402 | ) |
| 1403 | .expect("conflicting task_id and task_ids"); |
| 1404 | assert_eq!( |
| 1405 | invalid_both.call.resources, |
| 1406 | vec![ResourceClaim::GlobalExclusive] |
| 1407 | ); |
| 1408 | |
| 1409 | let read = prepare_tool_call("read", json!({"path": "src/lib.rs"}), Some(®istry), true) |
| 1410 | .expect("read"); |
| 1411 | |
| 1412 | let batches = plan_tool_execution_batches(vec![ |
| 1413 | plan_from_prepared(0, read), |
| 1414 | plan_from_prepared(1, multi_ab), |
| 1415 | plan_from_prepared(2, single_c), |
| 1416 | plan_from_prepared(3, overlapping_a), |
| 1417 | plan_from_prepared(4, cancel_a), |
| 1418 | ]); |
| 1419 | assert_eq!(batches.len(), 3); |
| 1420 | match &batches[0] { |
| 1421 | ToolExecutionBatch::Parallel(items) => { |
| 1422 | assert_eq!( |
| 1423 | items.iter().map(|p| p.index).collect::<Vec<_>>(), |
| 1424 | vec![0, 1, 2] |
| 1425 | ); |
| 1426 | } |
| 1427 | ToolExecutionBatch::Serial(_) => panic!("disjoint waits and read should share batch"), |
| 1428 | } |
| 1429 | match &batches[1] { |
| 1430 | ToolExecutionBatch::Parallel(items) => { |
| 1431 | assert_eq!(items.iter().map(|p| p.index).collect::<Vec<_>>(), vec![3]); |
| 1432 | } |
| 1433 | ToolExecutionBatch::Serial(_) => panic!("overlapping wait should start next batch"), |
| 1434 | } |
| 1435 | assert!(matches!(&batches[2], ToolExecutionBatch::Serial(item) if item.index == 4)); |
| 1436 | } |
| 1437 | } |
| 1438 |