返回 CodeWhale
test_cases_12.rs
根目录 / crates / engine / src / core / engine / tests / test_cases_12.rs
1 #[tokio::test]
2 #[allow(clippy::await_holding_lock)]
3 async fn auto_review_asks_the_user_and_returns_the_answer() {
4 use wiremock::matchers::{body_string_contains, method, path};
5 use wiremock::{Mock, MockServer, ResponseTemplate};
6
7 let _lock = lock_test_env();
8 let workspace = tempdir().expect("tempdir");
9 let server = MockServer::start().await;
10 let arguments = json!({
11 "questions": [{
12 "header": "Choice",
13 "id": "choice",
14 "question": "Which path should I take?",
15 "options": [
16 {"label": "A", "description": "Take path A"},
17 {"label": "B", "description": "Take path B"}
18 ]
19 }]
20 })
21 .to_string();
22 let tool_delta = json!({
23 "id": "chatcmpl-auto-review-question",
24 "choices": [{
25 "index": 0,
26 "delta": {"tool_calls": [{
27 "index": 0,
28 "id": "call_auto_review_question",
29 "type": "function",
30 "function": {
31 "name": REQUEST_USER_INPUT_NAME,
32 "arguments": arguments,
33 },
34 }]},
35 "finish_reason": serde_json::Value::Null,
36 }],
37 });
38 let tool_finish = json!({
39 "id": "chatcmpl-auto-review-question",
40 "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}],
41 });
42 let tool_call_sse = format!("data: {tool_delta}\n\ndata: {tool_finish}\n\ndata: [DONE]\n\n");
43 let done_sse = concat!(
44 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,",
45 "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n",
46 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,\"delta\":{},",
47 "\"finish_reason\":\"stop\"}]}\n\n",
48 "data: [DONE]\n\n",
49 );
50
51 Mock::given(method("POST"))
52 .and(path("/v1/chat/completions"))
53 .and(body_string_contains("take-path-b"))
54 .respond_with(
55 ResponseTemplate::new(200)
56 .insert_header("content-type", "text/event-stream")
57 .set_body_string(done_sse),
58 )
59 .expect(1)
60 .with_priority(1)
61 .mount(&server)
62 .await;
63 Mock::given(method("POST"))
64 .and(path("/v1/chat/completions"))
65 .respond_with(
66 ResponseTemplate::new(200)
67 .insert_header("content-type", "text/event-stream")
68 .set_body_string(tool_call_sse),
69 )
70 .expect(1)
71 .with_priority(2)
72 .mount(&server)
73 .await;
74
75 let api_config =
76 Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
77 let (engine, handle) = Engine::new(
78 EngineConfig {
79 user_input_responder: true,
80 model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(),
81 workspace: workspace.path().to_path_buf(),
82 snapshots_enabled: false,
83 subagents_enabled: false,
84 ..EngineConfig::default()
85 },
86 &api_config,
87 );
88 let run_task = tokio::spawn(engine.run());
89
90 handle
91 .send(Op::SendMessage(TurnSpec {
92 profile_constitution: None,
93 max_output_tokens: None,
94 content: "continue autonomously".to_string(),
95 images: Vec::new(),
96 mode: AppMode::Agent,
97 route: resolved_route_for_test(
98 &api_config,
99 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL,
100 ),
101 compaction: Box::new(CompactionConfig::default()),
102 initial_routed_usage: Box::default(),
103 goal_objective: None,
104 goal_token_budget: None,
105 goal_status: crate::tools::goal::GoalStatus::Active,
106 reasoning_effort: None,
107 reasoning_effort_auto: false,
108 auto_model: false,
109 allow_shell: true,
110 trust_mode: false,
111 auto_approve: false,
112 approval_mode: ApprovalMode::Auto,
113 translation_enabled: false,
114 allowed_tools: None,
115 dynamic_tools: Vec::new(),
116 hook_executor: None,
117 verbosity: None,
118 provenance: UserInputProvenance::ExternalUser,
119 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
120 submission_id: None,
121 }))
122 .await
123 .expect("send Auto-Review model turn");
124
125 let mut saw_question = false;
126 let mut saw_tool_result = false;
127 let mut saw_turn_complete = false;
128 let mut rx = handle.rx_event.write().await;
129 while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
130 .await
131 .expect("timed out waiting for Auto-Review question event")
132 {
133 match event {
134 Event::UserInputRequired { id, .. } => {
135 // Auto-Review reviews tool approvals only; a question still
136 // reaches the user.
137 handle
138 .submit_user_input(
139 id,
140 crate::tools::user_input::UserInputResponse {
141 answers: vec![crate::tools::user_input::UserInputAnswer {
142 kind: None,
143 id: "choice".to_string(),
144 label: "B".to_string(),
145 value: "take-path-b".to_string(),
146 }],
147 },
148 )
149 .await
150 .expect("submit answer");
151 saw_question = true;
152 }
153 Event::ApprovalRequired { .. } => {
154 panic!("an Auto-Review question must not become an approval")
155 }
156 Event::ToolCallComplete { name, result, .. } if name == REQUEST_USER_INPUT_NAME => {
157 let result = result.expect("the answered question succeeds");
158 assert!(result.success, "{result:?}");
159 assert!(result.content.contains("take-path-b"), "{result:?}");
160 saw_tool_result = true;
161 }
162 Event::TurnComplete { status, .. } => {
163 assert_eq!(status, TurnOutcomeStatus::Completed);
164 saw_turn_complete = true;
165 break;
166 }
167 _ => {}
168 }
169 }
170 drop(rx);
171
172 handle.send(Op::Shutdown).await.expect("shutdown engine");
173 run_task.await.expect("engine task");
174 assert!(saw_question);
175 assert!(saw_tool_result);
176 assert!(saw_turn_complete);
177 }
178
179 #[tokio::test]
180 #[allow(clippy::await_holding_lock)]
181 async fn full_access_permission_allow_runs_background_destructive_shell_without_a_hold() {
182 use wiremock::matchers::{body_string_contains, method, path};
183 use wiremock::{Mock, MockServer, ResponseTemplate};
184
185 let _lock = lock_test_env();
186 let workspace = tempdir().expect("tempdir");
187 let server = MockServer::start().await;
188 let victim = workspace.path().join("must-survive");
189 fs::write(&victim, "guarded\n").expect("write guarded fixture");
190 // Full Access owns the call: neither a remembered workspace grant nor the
191 // built-in hold may strand it. The fixture writes its own sentinel, so an
192 // execution regression is visible without any destructive command running.
193 let command = format!("echo \"rm -rf /\" > \"{}\"", victim.display());
194 let allow_rule = codewhale_execpolicy::ToolAskRule::exec_shell(command.clone())
195 .into_exact_workspace_allow(workspace.path().to_string_lossy().into_owned());
196 let tool_input = json!({
197 "command": command,
198 "background": true,
199 });
200 let arguments = serde_json::to_string(&tool_input).expect("serialize tool arguments");
201
202 let tool_delta = json!({
203 "id": "chatcmpl-bg",
204 "choices": [{
205 "index": 0,
206 "delta": {"tool_calls": [{
207 "index": 0,
208 "id": "call_bg",
209 "type": "function",
210 "function": {"name": "bash", "arguments": arguments},
211 }]},
212 "finish_reason": serde_json::Value::Null,
213 }],
214 });
215 let tool_finish = json!({
216 "id": "chatcmpl-bg",
217 "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}],
218 });
219 let tool_call_sse = format!("data: {tool_delta}\n\ndata: {tool_finish}\n\ndata: [DONE]\n\n");
220 let done_sse = concat!(
221 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,",
222 "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n",
223 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,\"delta\":{},",
224 "\"finish_reason\":\"stop\"}]}\n\n",
225 "data: [DONE]\n\n",
226 );
227
228 Mock::given(method("POST"))
229 .and(path("/v1/chat/completions"))
230 .and(body_string_contains("call_bg"))
231 .respond_with(
232 ResponseTemplate::new(200)
233 .insert_header("content-type", "text/event-stream")
234 .set_body_string(done_sse),
235 )
236 .expect(1)
237 .with_priority(1)
238 .mount(&server)
239 .await;
240 Mock::given(method("POST"))
241 .and(path("/v1/chat/completions"))
242 .respond_with(
243 ResponseTemplate::new(200)
244 .insert_header("content-type", "text/event-stream")
245 .set_body_string(tool_call_sse),
246 )
247 .expect(1)
248 .with_priority(2)
249 .mount(&server)
250 .await;
251
252 let api_config =
253 Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
254 let engine_config = EngineConfig {
255 model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(),
256 workspace: workspace.path().to_path_buf(),
257 snapshots_enabled: false,
258 subagents_enabled: false,
259 exec_policy_engine: codewhale_execpolicy::ExecPolicyEngine::with_rulesets(vec![
260 codewhale_execpolicy::Ruleset::user(vec![], vec![]).with_ask_rules(vec![allow_rule]),
261 ]),
262 ..EngineConfig::default()
263 };
264 assert_eq!(
265 exec_shell_ask_rule_decision(
266 &engine_config,
267 "exec_shell",
268 &tool_input,
269 workspace.path(),
270 ApprovalMode::Bypass,
271 ),
272 Some(ToolAskRuleDecision::Allow),
273 "precondition: the remembered grant matches and Full Access adds no hold"
274 );
275 let (engine, handle) = Engine::new(engine_config, &api_config);
276 let run_task = tokio::spawn(engine.run());
277
278 handle
279 .send(Op::SendMessage(TurnSpec {
280 profile_constitution: None,
281 max_output_tokens: None,
282 content: "please run a background shell".to_string(),
283 images: Vec::new(),
284 mode: AppMode::Agent,
285 route: resolved_route_for_test(
286 &api_config,
287 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL,
288 ),
289 compaction: Box::new(CompactionConfig::default()),
290 initial_routed_usage: Box::default(),
291 goal_objective: None,
292 goal_token_budget: None,
293 goal_status: crate::tools::goal::GoalStatus::Active,
294 reasoning_effort: None,
295 reasoning_effort_auto: false,
296 auto_model: false,
297 allow_shell: true,
298 trust_mode: true,
299 auto_approve: true,
300 approval_mode: ApprovalMode::Bypass,
301 translation_enabled: false,
302 allowed_tools: None,
303 dynamic_tools: Vec::new(),
304 hook_executor: None,
305 verbosity: None,
306 provenance: UserInputProvenance::ExternalUser,
307 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
308 submission_id: None,
309 }))
310 .await
311 .expect("send model turn");
312
313 let mut saw_tool_result = false;
314 let mut saw_complete = false;
315 let mut rx = handle.rx_event.write().await;
316 while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
317 .await
318 .expect("timed out waiting for engine event")
319 {
320 match event {
321 Event::ApprovalRequired { .. } => {
322 panic!("Full Access must not prompt for a remembered grant")
323 }
324 Event::ToolCallComplete { name, result, .. } => {
325 if name == "bash" {
326 saw_tool_result = true;
327 let result = result.expect("Full Access runs the granted command");
328 assert!(result.success, "unexpected shell failure: {result:?}");
329 }
330 }
331 Event::TurnComplete { status, .. } => {
332 assert_eq!(status, TurnOutcomeStatus::Completed);
333 saw_complete = true;
334 break;
335 }
336 _ => {}
337 }
338 }
339 drop(rx);
340
341 let granted = tokio::time::timeout(std::time::Duration::from_secs(60), async {
342 loop {
343 let text = crate::test_support::read_shell_sentinel(&victim);
344 if !text.is_empty() && text != "guarded" {
345 break text;
346 }
347 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
348 }
349 })
350 .await
351 .expect("the granted command never wrote its sentinel");
352
353 handle.send(Op::Shutdown).await.expect("shutdown engine");
354 run_task.await.expect("engine task");
355 assert!(saw_tool_result);
356 assert!(saw_complete);
357 assert_eq!(
358 granted, "rm -rf /",
359 "the granted command must run to completion"
360 );
361 }
362
363 #[tokio::test]
364 #[allow(clippy::await_holding_lock)]
365 async fn yolo_mode_does_not_prompt_for_background_shell() {
366 // #3883: the durable-review floor keys on what the command does, not on
367 // "not provably read-only". An ordinary background command in YOLO must
368 // run without a prompt. Full Access skips the floor entirely; the
369 // reviewing postures keep it (see the policy-level tests).
370 use wiremock::matchers::{body_string_contains, method, path};
371 use wiremock::{Mock, MockServer, ResponseTemplate};
372
373 let _lock = lock_test_env();
374 let workspace = tempdir().expect("tempdir");
375 let server = MockServer::start().await;
376
377 let tool_call_sse = concat!(
378 "data: {\"id\":\"chatcmpl-bgok\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[",
379 "{\"index\":0,\"id\":\"call_bgok\",\"type\":\"function\",\"function\":{\"name\":\"bash\",",
380 "\"arguments\":\"{\\\"command\\\":\\\"echo bg-yolo-no-prompt\\\",\\\"background\\\":true}\"}}",
381 "]},\"finish_reason\":null}]}\n\n",
382 "data: {\"id\":\"chatcmpl-bgok\",\"choices\":[{\"index\":0,\"delta\":{},",
383 "\"finish_reason\":\"tool_calls\"}]}\n\n",
384 "data: [DONE]\n\n",
385 );
386 let done_sse = concat!(
387 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,",
388 "\"delta\":{\"content\":\"done\"},\"finish_reason\":null}]}\n\n",
389 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,\"delta\":{},",
390 "\"finish_reason\":\"stop\"}]}\n\n",
391 "data: [DONE]\n\n",
392 );
393
394 Mock::given(method("POST"))
395 .and(path("/v1/chat/completions"))
396 .and(body_string_contains("bg-yolo-no-prompt"))
397 .respond_with(
398 ResponseTemplate::new(200)
399 .insert_header("content-type", "text/event-stream")
400 .set_body_string(done_sse),
401 )
402 .expect(1)
403 .with_priority(1)
404 .mount(&server)
405 .await;
406 Mock::given(method("POST"))
407 .and(path("/v1/chat/completions"))
408 .respond_with(
409 ResponseTemplate::new(200)
410 .insert_header("content-type", "text/event-stream")
411 .set_body_string(tool_call_sse),
412 )
413 .expect(1)
414 .with_priority(2)
415 .mount(&server)
416 .await;
417
418 let api_config =
419 Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
420 let (engine, handle) = Engine::new(
421 EngineConfig {
422 model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(),
423 workspace: workspace.path().to_path_buf(),
424 snapshots_enabled: false,
425 subagents_enabled: false,
426 ..EngineConfig::default()
427 },
428 &api_config,
429 );
430 let run_task = tokio::spawn(engine.run());
431
432 handle
433 .send(Op::SendMessage(TurnSpec {
434 profile_constitution: None,
435 max_output_tokens: None,
436 content: "please run a background shell".to_string(),
437 images: Vec::new(),
438 mode: AppMode::Agent,
439 route: resolved_route_for_test(
440 &api_config,
441 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL,
442 ),
443 compaction: Box::new(CompactionConfig::default()),
444 initial_routed_usage: Box::default(),
445 goal_objective: None,
446 goal_token_budget: None,
447 goal_status: crate::tools::goal::GoalStatus::Active,
448 reasoning_effort: None,
449 reasoning_effort_auto: false,
450 auto_model: false,
451 allow_shell: true,
452 trust_mode: true,
453 auto_approve: true,
454 approval_mode: ApprovalMode::Auto,
455 translation_enabled: false,
456 allowed_tools: None,
457 dynamic_tools: Vec::new(),
458 hook_executor: None,
459 verbosity: None,
460 provenance: UserInputProvenance::ExternalUser,
461 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
462 submission_id: None,
463 }))
464 .await
465 .expect("send model turn");
466
467 let mut saw_tool_result = false;
468 let mut saw_complete = false;
469 let mut rx = handle.rx_event.write().await;
470 while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
471 .await
472 .expect("timed out waiting for engine event")
473 {
474 match event {
475 Event::ApprovalRequired { .. } => {
476 panic!("YOLO mode must not prompt for an ordinary background shell command");
477 }
478 Event::ToolCallComplete { name, result, .. } => {
479 if name == "bash" {
480 saw_tool_result = true;
481 let result = result.expect("shell result");
482 assert!(result.success, "{result:?}");
483 assert!(
484 result.content.contains("Background task started"),
485 "expected a background start, got: {result:?}"
486 );
487 }
488 }
489 Event::TurnComplete { status, .. } => {
490 assert_eq!(status, TurnOutcomeStatus::Completed);
491 saw_complete = true;
492 break;
493 }
494 _ => {}
495 }
496 }
497 drop(rx);
498
499 handle.send(Op::Shutdown).await.expect("shutdown engine");
500 run_task.await.expect("engine task");
501 assert!(saw_tool_result);
502 assert!(saw_complete);
503 }
504
505 #[tokio::test]
506 #[allow(clippy::await_holding_lock)]
507 async fn yolo_mode_executes_publish_like_shell_without_prompt() {
508 // #4595: Full Access (Bypass/YOLO) is truly full access — the publish
509 // floor prompts only in Ask/Auto-Review postures. The regression guard is
510 // the absence of ApprovalRequired; execution itself may fail (the tempdir
511 // is not a git repo), which is fine.
512 use wiremock::matchers::{body_string_contains, method, path};
513 use wiremock::{Mock, MockServer, ResponseTemplate};
514
515 let _lock = lock_test_env();
516 let workspace = tempdir().expect("tempdir");
517 let server = MockServer::start().await;
518
519 let tool_call_sse = concat!(
520 "data: {\"id\":\"chatcmpl-publish\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[",
521 "{\"index\":0,\"id\":\"call_publish\",\"type\":\"function\",\"function\":{\"name\":\"bash\",",
522 "\"arguments\":\"{\\\"command\\\":\\\"git push origin main\\\",\\\"background\\\":true}\"}}",
523 "]},\"finish_reason\":null}]}\n\n",
524 "data: {\"id\":\"chatcmpl-publish\",\"choices\":[{\"index\":0,\"delta\":{},",
525 "\"finish_reason\":\"tool_calls\"}]}\n\n",
526 "data: [DONE]\n\n",
527 );
528 let done_sse = concat!(
529 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,",
530 "\"delta\":{\"content\":\"ack\"},\"finish_reason\":null}]}\n\n",
531 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,\"delta\":{},",
532 "\"finish_reason\":\"stop\"}]}\n\n",
533 "data: [DONE]\n\n",
534 );
535
536 Mock::given(method("POST"))
537 .and(path("/v1/chat/completions"))
538 .and(body_string_contains("call_publish"))
539 .respond_with(
540 ResponseTemplate::new(200)
541 .insert_header("content-type", "text/event-stream")
542 .set_body_string(done_sse),
543 )
544 .expect(1)
545 .with_priority(1)
546 .mount(&server)
547 .await;
548 Mock::given(method("POST"))
549 .and(path("/v1/chat/completions"))
550 .respond_with(
551 ResponseTemplate::new(200)
552 .insert_header("content-type", "text/event-stream")
553 .set_body_string(tool_call_sse),
554 )
555 .expect(1)
556 .with_priority(2)
557 .mount(&server)
558 .await;
559
560 let api_config =
561 Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
562 let (engine, handle) = Engine::new(
563 EngineConfig {
564 model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(),
565 workspace: workspace.path().to_path_buf(),
566 snapshots_enabled: false,
567 subagents_enabled: false,
568 ..EngineConfig::default()
569 },
570 &api_config,
571 );
572 let run_task = tokio::spawn(engine.run());
573
574 handle
575 .send(Op::SendMessage(TurnSpec {
576 profile_constitution: None,
577 max_output_tokens: None,
578 content: "please publish this crate".to_string(),
579 images: Vec::new(),
580 mode: AppMode::Agent,
581 route: resolved_route_for_test(
582 &api_config,
583 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL,
584 ),
585 compaction: Box::new(CompactionConfig::default()),
586 initial_routed_usage: Box::default(),
587 goal_objective: None,
588 goal_token_budget: None,
589 goal_status: crate::tools::goal::GoalStatus::Active,
590 reasoning_effort: None,
591 reasoning_effort_auto: false,
592 auto_model: false,
593 allow_shell: true,
594 trust_mode: true,
595 auto_approve: true,
596 approval_mode: ApprovalMode::Bypass,
597 translation_enabled: false,
598 allowed_tools: None,
599 dynamic_tools: Vec::new(),
600 hook_executor: None,
601 verbosity: None,
602 provenance: UserInputProvenance::ExternalUser,
603 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
604 submission_id: None,
605 }))
606 .await
607 .expect("send model turn");
608
609 let mut saw_tool_complete = false;
610 let mut saw_complete = false;
611 let mut rx = handle.rx_event.write().await;
612 while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
613 .await
614 .expect("timed out waiting for engine event")
615 {
616 match event {
617 Event::ApprovalRequired {
618 tool_name,
619 description,
620 ..
621 } => {
622 panic!(
623 "Full Access must not prompt for publish-like shell \
624 (#4595); got prompt for {tool_name}: {description}"
625 );
626 }
627 Event::ToolCallComplete { name, .. } if name == "bash" => {
628 // Execution outcome is irrelevant (the tempdir is not a git
629 // repo); the contract is that it ran without a prompt.
630 saw_tool_complete = true;
631 }
632 Event::TurnComplete { status, .. } => {
633 assert_eq!(status, TurnOutcomeStatus::Completed);
634 saw_complete = true;
635 break;
636 }
637 _ => {}
638 }
639 }
640 drop(rx);
641
642 handle.send(Op::Shutdown).await.expect("shutdown engine");
643 run_task.await.expect("engine task");
644 assert!(
645 saw_tool_complete,
646 "the publish-like shell should execute without a prompt under Full Access"
647 );
648 assert!(saw_complete, "the publish-like turn should complete");
649 }
650
651 #[tokio::test]
652 #[allow(clippy::await_holding_lock)]
653 async fn yolo_mode_does_not_prompt_for_mcp_action() {
654 // #3790: MCP mutations are governed by the selected mode, just like shell.
655 // YOLO must not emit an approval request for a non-read-only MCP tool; this
656 // fixture has no GitHub MCP server, so execution may fail after the no-prompt
657 // planning decision. The regression guard is the absence of ApprovalRequired.
658 use wiremock::matchers::{body_string_contains, method, path};
659 use wiremock::{Mock, MockServer, ResponseTemplate};
660
661 let _lock = lock_test_env();
662 let workspace = tempdir().expect("tempdir");
663 let server = MockServer::start().await;
664
665 let tool_call_sse = concat!(
666 "data: {\"id\":\"chatcmpl-mcp\",\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[",
667 "{\"index\":0,\"id\":\"call_mcp\",\"type\":\"function\",\"function\":{\"name\":\"mcp_github_create_pull_request\",",
668 "\"arguments\":\"{\\\"title\\\":\\\"test\\\",\\\"body\\\":\\\"body\\\"}\"}}",
669 "]},\"finish_reason\":null}]}\n\n",
670 "data: {\"id\":\"chatcmpl-mcp\",\"choices\":[{\"index\":0,\"delta\":{},",
671 "\"finish_reason\":\"tool_calls\"}]}\n\n",
672 "data: [DONE]\n\n",
673 );
674 let done_sse = concat!(
675 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,",
676 "\"delta\":{\"content\":\"ack\"},\"finish_reason\":null}]}\n\n",
677 "data: {\"id\":\"chatcmpl-done\",\"choices\":[{\"index\":0,\"delta\":{},",
678 "\"finish_reason\":\"stop\"}]}\n\n",
679 "data: [DONE]\n\n",
680 );
681
682 Mock::given(method("POST"))
683 .and(path("/v1/chat/completions"))
684 .and(body_string_contains("MCP tool failed"))
685 .respond_with(
686 ResponseTemplate::new(200)
687 .insert_header("content-type", "text/event-stream")
688 .set_body_string(done_sse),
689 )
690 .expect(1)
691 .with_priority(1)
692 .mount(&server)
693 .await;
694 Mock::given(method("POST"))
695 .and(path("/v1/chat/completions"))
696 .respond_with(
697 ResponseTemplate::new(200)
698 .insert_header("content-type", "text/event-stream")
699 .set_body_string(tool_call_sse),
700 )
701 .expect(1)
702 .with_priority(2)
703 .mount(&server)
704 .await;
705
706 let api_config =
707 Config::default().with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
708 let (engine, handle) = Engine::new(
709 EngineConfig {
710 model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(),
711 workspace: workspace.path().to_path_buf(),
712 snapshots_enabled: false,
713 subagents_enabled: false,
714 ..EngineConfig::default()
715 },
716 &api_config,
717 );
718 let run_task = tokio::spawn(engine.run());
719
720 handle
721 .send(Op::SendMessage(TurnSpec {
722 profile_constitution: None,
723 max_output_tokens: None,
724 content: "please open the PR".to_string(),
725 images: Vec::new(),
726 mode: AppMode::Agent,
727 route: resolved_route_for_test(
728 &api_config,
729 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL,
730 ),
731 compaction: Box::new(CompactionConfig::default()),
732 initial_routed_usage: Box::default(),
733 goal_objective: None,
734 goal_token_budget: None,
735 goal_status: crate::tools::goal::GoalStatus::Active,
736 reasoning_effort: None,
737 reasoning_effort_auto: false,
738 auto_model: false,
739 allow_shell: true,
740 trust_mode: true,
741 auto_approve: true,
742 approval_mode: ApprovalMode::Bypass,
743 translation_enabled: false,
744 allowed_tools: None,
745 dynamic_tools: Vec::new(),
746 hook_executor: None,
747 verbosity: None,
748 provenance: UserInputProvenance::ExternalUser,
749 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
750 submission_id: None,
751 }))
752 .await
753 .expect("send model turn");
754
755 let mut saw_mcp_result = false;
756 let mut saw_complete = false;
757 let mut rx = handle.rx_event.write().await;
758 while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
759 .await
760 .expect("timed out waiting for engine event")
761 {
762 match event {
763 Event::ApprovalRequired { .. } => {
764 panic!("YOLO mode must not prompt for an MCP action");
765 }
766 Event::ToolCallComplete { name, result, .. }
767 if name == "mcp_github_create_pull_request" =>
768 {
769 saw_mcp_result = true;
770 let err = result
771 .expect_err("unconfigured MCP server should fail after no-prompt planning");
772 assert!(
773 err.to_string().contains("MCP tool failed"),
774 "unexpected MCP error: {err:?}"
775 );
776 }
777 Event::TurnComplete { status, .. } => {
778 assert_eq!(status, TurnOutcomeStatus::Completed);
779 saw_complete = true;
780 break;
781 }
782 _ => {}
783 }
784 }
785 drop(rx);
786
787 handle.send(Op::Shutdown).await.expect("shutdown engine");
788 run_task.await.expect("engine task");
789 assert!(
790 saw_mcp_result,
791 "the MCP tool should execute without an approval gate"
792 );
793 assert!(saw_complete, "the YOLO MCP turn should complete");
794 }
795
796 #[tokio::test]
797 async fn run_shell_command_op_preserves_plan_mode_shell_block() {
798 let (mut engine, handle) = Engine::new(EngineConfig::default(), &Config::default());
799
800 engine
801 .handle_run_shell_command(
802 "echo blocked".to_string(),
803 AppMode::Plan,
804 false,
805 false,
806 false,
807 ApprovalMode::Suggest,
808 )
809 .await;
810
811 let mut saw_complete = false;
812 let mut saw_turn_complete = false;
813 let mut rx = handle.rx_event.write().await;
814 while let Some(event) = rx.recv().await {
815 match event {
816 Event::ApprovalRequired { .. } => {
817 panic!("Plan mode shell should be blocked before approval");
818 }
819 Event::ToolCallComplete { name, result, .. } => {
820 saw_complete = true;
821 assert_eq!(name, "bash");
822 let err = result.expect_err("plan shell should fail");
823 assert!(
824 err.to_string()
825 .contains("Tool 'bash' is unavailable in Plan mode"),
826 "{err}"
827 );
828 }
829 Event::TurnComplete { status, .. } => {
830 saw_turn_complete = true;
831 assert_eq!(status, TurnOutcomeStatus::Failed);
832 break;
833 }
834 _ => {}
835 }
836 }
837
838 assert!(saw_complete);
839 assert!(saw_turn_complete);
840 }
841
842 #[test]
843 fn deferred_tool_preflight_skips_already_active_tools() {
844 let mut tool = api_tool("deferred_tool");
845 tool.defer_loading = Some(true);
846 let catalog = vec![tool];
847 let mut active = HashSet::from(["deferred_tool".to_string()]);
848
849 assert!(
850 preflight_requested_deferred_tool("deferred_tool", &json!({}), &catalog, &mut active,)
851 .is_none(),
852 "already active tools should execute normally"
853 );
854 }
855
856 #[test]
857 fn turn_tool_registry_builder_keeps_plan_primitive_identity() {
858 let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default());
859 let registry = engine
860 .build_turn_tool_registry_builder(AppMode::Plan, engine.config.todos.clone())
861 .build(engine.build_tool_context(AppMode::Plan, false));
862
863 for primitive in ["read", "write", "edit", "bash"] {
864 assert!(registry.contains(primitive), "missing {primitive}");
865 }
866 for retired in ["File", "Bash"] {
867 assert!(
868 !registry.contains(retired),
869 "retired {retired} still registered"
870 );
871 }
872 for hidden in ["read_file", "write_file", "edit_file"] {
873 assert!(registry.contains(hidden), "missing hidden {hidden}");
874 }
875 assert!(registry.contains("list_dir"));
876 let api_names = registry
877 .to_api_tools()
878 .into_iter()
879 .map(|tool| tool.name)
880 .collect::<HashSet<_>>();
881 for primitive in ["read", "write", "edit", "bash"] {
882 assert!(api_names.contains(primitive), "missing visible {primitive}");
883 }
884 for hidden in ["File", "Bash", "read_file", "write_file", "edit_file"] {
885 assert!(!api_names.contains(hidden), "visible hidden tool {hidden}");
886 }
887 assert!(!registry.contains("exec_shell"));
888 assert!(!registry.contains("exec_shell_wait"));
889 assert!(!registry.contains("exec_shell_interact"));
890 assert!(!registry.contains("task_shell_start"));
891 assert!(!registry.contains("task_create"));
892 assert!(!registry.contains("task_gate_run"));
893 assert!(!registry.contains("rlm"));
894 assert!(!registry.contains("fim_edit"));
895 assert!(!registry.contains("update_plan"));
896 assert!(registry.contains("create_goal"));
897 assert!(registry.contains("get_goal"));
898 assert!(registry.contains("update_goal"));
899 assert!(registry.contains("tasks"));
900 assert!(!registry.contains("task_list"));
901 assert!(!registry.contains("task_read"));
902 assert!(registry.contains("handle_read"));
903 assert_eq!(
904 registry.context().shell_policy,
905 codewhale_agent_contract::worker_profile::ShellPolicy::None
906 );
907 }
908
909 /// Plan mode toggle must not change the byte representation of the tool
910 /// catalog head. DeepSeek's KV prefix cache includes the tools array in
911 /// the immutable prefix; if toggling between Plan and Agent mode changes
912 /// the tool bytes, every mode switch forces a full re-prefill.
913 ///
914 /// This test verifies two invariants:
915 /// 1. Building the catalog twice for the same mode produces identical bytes.
916 /// 2. The head of the catalog (non-deferred tools) preserves its order
917 /// when deferred tools are activated mid-session.
918 #[test]
919 fn plan_mode_toggle_preserves_catalog_byte_stability() {
920 let always_load = HashSet::new();
921
922 // Build catalog for Plan mode twice — must be byte-identical.
923 let plan_native = vec![
924 api_tool("read"),
925 api_tool("write"),
926 api_tool("edit"),
927 api_tool("bash"),
928 api_tool("agent"),
929 api_tool("tool_search"),
930 api_tool("list_dir"),
931 ];
932 let plan_mcp = vec![api_tool("mcp_search"), api_tool("mcp_write")];
933
934 let catalog_a = build_model_tool_catalog(
935 plan_native.clone(),
936 plan_mcp.clone(),
937 AppMode::Plan,
938 &always_load,
939 );
940 let catalog_b = build_model_tool_catalog(
941 plan_native.clone(),
942 plan_mcp.clone(),
943 AppMode::Plan,
944 &always_load,
945 );
946
947 let json_a = serde_json::to_string(&catalog_a).unwrap();
948 let json_b = serde_json::to_string(&catalog_b).unwrap();
949 assert_eq!(
950 json_a, json_b,
951 "building the catalog twice for Plan mode must produce identical bytes"
952 );
953
954 // Build catalog for Agent mode twice — must be byte-identical.
955 let agent_catalog_a = build_model_tool_catalog(
956 plan_native.clone(),
957 plan_mcp.clone(),
958 AppMode::Agent,
959 &always_load,
960 );
961 let agent_catalog_b = build_model_tool_catalog(
962 plan_native.clone(),
963 plan_mcp.clone(),
964 AppMode::Agent,
965 &always_load,
966 );
967
968 let agent_json_a = serde_json::to_string(&agent_catalog_a).unwrap();
969 let agent_json_b = serde_json::to_string(&agent_catalog_b).unwrap();
970 assert_eq!(
971 agent_json_a, agent_json_b,
972 "building the catalog twice for Agent mode must produce identical bytes"
973 );
974
975 // Modes keep the same primitive identities; central authority gates decide
976 // whether an advertised write/edit/bash call may execute.
977 let plan_names: Vec<&str> = catalog_a
978 .iter()
979 .filter(|t| !t.defer_loading.unwrap_or(false))
980 .map(|t| t.name.as_str())
981 .collect();
982 let agent_names: Vec<&str> = agent_catalog_a
983 .iter()
984 .filter(|t| !t.defer_loading.unwrap_or(false))
985 .map(|t| t.name.as_str())
986 .collect();
987
988 let expected_head = ["agent", "bash", "edit", "list_dir", "read", "write"];
989 assert_eq!(plan_names, expected_head);
990 assert_eq!(agent_names, expected_head);
991
992 // Verify that activating a deferred tool mid-session appends to the
993 // tail without reordering the head.
994 let mut tools_with_deferred = plan_native.clone();
995 tools_with_deferred.push({
996 let mut t = api_tool("deferred_search");
997 t.defer_loading = Some(true);
998 t
999 });
1000 let catalog_with_deferred = build_model_tool_catalog(
1001 tools_with_deferred,
1002 plan_mcp.clone(),
1003 AppMode::Agent,
1004 &always_load,
1005 );
1006
1007 // Activate the deferred tool.
1008 let mut active: HashSet<String> = catalog_with_deferred
1009 .iter()
1010 .filter(|t| !t.defer_loading.unwrap_or(false))
1011 .map(|t| t.name.clone())
1012 .collect();
1013 active.insert("deferred_search".to_string());
1014
1015 let listed = active_tools_for_step(&catalog_with_deferred, &active);
1016 let listed_names: Vec<&str> = listed.iter().map(|t| t.name.as_str()).collect();
1017
1018 // The head (non-deferred tools) must still be in their original order.
1019 let head_names: Vec<&str> = catalog_with_deferred
1020 .iter()
1021 .filter(|t| !t.defer_loading.unwrap_or(false))
1022 .map(|t| t.name.as_str())
1023 .collect();
1024 assert!(
1025 listed_names.starts_with(&head_names),
1026 "activating a deferred tool must not reorder the catalog head: \
1027 expected {head_names:?} as prefix, got {listed_names:?}"
1028 );
1029 // The deferred tool must be at the tail.
1030 assert_eq!(
1031 listed_names.last(),
1032 Some(&"deferred_search"),
1033 "deferred tool must be appended at the tail"
1034 );
1035 }
1036
1037 #[test]
1038 fn parent_turn_registry_includes_goal_tools_for_all_modes() {
1039 let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default());
1040
1041 for mode in [AppMode::Plan, AppMode::Agent] {
1042 let registry = engine
1043 .build_turn_tool_registry_builder(mode, engine.config.todos.clone())
1044 .build(engine.build_tool_context(mode, false));
1045
1046 for name in ["create_goal", "get_goal", "update_goal"] {
1047 assert!(
1048 registry.contains(name),
1049 "parent {mode:?} registry should expose {name}"
1050 );
1051 }
1052 }
1053 }
1054
1055 #[tokio::test]
1056 async fn plan_registry_with_complete_judge_and_no_client_does_not_complete_the_goal() {
1057 let (mut engine, _handle) = Engine::new(
1058 EngineConfig {
1059 goal_objective: Some("ship the slice".to_string()),
1060 goal_complete_judge: true,
1061 ..Default::default()
1062 },
1063 &Config::default(),
1064 );
1065 engine.codewhale_client = None;
1066 let registry = engine
1067 .build_turn_tool_registry_builder(AppMode::Plan, engine.config.todos.clone())
1068 .build(engine.build_tool_context(AppMode::Plan, false));
1069
1070 registry
1071 .execute_full(
1072 "update_goal",
1073 json!({
1074 "status": "complete",
1075 "evidence": "tests passed",
1076 "verification": {
1077 "status": "passed",
1078 "check": "cargo test",
1079 "summary": "green"
1080 }
1081 }),
1082 )
1083 .await
1084 .expect("an unjudgeable completion is handed back, not refused");
1085
1086 let snapshot = engine
1087 .config
1088 .goal_state
1089 .lock()
1090 .expect("goal state")
1091 .snapshot();
1092 assert_ne!(snapshot.status, GoalStatus::Complete.as_str());
1093 assert_eq!(snapshot.pause_reason, Some(GoalPauseReason::Yielded));
1094 }
1095
1096 #[test]
1097 fn plan_mode_registry_can_expose_agent_launcher_without_shell_tools() {
1098 let tmp = tempdir().expect("tempdir");
1099 let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default());
1100 let context = engine.build_tool_context(AppMode::Plan, false);
1101 let client = CodewhaleClient::new(
1102 &Config::default().with_legacy_root(Some("test-key".to_string()), None),
1103 )
1104 .expect("stub client");
1105 let manager = crate::tools::subagent::new_shared_subagent_manager(tmp.path().to_path_buf(), 4);
1106 let mut runtime = SubAgentRuntime::new(
1107 client,
1108 DEFAULT_TEXT_MODEL.to_string(),
1109 context.clone(),
1110 false,
1111 None,
1112 manager.clone(),
1113 )
1114 .with_agent_tool_surface_options(
1115 engine.agent_tool_surface_options(shell_policy_for_mode(AppMode::Plan, false)),
1116 );
1117 runtime.worker_profile = WorkerRuntimeProfile::for_role(FleetRole::Planner);
1118
1119 let registry = engine
1120 .build_turn_tool_registry_builder(AppMode::Plan, engine.config.todos.clone())
1121 .with_subagent_tools(manager, runtime)
1122 .build(context);
1123
1124 assert!(
1125 registry.contains("agent"),
1126 "Plan mode should be able to request focused read-only sub-agents"
1127 );
1128 assert!(
1129 !registry.contains("exec_shell"),
1130 "Plan mode must remain shell-free while exposing sub-agent delegation"
1131 );
1132 }
1133
1134 #[test]
1135 fn mode_invariant_matrix_covers_context_catalog_subagents_and_prompt_metadata() {
1136 use ApprovalMode;
1137 use codewhale_agent_contract::worker_profile::ShellPolicy;
1138 use codewhale_sandbox::SandboxPolicy;
1139
1140 #[derive(Clone, Copy)]
1141 enum ExpectedSandbox {
1142 ReadOnly,
1143 WorkspaceWrite,
1144 DangerFullAccess,
1145 }
1146
1147 struct ModeCase {
1148 name: &'static str,
1149 mode: AppMode,
1150 shell_policy: ShellPolicy,
1151 sandbox: ExpectedSandbox,
1152 trust_mode: bool,
1153 auto_approve: bool,
1154 approval_mode: ApprovalMode,
1155 plan_hint: bool,
1156 }
1157
1158 let cases = [
1159 ModeCase {
1160 name: "plan",
1161 mode: AppMode::Plan,
1162 shell_policy: ShellPolicy::None,
1163 sandbox: ExpectedSandbox::ReadOnly,
1164 trust_mode: false,
1165 auto_approve: false,
1166 approval_mode: ApprovalMode::Suggest,
1167 plan_hint: true,
1168 },
1169 ModeCase {
1170 name: "agent",
1171 mode: AppMode::Agent,
1172 shell_policy: ShellPolicy::Full,
1173 sandbox: ExpectedSandbox::WorkspaceWrite,
1174 trust_mode: false,
1175 auto_approve: false,
1176 approval_mode: ApprovalMode::Suggest,
1177 plan_hint: false,
1178 },
1179 ModeCase {
1180 name: "agent-full-access",
1181 mode: AppMode::Agent,
1182 shell_policy: ShellPolicy::Full,
1183 sandbox: ExpectedSandbox::DangerFullAccess,
1184 trust_mode: true,
1185 auto_approve: true,
1186 approval_mode: ApprovalMode::Bypass,
1187 plan_hint: false,
1188 },
1189 ModeCase {
1190 name: "operate",
1191 mode: AppMode::Agent,
1192 shell_policy: ShellPolicy::Full,
1193 sandbox: ExpectedSandbox::WorkspaceWrite,
1194 trust_mode: false,
1195 auto_approve: false,
1196 approval_mode: ApprovalMode::Suggest,
1197 plan_hint: false,
1198 },
1199 ];
1200
1201 for case in cases {
1202 let tmp = tempdir().expect("tempdir");
1203 let config = EngineConfig {
1204 workspace: tmp.path().to_path_buf(),
1205 allow_shell: true,
1206 trust_mode: case.trust_mode,
1207 ..EngineConfig::default()
1208 };
1209 let (mut engine, _handle) = Engine::new(config, &Config::default());
1210 engine.current_mode = case.mode;
1211 engine.session.allow_shell = true;
1212 engine.session.trust_mode = case.trust_mode;
1213 engine.session.auto_approve = case.auto_approve;
1214 engine.session.approval_mode = case.approval_mode;
1215
1216 let policy = effective_input_policy(
1217 UserInputProvenance::ExternalUser,
1218 case.mode,
1219 "continue",
1220 engine.session.allow_shell,
1221 engine.session.trust_mode,
1222 engine.session.auto_approve,
1223 engine.session.approval_mode,
1224 );
1225 assert_eq!(policy.mode, case.mode, "{}", case.name);
1226 assert_eq!(policy.trust_mode, case.trust_mode, "{}", case.name);
1227 assert_eq!(policy.auto_approve, case.auto_approve, "{}", case.name);
1228 assert_eq!(policy.approval_mode, case.approval_mode, "{}", case.name);
1229 assert!(policy.allow_shell, "{}", case.name);
1230
1231 let context = engine.build_tool_context(case.mode, case.auto_approve);
1232 assert_eq!(context.shell_policy, case.shell_policy, "{}", case.name);
1233 assert_eq!(context.trust_mode, case.trust_mode, "{}", case.name);
1234 assert_eq!(context.auto_approve, case.auto_approve, "{}", case.name);
1235 assert_eq!(
1236 context.shell_network_denied_hint.is_some(),
1237 case.plan_hint,
1238 "{}",
1239 case.name
1240 );
1241 let sandbox = context
1242 .elevated_sandbox_policy
1243 .as_ref()
1244 .expect("mode context should always carry an elevated sandbox policy");
1245 match (case.sandbox, sandbox) {
1246 (ExpectedSandbox::ReadOnly, SandboxPolicy::ReadOnly { .. }) => {}
1247 (
1248 ExpectedSandbox::WorkspaceWrite,
1249 SandboxPolicy::WorkspaceWrite {
1250 writable_roots,
1251 network_access,
1252 ..
1253 },
1254 ) => {
1255 assert_eq!(
1256 writable_roots,
1257 &vec![tmp.path().to_path_buf()],
1258 "{}",
1259 case.name
1260 );
1261 // Workspace-write grants writes, not egress. Network is a
1262 // separate, explicit grant in every mode that reaches here.
1263 assert!(!*network_access, "{}", case.name);
1264 }
1265 (ExpectedSandbox::DangerFullAccess, SandboxPolicy::DangerFullAccess) => {}
1266 _ => panic!("{}: unexpected sandbox policy {sandbox:?}", case.name),
1267 }
1268
1269 let client = CodewhaleClient::new(
1270 &Config::default().with_legacy_root(Some("test-key".to_string()), None),
1271 )
1272 .expect("stub client");
1273 let manager =
1274 crate::tools::subagent::new_shared_subagent_manager(tmp.path().to_path_buf(), 4);
1275 let mut runtime = SubAgentRuntime::new(
1276 client,
1277 DEFAULT_TEXT_MODEL.to_string(),
1278 context.clone(),
1279 false,
1280 None,
1281 manager.clone(),
1282 )
1283 .with_agent_tool_surface_options(
1284 engine.agent_tool_surface_options(shell_policy_for_mode(case.mode, true)),
1285 );
1286 runtime.worker_profile = WorkerRuntimeProfile::for_role(match case.mode {
1287 AppMode::Plan => FleetRole::Planner,
1288 _ => FleetRole::Worker,
1289 });
1290
1291 let registry = engine
1292 .build_turn_tool_registry_builder(case.mode, engine.config.todos.clone())
1293 .with_subagent_tools(manager, runtime)
1294 .build(context);
1295 assert!(registry.contains("agent"), "{}", case.name);
1296 assert!(registry.contains("bash"), "{}", case.name);
1297 assert!(
1298 !registry.contains("Bash"),
1299 "{}: retired Bash must remain absent",
1300 case.name
1301 );
1302 assert!(
1303 !registry.contains("exec_shell"),
1304 "{}: retired exec_shell must remain absent",
1305 case.name
1306 );
1307
1308 let msg = engine.user_text_message_with_turn_metadata_for_route(
1309 "check current policy".to_string(),
1310 DEFAULT_TEXT_MODEL,
1311 false,
1312 None,
1313 false,
1314 );
1315 let metadata = msg.content.last().expect("turn metadata block");
1316 let ContentBlock::Text { text, .. } = metadata else {
1317 panic!("{}: expected text metadata block", case.name);
1318 };
1319 assert!(
1320 text.contains(&format!(
1321 "Current permission posture: {}",
1322 case.approval_mode.permission_chip_label()
1323 )),
1324 "{}: {text}",
1325 case.name
1326 );
1327 // Mode is enforced by runtime policy and the live tool catalog. The
1328 // turn block carries only the independently actionable permission posture.
1329 assert!(
1330 !text.contains("Current mode:"),
1331 "{}: turn metadata must not repeat the mode: {text}",
1332 case.name
1333 );
1334 let prefix = crate::prompts::system_prompt_flat_text(
1335 &crate::prompts::system_prompt_for_mode_with_context_skills_session_and_approval(
1336 &engine.config.workspace,
1337 None,
1338 None,
1339 None,
1340 crate::prompts::PromptSessionContext {
1341 mode: case.mode,
1342 ..Default::default()
1343 },
1344 ),
1345 );
1346 assert!(
1347 !prefix.contains("##### Mode:"),
1348 "{}: mode doctrine must not enter the shared prompt: {prefix}",
1349 case.name
1350 );
1351 }
1352 }
1353
1354 #[test]
1355 fn engine_context_honors_stricter_config_under_full_access() {
1356 use ApprovalMode;
1357 use codewhale_sandbox::SandboxPolicy;
1358
1359 let tmp = tempdir().expect("tempdir");
1360 let config = EngineConfig {
1361 workspace: tmp.path().to_path_buf(),
1362 ..EngineConfig::default()
1363 };
1364 let api_config = {
1365 let __cw_config_init_7_0 = Some("workspace-write".to_string());
1366 let mut __cw_config_init_7_value: Config = Config::default();
1367 __cw_config_init_7_value.sandbox_mode = __cw_config_init_7_0;
1368 __cw_config_init_7_value
1369 };
1370 let (mut engine, _handle) = Engine::new(config, &api_config);
1371 engine.session.approval_mode = ApprovalMode::Bypass;
1372 engine.session.auto_approve = true;
1373
1374 let context = engine.build_tool_context(AppMode::Agent, true);
1375 assert!(matches!(
1376 context.elevated_sandbox_policy.as_ref(),
1377 Some(SandboxPolicy::WorkspaceWrite { writable_roots, .. })
1378 if *writable_roots == vec![tmp.path().to_path_buf()]
1379 ));
1380 }
1381
1382 #[test]
1383 fn mode_invariant_matrix_covers_provenance_authority_narrowing() {
1384 use ApprovalMode;
1385
1386 struct ProvenanceCase {
1387 name: &'static str,
1388 provenance: UserInputProvenance,
1389 expected_mode: AppMode,
1390 expected_trust: bool,
1391 expected_auto: bool,
1392 expected_approval: ApprovalMode,
1393 expect_status: bool,
1394 }
1395
1396 let cases = [
1397 ProvenanceCase {
1398 name: "external user",
1399 provenance: UserInputProvenance::ExternalUser,
1400 expected_mode: AppMode::Agent,
1401 expected_trust: true,
1402 expected_auto: true,
1403 expected_approval: ApprovalMode::Bypass,
1404 expect_status: false,
1405 },
1406 ProvenanceCase {
1407 name: "runtime continuation",
1408 provenance: UserInputProvenance::Runtime,
1409 expected_mode: AppMode::Agent,
1410 expected_trust: true,
1411 expected_auto: true,
1412 expected_approval: ApprovalMode::Bypass,
1413 expect_status: false,
1414 },
1415 ProvenanceCase {
1416 name: "sub-agent handoff",
1417 provenance: UserInputProvenance::SubAgentHandoff,
1418 expected_mode: AppMode::Agent,
1419 expected_trust: true,
1420 expected_auto: true,
1421 expected_approval: ApprovalMode::Bypass,
1422 expect_status: false,
1423 },
1424 ProvenanceCase {
1425 name: "imported transcript",
1426 provenance: UserInputProvenance::ImportedTranscript,
1427 expected_mode: AppMode::Agent,
1428 expected_trust: false,
1429 expected_auto: false,
1430 expected_approval: ApprovalMode::Suggest,
1431 expect_status: true,
1432 },
1433 ProvenanceCase {
1434 name: "memory recall",
1435 provenance: UserInputProvenance::MemoryRecall,
1436 expected_mode: AppMode::Agent,
1437 expected_trust: false,
1438 expected_auto: false,
1439 expected_approval: ApprovalMode::Suggest,
1440 expect_status: true,
1441 },
1442 ProvenanceCase {
1443 name: "assistant generated",
1444 provenance: UserInputProvenance::AssistantGenerated,
1445 expected_mode: AppMode::Agent,
1446 expected_trust: false,
1447 expected_auto: false,
1448 expected_approval: ApprovalMode::Suggest,
1449 expect_status: true,
1450 },
1451 ];
1452
1453 for case in cases {
1454 let policy = effective_input_policy(
1455 case.provenance,
1456 AppMode::Agent,
1457 "continue",
1458 true,
1459 true,
1460 true,
1461 ApprovalMode::Bypass,
1462 );
1463 assert_eq!(policy.mode, case.expected_mode, "{}", case.name);
1464 assert_eq!(policy.trust_mode, case.expected_trust, "{}", case.name);
1465 assert_eq!(policy.auto_approve, case.expected_auto, "{}", case.name);
1466 assert_eq!(
1467 policy.approval_mode, case.expected_approval,
1468 "{}",
1469 case.name
1470 );
1471 assert!(policy.allow_shell, "{}", case.name);
1472 assert_eq!(
1473 policy.status().is_some(),
1474 case.expect_status,
1475 "{}",
1476 case.name
1477 );
1478 }
1479 }
1480
1481 #[test]
1482 fn agent_mode_can_build_auto_approved_tool_context() {
1483 let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default());
1484
1485 assert!(
1486 !engine
1487 .build_tool_context(AppMode::Agent, false)
1488 .auto_approve
1489 );
1490 assert!(engine.build_tool_context(AppMode::Agent, true).auto_approve);
1491 }
1492
1493 #[test]
1494 fn build_tool_context_preserves_read_snapshots_across_turns() {
1495 let workspace = tempdir().expect("tempdir");
1496 let path = workspace.path().join("observed.txt");
1497 fs::write(&path, "before\n").expect("write fixture");
1498 let config = EngineConfig {
1499 workspace: workspace.path().to_path_buf(),
1500 ..EngineConfig::default()
1501 };
1502 let (engine, _handle) = Engine::new(config, &Config::default());
1503
1504 let read_turn = engine.build_tool_context(AppMode::Agent, false);
1505 read_turn.note_file_read(&path);
1506
1507 let later_turn = engine.build_tool_context(AppMode::Agent, false);
1508 later_turn
1509 .require_fresh_file_read(&path, "observed.txt")
1510 .expect("a later turn should retain the session's fresh read snapshot");
1511
1512 fs::write(&path, "changed contents\n").expect("change fixture");
1513 let err = later_turn
1514 .require_fresh_file_read(&path, "observed.txt")
1515 .expect_err("a retained snapshot must still reject stale edits");
1516 // Names the tool the model can actually call. `read_file` is a retired name
1517 // and pointing a stale-read refusal at it sent the model to a tool that does
1518 // not exist — the guard-then-bad-advice chain this release set out to close.
1519 assert!(
1520 err.to_string().contains("changed since the last read call"),
1521 "stale-read refusal must name a live tool, got: {err}"
1522 );
1523 }
1524
1525 #[test]
1526 fn build_tool_context_uses_typed_shell_policy_per_mode() {
1527 let mut config = EngineConfig {
1528 allow_shell: true,
1529 ..EngineConfig::default()
1530 };
1531 let (engine, _handle) = Engine::new(config.clone(), &Config::default());
1532
1533 // Plan mode is shell-free and exposes no shell tools.
1534 assert_eq!(
1535 engine.build_tool_context(AppMode::Plan, false).shell_policy,
1536 codewhale_agent_contract::worker_profile::ShellPolicy::None
1537 );
1538 assert_eq!(
1539 engine
1540 .build_tool_context(AppMode::Agent, false)
1541 .shell_policy,
1542 codewhale_agent_contract::worker_profile::ShellPolicy::Full
1543 );
1544
1545 config.allow_shell = false;
1546 let (engine, _handle) = Engine::new(config, &Config::default());
1547 assert_eq!(
1548 engine
1549 .build_tool_context(AppMode::Agent, false)
1550 .shell_policy,
1551 codewhale_agent_contract::worker_profile::ShellPolicy::None
1552 );
1553 }
1554
1555 #[test]
1556 fn turn_tool_context_uses_planned_authority_and_route_not_installed_session() {
1557 let (mut engine, _handle) = Engine::new(EngineConfig::default(), &Config::default());
1558 engine.session.allow_shell = false;
1559 engine.session.trust_mode = false;
1560 engine.session.model = "installed-old-model".to_string();
1561
1562 let authority = crate::core::authority::TurnAuthority::from_effective_fields(
1563 AppMode::Agent,
1564 true,
1565 true,
1566 true,
1567 ApprovalMode::Bypass,
1568 );
1569 let route = TurnRouteContext {
1570 provider: ProviderKind::Deepseek,
1571 model: "planned-next-model".to_string(),
1572 capabilities: codewhale_config::route::RouteCapabilities::default(),
1573 limits: Some(codewhale_config::route::RouteLimits {
1574 context_tokens: Some(123_456),
1575 input_tokens: None,
1576 output_tokens: Some(4_096),
1577 output_declared: false,
1578 }),
1579 client: None,
1580 api_config: Box::new(Config::default()),
1581 locale_tag: engine.config.locale_tag.clone(),
1582 role_models: engine.subagent_role_models(),
1583 auto_model: false,
1584 reasoning_effort: None,
1585 reasoning_effort_auto: false,
1586 };
1587
1588 let context = engine.build_tool_context_for_turn(&authority, &route);
1589 assert_eq!(
1590 context.shell_policy,
1591 codewhale_agent_contract::worker_profile::ShellPolicy::Full
1592 );
1593 assert!(context.trust_mode);
1594 assert!(context.auto_approve);
1595 assert_eq!(
1596 context.approval_mode,
1597 ApprovalMode::Bypass,
1598 "the turn's posture travels with the context its tools see"
1599 );
1600 // Auto-Review is the case the legacy bit cannot express: folding `false`
1601 // alone would read as Ask, so this is what proves the posture itself is
1602 // carried rather than re-derived.
1603 let auto_review = crate::core::authority::TurnAuthority::from_effective_fields(
1604 AppMode::Agent,
1605 true,
1606 false,
1607 false,
1608 ApprovalMode::Auto,
1609 );
1610 assert_eq!(
1611 engine
1612 .build_tool_context_for_turn(&auto_review, &route)
1613 .approval_mode,
1614 ApprovalMode::Auto
1615 );
1616 assert_eq!(context.route_context_window, Some(123_456));
1617 assert_eq!(context.route_capabilities, route.capabilities);
1618 assert_eq!(
1619 context
1620 .session_objects
1621 .as_ref()
1622 .expect("session object snapshot")
1623 .model,
1624 "planned-next-model"
1625 );
1626 }
1627
1628 /// `/network allow <host>` edits `config.toml` and tells the operator to retry
1629 /// the command. The engine holds its policy by value, so that retry only works
1630 /// when the tool context re-reads the document — this is the regression guard
1631 /// for a session that kept refusing a host the file already allowed.
1632 #[test]
1633 fn tool_context_network_policy_follows_the_config_document_mid_session() {
1634 use codewhale_net::network_policy::{
1635 Decision, DecisionToml, NetworkPolicy, NetworkPolicyDecider,
1636 };
1637
1638 let dir = tempdir().expect("temp dir");
1639 let config_path = dir.path().join("config.toml");
1640 fs::write(
1641 &config_path,
1642 "[network]\ndefault = \"prompt\"\nallow = [\"api.github.com\"]\n",
1643 )
1644 .expect("write config");
1645
1646 let api_config = {
1647 let __cw_config_init_8_0 = Some(config_path);
1648 let mut __cw_config_init_8_value: Config = Config::default();
1649 __cw_config_init_8_value.loaded_config_path = __cw_config_init_8_0;
1650 __cw_config_init_8_value
1651 };
1652
1653 // The snapshot the engine was spawned with does not allow the host yet.
1654 let engine_config = EngineConfig {
1655 network_policy: Some(NetworkPolicyDecider::new(
1656 NetworkPolicy {
1657 default: DecisionToml::Prompt,
1658 ..NetworkPolicy::default()
1659 },
1660 None,
1661 )),
1662 ..EngineConfig::default()
1663 };
1664 let (engine, _handle) = Engine::new(engine_config, &api_config);
1665
1666 let authority = crate::core::authority::TurnAuthority::from_effective_fields(
1667 AppMode::Agent,
1668 true,
1669 true,
1670 true,
1671 ApprovalMode::Bypass,
1672 );
1673 let route = TurnRouteContext {
1674 provider: ProviderKind::Deepseek,
1675 model: "network-refresh-model".to_string(),
1676 capabilities: codewhale_config::route::RouteCapabilities::default(),
1677 limits: None,
1678 client: None,
1679 api_config: Box::new(Config::default()),
1680 locale_tag: engine.config.locale_tag.clone(),
1681 role_models: engine.subagent_role_models(),
1682 auto_model: false,
1683 reasoning_effort: None,
1684 reasoning_effort_auto: false,
1685 };
1686
1687 let context = engine.build_tool_context_for_turn(&authority, &route);
1688 let decider = context
1689 .network_policy
1690 .as_ref()
1691 .expect("the configured policy is injected");
1692 assert_eq!(
1693 decider.evaluate("api.github.com", "Bash"),
1694 Decision::Allow,
1695 "the document already allows the host; the retry must see it"
1696 );
1697 assert_eq!(
1698 decider.evaluate("unlisted.example.com", "Bash"),
1699 Decision::Prompt,
1700 "a host the document does not name still prompts"
1701 );
1702 }
1703
1704 /// `/network deny <host>` writes the same `[network]` table `/network allow`
1705 /// does. A session that started without one has to adopt it — otherwise
1706 /// tightening the policy mid-session needs the restart this fix removes — and a
1707 /// session that started gated must not lose its policy because the table went
1708 /// away.
1709 #[test]
1710 fn tool_context_adopts_a_policy_written_mid_session_and_never_ungates_one() {
1711 use codewhale_net::network_policy::{
1712 Decision, DecisionToml, NetworkPolicy, NetworkPolicyDecider,
1713 };
1714
1715 let dir = tempdir().expect("temp dir");
1716 let config_path = dir.path().join("config.toml");
1717 fs::write(
1718 &config_path,
1719 "[network]\ndefault = \"prompt\"\ndeny = [\"evil.example.com\"]\n",
1720 )
1721 .expect("write config");
1722
1723 let api_config = {
1724 let __cw_config_init_9_0 = Some(config_path.clone());
1725 let mut __cw_config_init_9_value: Config = Config::default();
1726 __cw_config_init_9_value.loaded_config_path = __cw_config_init_9_0;
1727 __cw_config_init_9_value
1728 };
1729
1730 // A session that started with no `[network]` table at all adopts the deny.
1731 let (engine, _handle) = Engine::new(EngineConfig::default(), &api_config);
1732 let authority = crate::core::authority::TurnAuthority::from_effective_fields(
1733 AppMode::Agent,
1734 true,
1735 true,
1736 true,
1737 ApprovalMode::Bypass,
1738 );
1739 let route = TurnRouteContext {
1740 provider: ProviderKind::Deepseek,
1741 model: "network-adopt-model".to_string(),
1742 capabilities: codewhale_config::route::RouteCapabilities::default(),
1743 limits: None,
1744 client: None,
1745 api_config: Box::new(Config::default()),
1746 locale_tag: engine.config.locale_tag.clone(),
1747 role_models: engine.subagent_role_models(),
1748 auto_model: false,
1749 reasoning_effort: None,
1750 reasoning_effort_auto: false,
1751 };
1752 let context = engine.build_tool_context_for_turn(&authority, &route);
1753 let decider = context
1754 .network_policy
1755 .as_ref()
1756 .expect("a table written mid-session is adopted");
1757 assert_eq!(
1758 decider.evaluate("evil.example.com", "Bash"),
1759 Decision::Deny,
1760 "the deny direction must land mid-session too"
1761 );
1762
1763 // Removing the table must not ungate a session that started gated.
1764 fs::write(&config_path, "# `[network]` removed\n").expect("rewrite config");
1765 let engine_config = EngineConfig {
1766 network_policy: Some(NetworkPolicyDecider::new(
1767 NetworkPolicy {
1768 default: DecisionToml::Deny,
1769 ..NetworkPolicy::default()
1770 },
1771 None,
1772 )),
1773 ..EngineConfig::default()
1774 };
1775 let (gated, _handle) = Engine::new(engine_config, &api_config);
1776 let context = gated.build_tool_context_for_turn(&authority, &route);
1777 let decider = context
1778 .network_policy
1779 .as_ref()
1780 .expect("a gated session stays gated");
1781 assert_eq!(
1782 decider.evaluate("unlisted.example.com", "Bash"),
1783 Decision::Deny,
1784 "removing the table must not hand a gated session an open policy"
1785 );
1786 }
1787
1788 /// Both continuation dispatchers test `is_active()` before re-arming. A goal the
1789 /// model handed back must therefore land as `Inactive` at the gate the loop
1790 /// actually consults — the unit tests pin `GoalState`, not this decision.
1791 #[test]
1792 fn a_yielded_goal_is_not_rearmed_by_the_continuation_gate() {
1793 let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default());
1794 {
1795 let mut state = engine.config.goal_state.lock().expect("goal lock");
1796 state.replace("ship the milestone", None, Some("goal-1".to_string()));
1797 state.mark_yielded().expect("yield an active goal");
1798 }
1799
1800 assert!(
1801 matches!(
1802 engine.goal_continuation_if_active(),
1803 GoalContinuationAction::Inactive
1804 ),
1805 "a handed-back goal must not be re-armed by the cross-turn gate"
1806 );
1807 }
1808
1809 /// The same gate, against an active goal, still dispatches — so the test above
1810 /// is measuring the yield and not a gate that is dead in test conditions.
1811 #[test]
1812 fn an_active_goal_is_still_rearmed_by_the_continuation_gate() {
1813 let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default());
1814 {
1815 let mut state = engine.config.goal_state.lock().expect("goal lock");
1816 state.replace("ship the milestone", None, Some("goal-1".to_string()));
1817 }
1818
1819 assert!(
1820 matches!(
1821 engine.goal_continuation_if_active(),
1822 GoalContinuationAction::Dispatch { .. }
1823 ),
1824 "an active goal still continues; otherwise the yield test proves nothing"
1825 );
1826 }
1827
1827 lines RUST