返回 CodeWhale
test_cases_06.rs
根目录 / crates / engine / src / core / engine / tests / test_cases_06.rs
1 /// A repeated provider ID is a different host execution each time. The FIFO
2 /// child waiter proves the stale answer was consumed while the second Ask was
3 /// pending, without relying on a sleep or a second execution racing an assert.
4 #[cfg(unix)]
5 #[test]
6 fn repeated_provider_id_ask_rejects_stale_answer_and_keeps_local_artifact_origin() {
7 use crate::approval_log::{ApprovalOutcome, ApprovalReceipt};
8 use crate::llm_client::mock::{MockLlmClient, canned};
9 use crate::tools::subagent::ChildApprovalOutcome;
10
11 with_artifact_home(|home| {
12 tokio::runtime::Builder::new_current_thread()
13 .enable_all()
14 .build()
15 .unwrap()
16 .block_on(async {
17 let command = "printf 'identity:%10000s:done\\n' x";
18 let arguments = json!({"command": command}).to_string();
19 let mock = Arc::new(MockLlmClient::new(vec![
20 canned::tool_call_turn("reused-ask", "bash", &arguments),
21 canned::tool_call_turn("reused-ask", "bash", &arguments),
22 canned::simple_text_turn("done"),
23 ]));
24 let mut config = Config::default();
25 let mut op = external_user_message_op(
26 "Run the same output fixture twice.",
27 AppMode::Agent,
28 &config,
29 );
30 let Op::SendMessage(turn) = &mut op else {
31 unreachable!("fixture creates a model turn");
32 };
33 // Declare both limits on the actual route. A 64K window alone
34 // still reserves the model's 64K output cap, leaving 1K input.
35 config.custom_models = Some(vec![
36 serde_json::from_value(json!({
37 "provider": turn.route.identity.key,
38 "base_url": turn.route.candidate.endpoint().base_url,
39 "id": turn.route.model,
40 "tool_call": true,
41 "limit": {"context": 64_000, "output": 4_096},
42 }))
43 .expect("fixture model limits"),
44 ]);
45 turn.route = resolved_route_for_test(&config, &turn.route.model);
46 let limits = turn.route.candidate.limits();
47 let provider = turn.route.identity.provider;
48 assert_eq!(limits.context_tokens, Some(64_000));
49 assert_eq!(limits.output_tokens, Some(4_096));
50 assert!(
51 context_input_budget_for_route(provider, &turn.route.model, Some(limits), 0)
52 .unwrap()
53 >= 58_880,
54 "the resolved input budget must fit the real instructions and two calls"
55 );
56 assert!(
57 crate::route_budget::route_inline_char_budget_for_route(
58 provider,
59 &turn.route.model,
60 Some(limits),
61 ) < 10_000,
62 "the unchanged output fixture must still require an artifact"
63 );
64 let mut engine_config = deterministic_engine_config(home);
65 engine_config.exec_policy_engine = ask_rule_engine(command);
66 let (engine, handle) =
67 Engine::new_with_model_client(engine_config, &config, mock.clone());
68 let shell_manager = engine.shell_manager.clone();
69 let child_manager = engine.subagent_manager.clone();
70 let session_id = engine.session.id.clone();
71 let receipt_store = engine.approval_receipt_store.clone().unwrap();
72 let task = tokio::spawn(engine.run());
73 handle.send(op).await.unwrap();
74
75 let mut starts = Vec::new();
76 let mut approvals = Vec::new();
77 let mut completions = Vec::new();
78 let mut artifact_paths = Vec::new();
79 let mut rx = handle.rx_event.write().await;
80 loop {
81 match tokio::time::timeout(model_turn_event_timeout(), rx.recv())
82 .await
83 .expect("the fixture turn must settle")
84 .expect("engine event stream")
85 {
86 Event::ToolCallStarted { id, model_call, .. } => {
87 assert_eq!(model_call.unwrap().provider_id, "reused-ask");
88 assert!(uuid::Uuid::parse_str(&id).is_ok());
89 assert!(!starts.contains(&id));
90 starts.push(id);
91 }
92 Event::ApprovalRequired { id, .. } => {
93 assert_eq!(starts.last(), Some(&id));
94 if let Some(first) = approvals.first() {
95 assert_ne!(first, &id);
96 assert_eq!(completions, approvals);
97 let (barrier_id, barrier) = child_manager
98 .write()
99 .await
100 .register_child_approval(
101 "agent_barrier",
102 &format!("agent:agent_barrier:approval:{}", uuid::Uuid::new_v4()),
103 "bash",
104 "approval-channel barrier", None)
105 .unwrap();
106 assert!(handle.approve_tool_call(first).await.is_err());
107 handle.approve_tool_call(&barrier_id).await.unwrap();
108 assert_eq!(
109 tokio::time::timeout(model_turn_event_timeout(), barrier)
110 .await
111 .expect("queued decisions are consumed")
112 .unwrap().outcome,
113 ChildApprovalOutcome::Approved { by: crate::approval_log::ApprovalDecider::User }
114 );
115 let receipts = receipt_store.load(&session_id).unwrap();
116 assert_eq!(receipts.len(), 3, "stale answer cannot decide the second Ask");
117 assert!(matches!(receipts.last(), Some(ApprovalReceipt::Asked { tool_call_id, .. }) if tool_call_id == &id));
118 let jobs = shell_manager.lock().unwrap().list_jobs_for_session(&session_id);
119 assert_eq!(jobs.len(), 1, "the second command is still unexecuted");
120 assert_eq!(jobs[0].origin_tool_call_id.as_ref(), Some(first));
121 }
122 handle.approve_tool_call(&id).await.unwrap();
123 approvals.push(id);
124 }
125 Event::ToolCallComplete { id, model_call, result, .. } => {
126 assert_eq!(model_call.unwrap().provider_id, "reused-ask");
127 assert_eq!(approvals.last(), Some(&id));
128 let output = result.expect("approved shell fixture succeeds");
129 assert!(output.success, "{output:?}");
130 let metadata = output.metadata.as_ref().expect("over-budget output is archived");
131 assert_eq!(metadata["artifact_id"], codewhale_runtime::artifacts::artifact_id_for_tool_call(&id));
132 let path = metadata["artifact_path"].as_str().unwrap().to_string();
133 assert_eq!(fs::read_to_string(&path).unwrap(), output.content);
134 assert!(!artifact_paths.contains(&path));
135 artifact_paths.push(path);
136 completions.push(id);
137 }
138 Event::TurnComplete { status, error, .. } => {
139 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
140 break;
141 }
142 _ => {}
143 }
144 }
145 drop(rx);
146 assert_eq!(starts.len(), 2);
147 assert_eq!(starts, approvals);
148 assert_eq!(starts, completions);
149 let receipts = receipt_store.load(&session_id).unwrap();
150 assert_eq!(receipts.len(), 4);
151 for (pair, id) in receipts.as_chunks::<2>().0.iter().zip(&starts) {
152 assert!(matches!(&pair[0], ApprovalReceipt::Asked { approval_id, tool_call_id, .. } if approval_id == id && tool_call_id == id));
153 assert!(matches!(&pair[1], ApprovalReceipt::Decided { approval_id, tool_call_id, outcome: ApprovalOutcome::ApprovedOnce, .. } if approval_id == id && tool_call_id == id));
154 }
155 let origins = shell_manager
156 .lock()
157 .unwrap()
158 .list_jobs_for_session(&session_id)
159 .into_iter()
160 .map(|job| job.origin_tool_call_id.unwrap())
161 .collect::<HashSet<_>>();
162 assert_eq!(origins, starts.iter().cloned().collect());
163 let requests = mock.captured_requests();
164 assert_eq!(requests.len(), 3);
165 for id in &starts {
166 let pairs = requests[2].messages.iter().flat_map(|message| &message.content)
167 .filter(|block| block.tool_call_key() == Some(codewhale_models::ToolCallKey::Execution(id)))
168 .collect::<Vec<_>>();
169 assert_eq!(pairs.len(), 2);
170 assert!(matches!(pairs[0], ContentBlock::ToolUse { id, .. } if id == "reused-ask"));
171 assert!(matches!(pairs[1], ContentBlock::ToolResult { tool_use_id, content, .. } if tool_use_id == "reused-ask" && content.contains(&codewhale_runtime::artifacts::artifact_id_for_tool_call(id))));
172 }
173 handle.send(Op::Shutdown).await.unwrap();
174 task.await.unwrap();
175 });
176 });
177 }
178
179 /// #4415 AC(b): a 4-call parallel batch proposed with 2 calls remaining is
180 /// truncated to the first 2 calls in proposal order; the excess 2 are
181 /// rejected with the same typed reason, and the batch is counted in full.
182 #[tokio::test]
183 async fn tool_call_budget_truncates_an_over_budget_parallel_batch() {
184 use crate::llm_client::mock::{MockLlmClient, canned};
185
186 let workspace = tempdir().expect("tempdir");
187 let mut calls = Vec::new();
188 for index in 1..=4 {
189 let name = format!("fixture-{index}.txt");
190 fs::write(workspace.path().join(&name), format!("fixture-{index}\n"))
191 .expect("write fixture");
192 calls.push((
193 format!("call-{index}"),
194 "read_file".to_string(),
195 format!(r#"{{"path":"{name}"}}"#),
196 ));
197 }
198 let call_refs = calls
199 .iter()
200 .map(|(id, name, args)| (id.as_str(), name.as_str(), args.as_str()))
201 .collect::<Vec<_>>();
202 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
203 tool_batch_turn(&call_refs),
204 canned::simple_text_turn("done"),
205 ]));
206
207 let (status, error, completions) =
208 run_budgeted_read_turn(workspace.path(), Some(2), mock.clone()).await;
209 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
210 assert_eq!(mock.call_count(), 2, "batch turn then the final text turn");
211 assert_eq!(completions.len(), 4);
212
213 let mut admitted = 0;
214 for (id, result) in &completions {
215 match id.as_str() {
216 "call-1" | "call-2" => {
217 admitted += 1;
218 assert!(result.is_ok(), "{id} must execute: {result:?}");
219 }
220 "call-3" | "call-4" => {
221 let rejection = result.as_ref().expect_err("excess calls are rejected");
222 let reason = rejection.to_string();
223 assert!(reason.contains("budget of 2"), "{reason}");
224 assert!(reason.contains("remaining=0"), "{reason}");
225 }
226 other => panic!("unexpected call id {other}"),
227 }
228 }
229 assert_eq!(admitted, 2, "exactly the remaining 2 calls are admitted");
230 }
231
232 /// #4415: the budget is per-turn, not per-batch — a counter that survives
233 /// every model step of the turn. A full 8-call first batch leaves the next
234 /// step's single call with `remaining=0`.
235 #[tokio::test]
236 async fn tool_call_budget_persists_across_model_steps_within_a_turn() {
237 use crate::llm_client::mock::{MockLlmClient, canned};
238
239 let workspace = tempdir().expect("tempdir");
240 let mut first_batch = Vec::new();
241 for index in 1..=8 {
242 let name = format!("fixture-{index}.txt");
243 fs::write(workspace.path().join(&name), format!("fixture-{index}\n"))
244 .expect("write fixture");
245 first_batch.push((
246 format!("call-{index}"),
247 "read_file".to_string(),
248 format!(r#"{{"path":"{name}"}}"#),
249 ));
250 }
251 let first_refs = first_batch
252 .iter()
253 .map(|(id, name, args)| (id.as_str(), name.as_str(), args.as_str()))
254 .collect::<Vec<_>>();
255 fs::write(workspace.path().join("fixture-9.txt"), "fixture-9\n").expect("write fixture");
256 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
257 tool_batch_turn(&first_refs),
258 canned::tool_call_turn("call-9", "read_file", r#"{"path":"fixture-9.txt"}"#),
259 canned::simple_text_turn("done"),
260 ]));
261
262 let (status, error, completions) =
263 run_budgeted_read_turn(workspace.path(), Some(8), mock.clone()).await;
264 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
265 assert_eq!(
266 mock.call_count(),
267 3,
268 "two tool steps then the final text turn"
269 );
270 assert_eq!(completions.len(), 9);
271
272 let (id, ninth) = completions
273 .iter()
274 .find(|(id, _)| id == "call-9")
275 .expect("the ninth call still reports a completion");
276 assert_eq!(id, "call-9");
277 let reason = ninth
278 .as_ref()
279 .expect_err("ninth call exceeds the turn budget");
280 let reason = reason.to_string();
281 assert!(reason.contains("remaining=0"), "{reason}");
282 assert!(
283 completions
284 .iter()
285 .filter(|(id, result)| id != "call-9" && result.is_ok())
286 .count()
287 == 8,
288 "the first batch of 8 all executed: {completions:?}"
289 );
290 }
291
292 /// #5986: a provider that cuts the stream at its output limit omits the
293 /// closing `ContentBlockStop` for the tool block in flight. The mid-stream
294 /// mirror had already assigned the truncated buffer's best-effort parse
295 /// (the repair ladder appends the missing `}`), and dispatch reads
296 /// `tool.input` directly — so the cut call used to execute with a partial
297 /// argument. The post-stream finalization pass must send it down the same
298 /// malformed-arguments gate a normal block stop applies.
299 #[tokio::test]
300 async fn truncated_tool_call_without_block_stop_never_dispatches() {
301 use crate::llm_client::mock::{MockLlmClient, canned};
302
303 let workspace = tempdir().expect("tempdir");
304 fs::write(workspace.path().join("fixture.txt"), "fixture\n").expect("write fixture");
305 // Cut mid-argument, right after a complete string value: stage 4 of the
306 // repair ladder appends one `}` and the text parses — synthesized.
307 let cut_turn = vec![
308 canned::message_start("mock_msg_cut"),
309 canned::tool_use_block_start(0, "call-cut", "read_file"),
310 canned::tool_input_delta(0, r#"{"path": "fixture.txt""#),
311 // Deliberately no block_stop(0): the output limit ended the turn.
312 canned::message_delta("max_tokens", None),
313 canned::message_stop(),
314 ];
315 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
316 cut_turn,
317 canned::simple_text_turn("done"),
318 ]));
319
320 let (status, error, completions) =
321 run_budgeted_read_turn(workspace.path(), None, mock.clone()).await;
322 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
323
324 let (_, result) = completions
325 .iter()
326 .find(|(id, _)| id == "call-cut")
327 .expect("the cut tool call still reports a completion");
328 let reason = result
329 .as_ref()
330 .expect_err("a truncated tool call must never execute")
331 .to_string();
332 assert!(
333 reason.contains("malformed tool arguments"),
334 "expected the malformed-arguments gate, got: {reason}"
335 );
336 }
337
338 /// The control for the cut-stream pass: when the omitted block stop is the
339 /// only irregularity and the buffered arguments were structurally complete,
340 /// the tool still dispatches. Otherwise every provider that skips closing
341 /// events would lose all of its tool calls.
342 #[tokio::test]
343 async fn complete_tool_call_without_block_stop_still_dispatches() {
344 use crate::llm_client::mock::{MockLlmClient, canned};
345
346 let workspace = tempdir().expect("tempdir");
347 fs::write(workspace.path().join("fixture.txt"), "fixture\n").expect("write fixture");
348 let no_stop_turn = vec![
349 canned::message_start("mock_msg_nostop"),
350 canned::tool_use_block_start(0, "call-complete", "read_file"),
351 canned::tool_input_delta(0, r#"{"path": "fixture.txt"}"#),
352 canned::message_delta("tool_use", None),
353 canned::message_stop(),
354 ];
355 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
356 no_stop_turn,
357 canned::simple_text_turn("done"),
358 ]));
359
360 let (status, error, completions) =
361 run_budgeted_read_turn(workspace.path(), None, mock.clone()).await;
362 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
363
364 let (_, result) = completions
365 .iter()
366 .find(|(id, _)| id == "call-complete")
367 .expect("the tool call reports a completion");
368 let output = result
369 .as_ref()
370 .expect("structurally complete arguments still dispatch")
371 .content
372 .clone();
373 assert!(output.contains("fixture"), "{output}");
374 }
375
376 /// #4415 AC(c): a write-first named-file task carries a scoped-write
377 /// authority envelope naming its exact files. The existing allowed-paths
378 /// machinery (`ToolAuthorityEnvelope`, enforced at the registry boundary)
379 /// permits mutating a named file and denies mutating anything outside it
380 /// with a typed permission error, and the denied write never executes.
381 ///
382 /// Seam: the envelope is a MUTATION boundary only — `read_file` outside the
383 /// named files is NOT denied by policy today (read-only tools pass the
384 /// envelope by design). Denying out-of-scope reads for write-first tasks is
385 /// a #4415 follow-up; this test pins the current contract so the seam is
386 /// explicit rather than assumed.
387 #[tokio::test]
388 async fn named_file_write_scope_denies_mutation_outside_the_named_files() {
389 let workspace = tempdir().expect("tempdir");
390 fs::create_dir_all(workspace.path().join("src")).expect("src dir");
391 fs::create_dir_all(workspace.path().join("docs")).expect("docs dir");
392 fs::write(workspace.path().join("docs/other.md"), "outside\n").expect("write fixture");
393 let envelope = crate::tools::spec::ToolAuthorityEnvelope {
394 schema_version: 1,
395 owner: "test-worker".to_string(),
396 authority: crate::tools::spec::ToolMutationAuthority::ScopedWrite,
397 network_access: None,
398 shell: crate::tools::spec::ToolShellAuthority::None,
399 verification: crate::tools::spec::ToolVerificationAuthority::None,
400 writable_roots: Vec::new(),
401 writable_files: vec!["src/named.rs".to_string()],
402 coordination_contracts: Vec::new(),
403 };
404 let context = crate::tools::ToolContext::new(workspace.path().to_path_buf())
405 .with_tool_authority(envelope)
406 .expect("valid envelope");
407 let mut registry = crate::tools::ToolRegistry::new(context);
408 registry.register(std::sync::Arc::new(crate::tools::file::ReadFileTool));
409 registry.register(std::sync::Arc::new(crate::tools::file::WriteFileTool));
410
411 // The named file is writable under the envelope.
412 let named = registry
413 .execute_full(
414 "write_file",
415 json!({"path": "src/named.rs", "content": "fn named() {}\n"}),
416 )
417 .await
418 .expect("mutation of the named file is permitted");
419 assert!(named.success, "{named:?}");
420 assert!(workspace.path().join("src/named.rs").exists());
421
422 // A mutation outside the named files is denied by policy and never runs.
423 let denied = registry
424 .execute_full(
425 "write_file",
426 json!({"path": "docs/other.md", "content": "rewritten\n"}),
427 )
428 .await
429 .expect_err("mutation outside the named files is denied");
430 assert!(
431 denied.to_string().contains("authority envelope"),
432 "{denied}"
433 );
434 assert_eq!(
435 fs::read_to_string(workspace.path().join("docs/other.md")).expect("read back"),
436 "outside\n",
437 "the denied write must not have executed"
438 );
439
440 // Pin the read-side seam: a read outside the named files is allowed
441 // through the mutation-scoped envelope today.
442 let read = registry
443 .execute_full("read_file", json!({"path": "docs/other.md"}))
444 .await
445 .expect("reads are not path-scoped by the mutation envelope today");
446 assert!(read.content.contains("outside"), "{read:?}");
447 }
448
449 #[test]
450 fn empty_allowed_tools_surface_is_empty_and_sends_no_tools_field() {
451 let surface = policy_for_catalog(vec![catalog_tool("read_file")], Some(Vec::new()), None);
452
453 assert!(surface.catalog.is_empty());
454 assert!(surface.active_names.is_empty());
455 assert!(surface.active.is_none());
456 assert!(!surface.allows_tool("read_file"));
457 }
458
459 /// The turn-start capture carries mode/workspace/working-set state only. Work
460 /// used to be rendered here; it moved to the fork seam (#3983) because this
461 /// block is captured before the turn's first tool call. Fork-seam Work parity is
462 /// covered by `fork_state_block_reuses_the_canonical_work_body`.
463 #[test]
464 fn structured_state_block_carries_stable_state_without_work() {
465 let state = StructuredState {
466 mode_label: "Agent".to_string(),
467 workspace: PathBuf::from("/workspace/codewhale"),
468 cwd: Some(PathBuf::from("/workspace/codewhale")),
469 working_set_summary: None,
470 subagent_snapshots: Vec::new(),
471 };
472
473 let block = state.to_system_block().expect("fork state block");
474
475 assert!(block.contains("- Mode: `Agent`"));
476 assert!(!block.contains(crate::todo_snapshot::FORK_TODO_SECTION_HEADING));
477 assert!(!block.contains("To-do ("));
478 assert!(!block.contains("Strategy"));
479 }
480
481 #[test]
482 fn env_only_auth_error_gets_recovery_hint() {
483 let _guard = lock_test_env();
484 let _env = ScopedDeepSeekApiKey::set("stale-env-key");
485 let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default());
486
487 let message =
488 engine.decorate_auth_error_message("Authentication failed: invalid API key".to_string());
489
490 assert!(message.contains("DEEPSEEK_API_KEY"));
491 assert!(message.contains("no saved config key is present"));
492 assert!(message.contains("codewhale auth status"));
493 assert!(message.contains("codewhale auth set --provider deepseek"));
494 }
495
496 #[test]
497 fn config_auth_error_does_not_blame_env() {
498 let _guard = lock_test_env();
499 let _env = ScopedDeepSeekApiKey::set("stale-env-key");
500 let cfg = Config::default().with_legacy_root(Some("fresh-config-key".to_string()), None);
501 let (engine, _handle) = Engine::new(EngineConfig::default(), &cfg);
502
503 let message =
504 engine.decorate_auth_error_message("Authentication failed: invalid API key".to_string());
505
506 assert_eq!(message, "Authentication failed: invalid API key");
507 }
508
509 #[test]
510 fn plugin_tools_dir_honors_missing_custom_directory_without_fallback() {
511 let missing = PathBuf::from("definitely-missing-codewhale-plugin-dir");
512 let tools_config = codewhale_runtime::config::ToolsConfig {
513 plugin_dir: Some(missing.to_string_lossy().to_string()),
514 ..Default::default()
515 };
516
517 assert_eq!(plugin_tools_dir(Some(&tools_config)), missing);
518 }
519
520 #[test]
521 fn configure_plugin_tools_applies_overrides_after_discovered_plugins() {
522 let tmp = tempdir().expect("tempdir");
523 let plugin_dir = tmp.path().join("tools");
524 fs::create_dir(&plugin_dir).expect("plugin dir");
525 fs::write(
526 plugin_dir.join("same-name.sh"),
527 "# name: same_tool\n# description: discovered plugin\n",
528 )
529 .expect("plugin script");
530
531 let mut overrides = HashMap::new();
532 overrides.insert(
533 "same_tool".to_string(),
534 codewhale_runtime::config::ToolOverride::Command {
535 command: "configured-command".to_string(),
536 args: None,
537 },
538 );
539 // Everything registered before configuration is built in: D4 refuses a
540 // replacement for it.
541 overrides.insert(
542 "read".to_string(),
543 codewhale_runtime::config::ToolOverride::Command {
544 command: "configured-file".to_string(),
545 args: None,
546 },
547 );
548 let tools_config = codewhale_runtime::config::ToolsConfig {
549 plugin_dir: Some(plugin_dir.to_string_lossy().to_string()),
550 overrides: Some(overrides),
551 ..Default::default()
552 };
553
554 let ctx = crate::tools::ToolContext::new(tmp.path().to_path_buf());
555 let mut registry = crate::tools::ToolRegistryBuilder::new()
556 .with_file_tools()
557 .build(ctx);
558 let read = registry.get("read").expect("built-in read");
559
560 let (plugin_names, refused) = configure_plugin_tools(&mut registry, Some(&tools_config));
561
562 let tool = registry.get("same_tool").expect("same_tool registered");
563 assert!(tool.description().contains("configured-command"));
564 assert!(plugin_names.contains("same_tool"));
565 assert!(Arc::ptr_eq(
566 &registry.get("read").expect("read kept"),
567 &read
568 ));
569 assert!(!plugin_names.contains("read"));
570 // The refusal reaches the engine so it can name it to the user.
571 assert_eq!(refused, vec!["read".to_string()]);
572 assert!(
573 crate::tools::registry::override_refusal_notice("read").contains("[tools.overrides.read]")
574 );
575 }
576
577 fn make_plan(
578 read_only: bool,
579 supports_parallel: bool,
580 approval_required: bool,
581 interactive: bool,
582 ) -> ToolExecutionPlan {
583 make_plan_at(
584 0,
585 read_only,
586 supports_parallel,
587 approval_required,
588 interactive,
589 )
590 }
591
592 fn make_plan_at(
593 index: usize,
594 read_only: bool,
595 supports_parallel: bool,
596 approval_required: bool,
597 interactive: bool,
598 ) -> ToolExecutionPlan {
599 ToolExecutionPlan {
600 model_call: None,
601 index,
602 id: format!("tool-{index}"),
603 name: "grep_files".to_string(),
604 input: json!({"pattern": "test"}),
605 caller: None,
606 interactive,
607 approval_required,
608 approval_description: "desc".to_string(),
609 mcp_always_binding: None,
610 approval_force_prompt: false,
611 supports_parallel,
612 read_only,
613 detached_start: false,
614 resources: vec![ResourceClaim::ReadPath(PathBuf::from(format!(
615 "src-{index}.rs"
616 )))],
617 blocked_error: None,
618 guard_result: None,
619 grants_outside_workspace_read: false,
620 creator_gate: None,
621 search_consent: false,
622 }
623 }
624
625 fn parallel_batch_indices(batch: &ToolExecutionBatch) -> Vec<usize> {
626 match batch {
627 ToolExecutionBatch::Parallel(plans) => plans.iter().map(|plan| plan.index).collect(),
628 ToolExecutionBatch::Serial(_) => panic!("expected parallel batch"),
629 }
630 }
631
632 fn ask_rule_engine(command: &str) -> codewhale_execpolicy::ExecPolicyEngine {
633 codewhale_execpolicy::ExecPolicyEngine::with_rulesets(vec![
634 codewhale_execpolicy::Ruleset::user(vec![], vec![])
635 .with_ask_rules(vec![codewhale_execpolicy::ToolAskRule::exec_shell(command)]),
636 ])
637 }
638
639 fn file_ask_rule_engine(tool: &str, path: &str) -> codewhale_execpolicy::ExecPolicyEngine {
640 codewhale_execpolicy::ExecPolicyEngine::with_rulesets(vec![
641 codewhale_execpolicy::Ruleset::user(vec![], vec![]).with_ask_rules(vec![
642 codewhale_execpolicy::ToolAskRule::file_path(tool, path),
643 ]),
644 ])
645 }
646
647 fn model_turn_event_timeout() -> Duration {
648 if cfg!(windows) {
649 // The Windows CI runner executes the full TUI test binary with thousands of
650 // tests competing for CPU. Keep this high enough that an approval-gated
651 // model turn is not mistaken for a lifecycle failure under runner load.
652 Duration::from_secs(60)
653 } else {
654 Duration::from_secs(10)
655 }
656 }
657
658 fn resolved_route_for_test(
659 config: &Config,
660 model: &str,
661 ) -> Box<crate::route_runtime::ResolvedRuntimeRoute> {
662 Box::new(
663 resolve_runtime_route(
664 config,
665 config.active_provider_identity().unwrap().provider,
666 Some(model),
667 )
668 .expect("resolve test route"),
669 )
670 }
671
672 fn active_goal_message_op(
673 config: &Config,
674 content: &str,
675 objective: &str,
676 token_budget: Option<u32>,
677 ) -> Op {
678 Op::SendMessage(TurnSpec {
679 profile_constitution: None,
680 max_output_tokens: None,
681 content: content.to_string(),
682 images: Vec::new(),
683 mode: AppMode::Agent,
684 route: resolved_route_for_test(config, "local-model"),
685 compaction: Box::new(CompactionConfig::default()),
686 initial_routed_usage: Box::default(),
687 goal_objective: Some(objective.to_string()),
688 goal_token_budget: token_budget,
689 goal_status: crate::tools::goal::GoalStatus::Active,
690 reasoning_effort: None,
691 reasoning_effort_auto: false,
692 auto_model: false,
693 allow_shell: false,
694 trust_mode: false,
695 auto_approve: false,
696 approval_mode: ApprovalMode::Suggest,
697 translation_enabled: false,
698 allowed_tools: None,
699 dynamic_tools: Vec::new(),
700 hook_executor: None,
701 verbosity: None,
702 provenance: UserInputProvenance::ExternalUser,
703 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
704 submission_id: None,
705 })
706 }
707
708 fn system_prompt_text(prompt: SystemPrompt) -> String {
709 match prompt {
710 SystemPrompt::Text(text) => text,
711 SystemPrompt::Blocks(blocks) => blocks
712 .into_iter()
713 .map(|block| block.text)
714 .collect::<Vec<_>>()
715 .join("\n"),
716 }
717 }
718
719 fn external_user_message_op(content: &str, mode: AppMode, config: &Config) -> Op {
720 Op::SendMessage(TurnSpec {
721 profile_constitution: None,
722 max_output_tokens: None,
723 content: content.to_string(),
724 images: Vec::new(),
725 mode,
726 route: resolved_route_for_test(
727 config,
728 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL,
729 ),
730 compaction: Box::new(CompactionConfig::default()),
731 initial_routed_usage: Box::default(),
732 goal_objective: None,
733 goal_token_budget: None,
734 goal_status: crate::tools::goal::GoalStatus::Active,
735 reasoning_effort: None,
736 reasoning_effort_auto: false,
737 auto_model: false,
738 allow_shell: true,
739 trust_mode: false,
740 auto_approve: false,
741 approval_mode: ApprovalMode::Suggest,
742 translation_enabled: false,
743 allowed_tools: None,
744 dynamic_tools: Vec::new(),
745 hook_executor: None,
746 verbosity: None,
747 provenance: UserInputProvenance::ExternalUser,
748 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
749 submission_id: None,
750 })
751 }
752
753 fn external_user_message_op_with_submission(
754 content: &str,
755 mode: AppMode,
756 config: &Config,
757 submission_id: Option<String>,
758 ) -> Op {
759 let mut op = external_user_message_op(content, mode, config);
760 if let Op::SendMessage(TurnSpec {
761 submission_id: token,
762 ..
763 }) = &mut op
764 {
765 *token = submission_id;
766 }
767 op
768 }
769
770 fn auto_review_message_op(content: &str, config: &Config) -> Op {
771 Op::SendMessage(TurnSpec {
772 profile_constitution: None,
773 max_output_tokens: None,
774 content: content.to_string(),
775 images: Vec::new(),
776 mode: AppMode::Agent,
777 route: resolved_route_for_test(
778 config,
779 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL,
780 ),
781 compaction: Box::new(CompactionConfig::default()),
782 initial_routed_usage: Box::default(),
783 goal_objective: None,
784 goal_token_budget: None,
785 goal_status: crate::tools::goal::GoalStatus::Active,
786 reasoning_effort: None,
787 reasoning_effort_auto: false,
788 auto_model: false,
789 allow_shell: true,
790 trust_mode: false,
791 auto_approve: false,
792 approval_mode: ApprovalMode::Auto,
793 translation_enabled: false,
794 allowed_tools: None,
795 dynamic_tools: Vec::new(),
796 hook_executor: None,
797 verbosity: None,
798 provenance: UserInputProvenance::ExternalUser,
799 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
800 submission_id: None,
801 })
802 }
803
804 struct DropSignal(std::sync::Arc<std::sync::atomic::AtomicBool>);
805
806 impl Drop for DropSignal {
807 fn drop(&mut self) {
808 self.0.store(true, std::sync::atomic::Ordering::SeqCst);
809 }
810 }
811
812 struct BlockingModelClient {
813 entered: std::sync::Arc<tokio::sync::Notify>,
814 request_dropped: std::sync::Arc<std::sync::atomic::AtomicBool>,
815 }
816
817 struct BlockingGuardianModelClient {
818 guardian_entered: std::sync::Arc<tokio::sync::Notify>,
819 guardian_dropped: std::sync::Arc<std::sync::atomic::AtomicBool>,
820 streaming_calls: std::sync::atomic::AtomicUsize,
821 }
822
823 struct FailingGuardianModelClient {
824 inner: crate::llm_client::mock::MockLlmClient,
825 }
826
827 #[async_trait::async_trait]
828 impl crate::core::model_client::ModelClient for FailingGuardianModelClient {
829 fn provider_name(&self) -> &str {
830 self.inner.provider_name()
831 }
832
833 fn model(&self) -> &str {
834 self.inner.model()
835 }
836
837 async fn create_message(
838 &self,
839 _request: codewhale_models::MessageRequest,
840 ) -> anyhow::Result<codewhale_models::MessageResponse> {
841 anyhow::bail!("fixture guardian transport failure")
842 }
843
844 async fn create_message_stream(
845 &self,
846 request: codewhale_models::MessageRequest,
847 ) -> anyhow::Result<crate::llm_client::StreamEventBox> {
848 crate::core::model_client::ModelClient::create_message_stream(&self.inner, request).await
849 }
850
851 async fn health_check(&self) -> anyhow::Result<bool> {
852 Ok(true)
853 }
854 }
855
856 #[async_trait::async_trait]
857 impl crate::core::model_client::ModelClient for BlockingGuardianModelClient {
858 fn provider_name(&self) -> &str {
859 "deterministic-blocking-guardian"
860 }
861
862 fn model(&self) -> &str {
863 "deterministic-blocking-guardian-model"
864 }
865
866 async fn create_message(
867 &self,
868 _request: codewhale_models::MessageRequest,
869 ) -> anyhow::Result<codewhale_models::MessageResponse> {
870 let _drop_signal = DropSignal(std::sync::Arc::clone(&self.guardian_dropped));
871 self.guardian_entered.notify_one();
872 std::future::pending().await
873 }
874
875 async fn create_message_stream(
876 &self,
877 _request: codewhale_models::MessageRequest,
878 ) -> anyhow::Result<crate::llm_client::StreamEventBox> {
879 use crate::llm_client::mock::canned;
880
881 assert_eq!(
882 self.streaming_calls
883 .fetch_add(1, std::sync::atomic::Ordering::SeqCst),
884 0,
885 "cancellation must prevent a follow-up model request"
886 );
887 let events = canned::tool_call_turn(
888 "call-cancelled-guardian",
889 "write",
890 r#"{"path":".env","content":"must-not-run\n"}"#,
891 );
892 Ok(Box::pin(futures_util::stream::iter(
893 events.into_iter().map(Ok),
894 )))
895 }
896
897 async fn health_check(&self) -> anyhow::Result<bool> {
898 Ok(true)
899 }
900 }
901
902 #[async_trait::async_trait]
903 impl crate::core::model_client::ModelClient for BlockingModelClient {
904 fn provider_name(&self) -> &str {
905 "deterministic-blocking"
906 }
907
908 fn model(&self) -> &str {
909 "deterministic-blocking-model"
910 }
911
912 async fn create_message(
913 &self,
914 _request: codewhale_models::MessageRequest,
915 ) -> anyhow::Result<codewhale_models::MessageResponse> {
916 std::future::pending().await
917 }
918
919 async fn create_message_stream(
920 &self,
921 _request: codewhale_models::MessageRequest,
922 ) -> anyhow::Result<crate::llm_client::StreamEventBox> {
923 let _drop_signal = DropSignal(std::sync::Arc::clone(&self.request_dropped));
924 self.entered.notify_one();
925 std::future::pending().await
926 }
927
928 async fn health_check(&self) -> anyhow::Result<bool> {
929 Ok(true)
930 }
931 }
932
933 fn test_tool_surface(
934 engine: &Engine,
935 registry: crate::tools::ToolRegistry,
936 tools: Option<Vec<codewhale_models::Tool>>,
937 mode: AppMode,
938 ) -> ToolSurfacePolicy {
939 ToolSurfacePolicy::new(
940 registry,
941 tools,
942 mode,
943 &engine.config.tools_always_load,
944 engine.config.strict_tool_mode,
945 engine.config.allowed_tools.clone(),
946 engine.config.disallowed_tools.clone(),
947 engine.config.max_tool_calls,
948 crate::core::engine::tool_catalog::ToolMode::Direct,
949 )
950 }
951
952 #[tokio::test]
953 async fn tool_request_snapshot_matches_the_exact_mock_request_payload() {
954 use crate::llm_client::mock::{MockLlmClient, canned};
955
956 let workspace = tempdir().expect("tempdir");
957 let mock = std::sync::Arc::new(MockLlmClient::new(vec![canned::simple_text_turn("Done.")]));
958 let client: crate::core::model_client::SharedModelClient = mock.clone();
959 let (mut engine, handle) = Engine::new_with_model_client(
960 deterministic_engine_config(workspace.path()),
961 &Config::default(),
962 client,
963 );
964 let context = crate::tools::ToolContext::new(workspace.path().to_path_buf());
965 let mut registry = crate::tools::ToolRegistry::new(context);
966 registry.register(std::sync::Arc::new(crate::tools::file::ReadFileTool));
967 let tools = Some(registry.to_api_tools_with_cache(true));
968 let surface = test_tool_surface(&engine, registry, tools, AppMode::Agent);
969 let mut turn = crate::core::turn::TurnContext::new(4);
970
971 let (status, error) = engine.run_turn(&mut turn, surface, None, None).await;
972 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
973
974 let request = mock.last_request().expect("mock request");
975 let mut events = handle.rx_event.write().await;
976 let snapshot = std::iter::from_fn(|| events.try_recv().ok())
977 .find_map(|event| match event {
978 Event::ToolRequestSnapshot { snapshot } => Some(snapshot),
979 _ => None,
980 })
981 .expect("request snapshot event");
982
983 assert_eq!(snapshot.tools_field_present, request.tools.is_some());
984 assert_eq!(
985 snapshot.tool_count,
986 request.tools.as_ref().map_or(0, Vec::len)
987 );
988 if let Some(request_tool) = request.tools.as_ref().and_then(|tools| tools.first()) {
989 assert_eq!(
990 snapshot.tools.first().expect("projected tool").name.value,
991 request_tool.name
992 );
993 }
994 assert_eq!(snapshot.turn_id.value, turn.id);
995 assert_eq!(snapshot.step, 0);
996 assert!(snapshot.delivery_status.starts_with("unknown"));
997 }
998
999 /// A recursive `rlm_query` makes a child model write Python. That round runs
1000 /// only after the turn serving the `rlm` call admits it like `code_execution`:
1001 /// outside Full Access it waits on a card of its own, beyond the approval the
1002 /// direct `rlm` call already took. Denied, nothing runs; approved, it runs.
1003 #[tokio::test]
1004 async fn recursive_rlm_round_waits_on_the_code_execution_gate() {
1005 use crate::core::engine::tests::rlm_host::{
1006 admitted_context, fixture_config, install_fixture_route,
1007 };
1008 use crate::llm_client::mock::{MockLlmClient, canned};
1009 use codewhale_models::{ContentBlock, Message};
1010
1011 for (approval, should_run, read_only) in [
1012 (ApprovalMode::Suggest, false, false),
1013 (ApprovalMode::Suggest, true, false),
1014 (ApprovalMode::Bypass, false, false),
1015 (ApprovalMode::Bypass, false, true),
1016 (ApprovalMode::Auto, true, false),
1017 ] {
1018 let workspace = if cfg!(target_os = "linux") && read_only {
1019 tempfile::tempdir_in(env!("CARGO_MANIFEST_DIR"))
1020 } else {
1021 tempdir()
1022 }
1023 .expect("RLM fixture workspace");
1024 let marker = workspace.path().join("nested-round-ran");
1025 let path = marker.display().to_string();
1026 let nested = format!(
1027 "```repl\nimport errno\ntry:\n open({path:?}, 'w').write('x')\nexcept OSError as error:\n if error.errno not in (errno.EACCES, errno.EPERM, errno.EROFS):\n raise\n FINAL('fixture write refused')\nelse:\n FINAL('nested done')\n```"
1028 );
1029 let rlm = crate::tools::rlm::RLM_TOOL_NAME;
1030 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
1031 canned::tool_call_turn(
1032 "rlm-open",
1033 rlm,
1034 r#"{"action":"open","name":"ctx","content":"fixture context"}"#,
1035 ),
1036 canned::tool_call_turn(
1037 "rlm-eval",
1038 rlm,
1039 r#"{"action":"eval","name":"ctx","code":"print(rlm_query('nested context'))"}"#,
1040 ),
1041 canned::simple_text_turn(&nested),
1042 canned::simple_text_turn("Done."),
1043 ]));
1044 let client: crate::core::model_client::SharedModelClient = mock.clone();
1045 let mut config = fixture_config("captured-working-model");
1046 if approval == ApprovalMode::Bypass && !read_only {
1047 let mut block = codewhale_runtime::config::AutoReviewRuleConfig::default();
1048 block.id = Some("nested-note".into());
1049 block.tool = Some(CODE_EXECUTION_TOOL_NAME.into());
1050 block.reason = Some("recursive code blocked by fixture".into());
1051 config.auto_review = Some(codewhale_runtime::config::AutoReviewConfig {
1052 block: vec![block],
1053 ..Default::default()
1054 });
1055 } else if approval == ApprovalMode::Auto {
1056 for _ in 0..3 {
1057 mock.push_message_response(guardian_fixture_response(
1058 r#"{"risk_level":"low","decision":"allow","reason":"write a fixture marker"}"#,
1059 ));
1060 }
1061 }
1062 let mut engine_config = deterministic_engine_config(workspace.path());
1063 engine_config.auto_review_policy =
1064 crate::core::authority::auto_review::AutoReviewPolicy::from_config(&config);
1065 engine_config.model = "captured-working-model".into();
1066 let (mut engine, handle) = Engine::new_with_model_client(engine_config, &config, client);
1067 install_fixture_route(&mut engine);
1068 engine.session.auto_approve = approval == ApprovalMode::Bypass;
1069 engine.session.approval_mode = approval;
1070 if approval == ApprovalMode::Auto {
1071 engine.turn_run_origin = crate::core::authority::RunOrigin::Interactive;
1072 engine.turn_owner_present = true;
1073 }
1074 if read_only {
1075 let posture = engine.applied_runtime_authority();
1076 engine
1077 .apply_change_mode(
1078 posture.mode,
1079 posture.allow_shell,
1080 posture.trust_mode,
1081 true,
1082 approval,
1083 Some("read-only".into()),
1084 )
1085 .await;
1086 }
1087 engine.session.add_message(Message {
1088 role: Role::User,
1089 content: vec![ContentBlock::Text {
1090 text: "Recurse.".to_string(),
1091 cache_control: None,
1092 }],
1093 });
1094 let context = admitted_context(&engine, "nested-gate-fixture-turn");
1095 if read_only {
1096 assert!(matches!(
1097 context.elevated_sandbox_policy,
1098 Some(codewhale_sandbox::SandboxPolicy::ReadOnly { .. })
1099 ));
1100 }
1101 let registry = crate::tools::ToolRegistryBuilder::new()
1102 .with_rlm_tool()
1103 .build(context);
1104 let policy = test_tool_surface(
1105 &engine,
1106 registry,
1107 Some(vec![
1108 catalog_tool(rlm),
1109 catalog_tool(CODE_EXECUTION_TOOL_NAME),
1110 ]),
1111 AppMode::Agent,
1112 );
1113 let task = tokio::spawn(async move {
1114 let mut turn = crate::core::turn::TurnContext::new(6);
1115 engine.run_turn(&mut turn, policy, None, None).await
1116 });
1117
1118 if approval == ApprovalMode::Suggest {
1119 let events = handle.rx_event.clone();
1120 let nested_card = tokio::time::timeout(Duration::from_secs(30), async {
1121 let mut rx = events.write().await;
1122 while let Some(event) = rx.recv().await {
1123 if let Event::ApprovalRequired { id, tool_name, .. } = event {
1124 if tool_name == CODE_EXECUTION_TOOL_NAME {
1125 return id;
1126 }
1127 // The direct `rlm` call's own approval.
1128 handle.approve_tool_call(&id).await.expect("approve rlm");
1129 }
1130 }
1131 panic!("event stream closed before the nested round asked for approval");
1132 })
1133 .await
1134 .expect("the nested round must wait on its own approval card");
1135 assert!(
1136 nested_card.ends_with(".1"),
1137 "the round is the rlm call's first nested request: {nested_card}"
1138 );
1139 assert!(!marker.exists(), "nothing runs before the decision");
1140
1141 if should_run {
1142 handle
1143 .approve_tool_call(&nested_card)
1144 .await
1145 .expect("approve");
1146 } else {
1147 handle.deny_tool_call(&nested_card).await.expect("deny");
1148 }
1149 }
1150 if approval == ApprovalMode::Auto {
1151 let mut events = handle.rx_event.write().await;
1152 tokio::time::timeout(Duration::from_secs(30), async {
1153 while let Some(event) = events.recv().await {
1154 if let Event::ApprovalRequired {
1155 id,
1156 tool_name,
1157 input,
1158 ..
1159 } = event
1160 {
1161 assert_eq!(tool_name, rlm);
1162 assert_eq!(input["action"], "eval");
1163 handle
1164 .approve_tool_call(&id)
1165 .await
1166 .expect("approve the outer RLM evaluation");
1167 return;
1168 }
1169 }
1170 panic!("event stream closed before the outer RLM evaluation asked its owner");
1171 })
1172 .await
1173 .expect("the outer RLM eval requires its owner's confirmation");
1174 }
1175 let (status, error) = tokio::time::timeout(Duration::from_secs(60), task)
1176 .await
1177 .expect("turn deadline")
1178 .expect("turn task");
1179 assert_eq!(
1180 status,
1181 TurnOutcomeStatus::Completed,
1182 "mode={approval:?}, read_only={read_only}, should_run={should_run}, {error:?}"
1183 );
1184 assert_eq!(
1185 marker.exists(),
1186 should_run,
1187 "mode={approval:?}, read_only={read_only}"
1188 );
1189 if approval != ApprovalMode::Suggest {
1190 let mut rx = handle.rx_event.write().await;
1191 assert!(
1192 !std::iter::from_fn(|| rx.try_recv().ok())
1193 .any(|event| matches!(event, Event::ApprovalRequired { .. }))
1194 );
1195 let requests = mock.captured_requests();
1196 let results: Vec<_> = requests
1197 .iter()
1198 .flat_map(|request| &request.messages)
1199 .flat_map(|message| &message.content)
1200 .filter_map(|block| match block {
1201 ContentBlock::ToolResult {
1202 tool_use_id,
1203 content,
1204 is_error,
1205 ..
1206 } => Some((tool_use_id.as_str(), content.as_str(), *is_error)),
1207 _ => None,
1208 })
1209 .collect();
1210 let refused_start = read_only && results.iter().any(|(id, content, error)| {
1211 *id == "rlm-open" && *error == Some(true) && content.contains(
1212 "read_only execution requires an enforcing native read-only sandbox; nothing was run",
1213 )
1214 });
1215 assert_eq!(
1216 mock.remaining_turns(),
1217 usize::from(refused_start),
1218 "mode={approval:?}, read_only={read_only}, results={results:?}"
1219 );
1220 if read_only && !refused_start {
1221 assert!(
1222 results.iter().any(|(id, content, _)| {
1223 *id == "rlm-eval" && content.contains("fixture write refused")
1224 }),
1225 "the read-only child kernel must report refusing the attempted write: {results:?}"
1226 );
1227 }
1228 }
1229 }
1230 }
1231
1232 /// A kernel keeps what it loaded under the posture it ran in, so a narrower
1233 /// posture starts later code in a fresh interpreter; an unchanged or broader
1234 /// posture keeps the working kernel.
1235 #[tokio::test]
1236 async fn narrowing_the_posture_discards_python_kernels() {
1237 use crate::llm_client::mock::MockLlmClient;
1238
1239 let workspace = tempdir().expect("tempdir");
1240 let client: crate::core::model_client::SharedModelClient =
1241 std::sync::Arc::new(MockLlmClient::new(Vec::new()));
1242 let (mut engine, _handle) = Engine::new_with_model_client(
1243 deterministic_engine_config(workspace.path()),
1244 &Config::default(),
1245 client,
1246 );
1247 // Without a Python interpreter there is no kernel to discard.
1248 let Ok(kernel) =
1249 codewhale_repl::runtime::PythonRuntime::unconfined(&std::env::temp_dir()).await
1250 else {
1251 return;
1252 };
1253 engine.repl_kernel = Some(kernel);
1254 let posture = engine.applied_runtime_authority();
1255
1256 // Re-applying the same posture is not a narrowing.
1257 engine
1258 .apply_change_mode(
1259 posture.mode,
1260 posture.allow_shell,
1261 posture.trust_mode,
1262 posture.auto_approve,
1263 posture.approval_mode,
1264 posture.configured_sandbox_mode.clone(),
1265 )
1266 .await;
1267 assert!(
1268 engine.repl_kernel.is_some(),
1269 "an unchanged posture keeps the kernel"
1270 );
1271
1272 engine
1273 .apply_change_mode(
1274 posture.mode,
1275 posture.allow_shell,
1276 posture.trust_mode,
1277 posture.auto_approve,
1278 posture.approval_mode,
1279 Some("read-only".to_string()),
1280 )
1281 .await;
1282 assert!(
1283 engine.applied_runtime_authority().narrows(&posture),
1284 "fixture must actually narrow"
1285 );
1286 assert!(
1287 engine.repl_kernel.is_none(),
1288 "a narrower posture drops the kernel"
1289 );
1290 }
1291
1292 #[tokio::test]
1293 async fn repl_fence_does_not_run_when_code_execution_is_not_allowed() {
1294 use crate::llm_client::mock::{MockLlmClient, canned};
1295 use codewhale_models::{ContentBlock, Message};
1296
1297 let fence = "```repl\nprint('fence ran')\n```";
1298 for (allowed, disallowed) in [
1299 (Some(Vec::new()), None),
1300 (Some(vec!["read_file".to_string()]), None),
1301 (None, Some(vec!["code_execution".to_string()])),
1302 ] {
1303 let workspace = tempdir().expect("tempdir");
1304 let mock = std::sync::Arc::new(MockLlmClient::new(vec![canned::simple_text_turn(fence)]));
1305 let client: crate::core::model_client::SharedModelClient = mock.clone();
1306 let config = EngineConfig {
1307 allowed_tools: allowed.clone(),
1308 disallowed_tools: disallowed.clone(),
1309 ..deterministic_engine_config(workspace.path())
1310 };
1311 let (mut engine, _handle) =
1312 Engine::new_with_model_client(config, &Config::default(), client);
1313 engine.session.add_message(Message {
1314 role: Role::User,
1315 content: vec![ContentBlock::Text {
1316 text: "Answer.".to_string(),
1317 cache_control: None,
1318 }],
1319 });
1320 let registry = crate::tools::ToolRegistry::new(crate::tools::ToolContext::new(
1321 workspace.path().to_path_buf(),
1322 ));
1323 let policy = test_tool_surface(&engine, registry, None, AppMode::Agent);
1324 let mut turn = crate::core::turn::TurnContext::new(4);
1325 let (status, error) = engine.run_turn(&mut turn, policy, None, None).await;
1326
1327 let case = format!("allowed={allowed:?} disallowed={disallowed:?}");
1328 assert_eq!(status, TurnOutcomeStatus::Completed, "{case}: {error:?}");
1329 assert!(
1330 engine.repl_kernel.is_none(),
1331 "{case}: kernel must not start"
1332 );
1333 assert_eq!(mock.call_count(), 1, "{case}: no follow-up model call");
1334 }
1335 }
1336
1337 #[tokio::test]
1338 async fn plan_mode_repl_fence_does_not_execute() {
1339 use crate::llm_client::mock::{MockLlmClient, canned};
1340 use codewhale_models::{ContentBlock, Message};
1341
1342 let workspace = tempdir().expect("tempdir");
1343 let marker = workspace.path().join("fence-ran");
1344 let fence = format!(
1345 "```repl\nopen({:?}, 'w').write('x')\n```",
1346 marker.display().to_string()
1347 );
1348 let mock = std::sync::Arc::new(MockLlmClient::new(vec![canned::simple_text_turn(&fence)]));
1349 let client: crate::core::model_client::SharedModelClient = mock.clone();
1350 let (mut engine, _handle) = Engine::new_with_model_client(
1351 deterministic_engine_config(workspace.path()),
1352 &Config::default(),
1353 client,
1354 );
1355 engine.session.auto_approve = true;
1356 engine.session.add_message(Message {
1357 role: Role::User,
1358 content: vec![ContentBlock::Text {
1359 text: "Plan only.".to_string(),
1360 cache_control: None,
1361 }],
1362 });
1363 let registry = crate::tools::ToolRegistry::new(crate::tools::ToolContext::new(
1364 workspace.path().to_path_buf(),
1365 ));
1366 let policy = test_tool_surface(
1367 &engine,
1368 registry,
1369 Some(vec![catalog_tool(CODE_EXECUTION_TOOL_NAME)]),
1370 AppMode::Plan,
1371 );
1372 let mut turn = crate::core::turn::TurnContext::new(4);
1373 let (status, error) = engine.run_turn(&mut turn, policy, None, None).await;
1374
1375 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1376 assert!(
1377 engine.repl_kernel.is_none(),
1378 "kernel must not start in Plan"
1379 );
1380 assert!(!marker.exists(), "fenced Python must not run in Plan");
1381 assert_eq!(mock.call_count(), 1, "no follow-up model call");
1382 }
1383
1384 #[tokio::test]
1385 async fn prose_repl_fence_never_executes_outside_rlm() {
1386 use crate::llm_client::mock::{MockLlmClient, canned};
1387 use codewhale_models::{ContentBlock, Message};
1388
1389 for mode in [AppMode::Agent, AppMode::Plan] {
1390 let workspace = tempdir().expect("tempdir");
1391 let marker = workspace.path().join("fence-ran");
1392 let fence = format!(
1393 "Example:\n```repl\nopen({:?}, 'w').write('x')\n```",
1394 marker.display().to_string()
1395 );
1396 let mock = std::sync::Arc::new(MockLlmClient::new(vec![canned::simple_text_turn(&fence)]));
1397 let client: crate::core::model_client::SharedModelClient = mock.clone();
1398 let (mut engine, _handle) = Engine::new_with_model_client(
1399 deterministic_engine_config(workspace.path()),
1400 &Config::default(),
1401 client,
1402 );
1403 engine.session.auto_approve = true;
1404 engine.session.add_message(Message {
1405 role: Role::User,
1406 content: vec![ContentBlock::Text {
1407 text: "Show an example.".to_string(),
1408 cache_control: None,
1409 }],
1410 });
1411 let registry = crate::tools::ToolRegistry::new(crate::tools::ToolContext::new(
1412 workspace.path().to_path_buf(),
1413 ));
1414 let policy = test_tool_surface(
1415 &engine,
1416 registry,
1417 Some(vec![catalog_tool(CODE_EXECUTION_TOOL_NAME)]),
1418 mode,
1419 );
1420 let mut turn = crate::core::turn::TurnContext::new(4);
1421 let (status, error) = engine.run_turn(&mut turn, policy, None, None).await;
1422
1423 assert_eq!(status, TurnOutcomeStatus::Completed, "{mode:?}: {error:?}");
1424 assert!(engine.repl_kernel.is_none(), "{mode:?}: no kernel");
1425 assert!(!marker.exists(), "{mode:?}: prose fence must not run");
1426 assert_eq!(mock.call_count(), 1, "{mode:?}: no follow-up model call");
1427 }
1428 }
1429
1430 #[tokio::test]
1431 async fn any_sandbox_policy_change_discards_python_kernels() {
1432 use crate::llm_client::mock::MockLlmClient;
1433 use crate::rlm::session::{ContextMeta, RlmSession};
1434
1435 let workspace = tempdir().expect("tempdir");
1436 let client: crate::core::model_client::SharedModelClient =
1437 std::sync::Arc::new(MockLlmClient::new(Vec::new()));
1438 let (mut engine, _handle) = Engine::new_with_model_client(
1439 deterministic_engine_config(workspace.path()),
1440 &Config::default(),
1441 client,
1442 );
1443 let Ok(kernel) = codewhale_repl::PythonRuntime::unconfined(&std::env::temp_dir()).await else {
1444 return;
1445 };
1446 let Ok(rlm_kernel) = codewhale_repl::PythonRuntime::unconfined(&std::env::temp_dir()).await
1447 else {
1448 return;
1449 };
1450 engine.repl_kernel = Some(kernel);
1451 engine
1452 .config
1453 .runtime_services
1454 .rlm_sessions
1455 .lock()
1456 .await
1457 .insert(
1458 "ctx".to_string(),
1459 std::sync::Arc::new(tokio::sync::Mutex::new(RlmSession::new(
1460 "ctx".to_string(),
1461 rlm_kernel,
1462 ContextMeta::from_body("body", "text"),
1463 None,
1464 ))),
1465 );
1466 let posture = engine.applied_runtime_authority();
1467
1468 engine
1469 .apply_change_mode(
1470 posture.mode,
1471 posture.allow_shell,
1472 posture.trust_mode,
1473 true,
1474 ApprovalMode::Bypass,
1475 posture.configured_sandbox_mode.clone(),
1476 )
1477 .await;
1478 let widened = engine.applied_runtime_authority();
1479 assert!(!widened.narrows(&posture), "fixture must widen, not narrow");
1480 assert_ne!(
1481 engine.effective_sandbox_policy(&posture),
1482 engine.effective_sandbox_policy(&widened),
1483 "fixture must change the sandbox policy"
1484 );
1485 assert!(
1486 engine.repl_kernel.is_none(),
1487 "a different sandbox policy drops the session kernel"
1488 );
1489 assert!(
1490 engine
1491 .config
1492 .runtime_services
1493 .rlm_sessions
1494 .lock()
1495 .await
1496 .is_empty(),
1497 "a different sandbox policy drops the RLM kernels"
1498 );
1499 }
1500
1500 lines RUST