| 1 | #[test] |
| 2 | fn model_catalog_exposes_todo_write_as_sole_progress_surface() { |
| 3 | // #4132: ordinary progress is one model-visible and executable tool (todo_write). |
| 4 | let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default()); |
| 5 | let registry = engine |
| 6 | .build_turn_tool_registry_builder(AppMode::Agent, engine.config.todos.clone()) |
| 7 | .build(engine.build_tool_context(AppMode::Agent, false)); |
| 8 | let always_load = HashSet::new(); |
| 9 | let catalog = build_model_tool_catalog( |
| 10 | registry.to_api_tools_with_cache(true), |
| 11 | vec![], |
| 12 | AppMode::Agent, |
| 13 | &always_load, |
| 14 | ); |
| 15 | let active = initial_active_tools(&catalog); |
| 16 | let catalog_names: HashSet<&str> = catalog.iter().map(|tool| tool.name.as_str()).collect(); |
| 17 | |
| 18 | assert!( |
| 19 | catalog_names.contains("todo_write"), |
| 20 | "todo_write must be model-visible" |
| 21 | ); |
| 22 | assert!( |
| 23 | active.contains("todo_write"), |
| 24 | "todo_write must be available without a discovery turn" |
| 25 | ); |
| 26 | assert!( |
| 27 | !catalog_names.contains("update_plan"), |
| 28 | "retired Strategy/Plan must stay replay-only" |
| 29 | ); |
| 30 | for retired in [ |
| 31 | "work_update", |
| 32 | "TodoWrite", |
| 33 | "todo", |
| 34 | "checklist_write", |
| 35 | "checklist_update", |
| 36 | "checklist_add", |
| 37 | "checklist_list", |
| 38 | "todo_add", |
| 39 | "todo_update", |
| 40 | "todo_list", |
| 41 | ] { |
| 42 | assert!( |
| 43 | !registry.contains(retired), |
| 44 | "{retired} must not be callable" |
| 45 | ); |
| 46 | assert!( |
| 47 | !catalog_names.contains(retired), |
| 48 | "{retired} must not appear in the model catalog" |
| 49 | ); |
| 50 | } |
| 51 | for retired in [ |
| 52 | "checklist_write", |
| 53 | "checklist_add", |
| 54 | "checklist_update", |
| 55 | "checklist_list", |
| 56 | "work_update", |
| 57 | "TodoWrite", |
| 58 | "todo", |
| 59 | "todo_add", |
| 60 | "todo_update", |
| 61 | "todo_list", |
| 62 | ] { |
| 63 | assert!( |
| 64 | preflight_requested_deferred_tool( |
| 65 | retired, |
| 66 | &json!({ |
| 67 | "todos": [ |
| 68 | { "content": "should not hydrate hidden alias", "status": "completed" } |
| 69 | ] |
| 70 | }), |
| 71 | &catalog, |
| 72 | &mut active.clone(), |
| 73 | ) |
| 74 | .is_none(), |
| 75 | "{retired} must not have a deferred catalog preflight path" |
| 76 | ); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | #[test] |
| 81 | fn user_shell_turn_outcome_distinguishes_cancel_failure_and_success() { |
| 82 | let cancelled = Ok( |
| 83 | ToolResult::error("Command canceled; process killed.").with_metadata(json!({ |
| 84 | "status": "Killed", |
| 85 | "canceled": true, |
| 86 | })), |
| 87 | ); |
| 88 | assert_eq!( |
| 89 | user_shell_turn_outcome(&cancelled, false), |
| 90 | TurnOutcomeStatus::Interrupted |
| 91 | ); |
| 92 | |
| 93 | let cancelled_while_awaiting_approval = Err(ToolError::execution_failed( |
| 94 | "Request cancelled while awaiting approval", |
| 95 | )); |
| 96 | assert_eq!( |
| 97 | user_shell_turn_outcome(&cancelled_while_awaiting_approval, true), |
| 98 | TurnOutcomeStatus::Interrupted |
| 99 | ); |
| 100 | |
| 101 | let failed = Ok(ToolResult::error("Command failed (exit code: 1)")); |
| 102 | assert_eq!( |
| 103 | user_shell_turn_outcome(&failed, false), |
| 104 | TurnOutcomeStatus::Failed |
| 105 | ); |
| 106 | |
| 107 | let execution_error = Err(ToolError::execution_failed("shell manager unavailable")); |
| 108 | assert_eq!( |
| 109 | user_shell_turn_outcome(&execution_error, false), |
| 110 | TurnOutcomeStatus::Failed |
| 111 | ); |
| 112 | |
| 113 | let completed = Ok(ToolResult::success("done")); |
| 114 | assert_eq!( |
| 115 | user_shell_turn_outcome(&completed, true), |
| 116 | TurnOutcomeStatus::Interrupted |
| 117 | ); |
| 118 | assert_eq!( |
| 119 | user_shell_turn_outcome(&completed, false), |
| 120 | TurnOutcomeStatus::Completed |
| 121 | ); |
| 122 | } |
| 123 | |
| 124 | /// #5191: a user-typed `!` command is pre-approved by provenance — typing it |
| 125 | /// IS the approval. It must run without the tool-approval modal even in an |
| 126 | /// Ask/Suggest session, and the audit trail must record the user provenance. |
| 127 | #[tokio::test] |
| 128 | async fn run_shell_command_op_executes_without_approval_modal() { |
| 129 | let _guard = lock_test_env(); |
| 130 | let tmp = tempdir().expect("tempdir"); |
| 131 | let audit_path = tmp.path().join("tool-audit.jsonl"); |
| 132 | let _audit = EnvVarGuard::set("CODEWHALE_TOOL_AUDIT_LOG", &audit_path); |
| 133 | let (mut engine, handle) = Engine::new(EngineConfig::default(), &Config::default()); |
| 134 | engine.session.allow_shell = false; |
| 135 | engine.config.allow_shell = false; |
| 136 | |
| 137 | engine |
| 138 | .handle_run_shell_command( |
| 139 | "echo bang-ok".to_string(), |
| 140 | AppMode::Agent, |
| 141 | true, |
| 142 | false, |
| 143 | false, |
| 144 | ApprovalMode::Suggest, |
| 145 | ) |
| 146 | .await; |
| 147 | |
| 148 | let mut saw_started = false; |
| 149 | let mut saw_approval = false; |
| 150 | let mut saw_complete = false; |
| 151 | let mut saw_turn_complete = false; |
| 152 | let mut rx = handle.rx_event.write().await; |
| 153 | while let Some(event) = rx.recv().await { |
| 154 | match event { |
| 155 | Event::TurnStarted { turn_id, route, .. } => { |
| 156 | assert!(turn_id.starts_with(USER_SHELL_TOOL_ID_PREFIX)); |
| 157 | assert!(route.is_none()); |
| 158 | } |
| 159 | Event::ToolCallStarted { |
| 160 | id, |
| 161 | name, |
| 162 | input, |
| 163 | model_call, |
| 164 | } => { |
| 165 | saw_started = true; |
| 166 | assert!(model_call.is_none()); |
| 167 | assert!(id.starts_with(USER_SHELL_TOOL_ID_PREFIX)); |
| 168 | assert_eq!(name, "bash"); |
| 169 | assert_eq!(input["command"], json!("echo bang-ok")); |
| 170 | assert_eq!(input["source"], json!("user")); |
| 171 | } |
| 172 | Event::ApprovalRequired { .. } => { |
| 173 | saw_approval = true; |
| 174 | } |
| 175 | Event::ToolCallComplete { |
| 176 | id, |
| 177 | name, |
| 178 | result, |
| 179 | model_call, |
| 180 | } => { |
| 181 | saw_complete = true; |
| 182 | assert!(model_call.is_none()); |
| 183 | assert!(id.starts_with(USER_SHELL_TOOL_ID_PREFIX)); |
| 184 | assert_eq!(name, "bash"); |
| 185 | let result = result.expect("shell result"); |
| 186 | assert!(result.success, "{result:?}"); |
| 187 | assert!(result.content.contains("bang-ok"), "{result:?}"); |
| 188 | } |
| 189 | Event::TurnComplete { status, .. } => { |
| 190 | saw_turn_complete = true; |
| 191 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 192 | break; |
| 193 | } |
| 194 | _ => {} |
| 195 | } |
| 196 | } |
| 197 | drop(rx); |
| 198 | |
| 199 | assert!(saw_started); |
| 200 | assert!( |
| 201 | !saw_approval, |
| 202 | "user-typed bang commands must not raise the approval modal (#5191)" |
| 203 | ); |
| 204 | assert!(saw_complete); |
| 205 | assert!(saw_turn_complete); |
| 206 | |
| 207 | let audit = std::fs::read_to_string(&audit_path).expect("audit log written"); |
| 208 | assert!( |
| 209 | audit.contains("tool.user_provenance_preapproved"), |
| 210 | "audit trail must record the user-provenance pre-approval: {audit}" |
| 211 | ); |
| 212 | assert!( |
| 213 | audit.contains("composer_bang"), |
| 214 | "audit row must name the composer-bang source: {audit}" |
| 215 | ); |
| 216 | } |
| 217 | |
| 218 | #[tokio::test] |
| 219 | async fn run_shell_command_op_skips_approval_when_auto_approved() { |
| 220 | let workspace = tempdir().expect("tempdir"); |
| 221 | let todos = crate::tools::todo::new_shared_todo_list(); |
| 222 | let plan = crate::tools::plan::new_shared_plan_state(); |
| 223 | let work = crate::work_graph::new_shared_work_runtime(todos, plan); |
| 224 | let runtime_services = crate::tools::spec::RuntimeToolServices { |
| 225 | work: Some(work.clone()), |
| 226 | ..Default::default() |
| 227 | }; |
| 228 | let (mut engine, handle) = Engine::new( |
| 229 | EngineConfig { |
| 230 | workspace: workspace.path().to_path_buf(), |
| 231 | snapshots_enabled: false, |
| 232 | runtime_services, |
| 233 | ..EngineConfig::default() |
| 234 | }, |
| 235 | &Config::default(), |
| 236 | ); |
| 237 | let session_id = engine.session.id.clone(); |
| 238 | |
| 239 | engine |
| 240 | .handle_run_shell_command( |
| 241 | "echo bang-yolo".to_string(), |
| 242 | AppMode::Agent, |
| 243 | true, |
| 244 | true, |
| 245 | true, |
| 246 | ApprovalMode::Auto, |
| 247 | ) |
| 248 | .await; |
| 249 | |
| 250 | let mut saw_complete = false; |
| 251 | let mut rx = handle.rx_event.write().await; |
| 252 | while let Some(event) = rx.recv().await { |
| 253 | match event { |
| 254 | Event::ApprovalRequired { .. } => { |
| 255 | panic!("auto-approved shell shortcut should not request approval"); |
| 256 | } |
| 257 | Event::ToolCallComplete { result, .. } => { |
| 258 | saw_complete = true; |
| 259 | let result = result.expect("shell result"); |
| 260 | assert!(result.success, "{result:?}"); |
| 261 | assert!(result.content.contains("bang-yolo"), "{result:?}"); |
| 262 | } |
| 263 | Event::TurnComplete { status, .. } => { |
| 264 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 265 | break; |
| 266 | } |
| 267 | _ => {} |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | assert!(saw_complete); |
| 272 | let graph = work |
| 273 | .capture(Some(&session_id)) |
| 274 | .expect("capture bang-shell work") |
| 275 | .expect("bang-shell graph") |
| 276 | .graph; |
| 277 | let operation = graph |
| 278 | .nodes |
| 279 | .iter() |
| 280 | .find(|node| node.kind == crate::work_graph::NodeKind::Operation) |
| 281 | .expect("bang-shell operation registered before execution"); |
| 282 | assert_eq!(operation.state, crate::work_graph::NodeState::Completed); |
| 283 | let observation = operation |
| 284 | .binding |
| 285 | .as_ref() |
| 286 | .and_then(|binding| binding.last_observation.as_ref()) |
| 287 | .expect("terminal shell owner observation"); |
| 288 | assert!( |
| 289 | observation |
| 290 | .output |
| 291 | .as_ref() |
| 292 | .and_then(crate::work_graph::EvidenceRef::raw_bytes) |
| 293 | .is_some_and(|raw_bytes| raw_bytes > 0), |
| 294 | "bang-shell completion must retain a logical byte-count receipt" |
| 295 | ); |
| 296 | } |
| 297 | |
| 298 | #[tokio::test] |
| 299 | async fn run_shell_command_op_allows_readonly_shell_in_auto_mode() { |
| 300 | let (mut engine, handle) = Engine::new(EngineConfig::default(), &Config::default()); |
| 301 | let handle_for_approval = handle.clone(); |
| 302 | |
| 303 | let task = tokio::spawn(async move { |
| 304 | engine |
| 305 | .handle_run_shell_command( |
| 306 | "pwd".to_string(), |
| 307 | AppMode::Agent, |
| 308 | true, |
| 309 | false, |
| 310 | false, |
| 311 | ApprovalMode::Auto, |
| 312 | ) |
| 313 | .await; |
| 314 | }); |
| 315 | |
| 316 | let mut saw_approval = false; |
| 317 | let mut saw_complete = false; |
| 318 | let mut rx = handle.rx_event.write().await; |
| 319 | while let Some(event) = rx.recv().await { |
| 320 | match event { |
| 321 | Event::ApprovalRequired { id, .. } => { |
| 322 | saw_approval = true; |
| 323 | handle_for_approval |
| 324 | .approve_tool_call(id) |
| 325 | .await |
| 326 | .expect("approve unexpected shell prompt"); |
| 327 | } |
| 328 | Event::ToolCallComplete { result, .. } => { |
| 329 | saw_complete = true; |
| 330 | let result = result.expect("shell result"); |
| 331 | assert!(result.success, "{result:?}"); |
| 332 | } |
| 333 | Event::TurnComplete { status, .. } => { |
| 334 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 335 | break; |
| 336 | } |
| 337 | _ => {} |
| 338 | } |
| 339 | } |
| 340 | drop(rx); |
| 341 | task.await.expect("shell op task"); |
| 342 | |
| 343 | assert!( |
| 344 | !saw_approval, |
| 345 | "read-only shell shortcut should not request approval in Auto mode" |
| 346 | ); |
| 347 | assert!(saw_complete); |
| 348 | } |
| 349 | |
| 350 | #[tokio::test] |
| 351 | async fn yolo_mode_does_not_prompt_for_typed_ask_rule() { |
| 352 | // #3386: a command matching a typed ask-rule (permissions.toml) must not |
| 353 | // surface an approval modal in the Full Access posture, even though the |
| 354 | // stale ApprovalMode::Auto maps to OnFailure in the execpolicy (honors |
| 355 | // ask-rules). The auto_review safety floor and typed deny rules still |
| 356 | // apply; only the ask-rule Prompt is suppressed under Full Access. |
| 357 | let (mut engine, handle) = Engine::new( |
| 358 | EngineConfig { |
| 359 | exec_policy_engine: ask_rule_engine("echo"), |
| 360 | ..EngineConfig::default() |
| 361 | }, |
| 362 | &Config::default(), |
| 363 | ); |
| 364 | |
| 365 | engine |
| 366 | .handle_run_shell_command( |
| 367 | "echo yolo-ask-rule".to_string(), |
| 368 | AppMode::Agent, |
| 369 | true, |
| 370 | true, |
| 371 | true, |
| 372 | ApprovalMode::Auto, |
| 373 | ) |
| 374 | .await; |
| 375 | |
| 376 | let mut saw_complete = false; |
| 377 | let mut rx = handle.rx_event.write().await; |
| 378 | while let Some(event) = rx.recv().await { |
| 379 | match event { |
| 380 | Event::ApprovalRequired { .. } => { |
| 381 | panic!("YOLO mode must not prompt for a typed ask-rule"); |
| 382 | } |
| 383 | Event::ToolCallComplete { result, .. } => { |
| 384 | saw_complete = true; |
| 385 | let result = result.expect("shell result"); |
| 386 | assert!(result.success, "{result:?}"); |
| 387 | assert!(result.content.contains("yolo-ask-rule"), "{result:?}"); |
| 388 | } |
| 389 | Event::TurnComplete { status, .. } => { |
| 390 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 391 | break; |
| 392 | } |
| 393 | _ => {} |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | assert!(saw_complete); |
| 398 | } |
| 399 | |
| 400 | #[tokio::test] |
| 401 | #[allow(clippy::await_holding_lock)] |
| 402 | async fn operate_model_shell_uses_normal_approval_and_workspace_sandbox() { |
| 403 | use wiremock::matchers::{body_string_contains, method, path}; |
| 404 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 405 | |
| 406 | let _lock = lock_test_env(); |
| 407 | let workspace = tempdir().expect("tempdir"); |
| 408 | let server = MockServer::start().await; |
| 409 | |
| 410 | let tool_call_sse = concat!( |
| 411 | "data: {\"id\":\"chatcmpl-operate-tools\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[", |
| 412 | "{\"index\":0,\"id\":\"call_operate_shell\",\"type\":\"function\",\"function\":{\"name\":\"bash\",", |
| 413 | "\"arguments\":\"{\\\"command\\\":\\\"echo operate-approved > operate-mode-approved.txt\\\"}\"}}", |
| 414 | "]},\"finish_reason\":null}]}\n\n", |
| 415 | "data: {\"id\":\"chatcmpl-operate-tools\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 416 | "\"finish_reason\":\"tool_calls\"}]}\n\n", |
| 417 | "data: [DONE]\n\n", |
| 418 | ); |
| 419 | let done_sse = concat!( |
| 420 | "data: {\"id\":\"chatcmpl-operate-done\",\"choices\":[{\"index\":0,", |
| 421 | "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n", |
| 422 | "data: {\"id\":\"chatcmpl-operate-done\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 423 | "\"finish_reason\":\"stop\"}]}\n\n", |
| 424 | "data: [DONE]\n\n", |
| 425 | ); |
| 426 | // The goal this fixture seals is seeded directly (prose no longer |
| 427 | // creates goals since the #6290 rework); after the approved shell runs, |
| 428 | // the model seals it through the same `update_goal` tool a live Operate |
| 429 | // turn uses, and only then does the final "done" arrive. |
| 430 | let goal_seal_marker = "goal-seal-receipt-0902"; |
| 431 | let goal_sse = concat!( |
| 432 | "data: {\"id\":\"chatcmpl-operate-goal\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[", |
| 433 | "{\"index\":0,\"id\":\"call_operate_goal\",\"type\":\"function\",\"function\":{\"name\":\"update_goal\",", |
| 434 | "\"arguments\":\"{\\\"status\\\":\\\"complete\\\",\\\"evidence\\\":\\\"goal-seal-receipt-0902: operate-mode-approved.txt written\\\",", |
| 435 | "\\\"verification\\\":{\\\"status\\\":\\\"passed\\\",\\\"check\\\":\\\"cat operate-mode-approved.txt\\\",\\\"summary\\\":\\\"fixture contains operate-approved\\\"}}\"}}", |
| 436 | "]},\"finish_reason\":null}]}\n\n", |
| 437 | "data: {\"id\":\"chatcmpl-operate-goal\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 438 | "\"finish_reason\":\"tool_calls\"}]}\n\n", |
| 439 | "data: [DONE]\n\n", |
| 440 | ); |
| 441 | |
| 442 | Mock::given(method("POST")) |
| 443 | .and(path("/v1/chat/completions")) |
| 444 | .and(body_string_contains(goal_seal_marker)) |
| 445 | .and(body_string_contains("tokens_used")) |
| 446 | .respond_with( |
| 447 | ResponseTemplate::new(200) |
| 448 | .insert_header("content-type", "text/event-stream") |
| 449 | .set_body_string(done_sse), |
| 450 | ) |
| 451 | .expect(1) |
| 452 | .with_priority(1) |
| 453 | .mount(&server) |
| 454 | .await; |
| 455 | // Goal control must execute immediately: continuation cannot depend on |
| 456 | // discovering or retrying the very tool that lets the model stop it. |
| 457 | Mock::given(method("POST")) |
| 458 | .and(path("/v1/chat/completions")) |
| 459 | .and(body_string_contains("was deferred and has now been loaded")) |
| 460 | .respond_with( |
| 461 | ResponseTemplate::new(200) |
| 462 | .insert_header("content-type", "text/event-stream") |
| 463 | .set_body_string(goal_sse), |
| 464 | ) |
| 465 | .expect(0) |
| 466 | .with_priority(2) |
| 467 | .mount(&server) |
| 468 | .await; |
| 469 | Mock::given(method("POST")) |
| 470 | .and(path("/v1/chat/completions")) |
| 471 | .and(body_string_contains("operate-mode-approved.txt")) |
| 472 | .respond_with( |
| 473 | ResponseTemplate::new(200) |
| 474 | .insert_header("content-type", "text/event-stream") |
| 475 | .set_body_string(goal_sse), |
| 476 | ) |
| 477 | .expect(1) |
| 478 | .with_priority(3) |
| 479 | .mount(&server) |
| 480 | .await; |
| 481 | Mock::given(method("POST")) |
| 482 | .and(path("/v1/chat/completions")) |
| 483 | .respond_with( |
| 484 | ResponseTemplate::new(200) |
| 485 | .insert_header("content-type", "text/event-stream") |
| 486 | .set_body_string(tool_call_sse), |
| 487 | ) |
| 488 | .expect(1) |
| 489 | .with_priority(3) |
| 490 | .mount(&server) |
| 491 | .await; |
| 492 | |
| 493 | let api_config = |
| 494 | Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri())); |
| 495 | let (engine, handle) = Engine::new( |
| 496 | EngineConfig { |
| 497 | model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(), |
| 498 | workspace: workspace.path().to_path_buf(), |
| 499 | snapshots_enabled: false, |
| 500 | subagents_enabled: false, |
| 501 | terminal_chrome_enabled: false, |
| 502 | ..EngineConfig::default() |
| 503 | }, |
| 504 | &api_config, |
| 505 | ); |
| 506 | engine |
| 507 | .config |
| 508 | .goal_state |
| 509 | .lock() |
| 510 | .expect("goal lock") |
| 511 | .create("write the requested local fixture".to_string(), None) |
| 512 | .expect("seed fixture goal"); |
| 513 | let handle_for_approval = handle.clone(); |
| 514 | let run_task = tokio::spawn(engine.run()); |
| 515 | |
| 516 | handle |
| 517 | .send(Op::SendMessage(TurnSpec { |
| 518 | profile_constitution: None, |
| 519 | max_output_tokens: None, |
| 520 | content: "Write the requested local fixture to the workspace".to_string(), |
| 521 | images: Vec::new(), |
| 522 | mode: AppMode::Agent, |
| 523 | route: resolved_route_for_test( |
| 524 | &api_config, |
| 525 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 526 | ), |
| 527 | compaction: Box::new(CompactionConfig::default()), |
| 528 | initial_routed_usage: Box::default(), |
| 529 | goal_objective: Some("write the requested local fixture".to_string()), |
| 530 | goal_token_budget: None, |
| 531 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 532 | reasoning_effort: None, |
| 533 | reasoning_effort_auto: false, |
| 534 | auto_model: false, |
| 535 | allow_shell: true, |
| 536 | trust_mode: false, |
| 537 | auto_approve: false, |
| 538 | approval_mode: ApprovalMode::Suggest, |
| 539 | translation_enabled: false, |
| 540 | allowed_tools: None, |
| 541 | dynamic_tools: Vec::new(), |
| 542 | hook_executor: None, |
| 543 | verbosity: None, |
| 544 | provenance: UserInputProvenance::ExternalUser, |
| 545 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 546 | submission_id: None, |
| 547 | })) |
| 548 | .await |
| 549 | .expect("send Operate model turn"); |
| 550 | |
| 551 | let mut saw_approval = false; |
| 552 | let mut saw_shell_result = false; |
| 553 | let mut saw_complete = false; |
| 554 | let mut rx = handle.rx_event.write().await; |
| 555 | while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv()) |
| 556 | .await |
| 557 | .expect("timed out waiting for Operate tool event") |
| 558 | { |
| 559 | match event { |
| 560 | Event::ApprovalRequired { id, tool_name, .. } => { |
| 561 | saw_approval = true; |
| 562 | assert_eq!(tool_name, "bash"); |
| 563 | // The seeded fixture goal is orthogonal to this gate: |
| 564 | // Operate uses the normal approval flow either way. |
| 565 | handle_for_approval |
| 566 | .approve_tool_call(id) |
| 567 | .await |
| 568 | .expect("approve Operate shell"); |
| 569 | } |
| 570 | Event::ToolCallComplete { name, result, .. } if name == "bash" => { |
| 571 | saw_shell_result = true; |
| 572 | let result = result.expect("approved Operate shell result"); |
| 573 | assert!(result.success, "{result:?}"); |
| 574 | } |
| 575 | Event::TurnComplete { status, .. } => { |
| 576 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 577 | saw_complete = true; |
| 578 | break; |
| 579 | } |
| 580 | _ => {} |
| 581 | } |
| 582 | } |
| 583 | drop(rx); |
| 584 | |
| 585 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 586 | run_task.await.expect("engine task"); |
| 587 | |
| 588 | assert!( |
| 589 | saw_approval, |
| 590 | "Operate should use the normal approval gate instead of a mode-only denial" |
| 591 | ); |
| 592 | assert!(saw_shell_result); |
| 593 | assert!(saw_complete); |
| 594 | let requests = server.received_requests().await.expect("recorded requests"); |
| 595 | let first: serde_json::Value = serde_json::from_slice(&requests[0].body).expect("request JSON"); |
| 596 | for name in ["create_goal", "get_goal", "update_goal"] { |
| 597 | assert!( |
| 598 | first["tools"] |
| 599 | .as_array() |
| 600 | .expect("wire tools") |
| 601 | .iter() |
| 602 | .any(|tool| tool["function"]["name"] == name), |
| 603 | "first provider request must expose {name} without discovery" |
| 604 | ); |
| 605 | } |
| 606 | let written = std::fs::read_to_string(workspace.path().join("operate-mode-approved.txt")) |
| 607 | .expect("workspace-scoped shell output"); |
| 608 | assert_eq!(written.trim_end(), "operate-approved"); |
| 609 | } |
| 610 | |
| 611 | /// Drives one model turn whose single `Bash` call needs approval, publishes |
| 612 | /// `change_to` (as a runtime PATCH does) while the approval is pending, then |
| 613 | /// approves. Returns the call's result and whether the file was written. |
| 614 | async fn posture_change_during_approval_wait( |
| 615 | change_to: (AppMode, ApprovalMode, bool), |
| 616 | ) -> (Result<crate::tools::spec::ToolResult, ToolError>, bool) { |
| 617 | use wiremock::matchers::{body_string_contains, method, path}; |
| 618 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 619 | |
| 620 | let workspace = tempdir().expect("tempdir"); |
| 621 | let server = MockServer::start().await; |
| 622 | let tool_call_sse = concat!( |
| 623 | "data: {\"id\":\"chatcmpl-e2\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[", |
| 624 | "{\"index\":0,\"id\":\"call_e2_shell\",\"type\":\"function\",\"function\":{\"name\":\"bash\",", |
| 625 | "\"arguments\":\"{\\\"command\\\":\\\"echo approved > e2-approved.txt\\\"}\"}}", |
| 626 | "]},\"finish_reason\":null}]}\n\n", |
| 627 | "data: {\"id\":\"chatcmpl-e2\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 628 | "\"finish_reason\":\"tool_calls\"}]}\n\n", |
| 629 | "data: [DONE]\n\n", |
| 630 | ); |
| 631 | let done_sse = concat!( |
| 632 | "data: {\"id\":\"chatcmpl-e2-done\",\"choices\":[{\"index\":0,", |
| 633 | "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n", |
| 634 | "data: {\"id\":\"chatcmpl-e2-done\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 635 | "\"finish_reason\":\"stop\"}]}\n\n", |
| 636 | "data: [DONE]\n\n", |
| 637 | ); |
| 638 | Mock::given(method("POST")) |
| 639 | .and(path("/v1/chat/completions")) |
| 640 | .and(body_string_contains("call_e2_shell")) |
| 641 | .respond_with( |
| 642 | ResponseTemplate::new(200) |
| 643 | .insert_header("content-type", "text/event-stream") |
| 644 | .set_body_string(done_sse), |
| 645 | ) |
| 646 | .with_priority(1) |
| 647 | .mount(&server) |
| 648 | .await; |
| 649 | Mock::given(method("POST")) |
| 650 | .and(path("/v1/chat/completions")) |
| 651 | .respond_with( |
| 652 | ResponseTemplate::new(200) |
| 653 | .insert_header("content-type", "text/event-stream") |
| 654 | .set_body_string(tool_call_sse), |
| 655 | ) |
| 656 | .expect(1) |
| 657 | .with_priority(2) |
| 658 | .mount(&server) |
| 659 | .await; |
| 660 | |
| 661 | let api_config = |
| 662 | Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri())); |
| 663 | let (engine, handle) = Engine::new( |
| 664 | EngineConfig { |
| 665 | model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(), |
| 666 | workspace: workspace.path().to_path_buf(), |
| 667 | snapshots_enabled: false, |
| 668 | subagents_enabled: false, |
| 669 | terminal_chrome_enabled: false, |
| 670 | ..EngineConfig::default() |
| 671 | }, |
| 672 | &api_config, |
| 673 | ); |
| 674 | let run_task = tokio::spawn(engine.run()); |
| 675 | handle |
| 676 | .send(Op::SendMessage(TurnSpec { |
| 677 | profile_constitution: None, |
| 678 | max_output_tokens: None, |
| 679 | content: "Record the approval fixture in the workspace".to_string(), |
| 680 | images: Vec::new(), |
| 681 | mode: AppMode::Agent, |
| 682 | route: resolved_route_for_test( |
| 683 | &api_config, |
| 684 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 685 | ), |
| 686 | compaction: Box::new(CompactionConfig::default()), |
| 687 | initial_routed_usage: Box::default(), |
| 688 | goal_objective: None, |
| 689 | goal_token_budget: None, |
| 690 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 691 | reasoning_effort: None, |
| 692 | reasoning_effort_auto: false, |
| 693 | auto_model: false, |
| 694 | allow_shell: true, |
| 695 | trust_mode: false, |
| 696 | auto_approve: false, |
| 697 | approval_mode: ApprovalMode::Suggest, |
| 698 | translation_enabled: false, |
| 699 | allowed_tools: None, |
| 700 | dynamic_tools: Vec::new(), |
| 701 | hook_executor: None, |
| 702 | verbosity: None, |
| 703 | provenance: UserInputProvenance::ExternalUser, |
| 704 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 705 | submission_id: None, |
| 706 | })) |
| 707 | .await |
| 708 | .expect("send model turn"); |
| 709 | |
| 710 | let (mode, approval_mode, auto_approve) = change_to; |
| 711 | let mut shell_result = None; |
| 712 | let mut rx = handle.rx_event.write().await; |
| 713 | while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv()) |
| 714 | .await |
| 715 | .expect("timed out waiting for turn event") |
| 716 | { |
| 717 | match event { |
| 718 | Event::ApprovalRequired { id, .. } => { |
| 719 | // The PATCH lands while the approval card is open. |
| 720 | handle |
| 721 | .try_send(Op::ChangeMode { |
| 722 | mode, |
| 723 | allow_shell: true, |
| 724 | trust_mode: false, |
| 725 | auto_approve, |
| 726 | approval_mode, |
| 727 | configured_sandbox_mode: None, |
| 728 | }) |
| 729 | .expect("publish posture change"); |
| 730 | handle.approve_tool_call(id).await.expect("approve shell"); |
| 731 | } |
| 732 | Event::ToolCallComplete { name, result, .. } if name == "bash" => { |
| 733 | shell_result = Some(result); |
| 734 | } |
| 735 | Event::TurnComplete { .. } => break, |
| 736 | _ => {} |
| 737 | } |
| 738 | } |
| 739 | drop(rx); |
| 740 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 741 | run_task.await.expect("engine task"); |
| 742 | let written = workspace.path().join("e2-approved.txt").exists(); |
| 743 | (shell_result.expect("the approved call completes"), written) |
| 744 | } |
| 745 | |
| 746 | #[test] |
| 747 | fn live_runtime_authority_narrows_only_when_a_grant_is_withdrawn() { |
| 748 | let at = |mode, approval_mode, sandbox: Option<&str>| { |
| 749 | LiveRuntimeAuthority::from_fields( |
| 750 | mode, |
| 751 | true, |
| 752 | false, |
| 753 | approval_mode == ApprovalMode::Bypass, |
| 754 | approval_mode, |
| 755 | sandbox.map(str::to_string), |
| 756 | ) |
| 757 | }; |
| 758 | let ask = at(AppMode::Agent, ApprovalMode::Suggest, None); |
| 759 | assert!(!ask.narrows(&ask)); |
| 760 | assert!(!at(AppMode::Agent, ApprovalMode::Auto, None).narrows(&ask)); |
| 761 | assert!(!at(AppMode::Agent, ApprovalMode::Bypass, None).narrows(&ask)); |
| 762 | assert!(!ask.narrows(&at(AppMode::Plan, ApprovalMode::Suggest, None))); |
| 763 | assert!(at(AppMode::Plan, ApprovalMode::Suggest, None).narrows(&ask)); |
| 764 | assert!(ask.narrows(&at(AppMode::Agent, ApprovalMode::Bypass, None))); |
| 765 | assert!(at(AppMode::Agent, ApprovalMode::Never, None).narrows(&ask)); |
| 766 | assert!(at(AppMode::Agent, ApprovalMode::Suggest, Some("read-only")).narrows(&ask)); |
| 767 | assert!( |
| 768 | !at( |
| 769 | AppMode::Agent, |
| 770 | ApprovalMode::Suggest, |
| 771 | Some("workspace-write") |
| 772 | ) |
| 773 | .narrows(&at( |
| 774 | AppMode::Agent, |
| 775 | ApprovalMode::Suggest, |
| 776 | Some("read-only") |
| 777 | )) |
| 778 | ); |
| 779 | assert!(at(AppMode::Agent, ApprovalMode::Suggest, Some("custom")).narrows(&ask)); |
| 780 | let mut no_shell = ask.clone(); |
| 781 | no_shell.allow_shell = false; |
| 782 | assert!(no_shell.narrows(&ask)); |
| 783 | } |
| 784 | |
| 785 | /// E2: approving a call must never invalidate the call it approves. A posture |
| 786 | /// PATCH that is equal or broader (Ask -> Auto-Review, Ask -> Full Access) |
| 787 | /// while the approval card is open leaves the approved call running. |
| 788 | #[tokio::test] |
| 789 | #[allow(clippy::await_holding_lock)] |
| 790 | async fn broader_posture_patch_during_approval_wait_keeps_the_approved_call() { |
| 791 | let _lock = lock_test_env(); |
| 792 | for change_to in [ |
| 793 | (AppMode::Agent, ApprovalMode::Auto, false), |
| 794 | (AppMode::Agent, ApprovalMode::Bypass, true), |
| 795 | (AppMode::Agent, ApprovalMode::Suggest, false), |
| 796 | ] { |
| 797 | let (result, written) = posture_change_during_approval_wait(change_to).await; |
| 798 | let result = result.unwrap_or_else(|err| panic!("{change_to:?}: {err}")); |
| 799 | assert!(result.success, "{change_to:?}: {result:?}"); |
| 800 | assert!(written, "{change_to:?}: the approved shell ran"); |
| 801 | } |
| 802 | } |
| 803 | |
| 804 | /// E2 counterpart: a narrowing PATCH (Work -> Plan, Ask -> Never) still sends |
| 805 | /// the approved call back to the model instead of running it under a grant |
| 806 | /// the user has since withdrawn. |
| 807 | #[tokio::test] |
| 808 | #[allow(clippy::await_holding_lock)] |
| 809 | async fn narrower_posture_patch_during_approval_wait_fails_the_call() { |
| 810 | let _lock = lock_test_env(); |
| 811 | for change_to in [ |
| 812 | (AppMode::Plan, ApprovalMode::Suggest, false), |
| 813 | (AppMode::Agent, ApprovalMode::Never, false), |
| 814 | ] { |
| 815 | let (result, written) = posture_change_during_approval_wait(change_to).await; |
| 816 | let err = result.expect_err("narrowed posture fails the call"); |
| 817 | assert!( |
| 818 | err.to_string() |
| 819 | .contains("Permissions changed before this tool call executed"), |
| 820 | "{change_to:?}: {err}" |
| 821 | ); |
| 822 | assert!(!written, "{change_to:?}: the shell must not run"); |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | #[tokio::test] |
| 827 | #[allow(clippy::await_holding_lock)] |
| 828 | async fn full_access_subagent_handoff_keeps_model_shell_free_of_approval_prompts() { |
| 829 | use wiremock::matchers::{body_string_contains, method, path}; |
| 830 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 831 | |
| 832 | let _lock = lock_test_env(); |
| 833 | let workspace = tempdir().expect("tempdir"); |
| 834 | let server = MockServer::start().await; |
| 835 | |
| 836 | let tool_call_sse = concat!( |
| 837 | "data: {\"id\":\"chatcmpl-yolo\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[", |
| 838 | "{\"index\":0,\"id\":\"call_yolo\",\"type\":\"function\",\"function\":{\"name\":\"bash\",", |
| 839 | "\"arguments\":\"{\\\"command\\\":\\\"echo yolo-model-ask-rule\\\"}\"}}", |
| 840 | "]},\"finish_reason\":null}]}\n\n", |
| 841 | "data: {\"id\":\"chatcmpl-yolo\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 842 | "\"finish_reason\":\"tool_calls\"}]}\n\n", |
| 843 | "data: [DONE]\n\n", |
| 844 | ); |
| 845 | let done_sse = concat!( |
| 846 | "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,", |
| 847 | "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n", |
| 848 | "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 849 | "\"finish_reason\":\"stop\"}]}\n\n", |
| 850 | "data: [DONE]\n\n", |
| 851 | ); |
| 852 | |
| 853 | Mock::given(method("POST")) |
| 854 | .and(path("/v1/chat/completions")) |
| 855 | .and(body_string_contains("yolo-model-ask-rule")) |
| 856 | .respond_with( |
| 857 | ResponseTemplate::new(200) |
| 858 | .insert_header("content-type", "text/event-stream") |
| 859 | .set_body_string(done_sse), |
| 860 | ) |
| 861 | .expect(1) |
| 862 | .with_priority(1) |
| 863 | .mount(&server) |
| 864 | .await; |
| 865 | Mock::given(method("POST")) |
| 866 | .and(path("/v1/chat/completions")) |
| 867 | .respond_with( |
| 868 | ResponseTemplate::new(200) |
| 869 | .insert_header("content-type", "text/event-stream") |
| 870 | .set_body_string(tool_call_sse), |
| 871 | ) |
| 872 | .expect(1) |
| 873 | .with_priority(2) |
| 874 | .mount(&server) |
| 875 | .await; |
| 876 | |
| 877 | let api_config = |
| 878 | Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri())); |
| 879 | let (engine, handle) = Engine::new( |
| 880 | EngineConfig { |
| 881 | model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(), |
| 882 | workspace: workspace.path().to_path_buf(), |
| 883 | snapshots_enabled: false, |
| 884 | subagents_enabled: false, |
| 885 | exec_policy_engine: ask_rule_engine("echo"), |
| 886 | ..EngineConfig::default() |
| 887 | }, |
| 888 | &api_config, |
| 889 | ); |
| 890 | let run_task = tokio::spawn(engine.run()); |
| 891 | |
| 892 | handle |
| 893 | .send(Op::SendMessage(TurnSpec { |
| 894 | profile_constitution: None, |
| 895 | max_output_tokens: None, |
| 896 | content: "continue from the completed child".to_string(), |
| 897 | images: Vec::new(), |
| 898 | mode: AppMode::Agent, |
| 899 | route: resolved_route_for_test( |
| 900 | &api_config, |
| 901 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 902 | ), |
| 903 | compaction: Box::new(CompactionConfig::default()), |
| 904 | initial_routed_usage: Box::default(), |
| 905 | goal_objective: None, |
| 906 | goal_token_budget: None, |
| 907 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 908 | reasoning_effort: None, |
| 909 | reasoning_effort_auto: false, |
| 910 | auto_model: false, |
| 911 | allow_shell: true, |
| 912 | trust_mode: true, |
| 913 | // Exercise the valid legacy/host shape where the named posture is |
| 914 | // authoritative but the redundant bit is stale. |
| 915 | auto_approve: false, |
| 916 | approval_mode: ApprovalMode::Bypass, |
| 917 | translation_enabled: false, |
| 918 | allowed_tools: None, |
| 919 | dynamic_tools: Vec::new(), |
| 920 | hook_executor: None, |
| 921 | verbosity: None, |
| 922 | provenance: UserInputProvenance::SubAgentHandoff, |
| 923 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 924 | submission_id: None, |
| 925 | })) |
| 926 | .await |
| 927 | .expect("send model turn"); |
| 928 | |
| 929 | let mut saw_complete = false; |
| 930 | let mut rx = handle.rx_event.write().await; |
| 931 | while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv()) |
| 932 | .await |
| 933 | .expect("timed out waiting for engine event") |
| 934 | { |
| 935 | match event { |
| 936 | Event::ApprovalRequired { .. } => { |
| 937 | panic!("Full Access child handoff must not prompt for an ordinary shell call"); |
| 938 | } |
| 939 | Event::ToolCallComplete { name, result, .. } if name == "bash" => { |
| 940 | saw_complete = true; |
| 941 | let result = result.expect("shell result"); |
| 942 | assert!(result.success, "{result:?}"); |
| 943 | assert!(result.content.contains("yolo-model-ask-rule"), "{result:?}"); |
| 944 | } |
| 945 | Event::TurnComplete { status, .. } => { |
| 946 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 947 | break; |
| 948 | } |
| 949 | _ => {} |
| 950 | } |
| 951 | } |
| 952 | drop(rx); |
| 953 | |
| 954 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 955 | run_task.await.expect("engine task"); |
| 956 | assert!(saw_complete); |
| 957 | } |
| 958 | |
| 959 | async fn assert_full_access_model_tool_batch_is_blocked( |
| 960 | engine_config: EngineConfig, |
| 961 | tool_calls: Vec<(&'static str, serde_json::Value)>, |
| 962 | expected_errors: &[(&str, &str)], |
| 963 | followup_fragment: &str, |
| 964 | ) { |
| 965 | use wiremock::matchers::{body_string_contains, method, path}; |
| 966 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 967 | |
| 968 | let server = MockServer::start().await; |
| 969 | let model_tool_calls = tool_calls |
| 970 | .iter() |
| 971 | .enumerate() |
| 972 | .map(|(index, (name, arguments))| { |
| 973 | json!({ |
| 974 | "index": index, |
| 975 | "id": format!("call_full_access_{index}"), |
| 976 | "type": "function", |
| 977 | "function": { |
| 978 | "name": name, |
| 979 | "arguments": arguments.to_string(), |
| 980 | }, |
| 981 | }) |
| 982 | }) |
| 983 | .collect::<Vec<_>>(); |
| 984 | let tool_delta = json!({ |
| 985 | "id": "chatcmpl-full-access-blocked", |
| 986 | "choices": [{ |
| 987 | "index": 0, |
| 988 | "delta": {"tool_calls": model_tool_calls}, |
| 989 | "finish_reason": serde_json::Value::Null, |
| 990 | }], |
| 991 | }); |
| 992 | let tool_finish = json!({ |
| 993 | "id": "chatcmpl-full-access-blocked", |
| 994 | "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}], |
| 995 | }); |
| 996 | let tool_call_sse = format!("data: {tool_delta}\n\ndata: {tool_finish}\n\ndata: [DONE]\n\n"); |
| 997 | let done_sse = concat!( |
| 998 | "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,", |
| 999 | "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n", |
| 1000 | "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 1001 | "\"finish_reason\":\"stop\"}]}\n\n", |
| 1002 | "data: [DONE]\n\n", |
| 1003 | ); |
| 1004 | |
| 1005 | Mock::given(method("POST")) |
| 1006 | .and(path("/v1/chat/completions")) |
| 1007 | .and(body_string_contains(followup_fragment)) |
| 1008 | .respond_with( |
| 1009 | ResponseTemplate::new(200) |
| 1010 | .insert_header("content-type", "text/event-stream") |
| 1011 | .set_body_string(done_sse), |
| 1012 | ) |
| 1013 | .expect(1) |
| 1014 | .with_priority(1) |
| 1015 | .mount(&server) |
| 1016 | .await; |
| 1017 | Mock::given(method("POST")) |
| 1018 | .and(path("/v1/chat/completions")) |
| 1019 | .respond_with( |
| 1020 | ResponseTemplate::new(200) |
| 1021 | .insert_header("content-type", "text/event-stream") |
| 1022 | .set_body_string(tool_call_sse), |
| 1023 | ) |
| 1024 | .expect(1) |
| 1025 | .with_priority(2) |
| 1026 | .mount(&server) |
| 1027 | .await; |
| 1028 | |
| 1029 | let api_config = |
| 1030 | Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri())); |
| 1031 | let (engine, handle) = Engine::new(engine_config, &api_config); |
| 1032 | let run_task = tokio::spawn(engine.run()); |
| 1033 | |
| 1034 | handle |
| 1035 | .send(Op::SendMessage(TurnSpec { |
| 1036 | profile_constitution: None, |
| 1037 | max_output_tokens: None, |
| 1038 | content: "exercise the Full Access execution boundary".to_string(), |
| 1039 | images: Vec::new(), |
| 1040 | mode: AppMode::Agent, |
| 1041 | route: resolved_route_for_test( |
| 1042 | &api_config, |
| 1043 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 1044 | ), |
| 1045 | compaction: Box::new(CompactionConfig::default()), |
| 1046 | initial_routed_usage: Box::default(), |
| 1047 | goal_objective: None, |
| 1048 | goal_token_budget: None, |
| 1049 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 1050 | reasoning_effort: None, |
| 1051 | reasoning_effort_auto: false, |
| 1052 | auto_model: false, |
| 1053 | allow_shell: true, |
| 1054 | trust_mode: true, |
| 1055 | auto_approve: true, |
| 1056 | approval_mode: ApprovalMode::Bypass, |
| 1057 | translation_enabled: false, |
| 1058 | allowed_tools: None, |
| 1059 | dynamic_tools: Vec::new(), |
| 1060 | hook_executor: None, |
| 1061 | verbosity: None, |
| 1062 | provenance: UserInputProvenance::ExternalUser, |
| 1063 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 1064 | submission_id: None, |
| 1065 | })) |
| 1066 | .await |
| 1067 | .expect("send Full Access model turn"); |
| 1068 | |
| 1069 | let expected = expected_errors.iter().copied().collect::<HashMap<_, _>>(); |
| 1070 | let mut seen = HashSet::new(); |
| 1071 | let mut saw_turn_complete = false; |
| 1072 | let mut rx = handle.rx_event.write().await; |
| 1073 | while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv()) |
| 1074 | .await |
| 1075 | .expect("timed out waiting for Full Access boundary event") |
| 1076 | { |
| 1077 | match event { |
| 1078 | Event::ApprovalRequired { tool_name, .. } => { |
| 1079 | panic!("Full Access must not open an approval modal for blocked tool {tool_name}") |
| 1080 | } |
| 1081 | Event::ToolCallComplete { name, result, .. } |
| 1082 | if expected.contains_key(name.as_str()) => |
| 1083 | { |
| 1084 | let error = result.expect_err("blocked tool must return an error"); |
| 1085 | let fragment = expected[name.as_str()]; |
| 1086 | assert!( |
| 1087 | error.to_string().contains(fragment), |
| 1088 | "unexpected {name} denial: {error:?}" |
| 1089 | ); |
| 1090 | seen.insert(name); |
| 1091 | } |
| 1092 | Event::TurnComplete { status, .. } => { |
| 1093 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 1094 | saw_turn_complete = true; |
| 1095 | break; |
| 1096 | } |
| 1097 | _ => {} |
| 1098 | } |
| 1099 | } |
| 1100 | drop(rx); |
| 1101 | |
| 1102 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1103 | run_task.await.expect("engine task"); |
| 1104 | assert_eq!(seen.len(), expected.len(), "missing blocked tool results"); |
| 1105 | assert!(saw_turn_complete); |
| 1106 | } |
| 1107 | |
| 1108 | async fn assert_full_access_model_tool_batch_runs( |
| 1109 | engine_config: EngineConfig, |
| 1110 | tool_calls: Vec<(&'static str, serde_json::Value)>, |
| 1111 | expected_names: &[&str], |
| 1112 | ) { |
| 1113 | use wiremock::matchers::{body_string_contains, method, path}; |
| 1114 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 1115 | |
| 1116 | let server = MockServer::start().await; |
| 1117 | let model_tool_calls = tool_calls |
| 1118 | .iter() |
| 1119 | .enumerate() |
| 1120 | .map(|(index, (name, arguments))| { |
| 1121 | json!({ |
| 1122 | "index": index, |
| 1123 | "id": format!("call_full_access_{index}"), |
| 1124 | "type": "function", |
| 1125 | "function": { |
| 1126 | "name": name, |
| 1127 | "arguments": arguments.to_string(), |
| 1128 | }, |
| 1129 | }) |
| 1130 | }) |
| 1131 | .collect::<Vec<_>>(); |
| 1132 | let tool_delta = json!({ |
| 1133 | "id": "chatcmpl-full-access-blocked", |
| 1134 | "choices": [{ |
| 1135 | "index": 0, |
| 1136 | "delta": {"tool_calls": model_tool_calls}, |
| 1137 | "finish_reason": serde_json::Value::Null, |
| 1138 | }], |
| 1139 | }); |
| 1140 | let tool_finish = json!({ |
| 1141 | "id": "chatcmpl-full-access-blocked", |
| 1142 | "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}], |
| 1143 | }); |
| 1144 | let tool_call_sse = format!("data: {tool_delta}\n\ndata: {tool_finish}\n\ndata: [DONE]\n\n"); |
| 1145 | // Request 1's "model" response: discover the deferred specialized tools |
| 1146 | // through tool_search, exactly as the lowercase contract expects before |
| 1147 | // the first direct call. |
| 1148 | let search_tool_calls = vec![ |
| 1149 | json!({ |
| 1150 | "index": 0, |
| 1151 | "id": "call_search_mcp", |
| 1152 | "type": "function", |
| 1153 | "function": { |
| 1154 | "name": "tool_search", |
| 1155 | "arguments": r#"{"query":"mcp server"}"#, |
| 1156 | }, |
| 1157 | }), |
| 1158 | json!({ |
| 1159 | "index": 1, |
| 1160 | "id": "call_search_rlm", |
| 1161 | "type": "function", |
| 1162 | "function": { |
| 1163 | "name": "tool_search", |
| 1164 | "arguments": r#"{"query":"rlm"}"#, |
| 1165 | }, |
| 1166 | }), |
| 1167 | ]; |
| 1168 | let search_delta = json!({ |
| 1169 | "id": "chatcmpl-full-access-search", |
| 1170 | "choices": [{ |
| 1171 | "index": 0, |
| 1172 | "delta": {"tool_calls": search_tool_calls}, |
| 1173 | "finish_reason": serde_json::Value::Null, |
| 1174 | }], |
| 1175 | }); |
| 1176 | let search_finish = json!({ |
| 1177 | "id": "chatcmpl-full-access-search", |
| 1178 | "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}], |
| 1179 | }); |
| 1180 | let search_sse = format!("data: {search_delta}\n\ndata: {search_finish}\n\ndata: [DONE]\n\n"); |
| 1181 | let done_sse = concat!( |
| 1182 | "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,", |
| 1183 | "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n", |
| 1184 | "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,\"delta\":{},", |
| 1185 | "\"finish_reason\":\"stop\"}]}\n\n", |
| 1186 | "data: [DONE]\n\n", |
| 1187 | ); |
| 1188 | |
| 1189 | // wiremock keeps every mounted mock matching even after its expected |
| 1190 | // count is reached, and request history accumulates across the three |
| 1191 | // steps, so substring matchers on the *calls* would re-fire forever. |
| 1192 | // Anchor each mock on the tool-result ids that exist in exactly one |
| 1193 | // request body: request 3 carries the executed batch's results, request 2 |
| 1194 | // carries the search results, and request 1 carries neither. |
| 1195 | |
| 1196 | // Request 3 (exec batch results) terminates with the done turn. |
| 1197 | Mock::given(method("POST")) |
| 1198 | .and(path("/v1/chat/completions")) |
| 1199 | .and(body_string_contains( |
| 1200 | "\"tool_call_id\":\"call_full_access_0\"", |
| 1201 | )) |
| 1202 | .respond_with( |
| 1203 | ResponseTemplate::new(200) |
| 1204 | .insert_header("content-type", "text/event-stream") |
| 1205 | .set_body_string(done_sse), |
| 1206 | ) |
| 1207 | .expect(1) |
| 1208 | .with_priority(1) |
| 1209 | .mount(&server) |
| 1210 | .await; |
| 1211 | // Request 2 (search results) executes the deferred specialized tools that |
| 1212 | // request 1 discovered through tool_search. The search call activates |
| 1213 | // them in the session cache, so this request runs them under Full Access |
| 1214 | // without an approval modal. |
| 1215 | Mock::given(method("POST")) |
| 1216 | .and(path("/v1/chat/completions")) |
| 1217 | .and(body_string_contains("\"tool_call_id\":\"call_search_mcp\"")) |
| 1218 | .respond_with( |
| 1219 | ResponseTemplate::new(200) |
| 1220 | .insert_header("content-type", "text/event-stream") |
| 1221 | .set_body_string(tool_call_sse), |
| 1222 | ) |
| 1223 | .expect(1) |
| 1224 | .with_priority(2) |
| 1225 | .mount(&server) |
| 1226 | .await; |
| 1227 | // Request 1: the model discovers the deferred specialized tools it needs. |
| 1228 | Mock::given(method("POST")) |
| 1229 | .and(path("/v1/chat/completions")) |
| 1230 | .respond_with( |
| 1231 | ResponseTemplate::new(200) |
| 1232 | .insert_header("content-type", "text/event-stream") |
| 1233 | .set_body_string(search_sse), |
| 1234 | ) |
| 1235 | .expect(1) |
| 1236 | .with_priority(3) |
| 1237 | .mount(&server) |
| 1238 | .await; |
| 1239 | |
| 1240 | let api_config = |
| 1241 | Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri())); |
| 1242 | let (engine, handle) = Engine::new(engine_config, &api_config); |
| 1243 | let run_task = tokio::spawn(engine.run()); |
| 1244 | |
| 1245 | handle |
| 1246 | .send(Op::SendMessage(TurnSpec { |
| 1247 | profile_constitution: None, |
| 1248 | max_output_tokens: None, |
| 1249 | content: "exercise the Full Access auto-approval boundary".to_string(), |
| 1250 | images: Vec::new(), |
| 1251 | mode: AppMode::Agent, |
| 1252 | route: resolved_route_for_test( |
| 1253 | &api_config, |
| 1254 | codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL, |
| 1255 | ), |
| 1256 | compaction: Box::new(CompactionConfig::default()), |
| 1257 | initial_routed_usage: Box::default(), |
| 1258 | goal_objective: None, |
| 1259 | goal_token_budget: None, |
| 1260 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 1261 | reasoning_effort: None, |
| 1262 | reasoning_effort_auto: false, |
| 1263 | auto_model: false, |
| 1264 | allow_shell: true, |
| 1265 | trust_mode: true, |
| 1266 | auto_approve: true, |
| 1267 | approval_mode: ApprovalMode::Bypass, |
| 1268 | translation_enabled: false, |
| 1269 | allowed_tools: None, |
| 1270 | dynamic_tools: Vec::new(), |
| 1271 | hook_executor: None, |
| 1272 | verbosity: None, |
| 1273 | provenance: UserInputProvenance::ExternalUser, |
| 1274 | input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson, |
| 1275 | submission_id: None, |
| 1276 | })) |
| 1277 | .await |
| 1278 | .expect("send Full Access model turn"); |
| 1279 | |
| 1280 | let expected = expected_names |
| 1281 | .iter() |
| 1282 | .copied() |
| 1283 | .collect::<std::collections::HashSet<_>>(); |
| 1284 | let mut seen = HashSet::new(); |
| 1285 | let mut saw_turn_complete = false; |
| 1286 | let mut rx = handle.rx_event.write().await; |
| 1287 | while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv()) |
| 1288 | .await |
| 1289 | .expect("timed out waiting for Full Access auto-approval event") |
| 1290 | { |
| 1291 | match event { |
| 1292 | Event::ApprovalRequired { tool_name, .. } => { |
| 1293 | panic!( |
| 1294 | "Full Access must not open an approval modal for auto-approved tool {tool_name}" |
| 1295 | ) |
| 1296 | } |
| 1297 | Event::ToolCallComplete { name, result, .. } if expected.contains(name.as_str()) => { |
| 1298 | if let Err(error) = &result { |
| 1299 | let message = error.to_string(); |
| 1300 | assert!( |
| 1301 | !message.contains("blocked in Full Access"), |
| 1302 | "Full Access auto-approves non-bypassable tools: {message}" |
| 1303 | ); |
| 1304 | } |
| 1305 | seen.insert(name); |
| 1306 | } |
| 1307 | Event::TurnComplete { status, error, .. } => { |
| 1308 | assert_eq!( |
| 1309 | status, |
| 1310 | TurnOutcomeStatus::Completed, |
| 1311 | "Full Access turn must complete: {error:?}" |
| 1312 | ); |
| 1313 | saw_turn_complete = true; |
| 1314 | break; |
| 1315 | } |
| 1316 | _ => {} |
| 1317 | } |
| 1318 | } |
| 1319 | drop(rx); |
| 1320 | |
| 1321 | handle.send(Op::Shutdown).await.expect("shutdown engine"); |
| 1322 | run_task.await.expect("engine task"); |
| 1323 | assert_eq!( |
| 1324 | seen.len(), |
| 1325 | expected.len(), |
| 1326 | "every tool must reach execution, seen: {seen:?}" |
| 1327 | ); |
| 1328 | assert!(saw_turn_complete); |
| 1329 | } |
| 1330 | |
| 1331 | #[tokio::test] |
| 1332 | #[allow(clippy::await_holding_lock)] |
| 1333 | async fn full_access_auto_approves_non_bypassable_registered_tools() { |
| 1334 | let _lock = lock_test_env(); |
| 1335 | let workspace = tempdir().expect("tempdir"); |
| 1336 | let marker = workspace.path().join("runtime-tool-must-run"); |
| 1337 | let marker_literal = marker |
| 1338 | .to_string_lossy() |
| 1339 | .replace('\\', "/") |
| 1340 | .replace('\'', "\\'"); |
| 1341 | // GitHub's Windows image exposes the interpreter as `python`; Unix |
| 1342 | // images expose `python3`. Keep the runtime-tool execution receipt |
| 1343 | // platform-neutral so this test measures the Full Access boundary rather |
| 1344 | // than an executable-name convention. |
| 1345 | let python = if cfg!(windows) { "python" } else { "python3" }; |
| 1346 | let start_probe = |
| 1347 | format!("{python} -c \"__import__('pathlib').Path('{marker_literal}').write_text('ran')\""); |
| 1348 | let rlm_probe = format!("__import__('pathlib').Path('{marker_literal}').write_text('ran')"); |
| 1349 | let engine_config = EngineConfig { |
| 1350 | model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(), |
| 1351 | workspace: workspace.path().to_path_buf(), |
| 1352 | mcp_config_path: workspace.path().join("mcp.json"), |
| 1353 | snapshots_enabled: false, |
| 1354 | subagents_enabled: false, |
| 1355 | ..EngineConfig::default() |
| 1356 | }; |
| 1357 | assert_full_access_model_tool_batch_runs( |
| 1358 | engine_config, |
| 1359 | vec![ |
| 1360 | ( |
| 1361 | "start_mcp_server", |
| 1362 | json!({"server": start_probe, "name": "auto-approved"}), |
| 1363 | ), |
| 1364 | ( |
| 1365 | "rlm", |
| 1366 | json!({"action": "eval", "name": "missing-context", "code": rlm_probe}), |
| 1367 | ), |
| 1368 | ], |
| 1369 | &["start_mcp_server", "rlm"], |
| 1370 | ) |
| 1371 | .await; |
| 1372 | |
| 1373 | assert!( |
| 1374 | marker.exists(), |
| 1375 | "Full Access auto-approves start_mcp_server, so its server command must actually run" |
| 1376 | ); |
| 1377 | } |
| 1378 | |
| 1379 | #[tokio::test] |
| 1380 | #[allow(clippy::await_holding_lock)] |
| 1381 | async fn full_access_permission_allow_cannot_bypass_repo_law() { |
| 1382 | let _lock = lock_test_env(); |
| 1383 | let workspace = tempdir().expect("tempdir"); |
| 1384 | let law_dir = workspace.path().join(".codewhale"); |
| 1385 | fs::create_dir_all(&law_dir).expect("create law directory"); |
| 1386 | fs::write( |
| 1387 | law_dir.join("constitution.json"), |
| 1388 | r#"{ |
| 1389 | "protected_invariants": [{ |
| 1390 | "text": "Release notes need human review", |
| 1391 | "paths": ["CHANGELOG.md"] |
| 1392 | }] |
| 1393 | }"#, |
| 1394 | ) |
| 1395 | .expect("write repo law fixture"); |
| 1396 | let target = workspace.path().join("CHANGELOG.md"); |
| 1397 | let allow_rule = codewhale_execpolicy::ToolAskRule::file_path("write_file", "CHANGELOG.md") |
| 1398 | .into_exact_workspace_allow(workspace.path().to_string_lossy().into_owned()); |
| 1399 | let engine_config = EngineConfig { |
| 1400 | model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(), |
| 1401 | workspace: workspace.path().to_path_buf(), |
| 1402 | snapshots_enabled: false, |
| 1403 | subagents_enabled: false, |
| 1404 | exec_policy_engine: codewhale_execpolicy::ExecPolicyEngine::with_rulesets(vec![ |
| 1405 | codewhale_execpolicy::Ruleset::user(vec![], vec![]).with_ask_rules(vec![allow_rule]), |
| 1406 | ]), |
| 1407 | ..EngineConfig::default() |
| 1408 | }; |
| 1409 | let tool_input = json!({"filePath": "CHANGELOG.md", "content": "must not be written\n"}); |
| 1410 | assert_eq!( |
| 1411 | file_tool_ask_rule_decision( |
| 1412 | &engine_config, |
| 1413 | "write_file", |
| 1414 | &tool_input, |
| 1415 | workspace.path(), |
| 1416 | ApprovalMode::Bypass, |
| 1417 | ), |
| 1418 | Some(ToolAskRuleDecision::Allow), |
| 1419 | "precondition: the remembered grant must match before repo law tightens the plan" |
| 1420 | ); |
| 1421 | |
| 1422 | assert_full_access_model_tool_batch_is_blocked( |
| 1423 | engine_config, |
| 1424 | vec![("write_file", tool_input)], |
| 1425 | &[( |
| 1426 | "write_file", |
| 1427 | "Repository law blocked tool 'write_file' in Full Access: Repo law holds this write: \"Release notes need human review\"", |
| 1428 | )], |
| 1429 | "Repository law blocked tool 'write_file' in Full Access: Repo law holds this write:", |
| 1430 | ) |
| 1431 | .await; |
| 1432 | |
| 1433 | assert!(!target.exists(), "repo-law block must prevent the write"); |
| 1434 | } |
| 1435 | |
| 1436 | #[tokio::test] |
| 1437 | #[allow(clippy::await_holding_lock)] |
| 1438 | async fn full_access_file_rules_block_alias_and_parent_paths_without_mutation() { |
| 1439 | use codewhale_execpolicy::{ExecPolicyEngine, PermissionAction, Ruleset, ToolAskRule}; |
| 1440 | |
| 1441 | let _lock = lock_test_env(); |
| 1442 | let workspace = tempdir().expect("tempdir"); |
| 1443 | fs::create_dir(workspace.path().join("sub")).expect("fixture directory"); |
| 1444 | let target = workspace.path().join("protected.txt"); |
| 1445 | fs::write(&target, "original\n").expect("fixture contents"); |
| 1446 | let rules = ["write_file", "edit_file", "apply_patch"] |
| 1447 | .into_iter() |
| 1448 | .map(|tool| { |
| 1449 | let mut rule = ToolAskRule::file_path(tool, "protected.txt"); |
| 1450 | rule.action = PermissionAction::Deny; |
| 1451 | rule |
| 1452 | }) |
| 1453 | .collect(); |
| 1454 | let engine_config = EngineConfig { |
| 1455 | model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(), |
| 1456 | workspace: workspace.path().to_path_buf(), |
| 1457 | snapshots_enabled: false, |
| 1458 | subagents_enabled: false, |
| 1459 | exec_policy_engine: ExecPolicyEngine::with_rulesets(vec![ |
| 1460 | Ruleset::user(vec![], vec![]).with_ask_rules(rules), |
| 1461 | ]), |
| 1462 | ..EngineConfig::default() |
| 1463 | }; |
| 1464 | assert_full_access_model_tool_batch_is_blocked( |
| 1465 | engine_config, |
| 1466 | vec![ |
| 1467 | ( |
| 1468 | "write_file", |
| 1469 | json!({"filePath": "protected.txt", "content": "changed\n"}), |
| 1470 | ), |
| 1471 | ( |
| 1472 | "edit_file", |
| 1473 | json!({"file_path": "protected.txt", "search": "original", "replace": "changed"}), |
| 1474 | ), |
| 1475 | ( |
| 1476 | "apply_patch", |
| 1477 | json!({"filePath": "protected.txt", "patch": "@@ -1 +1 @@\n-original\n+changed\n"}), |
| 1478 | ), |
| 1479 | ( |
| 1480 | "write", |
| 1481 | json!({"path": "sub/../protected.txt", "content": "changed\n"}), |
| 1482 | ), |
| 1483 | ], |
| 1484 | &[ |
| 1485 | ( |
| 1486 | "write_file", |
| 1487 | "Permission rule 'tool=write_file path=protected.txt' explicitly denies", |
| 1488 | ), |
| 1489 | ( |
| 1490 | "edit_file", |
| 1491 | "Permission rule 'tool=edit_file path=protected.txt' explicitly denies", |
| 1492 | ), |
| 1493 | ( |
| 1494 | "apply_patch", |
| 1495 | "Permission rule 'tool=apply_patch path=protected.txt' explicitly denies", |
| 1496 | ), |
| 1497 | ( |
| 1498 | "write", |
| 1499 | "Permission rule 'tool=write_file path=protected.txt' explicitly denies", |
| 1500 | ), |
| 1501 | ], |
| 1502 | "explicitly denies this invocation", |
| 1503 | ) |
| 1504 | .await; |
| 1505 | assert_eq!( |
| 1506 | fs::read_to_string(&target).expect("retained contents"), |
| 1507 | "original\n" |
| 1508 | ); |
| 1509 | } |
| 1510 |