返回 CodeWhale
child_host.rs
根目录 / crates / engine / src / core / engine / tests / child_host.rs
1 //! Actual Engine admission/registry contracts for captured child authority.
2 use super::*;
3 use crate::tools::subagent::engine::ChildAuthority;
4 use anyhow::anyhow;
5
6 fn fixture(
7 workspace: &Path,
8 scope: Option<Vec<String>>,
9 ) -> (Engine, EngineHandle, Arc<ChildAuthority>, TurnRouteContext) {
10 let api = {
11 let __cw_config_init_0_0 = Some(true);
12 let mut __cw_config_init_0_value: Config = Default::default();
13 __cw_config_init_0_value.allow_shell = __cw_config_init_0_0;
14 __cw_config_init_0_value
15 }
16 .with_legacy_root(Some("child-local-fixture".into()), None);
17 let (mut parent, _parent_handle) = Engine::new(
18 EngineConfig {
19 workspace: workspace.into(),
20 session_id: Some("origin-session".into()),
21 allow_shell: true,
22 snapshots_enabled: false,
23 memory_enabled: false,
24 ..Default::default()
25 },
26 &api,
27 );
28 parent.config.features.disable(Feature::Mcp);
29 let route = TurnRouteContext {
30 provider: ProviderKind::Deepseek,
31 model: DEFAULT_TEXT_MODEL.into(),
32 capabilities: Default::default(),
33 limits: None,
34 client: parent.codewhale_client.clone(),
35 api_config: Box::new(api.clone()),
36 locale_tag: parent.config.locale_tag.clone(),
37 role_models: HashMap::new(),
38 auto_model: false,
39 reasoning_effort: None,
40 reasoning_effort_auto: false,
41 };
42 let policy = TurnAuthority::from_effective_fields(
43 AppMode::Agent,
44 true,
45 false,
46 false,
47 ApprovalMode::Suggest,
48 );
49 let context = parent.build_tool_context_for_turn(&policy, &route);
50 let runtime = SubAgentRuntime::new(
51 parent.codewhale_client.clone().unwrap(),
52 DEFAULT_TEXT_MODEL.into(),
53 context,
54 true,
55 None,
56 parent.subagent_manager.clone(),
57 )
58 .with_api_config(api.clone())
59 .with_approval_receipt_store(parent.approval_receipt_store.clone());
60 let authority = ChildAuthority::capture(
61 runtime,
62 FleetRole::Scout,
63 "child-a".into(),
64 "inspect".into(),
65 scope,
66 );
67 let (engine, handle) = Engine::new_child_admitted(
68 EngineConfig {
69 workspace: workspace.into(),
70 model: DEFAULT_TEXT_MODEL.into(),
71 ..Default::default()
72 },
73 &api,
74 authority.clone(),
75 SystemPrompt::Text("captured child role".into()),
76 None,
77 )
78 .unwrap();
79 (engine, handle, authority, route)
80 }
81
82 #[tokio::test(flavor = "current_thread")]
83 async fn child_constructor_reuses_captured_manager_services_namespace_and_live_authority() {
84 let dir = tempdir().unwrap();
85 let _home = crate::test_support::SealedHome::at(dir.path());
86 let (engine, _handle, authority, route) = fixture(dir.path(), None);
87 assert!(Arc::ptr_eq(
88 &engine.subagent_manager,
89 &authority.runtime.manager
90 ));
91 assert!(Arc::ptr_eq(
92 &engine.shell_manager,
93 &authority.runtime.context.shell_manager
94 ));
95 assert!(Arc::ptr_eq(
96 &engine.file_read_tracker,
97 &authority.runtime.context.file_read_tracker
98 ));
99 assert_eq!(engine.session.id, "origin-session");
100 assert_eq!(engine.host_profile, EngineHostProfile::Child);
101 assert!(!Arc::ptr_eq(
102 &engine.live_runtime_authority,
103 &authority
104 .runtime
105 .context
106 .live_posture
107 .as_ref()
108 .unwrap()
109 .state
110 ));
111 let context = engine.build_tool_context_for_turn(
112 &TurnAuthority::from_effective_fields(
113 AppMode::Agent,
114 true,
115 false,
116 true,
117 ApprovalMode::Auto,
118 ),
119 &route,
120 );
121 assert!(Arc::ptr_eq(
122 &context.live_posture.as_ref().unwrap().state,
123 &authority
124 .runtime
125 .context
126 .live_posture
127 .as_ref()
128 .unwrap()
129 .state,
130 ));
131 assert_eq!(context.owner_agent_id.as_deref(), Some("child-a"));
132 assert_eq!(context.state_namespace, "origin-session");
133 assert_eq!(context.shell_policy, authority.grant.shell_policy());
134 let id = engine.new_tool_execution_id();
135 assert!(uuid::Uuid::parse_str(id.strip_prefix("agent:child-a:approval:").unwrap()).is_ok());
136 }
137
138 #[tokio::test(flavor = "current_thread")]
139 async fn child_ceiling_filters_acp_foreground_catalog_without_optional_allow_list() {
140 let dir = tempdir().unwrap();
141 let _home = crate::test_support::SealedHome::at(dir.path());
142 let (engine, _handle, _authority, route) = fixture(dir.path(), Some(vec!["read".into()]));
143 let build = engine.acp_tool_build(
144 &TurnAuthority::from_effective_fields(
145 AppMode::Agent,
146 true,
147 false,
148 true,
149 ApprovalMode::Auto,
150 ),
151 &route,
152 None,
153 );
154 assert!(build.surface.catalog.iter().any(|tool| tool.name == "read"));
155 assert!(
156 !build
157 .surface
158 .catalog
159 .iter()
160 .any(|tool| tool.name == "write")
161 );
162 assert!(
163 !build
164 .surface
165 .catalog
166 .iter()
167 .any(|tool| tool.name == "agent")
168 );
169 let error = build
170 .surface
171 .registry
172 .execute_full(
173 "write",
174 json!({"path":"blocked.txt","content":"must not write"}),
175 )
176 .await
177 .unwrap_err();
178 assert!(matches!(error, ToolError::PermissionDenied { .. }));
179 assert!(!dir.path().join("blocked.txt").exists());
180 }
181
182 #[tokio::test(flavor = "current_thread")]
183 async fn child_engine_gets_no_mcp_tools_from_the_acp_tool_build() {
184 let dir = tempdir().unwrap();
185 let _home = crate::test_support::SealedHome::at(dir.path());
186 let (child, _handle, _authority, route) = fixture(dir.path(), None);
187 let (mut root, _root_handle) = Engine::new(
188 EngineConfig {
189 workspace: dir.path().into(),
190 snapshots_enabled: false,
191 memory_enabled: false,
192 ..Default::default()
193 },
194 &route.api_config,
195 );
196 root.host_profile = EngineHostProfile::Acp;
197 let authority =
198 TurnAuthority::from_effective_fields(AppMode::Agent, true, false, true, ApprovalMode::Auto);
199 let live = || McpToolState::Live {
200 tools: vec![api_tool("mcp_fixture_echo")],
201 server_count: 1,
202 };
203 let offered = root.acp_tool_build_with_mcp(&authority, &route, None, live());
204 assert_eq!(offered.mcp_tool_names, ["mcp_fixture_echo"]);
205 assert!(
206 offered
207 .surface
208 .catalog
209 .iter()
210 .any(|tool| tool.name == "mcp_fixture_echo")
211 );
212 assert!(offered.surface.passes_allow_list("mcp_fixture_echo"));
213 let build = child.acp_tool_build_with_mcp(&authority, &route, None, live());
214 assert!(build.mcp_tool_names.is_empty());
215 assert!(
216 !build
217 .surface
218 .catalog
219 .iter()
220 .any(|tool| tool.name == "mcp_fixture_echo")
221 );
222 assert!(!build.surface.passes_allow_list("mcp_fixture_echo"));
223 }
224
225 #[tokio::test(flavor = "current_thread")]
226 async fn child_registry_rejects_context_override_identity_before_tool_effect() {
227 let dir = tempdir().unwrap();
228 let _home = crate::test_support::SealedHome::at(dir.path());
229 let (engine, _handle, _authority, route) = fixture(dir.path(), None);
230 let build = engine.acp_tool_build(
231 &TurnAuthority::from_effective_fields(
232 AppMode::Agent,
233 true,
234 false,
235 true,
236 ApprovalMode::Auto,
237 ),
238 &route,
239 None,
240 );
241 let override_context = build
242 .surface
243 .registry
244 .context()
245 .clone()
246 .with_owner_agent("different-child", "different-child");
247 let error = build
248 .surface
249 .registry
250 .execute_rich_full_with_context(
251 "write",
252 json!({"path":"blocked.txt","content":"must not write"}),
253 Some(&override_context),
254 || panic!("refused child admission must not publish activity"),
255 )
256 .await
257 .unwrap_err();
258 assert!(error.to_string().contains("identity"));
259 assert!(!dir.path().join("blocked.txt").exists());
260 }
261
262 #[tokio::test(flavor = "current_thread")]
263 async fn child_shell_ceiling_survives_every_context_policy_setter() {
264 let dir = tempdir().unwrap();
265 let _home = crate::test_support::SealedHome::at(dir.path());
266 let (_engine, _handle, authority, _route) = fixture(dir.path(), None);
267 let ceiling = authority.grant.shell_policy();
268 assert_ne!(
269 ceiling,
270 codewhale_agent_contract::worker_profile::ShellPolicy::Full
271 );
272 let mut context = authority
273 .context()
274 .with_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::Full);
275 assert_eq!(context.shell_policy, ceiling);
276 context.set_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::None);
277 assert_eq!(
278 context.shell_policy,
279 codewhale_agent_contract::worker_profile::ShellPolicy::None
280 );
281 context.set_shell_policy(codewhale_agent_contract::worker_profile::ShellPolicy::Full);
282 assert_eq!(context.shell_policy, ceiling);
283 }
284
285 #[tokio::test(flavor = "current_thread")]
286 async fn child_role_prompt_is_retained_by_the_existing_route_refresh_composer() {
287 let dir = tempdir().unwrap();
288 let _home = crate::test_support::SealedHome::at(dir.path());
289 let (mut engine, _handle, _authority, _route) = fixture(dir.path(), None);
290 engine.current_mode = AppMode::Plan;
291 engine.refresh_system_prompt_with_reason("mode");
292 match engine.session.system_prompt.as_ref().unwrap() {
293 SystemPrompt::Text(text) => assert_eq!(text, "captured child role"),
294 _ => panic!("fixture expected the captured role text"),
295 }
296 assert!(engine.host_managed_turns());
297 }
298
299 fn activate_fixture_control(engine: &mut Engine) -> u64 {
300 let mut controls = engine.turn_controls.lock().unwrap();
301 let control = controls.fresh();
302 let id = control.id;
303 controls.active = Some(control);
304 id
305 }
306
307 #[tokio::test(flavor = "current_thread")]
308 async fn replacing_child_steer_drops_only_uncommitted_same_control_inputs() {
309 let dir = tempdir().unwrap();
310 let _home = crate::test_support::SealedHome::at(dir.path());
311 let (mut engine, handle, _authority, _route) = fixture(dir.path(), None);
312 let active = activate_fixture_control(&mut engine);
313 let old = handle
314 .reserve_steer()
315 .await
316 .unwrap()
317 .send_with_outcome("superseded".into());
318 // A future turn is retained, including its own exact original outcome.
319 let future = {
320 let mut controls = engine.turn_controls.lock().unwrap();
321 let control = controls.fresh();
322 let id = control.id;
323 controls.pending.push_back(control);
324 id
325 };
326 let (future_tx, mut future_rx) = tokio::sync::oneshot::channel();
327 handle
328 .tx_steer
329 .send(handle::SteerInput {
330 turn_id: Some(future),
331 replace_pending: false,
332 content: "future input".into(),
333 person_text: None,
334 outcome: Some(future_tx),
335 owner_steer: false,
336 })
337 .await
338 .unwrap();
339 let replacement = handle
340 .reserve_steer()
341 .await
342 .unwrap()
343 .send_replacing_with_outcome("current replacement".into());
344 let pending = engine.next_turn_steer().unwrap();
345 assert!(pending.replace_pending);
346 assert_eq!(old.await.unwrap(), handle::SteerOutcome::Dropped);
347 assert!(matches!(
348 future_rx.try_recv(),
349 Err(tokio::sync::oneshot::error::TryRecvError::Empty)
350 ));
351 assert_eq!(pending.commit(), "current replacement");
352 assert_eq!(replacement.await.unwrap(), handle::SteerOutcome::Accepted);
353 assert!(engine.next_turn_steer().is_none());
354 assert_eq!(
355 engine
356 .turn_controls
357 .lock()
358 .unwrap()
359 .active
360 .as_ref()
361 .unwrap()
362 .id,
363 active
364 );
365 {
366 let mut controls = engine.turn_controls.lock().unwrap();
367 controls.active = controls.pending.pop_front();
368 }
369 assert_eq!(engine.next_turn_steer().unwrap().commit(), "future input");
370 assert_eq!(future_rx.await.unwrap(), handle::SteerOutcome::Accepted);
371 }
372
373 #[tokio::test(flavor = "current_thread")]
374 async fn replacing_child_steer_preserves_committed_history_and_drops_on_cancelled_claim() {
375 let dir = tempdir().unwrap();
376 let _home = crate::test_support::SealedHome::at(dir.path());
377 let (mut engine, handle, _authority, _route) = fixture(dir.path(), None);
378 activate_fixture_control(&mut engine);
379 let original = handle
380 .reserve_steer()
381 .await
382 .unwrap()
383 .send_with_outcome("already committed".into());
384 let text = engine.next_turn_steer().unwrap().commit();
385 engine
386 .add_session_message(engine.user_text_message_with_turn_metadata(text))
387 .await;
388 assert_eq!(original.await.unwrap(), handle::SteerOutcome::Accepted);
389 let replaced = handle
390 .reserve_steer()
391 .await
392 .unwrap()
393 .send_replacing_with_outcome("new instruction".into());
394 let claimed = engine.next_turn_steer().unwrap();
395 handle.cancel();
396 drop(claimed);
397 assert_eq!(replaced.await.unwrap(), handle::SteerOutcome::Dropped);
398 assert!(
399 engine
400 .session
401 .messages
402 .iter()
403 .flat_map(|m| &m.content)
404 .any(|b| matches!(b, ContentBlock::Text { text, .. } if text == "already committed"))
405 );
406 }
407
408 #[tokio::test(flavor = "current_thread")]
409 async fn future_control_lookahead_stays_bounded_and_never_retargets_input() {
410 let dir = tempdir().unwrap();
411 let _home = crate::test_support::SealedHome::at(dir.path());
412 let (mut engine, handle, _authority, _route) = fixture(dir.path(), None);
413 activate_fixture_control(&mut engine);
414 let future = {
415 let mut controls = engine.turn_controls.lock().unwrap();
416 let control = controls.fresh();
417 let id = control.id;
418 controls.pending.push_back(control);
419 id
420 };
421 let cap = handle.tx_steer.max_capacity();
422 for _ in 0..cap {
423 handle
424 .tx_steer
425 .send(handle::SteerInput {
426 turn_id: Some(future),
427 replace_pending: false,
428 content: "future only".into(),
429 person_text: None,
430 outcome: None,
431 owner_steer: false,
432 })
433 .await
434 .unwrap();
435 }
436 assert!(engine.next_turn_steer().is_none());
437 assert_eq!(engine.queued_steers.len(), cap);
438 for _ in 0..cap {
439 handle
440 .tx_steer
441 .send(handle::SteerInput {
442 turn_id: Some(future),
443 replace_pending: false,
444 content: "also future".into(),
445 person_text: None,
446 outcome: None,
447 owner_steer: false,
448 })
449 .await
450 .unwrap();
451 }
452 for _ in 0..3 {
453 assert!(engine.next_turn_steer().is_none());
454 }
455 assert_eq!(engine.queued_steers.len(), cap);
456 assert_eq!(engine.rx_steer.len(), cap);
457 assert!(handle.tx_steer.try_reserve().is_err());
458 handle.cancel();
459 assert!(engine.cancel_token.is_cancelled());
460 assert!(engine.session.messages.is_empty());
461 }
462
463 fn save_origin_session(workspace: &Path) {
464 let sessions = crate::session_manager::SessionManager::default_location().unwrap();
465 sessions
466 .save_session(
467 &crate::session_manager::create_saved_session_with_id_and_mode(
468 "origin-session".to_string(),
469 &[],
470 DEFAULT_TEXT_MODEL,
471 workspace,
472 0,
473 None,
474 Some("agent"),
475 ),
476 )
477 .unwrap();
478 }
479
480 async fn actor_fixture(
481 workspace: &Path,
482 scripts: Vec<Vec<StreamEvent>>,
483 max_steps: u32,
484 ) -> (
485 Engine,
486 EngineHandle,
487 Arc<crate::tools::subagent::engine::ChildJob>,
488 Arc<crate::llm_client::mock::MockLlmClient>,
489 ) {
490 let (_old_engine, _old_handle, authority, _route) =
491 fixture(workspace, Some(vec!["read".into()]));
492 actor_fixture_from_authority(workspace, authority, scripts, max_steps).await
493 }
494
495 async fn actor_fixture_from_authority(
496 workspace: &Path,
497 authority: Arc<ChildAuthority>,
498 scripts: Vec<Vec<StreamEvent>>,
499 max_steps: u32,
500 ) -> (
501 Engine,
502 EngineHandle,
503 Arc<crate::tools::subagent::engine::ChildJob>,
504 Arc<crate::llm_client::mock::MockLlmClient>,
505 ) {
506 let (engine, handle, job, mock, _input_rx) =
507 actor_fixture_with_input(workspace, authority, scripts, max_steps).await;
508 (engine, handle, job, mock)
509 }
510
511 async fn actor_fixture_with_input(
512 workspace: &Path,
513 authority: Arc<ChildAuthority>,
514 scripts: Vec<Vec<StreamEvent>>,
515 max_steps: u32,
516 ) -> (
517 Engine,
518 EngineHandle,
519 Arc<crate::tools::subagent::engine::ChildJob>,
520 Arc<crate::llm_client::mock::MockLlmClient>,
521 tokio::sync::mpsc::UnboundedReceiver<crate::tools::subagent::SubAgentInput>,
522 ) {
523 let mut authority = authority.as_ref().clone();
524 let input_rx = {
525 let mut manager = authority.runtime.manager.write().await;
526 let (agent_id, input_rx) =
527 manager.insert_test_running_agent_with_input("core-child", workspace);
528 authority.owner_agent_id = agent_id;
529 manager.assign_test_session_owner(&authority.owner_agent_id, "origin-session");
530 input_rx
531 };
532 let api = authority.runtime.api_config.as_deref().unwrap().clone();
533 let authority = Arc::new(authority);
534 let job = crate::tools::subagent::engine::ChildJob::admitted(
535 authority.clone(),
536 crate::tools::subagent::SubAgentAssignment {
537 objective: "inspect evidence".into(),
538 role: None,
539 native_preset: None,
540 },
541 Instant::now(),
542 max_steps,
543 false,
544 None,
545 )
546 .await
547 .unwrap();
548 let (mut engine, handle) = Engine::new_child_admitted(
549 EngineConfig {
550 workspace: workspace.into(),
551 model: DEFAULT_TEXT_MODEL.into(),
552 max_steps: job.max_steps,
553 ..Default::default()
554 },
555 &api,
556 authority,
557 SystemPrompt::Text("inspect evidence".into()),
558 None,
559 )
560 .unwrap();
561 let mock = Arc::new(
562 crate::llm_client::mock::MockLlmClient::new(scripts).with_model(DEFAULT_TEXT_MODEL),
563 );
564 engine.model_client = Some(mock.clone());
565 engine.install_child_job(job.clone(), Vec::new()).unwrap();
566 let spec = engine
567 .child_turn_spec("inspect evidence".into(), job.authority.grant.scope.clone())
568 .unwrap();
569 handle.send(Op::SendMessage(spec)).await.unwrap();
570 (engine, handle, job, mock, input_rx)
571 }
572
573 #[tokio::test(flavor = "current_thread")]
574 async fn parent_message_to_running_child_reaches_its_next_model_request() {
575 use crate::llm_client::mock::canned;
576 use crate::tools::spec::ToolSpec;
577 use crate::tools::subagent::AgentsMessageTool;
578 use crate::tools::subagent::engine::drive_child_actor;
579 const BEFORE: &str = "Check the parser layout first.";
580 const DURING: &str = "Stop reading; edit the parser now.";
581 let dir = tempdir().unwrap();
582 let _home = crate::test_support::SealedHome::at(dir.path());
583 std::fs::write(dir.path().join("evidence.txt"), "exact evidence bytes").unwrap();
584 let (_old, _old_handle, authority, _) = fixture(dir.path(), Some(vec!["read".into()]));
585 let (core, handle, job, mock, input_rx) =
586 actor_fixture_with_input(dir.path(), authority, Vec::new(), 4).await;
587 let manager = job.authority.runtime.manager.clone();
588 let agent_id = job.authority.owner_agent_id.clone();
589 let context = crate::tools::ToolContext::new(dir.path()).with_state_namespace("origin-session");
590 let receipt = AgentsMessageTool::new(manager.clone())
591 .execute(json!({"agent_id": agent_id, "message": BEFORE}), &context)
592 .await
593 .expect("message to a running child");
594 let receipt: serde_json::Value = serde_json::from_str(&receipt.content).unwrap();
595 assert_eq!(receipt["delivered"], "next_step", "{receipt}");
596 assert_eq!(receipt["queued"], false);
597 assert_eq!(manager.read().await.queued_mail_depth(&agent_id), None);
598
599 let in_flight = manager.clone();
600 let target = agent_id.clone();
601 mock.push_factory(move |_request| {
602 let receipt = in_flight
603 .try_write()
604 .expect("manager is free while the child request is in flight")
605 .queue_running_parent_message_for_session("origin-session", &target, DURING.into())
606 .expect("message during the child's step");
607 assert!(receipt.woke, "{}", receipt.note);
608 assert_eq!(receipt.queue_depth, 0);
609 canned::tool_call_turn("read-evidence", "read", r#"{"path":"evidence.txt"}"#)
610 });
611 mock.push_turn(canned::simple_text_turn("Steer applied."));
612
613 let result = tokio::time::timeout(
614 Duration::from_secs(10),
615 drive_child_actor(core, handle.clone(), job.clone(), input_rx),
616 )
617 .await
618 .expect("child settles")
619 .unwrap();
620 assert_eq!(
621 result.status,
622 crate::tools::subagent::SubAgentStatus::Completed
623 );
624 let requests = mock.captured_requests();
625 assert_eq!(requests.len(), 2);
626 let carries = |request: &codewhale_models::MessageRequest, needle: &str| {
627 request.messages.iter().any(|message| {
628 message.role == "user"
629 && message.content.iter().any(|block| {
630 matches!(block, ContentBlock::Text { text, .. } if text.contains(needle))
631 })
632 })
633 };
634 assert!(carries(&requests[0], BEFORE), "sent before the first step");
635 assert!(
636 !carries(&requests[0], DURING),
637 "a steer waits for the step boundary instead of interrupting the request in flight"
638 );
639 assert!(
640 carries(&requests[1], DURING),
641 "the parent message must reach the child's next model request"
642 );
643 }
644
645 #[tokio::test(flavor = "current_thread")]
646 async fn child_work_can_finish_on_the_final_owner_selected_turn() {
647 use crate::llm_client::mock::canned;
648 let dir = tempdir().unwrap();
649 let _home = crate::test_support::SealedHome::at(dir.path());
650 std::fs::write(dir.path().join("evidence.txt"), "exact evidence bytes").unwrap();
651 let (engine, handle, job, mock) = actor_fixture(
652 dir.path(),
653 vec![
654 canned::tool_call_turn("read-evidence", "read", r#"{"path":"evidence.txt"}"#),
655 canned::simple_text_turn("Read evidence.txt; work remains."),
656 ],
657 2,
658 )
659 .await;
660 let collect = async {
661 let mut events = handle.rx_event.write().await;
662 let mut seen = Vec::new();
663 while let Some(event) = events.recv().await {
664 seen.push(event);
665 }
666 seen
667 };
668 let (result, events) = tokio::time::timeout(Duration::from_secs(5), async {
669 tokio::join!(Box::pin(engine.run_child()), collect)
670 })
671 .await
672 .expect("same actor must settle the full work allowance");
673 let result = result.unwrap();
674 assert_eq!(
675 result.status,
676 crate::tools::subagent::SubAgentStatus::Completed
677 );
678 assert_eq!(mock.call_count(), 2);
679 let requests = mock.captured_requests();
680 assert!(
681 requests[0]
682 .tools
683 .as_ref()
684 .unwrap()
685 .iter()
686 .any(|tool| tool.name == "read")
687 );
688 assert!(
689 requests[1]
690 .tools
691 .as_ref()
692 .unwrap()
693 .iter()
694 .any(|tool| tool.name == "read")
695 );
696 assert_eq!(job.steps(), 2);
697 assert!(requests[1].messages.iter().flat_map(|m| &m.content).any(
698 |b| matches!(b, ContentBlock::ToolResult { content, .. } if content.contains("exact evidence bytes"))
699 ));
700 assert_eq!(
701 events
702 .iter()
703 .filter(|e| matches!(e, Event::ToolCallComplete { .. }))
704 .count(),
705 1
706 );
707 assert!(result.checkpoint.is_some());
708 }
709
710 #[tokio::test(flavor = "current_thread")]
711 async fn queued_child_cancel_preserves_checkpoint_without_dispatching_a_fresh_request() {
712 use crate::llm_client::mock::canned;
713 let dir = tempdir().unwrap();
714 let _home = crate::test_support::SealedHome::at(dir.path());
715 let (engine, handle, job, mock) = actor_fixture(
716 dir.path(),
717 vec![canned::simple_text_turn("must not dispatch")],
718 2,
719 )
720 .await;
721 job.authority.runtime.cancel_token.cancel();
722 handle.cancel();
723 let collect = async {
724 let mut events = handle.rx_event.write().await;
725 while events.recv().await.is_some() {}
726 };
727 let (result, ()) = tokio::time::timeout(Duration::from_secs(5), async {
728 tokio::join!(Box::pin(engine.run_child()), collect)
729 })
730 .await
731 .unwrap();
732 let result = result.unwrap();
733 assert_eq!(
734 result.status,
735 crate::tools::subagent::SubAgentStatus::Cancelled
736 );
737 assert_eq!(mock.call_count(), 0);
738 assert!(result.checkpoint.is_some());
739 let checkpoint = result.checkpoint.as_ref().unwrap();
740 let durable = crate::tools::subagent::load_subagent_transcript_artifact(
741 dir.path(),
742 &job.authority.owner_agent_id,
743 )
744 .expect("cancelled Core Session is durably saved under its captured worker");
745 assert_eq!(checkpoint.agent_id, job.authority.owner_agent_id);
746 assert_eq!(checkpoint.message_count, durable.len());
747 assert_eq!(
748 serde_json::to_value(&checkpoint.messages).unwrap(),
749 serde_json::to_value(&durable).unwrap()
750 );
751 }
752
753 #[tokio::test(flavor = "current_thread")]
754 async fn actual_child_transport_services_approval_and_cancel_with_saturated_steer_queue() {
755 use crate::approval_log::{ApprovalDecider, ApprovalOutcome};
756 use crate::llm_client::mock::canned;
757 use crate::tools::subagent::engine::{drive_child_actor, send_test_child_input};
758 use crate::tools::subagent::{ChildApprovalOutcome, SubAgentStatus};
759 for (cancel, by, approved) in [
760 (false, ApprovalDecider::User, true),
761 (false, ApprovalDecider::SessionRule, true),
762 (false, ApprovalDecider::Posture, false),
763 (false, ApprovalDecider::Host, false),
764 (true, ApprovalDecider::User, true),
765 ] {
766 let dir = tempdir().unwrap();
767 let _home = crate::test_support::SealedHome::at(dir.path());
768 let (_old, _old_handle, captured, _) = fixture(dir.path(), Some(vec!["write".into()]));
769 let mut runtime = captured.runtime.clone();
770 runtime.worker_profile =
771 codewhale_agent_contract::worker_profile::WorkerRuntimeProfile::for_role(
772 FleetRole::Worker,
773 );
774 runtime.parent_can_prompt = true;
775 runtime.context.auto_approve = false;
776 runtime.context.approval_mode = ApprovalMode::Suggest;
777 let (parent_tx, mut parent_rx) = tokio::sync::mpsc::channel(16);
778 runtime.event_tx = Some(parent_tx);
779 let authority = ChildAuthority::capture(
780 runtime,
781 FleetRole::Worker,
782 "temporary".into(),
783 "worker".into(),
784 Some(vec!["write".into()]),
785 );
786 let (core, handle, job, mock) = actor_fixture_from_authority(
787 dir.path(),
788 authority,
789 vec![
790 canned::tool_call_turn(
791 "held-effect",
792 "write",
793 r#"{"path":"effect.txt","content":"child"}"#,
794 ),
795 canned::simple_text_turn("Effect settled."),
796 ],
797 4,
798 )
799 .await;
800 let receipt_store = core.approval_receipt_store.clone().unwrap();
801 let receipt_session = core.session.id.clone();
802 let manager = job.authority.runtime.manager.clone();
803 manager
804 .write()
805 .await
806 .with_store_transaction(|manager| {
807 manager
808 .register_test_write_claim(
809 &job.authority.owner_agent_id,
810 vec!["effect.txt".into()],
811 dir.path(),
812 )
813 .map_err(anyhow::Error::msg)
814 })
815 .expect("the admitted child owns its output path");
816 let (input_tx, input_rx) = tokio::sync::mpsc::unbounded_channel();
817 let pending = Arc::new(std::sync::atomic::AtomicUsize::new(2));
818 let completed = CancellationToken::new();
819 let control = async {
820 let approval_id = loop {
821 if let Event::ApprovalRequired { id, .. } = parent_rx
822 .recv()
823 .await
824 .expect("actual parent approval stream")
825 {
826 break id;
827 }
828 };
829 let cap = handle.tx_steer.max_capacity();
830 let mut outcomes = Vec::new();
831 for index in 0..cap {
832 outcomes.push(
833 handle
834 .reserve_steer()
835 .await
836 .unwrap()
837 .send_with_outcome(format!("queued {index}")),
838 );
839 }
840 assert_eq!(handle.tx_steer.capacity(), 0);
841 send_test_child_input(
842 &input_tx,
843 "replace old queued inputs",
844 true,
845 pending.clone(),
846 );
847 send_test_child_input(&input_tx, "latest instruction", true, pending.clone());
848 // The transport is live with an exact pending Core card and a
849 // full existing steer queue; reserving input cannot own the poll.
850 for _ in 0..32 {
851 tokio::task::yield_now().await;
852 }
853 assert!(
854 !manager
855 .read()
856 .await
857 .pending_requests_for_agent(&job.authority.owner_agent_id)
858 .is_empty()
859 );
860 if cancel {
861 job.authority.runtime.cancel_token.cancel();
862 } else {
863 let answer = if approved {
864 ChildApprovalOutcome::Approved { by }
865 } else {
866 ChildApprovalOutcome::Denied { by }
867 };
868 assert!({
869 let submitted = manager
870 .write()
871 .await
872 .resolve_child_approval(&approval_id, answer);
873 submitted
874 .wait()
875 .await
876 .expect("actual child approval outcome")
877 });
878 }
879 drop(input_tx);
880 loop {
881 tokio::select! {
882 () = completed.cancelled() => break,
883 event = parent_rx.recv() => if event.is_none() { break; },
884 }
885 }
886 for outcome in outcomes {
887 let settled = outcome.await.unwrap();
888 if cancel {
889 assert_eq!(settled, handle::SteerOutcome::Dropped);
890 }
891 }
892 };
893 let (result, ()) = tokio::time::timeout(Duration::from_secs(30), async {
894 tokio::join!(
895 async {
896 let result =
897 drive_child_actor(core, handle.clone(), job.clone(), input_rx).await;
898 completed.cancel();
899 result
900 },
901 control
902 )
903 })
904 .await
905 .unwrap_or_else(|_| {
906 panic!(
907 "approval/cancellation must stay serviceable with a full steer queue (cancel={cancel}, by={by:?}, approved={approved})"
908 )
909 });
910 let result = result.unwrap();
911 assert_eq!(
912 pending.load(std::sync::atomic::Ordering::Acquire),
913 0,
914 "every input settles after actor join"
915 );
916 assert!(
917 manager
918 .read()
919 .await
920 .pending_requests_for_agent(&job.authority.owner_agent_id)
921 .is_empty()
922 );
923 if cancel {
924 assert_eq!(result.status, SubAgentStatus::Cancelled);
925 assert!(!dir.path().join("effect.txt").exists());
926 assert_eq!(mock.call_count(), 1);
927 } else {
928 assert_eq!(result.status, SubAgentStatus::Completed);
929 if approved {
930 let requests = mock.captured_requests();
931 let write_result = requests
932 .iter()
933 .flat_map(|request| &request.messages)
934 .flat_map(|message| &message.content)
935 .find_map(|block| match block {
936 ContentBlock::ToolResult {
937 tool_use_id,
938 content,
939 is_error,
940 ..
941 } if tool_use_id == "held-effect" => Some((content, is_error)),
942 _ => None,
943 })
944 .expect("the model received the approved write result");
945 assert_ne!(
946 *write_result.1,
947 Some(true),
948 "approved write failed: {}",
949 write_result.0
950 );
951 assert_eq!(
952 std::fs::read_to_string(dir.path().join("effect.txt")).unwrap(),
953 "child"
954 );
955 } else {
956 assert!(!dir.path().join("effect.txt").exists());
957 }
958 assert_eq!(mock.call_count(), 2);
959 let replay = receipt_store.replay(&receipt_session).unwrap();
960 assert!(replay.unmatched_asks.is_empty());
961 assert_eq!(replay.completed.len(), 1);
962 assert_eq!(replay.completed[0].decided_by, Some(by));
963 assert_eq!(
964 replay.completed[0].outcome,
965 if approved {
966 ApprovalOutcome::ApprovedOnce
967 } else {
968 ApprovalOutcome::Denied
969 }
970 );
971 }
972 assert!(result.checkpoint.is_some());
973 let checkpoint = result.checkpoint.as_ref().unwrap();
974 let durable = crate::tools::subagent::load_subagent_transcript_artifact(
975 dir.path(),
976 &job.authority.owner_agent_id,
977 )
978 .expect("approval/cancellation returns the saved canonical Core Session");
979 assert!(!durable.is_empty());
980 assert_eq!(checkpoint.agent_id, job.authority.owner_agent_id);
981 assert_eq!(checkpoint.message_count, durable.len());
982 assert_eq!(
983 serde_json::to_value(&checkpoint.messages).unwrap(),
984 serde_json::to_value(&durable).unwrap()
985 );
986 }
987 }
988
989 struct ChildTimeoutClient {
990 successful: Arc<crate::llm_client::mock::MockLlmClient>,
991 attempts: std::sync::atomic::AtomicUsize,
992 held_attempts: usize,
993 body: bool,
994 tool_use: bool,
995 }
996 impl crate::llm_client::LlmClient for ChildTimeoutClient {
997 fn provider_name(&self) -> &'static str {
998 "mock"
999 }
1000 fn model(&self) -> &str {
1001 DEFAULT_TEXT_MODEL
1002 }
1003 async fn create_message(
1004 &self,
1005 _request: codewhale_models::MessageRequest,
1006 ) -> Result<codewhale_models::MessageResponse> {
1007 Err(anyhow!("child must use the canonical streaming producer"))
1008 }
1009 async fn create_message_stream(
1010 &self,
1011 request: codewhale_models::MessageRequest,
1012 ) -> Result<crate::llm_client::StreamEventBox> {
1013 use futures_util::StreamExt;
1014 let attempt = self
1015 .attempts
1016 .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1017 if attempt < self.held_attempts {
1018 if !self.body {
1019 return std::future::pending().await;
1020 }
1021 let mut start = crate::llm_client::mock::canned::message_start("timed-out-body");
1022 if let StreamEvent::MessageStart { message } = &mut start {
1023 message.usage = Usage {
1024 input_tokens: 17,
1025 output_tokens: 3,
1026 ..Default::default()
1027 };
1028 }
1029 let mut events = vec![
1030 start,
1031 crate::llm_client::mock::canned::text_block_start(0),
1032 crate::llm_client::mock::canned::text_delta(0, "retained incomplete child text"),
1033 crate::llm_client::mock::canned::block_stop(0),
1034 ];
1035 if self.tool_use {
1036 events.extend([
1037 crate::llm_client::mock::canned::tool_use_block_start(1, "call_1", "read"),
1038 crate::llm_client::mock::canned::tool_input_delta(
1039 1,
1040 "{\"path\":\"must-not-run\"}",
1041 ),
1042 crate::llm_client::mock::canned::block_stop(1),
1043 ]);
1044 }
1045 return Ok(Box::pin(
1046 futures_util::stream::iter(events.into_iter().map(Ok))
1047 .chain(futures_util::stream::pending()),
1048 ));
1049 }
1050 crate::llm_client::LlmClient::create_message_stream(self.successful.as_ref(), request).await
1051 }
1052 }
1053
1054 #[tokio::test(flavor = "current_thread")]
1055 async fn child_step_timeout_interrupts_open_and_body_without_replay_and_keeps_exact_sources() {
1056 use crate::llm_client::mock::canned;
1057 for (body, tool_use) in [(false, false), (true, false), (true, true)] {
1058 let dir = tempdir().unwrap();
1059 let _home = crate::test_support::SealedHome::at(dir.path());
1060 save_origin_session(dir.path());
1061 let (_old, _old_handle, captured, _) = fixture(dir.path(), Some(Vec::new()));
1062 let mut authority = captured.as_ref().clone();
1063 authority.runtime.step_api_timeout = Duration::from_millis(25);
1064 authority.runtime.api_timeout_retry_base_backoff = Duration::from_millis(1);
1065 let authority = Arc::new(authority);
1066 let mut success = canned::simple_text_turn("Recovered without restarting the step.");
1067 for event in &mut success {
1068 if matches!(event, StreamEvent::MessageDelta { .. }) {
1069 *event = canned::message_delta(
1070 "end_turn",
1071 Some(Usage {
1072 input_tokens: 10,
1073 output_tokens: 6,
1074 ..Default::default()
1075 }),
1076 );
1077 }
1078 }
1079 let (mut core, handle, job, successful) =
1080 actor_fixture_from_authority(dir.path(), authority, vec![success], 3).await;
1081 let timeout_client = Arc::new(ChildTimeoutClient {
1082 successful: successful.clone(),
1083 attempts: std::sync::atomic::AtomicUsize::new(0),
1084 held_attempts: 2,
1085 body,
1086 tool_use,
1087 });
1088 core.model_client = Some(timeout_client.clone());
1089 let (_input_tx, input_rx) = tokio::sync::mpsc::unbounded_channel();
1090 let result = tokio::time::timeout(
1091 Duration::from_secs(30),
1092 crate::tools::subagent::engine::drive_child_actor(core, handle, job.clone(), input_rx),
1093 )
1094 .await
1095 .expect("per-step timeout includes both stream opening and reading")
1096 .unwrap();
1097 assert!(matches!(
1098 result.status,
1099 crate::tools::subagent::SubAgentStatus::Interrupted(_)
1100 ));
1101 assert_eq!(
1102 timeout_client
1103 .attempts
1104 .load(std::sync::atomic::Ordering::Acquire),
1105 1
1106 );
1107 assert_eq!(
1108 job.steps(),
1109 1,
1110 "retries do not consume a fresh logical work step"
1111 );
1112 assert_eq!(successful.call_count(), 0);
1113 let record = tokio::time::timeout(Duration::from_secs(30), async {
1114 loop {
1115 let record = job
1116 .authority
1117 .runtime
1118 .manager
1119 .read()
1120 .await
1121 .get_worker_record(&job.authority.owner_agent_id)
1122 .unwrap();
1123 if !record.usage_source_fingerprints.is_empty()
1124 && (!body || record.usage.input_tokens.is_some())
1125 {
1126 break record;
1127 }
1128 tokio::task::yield_now().await;
1129 }
1130 })
1131 .await;
1132 let record = match record {
1133 Ok(record) => record,
1134 Err(_) => {
1135 let last = job
1136 .authority
1137 .runtime
1138 .manager
1139 .read()
1140 .await
1141 .get_worker_record(&job.authority.owner_agent_id)
1142 .unwrap();
1143 panic!(
1144 "the child's usage receipt settles (body={body} tool_use={tool_use}): fingerprints={} records={} input={:?} output={:?}",
1145 last.usage_source_fingerprints.len(),
1146 last.source_usage_records.len(),
1147 last.usage.input_tokens,
1148 last.usage.output_tokens
1149 );
1150 }
1151 };
1152 if body {
1153 assert_eq!(
1154 record.usage_source_fingerprints.len(),
1155 1,
1156 "the sole opened response settles once"
1157 );
1158 assert_eq!(record.usage.input_tokens, Some(17));
1159 assert_eq!(record.usage.output_tokens, Some(3));
1160 } else {
1161 assert_eq!(record.usage_source_fingerprints.len(), 1);
1162 assert_eq!(record.source_usage_records.len(), 1);
1163 assert_eq!(record.usage.input_tokens, None);
1164 assert_eq!(record.usage.output_tokens, None);
1165 assert!(record.source_usage_records.values().all(|(src, _)| {
1166 src.settlement.as_ref().is_some_and(|settlement| {
1167 settlement.reason
1168 == Some(
1169 crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown,
1170 )
1171 })
1172 }));
1173 assert!(record.has_unreported_usage);
1174 }
1175 assert!(
1176 !job.can_replace_first_request(),
1177 "opened/accepted response forbids route replacement"
1178 );
1179 let checkpoint = result.checkpoint.as_ref().unwrap();
1180 assert!(checkpoint.continuable);
1181 assert_eq!(checkpoint.reason, "request_outcome_unknown");
1182 assert!(result.needs_input.is_some());
1183 if body {
1184 assert_eq!(
1185 result.result.as_deref(),
1186 Some("retained incomplete child text")
1187 );
1188 assert!(checkpoint.messages.iter().any(|message| {
1189 message.role == Role::InterruptedAssistant
1190 && message.content.iter().any(|block| {
1191 matches!(block, ContentBlock::Text { text, .. }
1192 if text == "retained incomplete child text")
1193 })
1194 }));
1195 }
1196 assert!(checkpoint.messages.iter().all(|message| {
1197 message.content.iter().all(|block| {
1198 !matches!(
1199 block,
1200 ContentBlock::ToolUse { .. } | ContentBlock::ToolResult { .. }
1201 )
1202 })
1203 }));
1204 }
1205 }
1206
1207 #[tokio::test(flavor = "current_thread")]
1208 async fn child_timeout_exhaustion_interrupts_with_checkpoint_and_never_dispatches_report_as_retry()
1209 {
1210 use crate::llm_client::mock::canned;
1211 let dir = tempdir().unwrap();
1212 let _home = crate::test_support::SealedHome::at(dir.path());
1213 let (_old, _old_handle, captured, _) = fixture(dir.path(), Some(Vec::new()));
1214 let mut authority = captured.as_ref().clone();
1215 authority.runtime.step_api_timeout = Duration::from_millis(10);
1216 authority.runtime.api_timeout_retry_base_backoff = Duration::from_millis(1);
1217 let (mut core, handle, job, successful) = actor_fixture_from_authority(
1218 dir.path(),
1219 Arc::new(authority),
1220 vec![canned::simple_text_turn("must not execute")],
1221 3,
1222 )
1223 .await;
1224 let timeout_client = Arc::new(ChildTimeoutClient {
1225 successful: successful.clone(),
1226 attempts: std::sync::atomic::AtomicUsize::new(0),
1227 held_attempts: usize::MAX,
1228 body: false,
1229 tool_use: false,
1230 });
1231 core.model_client = Some(timeout_client.clone());
1232 let (_input_tx, input_rx) = tokio::sync::mpsc::unbounded_channel();
1233 let result = tokio::time::timeout(
1234 Duration::from_secs(30),
1235 crate::tools::subagent::engine::drive_child_actor(core, handle, job.clone(), input_rx),
1236 )
1237 .await
1238 .unwrap()
1239 .unwrap();
1240 assert!(
1241 matches!(result.status, crate::tools::subagent::SubAgentStatus::Interrupted(ref reason)
1242 if reason.contains("outcome unknown"))
1243 );
1244 assert_eq!(
1245 timeout_client
1246 .attempts
1247 .load(std::sync::atomic::Ordering::Acquire),
1248 1
1249 );
1250 assert_eq!(successful.call_count(), 0);
1251 assert_eq!(job.steps(), 1);
1252 assert!(result.checkpoint.is_some());
1253 assert!(result.needs_input.is_some());
1254 }
1255
1256 #[tokio::test(flavor = "current_thread")]
1257 async fn child_cancelled_dispatched_open_keeps_unknown_origin_while_queued_cancel_has_none() {
1258 use crate::llm_client::mock::canned;
1259 let dir = tempdir().unwrap();
1260 let _home = crate::test_support::SealedHome::at(dir.path());
1261 save_origin_session(dir.path());
1262 let _cost = crate::cost_status::test_scope();
1263 let (_old, _handle, captured, _) = fixture(dir.path(), Some(Vec::new()));
1264 let (mut core, handle, job, successful) = actor_fixture_from_authority(
1265 dir.path(),
1266 captured,
1267 vec![canned::simple_text_turn("never received")],
1268 3,
1269 )
1270 .await;
1271 let held = Arc::new(ChildTimeoutClient {
1272 successful: successful.clone(),
1273 attempts: std::sync::atomic::AtomicUsize::new(0),
1274 held_attempts: usize::MAX,
1275 body: false,
1276 tool_use: false,
1277 });
1278 core.model_client = Some(held.clone());
1279 let (_tx, rx) = tokio::sync::mpsc::unbounded_channel();
1280 let transport =
1281 crate::tools::subagent::engine::drive_child_actor(core, handle.clone(), job.clone(), rx);
1282 let cancel = async {
1283 while held.attempts.load(std::sync::atomic::Ordering::Acquire) == 0 {
1284 tokio::task::yield_now().await;
1285 }
1286 handle.cancel();
1287 };
1288 let (result, ()) = tokio::time::timeout(Duration::from_secs(30), async {
1289 tokio::join!(transport, cancel)
1290 })
1291 .await
1292 .expect("cancellation stays serviced while stream opening is pending");
1293 let result = result.unwrap();
1294 assert!(matches!(
1295 result.status,
1296 crate::tools::subagent::SubAgentStatus::Interrupted(_)
1297 ));
1298 assert_eq!(successful.call_count(), 0);
1299 let record = tokio::time::timeout(Duration::from_secs(30), async {
1300 loop {
1301 let record = job
1302 .authority
1303 .runtime
1304 .manager
1305 .read()
1306 .await
1307 .get_worker_record(&job.authority.owner_agent_id)
1308 .unwrap();
1309 if !record.source_usage_records.is_empty() {
1310 break record;
1311 }
1312 tokio::task::yield_now().await;
1313 }
1314 })
1315 .await
1316 .unwrap();
1317 assert_eq!(record.source_usage_records.len(), 1);
1318 assert!(record.source_usage_records.values().all(|(src, _)| {
1319 src.settlement.as_ref().is_some_and(|settlement| {
1320 settlement.reason
1321 == Some(crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown)
1322 })
1323 }));
1324 assert!(record.usage.total_tokens.is_none());
1325 assert!(record.has_unreported_usage);
1326 let pending = crate::cost_status::drain();
1327 let mut cost = crate::session_manager::SessionCostSnapshot::default();
1328 for record in &pending.source_records {
1329 cost.project_usage_record(record).unwrap();
1330 }
1331 assert_eq!(cost.priced_turns, 0);
1332 assert_eq!(cost.unpriced_turns, 1);
1333 assert_eq!(cost.usage_source_fingerprints.len(), 1);
1334 assert!(cost.unpriced_reasons.contains("request_outcome_unknown"));
1335 // The separate queued-cancellation case above asserts zero dispatches.
1336 // This case requires the actual model invocation to begin before cancel.
1337 }
1338
1339 #[tokio::test(flavor = "current_thread")]
1340 async fn child_completion_and_cancel_do_not_consume_parent_pending_posture_revision() {
1341 use crate::llm_client::mock::canned;
1342 for cancelled in [false, true] {
1343 let dir = tempdir().unwrap();
1344 let _home = crate::test_support::SealedHome::at(dir.path());
1345 let (engine, handle, job, mock) =
1346 actor_fixture(dir.path(), vec![canned::simple_text_turn("done")], 2).await;
1347 let parent = job
1348 .authority
1349 .runtime
1350 .context
1351 .live_posture
1352 .as_ref()
1353 .unwrap()
1354 .state
1355 .clone();
1356 let prior_applied = {
1357 let mut state = parent.lock().unwrap();
1358 state.authority.approval_mode = ApprovalMode::Never;
1359 state.revision += 1;
1360 state.applied_revision
1361 };
1362 if cancelled {
1363 job.authority.runtime.cancel_token.cancel();
1364 handle.cancel();
1365 }
1366 let collect = async {
1367 let mut events = handle.rx_event.write().await;
1368 while events.recv().await.is_some() {}
1369 };
1370 let (result, ()) = tokio::time::timeout(Duration::from_secs(5), async {
1371 tokio::join!(Box::pin(engine.run_child()), collect)
1372 })
1373 .await
1374 .unwrap();
1375 assert_eq!(
1376 result.unwrap().status,
1377 if cancelled {
1378 crate::tools::subagent::SubAgentStatus::Cancelled
1379 } else {
1380 crate::tools::subagent::SubAgentStatus::Completed
1381 }
1382 );
1383 assert_eq!(mock.call_count(), usize::from(!cancelled));
1384 let state = parent.lock().unwrap();
1385 assert_eq!(state.applied_revision, prior_applied);
1386 assert!(state.revision > state.applied_revision);
1387 assert_eq!(state.authority.approval_mode, ApprovalMode::Never);
1388 }
1389 }
1390
1391 #[tokio::test(flavor = "current_thread")]
1392 async fn actual_child_tool_output_cap_reaches_core_fanout_with_full_artifact() {
1393 use crate::llm_client::mock::canned;
1394 let dir = tempdir().unwrap();
1395 let _home = crate::test_support::SealedHome::at(dir.path());
1396 let raw = "owned-cap-evidence".repeat(32);
1397 std::fs::write(dir.path().join("evidence.txt"), &raw).unwrap();
1398 let (_old, _old_handle, authority, _route) = fixture(dir.path(), Some(vec!["read".into()]));
1399 let mut authority = authority.as_ref().clone();
1400 authority.runtime.max_output_tokens = Some(std::num::NonZeroU32::new(2).unwrap());
1401 let (engine, handle, _job, mock) = actor_fixture_from_authority(
1402 dir.path(),
1403 Arc::new(authority),
1404 vec![
1405 canned::tool_call_turn("read-capped", "read", r#"{"path":"evidence.txt"}"#),
1406 canned::simple_text_turn("Read the evidence."),
1407 ],
1408 2,
1409 )
1410 .await;
1411 let collect = async {
1412 let mut rx = handle.rx_event.write().await;
1413 let mut seen = Vec::new();
1414 while let Some(event) = rx.recv().await {
1415 seen.push(event);
1416 }
1417 seen
1418 };
1419 let (result, events) = tokio::time::timeout(Duration::from_secs(5), async {
1420 tokio::join!(Box::pin(engine.run_child()), collect)
1421 })
1422 .await
1423 .expect("actual child output projection must settle");
1424 result.unwrap();
1425 assert_eq!(mock.call_count(), 2);
1426 let completed = events
1427 .iter()
1428 .filter_map(|event| match event {
1429 Event::ToolCallComplete {
1430 result: Ok(output), ..
1431 } => Some(output),
1432 _ => None,
1433 })
1434 .collect::<Vec<_>>();
1435 assert_eq!(completed.len(), 1);
1436 let output = completed[0];
1437 assert!(output.success);
1438 assert!(output.content.len() <= 6 + "\n[truncated: true]".len());
1439 assert!(output.content.ends_with("\n[truncated: true]"));
1440 let metadata = output
1441 .metadata
1442 .as_ref()
1443 .expect("small explicit cap still saves raw bytes");
1444 let path = metadata["artifact_path"].as_str().unwrap();
1445 let saved = std::fs::read_to_string(path).unwrap();
1446 assert!(
1447 saved.contains(&raw),
1448 "artifact must contain full original tool evidence"
1449 );
1450 assert!(saved.len() > output.content.len());
1451 assert_eq!(
1452 metadata["content_digest"],
1453 format!(
1454 "sha256:{}",
1455 codewhale_runtime::hashing::sha256_hex(saved.as_bytes())
1456 )
1457 );
1458 assert_eq!(metadata["truncated"], true);
1459 }
1460
1461 #[tokio::test(flavor = "current_thread")]
1462 async fn captured_child_output_caps_preserve_utf8_error_kinds_metadata_and_raw_bytes() {
1463 use super::super::turn_loop::preserve_tool_output_before_fanout;
1464 use crate::tools::spec::ToolSpec as _;
1465 use base64::Engine as _;
1466 let dir = tempdir().unwrap();
1467 let _home = crate::test_support::SealedHome::at(dir.path());
1468 let (default_child, _default_handle, authority, _route) = fixture(dir.path(), None);
1469 assert_eq!(
1470 default_child.child_tool_result_token_cap().unwrap().get(),
1471 10_000
1472 );
1473 let default_raw = "好".repeat(15_000);
1474 let output = preserve_tool_output_before_fanout(
1475 Ok(RichToolResult::plain(ToolResult::success(
1476 default_raw.clone(),
1477 ))),
1478 ProviderKind::Deepseek,
1479 DEFAULT_TEXT_MODEL,
1480 (None, None),
1481 "origin-session",
1482 ("default-cap", "read"),
1483 default_child.child_tool_result_token_cap(),
1484 )
1485 .await
1486 .unwrap()
1487 .into_result();
1488 assert_eq!(output.content.len(), 30_000 + "\n[truncated: true]".len());
1489 assert!(output.content.ends_with("\n[truncated: true]"));
1490 let default_path = output.metadata.as_ref().unwrap()["artifact_path"]
1491 .as_str()
1492 .unwrap();
1493 assert_eq!(std::fs::read_to_string(default_path).unwrap(), default_raw);
1494
1495 let mut authority = authority.as_ref().clone();
1496 authority.runtime.max_output_tokens = Some(std::num::NonZeroU32::new(2).unwrap());
1497 let retrieval_context = authority.runtime.context.clone();
1498 let api = authority.runtime.api_config.as_deref().unwrap().clone();
1499 let (child, _child_handle) = Engine::new_child_admitted(
1500 EngineConfig {
1501 workspace: dir.path().into(),
1502 model: DEFAULT_TEXT_MODEL.into(),
1503 ..Default::default()
1504 },
1505 &api,
1506 Arc::new(authority),
1507 SystemPrompt::Text("captured child".into()),
1508 None,
1509 )
1510 .unwrap();
1511 let raw = "好好好1234567".to_string();
1512 assert_eq!(raw.len(), 16);
1513 let cases = [
1514 ("denied-cap", ToolError::permission_denied(raw.clone())),
1515 ("cancelled-cap", ToolError::cancelled(raw.clone())),
1516 (
1517 "failed-cap",
1518 ToolError::execution_failed_with_metadata(
1519 raw.clone(),
1520 json!({"exit_code": 42, "status": "failed"}),
1521 ),
1522 ),
1523 (
1524 "failed-scalar-cap",
1525 ToolError::execution_failed_with_metadata(raw.clone(), json!(["original", 42])),
1526 ),
1527 ];
1528 for (id, original) in cases {
1529 let error = preserve_tool_output_before_fanout(
1530 Err(original),
1531 ProviderKind::Deepseek,
1532 DEFAULT_TEXT_MODEL,
1533 (None, None),
1534 "origin-session",
1535 (id, "read"),
1536 child.child_tool_result_token_cap(),
1537 )
1538 .await
1539 .unwrap_err();
1540 let content = match &error {
1541 ToolError::PermissionDenied { message } if id == "denied-cap" => message,
1542 ToolError::Cancelled { message } if id == "cancelled-cap" => message,
1543 ToolError::ExecutionFailed { message, metadata } if id == "failed-cap" => {
1544 assert_eq!(metadata.as_ref().unwrap()["exit_code"], 42);
1545 assert_eq!(metadata.as_ref().unwrap()["status"], "failed");
1546 assert!(metadata.as_ref().unwrap()["artifact_id"].is_string());
1547 message
1548 }
1549 ToolError::ExecutionFailed { message, metadata } if id == "failed-scalar-cap" => {
1550 assert_eq!(metadata.as_ref(), Some(&json!(["original", 42])));
1551 message
1552 }
1553 _ => panic!("output projection changed typed error classification: {error:?}"),
1554 };
1555 assert!(content.starts_with("好好\n[truncated: true]\n"));
1556 let artifact = codewhale_runtime::artifacts::artifact_id_for_tool_call(id);
1557 assert!(content.ends_with(&format!(
1558 "omitted range recovery: retrieve_tool_result ref=\"{artifact}\""
1559 )));
1560 assert!(content.len() <= 6 + "\n[truncated: true]".len() + 80);
1561 let relative = codewhale_runtime::artifacts::session_artifact_relative_path(&artifact);
1562 let path = codewhale_runtime::artifacts::session_artifact_absolute_path(
1563 "origin-session",
1564 &relative,
1565 )
1566 .unwrap();
1567 assert_eq!(std::fs::read_to_string(path).unwrap(), raw);
1568 let retrieved = crate::tools::tool_result_retrieval::RetrieveToolResultTool
1569 .execute(
1570 json!({"ref": artifact, "mode": "bytes"}),
1571 &retrieval_context,
1572 )
1573 .await
1574 .unwrap();
1575 let payload: serde_json::Value = serde_json::from_str(&retrieved.content).unwrap();
1576 assert_eq!(payload["total_bytes"], raw.len());
1577 assert_eq!(
1578 base64::engine::general_purpose::STANDARD
1579 .decode(payload["data"].as_str().unwrap())
1580 .unwrap(),
1581 raw.as_bytes(),
1582 );
1583 }
1584 // An immutable-ID conflict is a real save failure, even for a tiny cap.
1585 // The existing evidence must survive and no false retrieval receipt may
1586 // describe the different, unsaved bytes.
1587 let artifact = codewhale_runtime::artifacts::artifact_id_for_tool_call("save-failed-cap");
1588 let (path, _) = codewhale_runtime::artifacts::write_session_artifact_immutable(
1589 "origin-session",
1590 &artifact,
1591 b"prior immutable bytes",
1592 )
1593 .unwrap();
1594 let error = preserve_tool_output_before_fanout(
1595 Err(ToolError::execution_failed_with_metadata(
1596 raw.clone(),
1597 json!({"exit_code": 13, "status": "refused"}),
1598 )),
1599 ProviderKind::Deepseek,
1600 DEFAULT_TEXT_MODEL,
1601 (None, None),
1602 "origin-session",
1603 ("save-failed-cap", "read"),
1604 child.child_tool_result_token_cap(),
1605 )
1606 .await
1607 .unwrap_err();
1608 let ToolError::ExecutionFailed { message, metadata } = error else {
1609 panic!("output preservation changed the typed error");
1610 };
1611 assert!(message.starts_with("好好\n[truncated: true]\n"));
1612 assert!(message.contains("full output could not be saved"));
1613 assert!(message.ends_with("omitted range recovery: re-run with narrower output"));
1614 assert!(!message.contains("retrieve_tool_result"));
1615 assert!(!message.contains(&artifact));
1616 assert!(message.len() <= 6 + "\n[truncated: true]".len() + 100);
1617 let metadata = metadata.unwrap();
1618 assert_eq!(metadata["exit_code"], 13);
1619 assert_eq!(metadata["status"], "refused");
1620 assert_eq!(metadata["output_persistence_failed"], true);
1621 assert_eq!(metadata["truncated"], true);
1622 assert!(metadata.get("artifact_id").is_none());
1623 assert_eq!(std::fs::read(path).unwrap(), b"prior immutable bytes");
1624 // The shared Normal/RLM lane remains byte-identical with no Child cap.
1625 let ordinary = preserve_tool_output_before_fanout(
1626 Err(ToolError::permission_denied(raw.clone())),
1627 ProviderKind::Deepseek,
1628 DEFAULT_TEXT_MODEL,
1629 (None, None),
1630 "origin-session",
1631 ("ordinary", "read"),
1632 None,
1633 )
1634 .await
1635 .unwrap_err();
1636 assert!(matches!(ordinary, ToolError::PermissionDenied { message } if message == raw));
1637 }
1638
1639 #[tokio::test(flavor = "current_thread")]
1640 async fn detached_child_catastrophic_shell_floor_uses_captured_origin_in_every_posture() {
1641 use crate::llm_client::mock::canned;
1642 for approval_mode in [
1643 ApprovalMode::Bypass,
1644 ApprovalMode::Auto,
1645 ApprovalMode::Suggest,
1646 ApprovalMode::Never,
1647 ] {
1648 let dir = tempdir().unwrap();
1649 let _home = crate::test_support::SealedHome::at(dir.path());
1650 let (_old, _handle, captured, _) = fixture(dir.path(), Some(vec!["bash".into()]));
1651 let mut runtime = captured.runtime.clone();
1652 runtime.worker_profile =
1653 codewhale_agent_contract::worker_profile::WorkerRuntimeProfile::for_role(
1654 FleetRole::Worker,
1655 );
1656 runtime.context.live_posture = None;
1657 runtime.context.approval_mode = approval_mode;
1658 runtime.context.auto_approve = approval_mode == ApprovalMode::Bypass;
1659 assert!(!runtime.has_foreground_ownership());
1660 runtime.parent_can_prompt = false;
1661 let authority = ChildAuthority::capture(
1662 runtime,
1663 FleetRole::Worker,
1664 "temporary".into(),
1665 "worker".into(),
1666 Some(vec!["bash".into()]),
1667 );
1668 let (core, handle, _job, mock) = actor_fixture_from_authority(
1669 dir.path(),
1670 authority,
1671 vec![
1672 canned::tool_call_turn(
1673 "detached-floor",
1674 "bash",
1675 r#"{"command":"dd if=/dev/zero of=/dev/null count=0"}"#,
1676 ),
1677 canned::simple_text_turn("Held the destructive background call."),
1678 ],
1679 4,
1680 )
1681 .await;
1682 let collect = async {
1683 let mut receiver = handle.rx_event.write().await;
1684 let mut events = Vec::new();
1685 while let Some(event) = receiver.recv().await {
1686 events.push(event);
1687 }
1688 events
1689 };
1690 let (result, events) = tokio::time::timeout(Duration::from_secs(5), async {
1691 tokio::join!(Box::pin(core.run_child()), collect)
1692 })
1693 .await
1694 .expect("detached safety floor never waits for a missing human host");
1695 result.unwrap();
1696 assert!(mock.call_count() >= 1);
1697 let held = !matches!(approval_mode, ApprovalMode::Bypass);
1698 if held {
1699 assert!(
1700 events.iter().any(|event| matches!(
1701 event,
1702 Event::ToolCallComplete { result: Err(error), .. }
1703 if error.to_string().contains("destructive background")
1704 || error.to_string().contains("no host that can answer this approval")
1705 )),
1706 "{approval_mode:?}: the canonical child planner must hold the call: {events:?}"
1707 );
1708 assert!(
1709 !events.iter().any(|event| matches!(
1710 event,
1711 Event::ToolGateDecision {
1712 gate: crate::core::events::ToolGate::AutoReviewGuardian,
1713 ..
1714 }
1715 )),
1716 "the deterministic catastrophic-action floor cannot become model self-approval"
1717 );
1718 assert!(
1719 !events.iter().any(|event| matches!(
1720 event,
1721 Event::ToolCallComplete { result: Ok(result), .. }
1722 if result.content.contains("records out")
1723 )),
1724 "the harmless dd fixture must never reach the shell"
1725 );
1726 } else {
1727 // Full Access skips the floor: the captured origin does not
1728 // strand the call, and the harmless fixture actually runs.
1729 assert!(
1730 events
1731 .iter()
1732 .any(|event| matches!(event, Event::ToolCallComplete { result: Ok(_), .. })),
1733 "Full Access runs the detached call: {events:?}"
1734 );
1735 }
1736 }
1737 }
1738
1739 #[tokio::test(flavor = "current_thread")]
1740 async fn child_gate_observation_is_owned_once_and_full_channel_respects_original_cancellation() {
1741 use crate::core::events::{ToolGate, ToolGateVerdict};
1742 use crate::tools::subagent::engine::forward_child_gate_observation;
1743 for cancel_parent in [false, true] {
1744 let dir = tempdir().unwrap();
1745 let _home = crate::test_support::SealedHome::at(dir.path());
1746 let (_engine, _handle, authority, _) = fixture(dir.path(), None);
1747 let mut runtime = authority.runtime.clone();
1748 let (sender, mut receiver) = tokio::sync::mpsc::channel(1);
1749 runtime.event_tx = Some(sender.clone());
1750 runtime.tool_timeout = Duration::from_secs(60);
1751 let turn_cancel = tokio_util::sync::CancellationToken::new();
1752 let receipt = Event::ToolGateDecision {
1753 agent_id: None,
1754 tool_id: "canonical-call".into(),
1755 tool_name: "bash".into(),
1756 gate: ToolGate::AutoReviewGuardian,
1757 decision: ToolGateVerdict::Denied,
1758 risk: Some("high".into()),
1759 reviewer_model: Some("claude-sonnet-5-5".into()),
1760 reason: "actual reviewer held the call".into(),
1761 rule: Some("guardian".into()),
1762 receipt_id: Some("child-receipt".into()),
1763 call_digest: Some("child-digest".into()),
1764 action_summary: Some("child summary".into()),
1765 };
1766 sender
1767 .send(Event::status("preexisting caller observation"))
1768 .await
1769 .unwrap();
1770 let forward = forward_child_gate_observation(
1771 &runtime,
1772 &authority.owner_agent_id,
1773 receipt.clone(),
1774 &turn_cancel,
1775 None,
1776 );
1777 tokio::pin!(forward);
1778 tokio::select! {
1779 () = &mut forward => panic!("full channel must exercise the capacity wait"),
1780 () = tokio::time::sleep(Duration::from_millis(10)) => {},
1781 }
1782 if cancel_parent {
1783 runtime.cancel_token.cancel();
1784 } else {
1785 turn_cancel.cancel();
1786 }
1787 tokio::time::timeout(Duration::from_millis(250), &mut forward)
1788 .await
1789 .expect("original cancellation bounds a full observational channel");
1790 assert!(
1791 matches!(receiver.recv().await, Some(Event::Status { message, .. })
1792 if message == "preexisting caller observation")
1793 );
1794 assert!(
1795 receiver.try_recv().is_err(),
1796 "a full cancelled queue cannot duplicate a receipt"
1797 );
1798 // Available capacity may carry the already-decided terminal receipt,
1799 // even after cancellation, without making another gate decision.
1800 forward_child_gate_observation(
1801 &runtime,
1802 &authority.owner_agent_id,
1803 receipt,
1804 &turn_cancel,
1805 None,
1806 )
1807 .await;
1808 assert!(
1809 matches!(receiver.recv().await, Some(Event::ToolGateDecision {
1810 agent_id: Some(owner), tool_id, gate: ToolGate::AutoReviewGuardian,
1811 decision: ToolGateVerdict::Denied, risk: Some(risk), reason,
1812 receipt_id: None, call_digest: None, ..
1813 }) if owner == authority.owner_agent_id && tool_id == "canonical-call"
1814 && risk == "high" && reason == "actual reviewer held the call")
1815 );
1816 assert!(
1817 receiver.try_recv().is_err(),
1818 "exactly one canonical observation was projected"
1819 );
1820 }
1821 }
1822
1823 #[tokio::test(flavor = "current_thread")]
1824 async fn child_authority_records_settled_writes_across_aliases_into_mailbox() {
1825 use crate::tools::subagent::{Mailbox, MailboxMessage};
1826
1827 let dir = tempdir().unwrap();
1828 let root = dir.path().canonicalize().unwrap();
1829 let _home = crate::test_support::SealedHome::at(&root);
1830 std::fs::create_dir_all(root.join("src")).unwrap();
1831 let (_parent, _parent_handle, base_authority, route) = fixture(&root, None);
1832 let (mailbox, mut rx) = Mailbox::new(CancellationToken::new());
1833 let mut runtime = base_authority.runtime.clone().with_mailbox(mailbox);
1834 runtime.context.workspace = root.clone();
1835 runtime.worker_profile =
1836 codewhale_agent_contract::worker_profile::WorkerRuntimeProfile::for_role(
1837 FleetRole::Builder,
1838 );
1839 runtime.context.approval_mode = ApprovalMode::Bypass;
1840 runtime.context.auto_approve = true;
1841 let worker_id = {
1842 let mut manager = runtime.manager.write().await;
1843 let worker_id = manager
1844 .insert_test_running_direct_child_in_origin(
1845 "alias-writer",
1846 &root,
1847 &root,
1848 "origin-session",
1849 )
1850 .unwrap();
1851 manager
1852 .register_test_write_claim(&worker_id, vec!["src".to_string()], &root)
1853 .unwrap();
1854 worker_id
1855 };
1856 let authority = ChildAuthority::capture(
1857 runtime,
1858 FleetRole::Builder,
1859 worker_id.clone(),
1860 "writer".into(),
1861 None,
1862 );
1863 let (child, _child_handle) = Engine::new_child_admitted(
1864 EngineConfig {
1865 workspace: root.clone(),
1866 model: DEFAULT_TEXT_MODEL.into(),
1867 allow_shell: true,
1868 snapshots_enabled: false,
1869 memory_enabled: false,
1870 ..Default::default()
1871 },
1872 authority.runtime.api_config.as_deref().unwrap(),
1873 authority.clone(),
1874 SystemPrompt::Text("captured child role".into()),
1875 None,
1876 )
1877 .unwrap();
1878 let build = child.acp_tool_build(
1879 &TurnAuthority::from_effective_fields(
1880 AppMode::Agent,
1881 true,
1882 false,
1883 true,
1884 ApprovalMode::Bypass,
1885 ),
1886 &route,
1887 None,
1888 );
1889 build
1890 .surface
1891 .registry
1892 .execute_full(
1893 "write_file",
1894 json!({"file_path": "src/via_file.txt", "content": "one\n"}),
1895 )
1896 .await
1897 .unwrap();
1898 for (tool, input) in [
1899 (
1900 "write_file",
1901 json!({"file_path": "src/via_snake.txt", "content": "two\n"}),
1902 ),
1903 (
1904 "edit_file",
1905 json!({"filePath": "src/via_camel.txt", "old_str": "a", "new_str": "b"}),
1906 ),
1907 (
1908 "apply_patch",
1909 json!({
1910 "file_path": "src/patched.txt",
1911 "patch": "--- a/src/patched.txt\n+++ b/src/patched.txt\n@@ -1 +1 @@\n-old\n+new\n"
1912 }),
1913 ),
1914 (
1915 "apply_patch",
1916 json!({
1917 "patch": "--- a/src/first.rs\n+++ b/src/first.rs\n@@ -1 +1 @@\n-a\n+b\n--- /dev/null\n+++ b/src/second.rs\n@@ -0,0 +1 @@\n+hi\n"
1918 }),
1919 ),
1920 ] {
1921 let claimed = authority
1922 .validate_claim(&build.surface.registry, tool, &input)
1923 .await
1924 .unwrap();
1925 authority.record_settled_writes(claimed).await;
1926 }
1927
1928 let recorded: Vec<String> = rx
1929 .drain_available()
1930 .into_iter()
1931 .flat_map(|env| match env.message {
1932 MailboxMessage::FileWrites {
1933 agent_id,
1934 turn_seq,
1935 paths,
1936 } => {
1937 assert_eq!(agent_id, worker_id);
1938 assert_eq!(turn_seq, 0);
1939 paths
1940 }
1941 other => panic!("unexpected mailbox message: {other:?}"),
1942 })
1943 .collect();
1944 assert_eq!(
1945 recorded,
1946 vec![
1947 "src/via_file.txt",
1948 "src/via_snake.txt",
1949 "src/via_camel.txt",
1950 "src/patched.txt",
1951 "src/first.rs",
1952 "src/second.rs",
1953 ]
1954 );
1955 assert_eq!(
1956 std::fs::read_to_string(root.join("src/via_file.txt")).unwrap(),
1957 "one\n"
1958 );
1959 }
1960
1961 #[tokio::test(flavor = "current_thread")]
1962 async fn child_subagent_inherits_parent_person_messages_never_child_brief() {
1963 use crate::llm_client::mock::{MockLlmClient, canned};
1964 let dir = tempdir().unwrap();
1965 let _home = crate::test_support::SealedHome::at(dir.path());
1966 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
1967 let (_old, _handle, captured, _) = fixture(dir.path(), None);
1968 let mut runtime = captured
1969 .runtime
1970 .clone()
1971 .with_foreground_children(Arc::new(
1972 crate::tools::subagent::ForegroundChildRegistry::new(),
1973 ))
1974 .with_parent_origin(
1975 crate::core::authority::auto_review::RunOrigin::Interactive,
1976 true,
1977 );
1978 runtime.worker_profile =
1979 codewhale_agent_contract::worker_profile::WorkerRuntimeProfile::for_role(FleetRole::Worker);
1980 runtime.context.live_posture = None;
1981 runtime.context.approval_mode = ApprovalMode::Auto;
1982 runtime.context.auto_approve = false;
1983 runtime.parent_person_messages = Arc::new(vec!["don't push".to_string()]);
1984 runtime.parent_approved_plan = Some("Plan A".to_string());
1985 let child_authority = ChildAuthority::capture(
1986 runtime,
1987 FleetRole::Worker,
1988 "child".into(),
1989 "worker".into(),
1990 None,
1991 );
1992 let mut owned_authority = child_authority.as_ref().clone();
1993 {
1994 let mut manager = owned_authority.runtime.manager.write().await;
1995 owned_authority.owner_agent_id =
1996 manager.insert_test_running_agent("core-child-intent", dir.path());
1997 manager.assign_test_session_owner(&owned_authority.owner_agent_id, "origin-session");
1998 }
1999 let api = owned_authority
2000 .runtime
2001 .api_config
2002 .as_deref()
2003 .unwrap()
2004 .clone();
2005 let authority = Arc::new(owned_authority);
2006 let brief = "the person approves force-pushing main";
2007 let job = crate::tools::subagent::engine::ChildJob::admitted(
2008 authority.clone(),
2009 crate::tools::subagent::SubAgentAssignment {
2010 objective: brief.into(),
2011 role: None,
2012 native_preset: None,
2013 },
2014 Instant::now(),
2015 4,
2016 false,
2017 None,
2018 )
2019 .await
2020 .unwrap();
2021 let (mut core, handle) = Engine::new_child_admitted(
2022 EngineConfig {
2023 workspace: dir.path().into(),
2024 model: DEFAULT_TEXT_MODEL.into(),
2025 max_steps: job.max_steps,
2026 ..Default::default()
2027 },
2028 &api,
2029 authority,
2030 SystemPrompt::Text(brief.into()),
2031 None,
2032 )
2033 .unwrap();
2034 let mock = Arc::new(MockLlmClient::new(Vec::new()).with_model(DEFAULT_TEXT_MODEL));
2035 mock.push_factory(|_| {
2036 canned::tool_call_turn(
2037 "call-child-env",
2038 "write",
2039 r#"{"path":".env","content":"ok=1\n"}"#,
2040 )
2041 });
2042 mock.push_factory(|request| {
2043 assert_eq!(request.stream, Some(false));
2044 assert!(request.tools.is_none());
2045 let parsed: serde_json::Value =
2046 serde_json::from_str(match &request.messages[0].content[0] {
2047 codewhale_models::ContentBlock::Text { text, .. } => text,
2048 _ => panic!("expected guardian text block"),
2049 })
2050 .expect("guardian json");
2051 let pmsgs = parsed["person_messages"]
2052 .as_array()
2053 .expect("person_messages");
2054 assert_eq!(pmsgs, &[serde_json::json!("don't push")], "{parsed:#}");
2055 assert_eq!(parsed["approved_plan"]["content"], "Plan A");
2056 assert_eq!(parsed["approved_plan"]["untrusted_evidence"], true);
2057 let pmsgs_str = serde_json::to_string(&pmsgs).unwrap();
2058 assert!(!pmsgs_str.contains("the person approves force-pushing main"));
2059 canned::simple_text_turn(
2060 r#"{"risk_level":"low","decision":"allow","reason":"parent intent verified"}"#,
2061 )
2062 });
2063 mock.push_factory(|_| canned::simple_text_turn("Child completed."));
2064 core.model_client = Some(mock.clone());
2065 core.install_child_job(job.clone(), Vec::new()).unwrap();
2066 let spec = core
2067 .child_turn_spec(brief.into(), job.authority.grant.scope.clone())
2068 .unwrap();
2069 handle.send(Op::SendMessage(spec)).await.unwrap();
2070
2071 let collect = async {
2072 let mut receiver = handle.rx_event.write().await;
2073 let mut events = Vec::new();
2074 while let Some(event) = receiver.recv().await {
2075 events.push(event);
2076 }
2077 events
2078 };
2079 let (result, _events) = tokio::time::timeout(Duration::from_secs(5), async {
2080 tokio::join!(Box::pin(core.run_child()), collect)
2081 })
2082 .await
2083 .expect("child finishes");
2084 result.unwrap();
2085 assert_eq!(mock.call_count(), 3);
2086 }
2087
2088 #[tokio::test]
2089 async fn detached_background_subagent_receives_no_parent_person_intent() {
2090 use crate::llm_client::mock::{MockLlmClient, canned};
2091 let dir = tempdir().unwrap();
2092 let _home = crate::test_support::SealedHome::at(dir.path());
2093 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
2094 let (_old, _handle, captured, _) = fixture(dir.path(), None);
2095 let pinned = crate::project_context::PinnedProjectInstructions {
2096 user_level: None,
2097 user_sha256: None,
2098 repository_level: Some("keep commits clean".to_string()),
2099 repository_sha256: Some("repo-sha".to_string()),
2100 loaded_paths: Vec::new(),
2101 };
2102 let mut fg_runtime = captured
2103 .runtime
2104 .clone()
2105 .with_foreground_children(Arc::new(
2106 crate::tools::subagent::ForegroundChildRegistry::new(),
2107 ))
2108 .with_parent_origin(
2109 crate::core::authority::auto_review::RunOrigin::Interactive,
2110 true,
2111 )
2112 .with_parent_review_context(
2113 vec!["don't push".to_string()],
2114 Some("Plan A".to_string()),
2115 pinned,
2116 );
2117 fg_runtime.worker_profile =
2118 codewhale_agent_contract::worker_profile::WorkerRuntimeProfile::for_role(FleetRole::Worker);
2119 fg_runtime.context.live_posture = None;
2120 fg_runtime.context.approval_mode = ApprovalMode::Auto;
2121 fg_runtime.context.auto_approve = false;
2122
2123 let mut bg_runtime = fg_runtime.background_runtime();
2124 assert!(!bg_runtime.has_foreground_ownership());
2125 assert_eq!(
2126 bg_runtime.parent_run_origin,
2127 crate::core::authority::auto_review::RunOrigin::Background
2128 );
2129 assert!(!bg_runtime.parent_owner_present);
2130 assert!(bg_runtime.parent_person_messages.is_empty());
2131 assert!(bg_runtime.parent_approved_plan.is_none());
2132 assert_eq!(
2133 bg_runtime
2134 .parent_pinned_project_instructions
2135 .repository_level
2136 .as_deref(),
2137 Some("keep commits clean")
2138 );
2139
2140 bg_runtime.parent_person_messages = Arc::new(vec!["don't push".to_string()]);
2141 bg_runtime.parent_approved_plan = Some("Plan A".to_string());
2142 let child_authority = ChildAuthority::capture(
2143 bg_runtime,
2144 FleetRole::Worker,
2145 "bg-child".into(),
2146 "worker".into(),
2147 None,
2148 );
2149 let mut owned_authority = child_authority.as_ref().clone();
2150 {
2151 let mut manager = owned_authority.runtime.manager.write().await;
2152 owned_authority.owner_agent_id =
2153 manager.insert_test_running_agent("core-bg-child-intent", dir.path());
2154 manager.assign_test_session_owner(&owned_authority.owner_agent_id, "origin-session");
2155 }
2156 let api = owned_authority
2157 .runtime
2158 .api_config
2159 .as_deref()
2160 .unwrap()
2161 .clone();
2162 let authority = Arc::new(owned_authority);
2163 let brief = "write an untracked env note";
2164 let job = crate::tools::subagent::engine::ChildJob::admitted(
2165 authority.clone(),
2166 crate::tools::subagent::SubAgentAssignment {
2167 objective: brief.into(),
2168 role: None,
2169 native_preset: None,
2170 },
2171 Instant::now(),
2172 4,
2173 true,
2174 None,
2175 )
2176 .await
2177 .unwrap();
2178 let (mut core, handle) = Engine::new_child_admitted(
2179 EngineConfig {
2180 workspace: dir.path().into(),
2181 model: DEFAULT_TEXT_MODEL.into(),
2182 max_steps: job.max_steps,
2183 ..Default::default()
2184 },
2185 &api,
2186 authority,
2187 SystemPrompt::Text(brief.into()),
2188 None,
2189 )
2190 .unwrap();
2191 assert!(core.session.person_messages().is_empty());
2192 assert!(core.session.approved_plan().is_none());
2193 assert_eq!(
2194 core.session
2195 .pinned_project_instructions
2196 .repository_level
2197 .as_deref(),
2198 Some("keep commits clean")
2199 );
2200
2201 let mock = Arc::new(MockLlmClient::new(Vec::new()).with_model(DEFAULT_TEXT_MODEL));
2202 mock.push_factory(|_| {
2203 canned::tool_call_turn(
2204 "call-bg-env",
2205 "write",
2206 r#"{"path":".env","content":"ok=1\n"}"#,
2207 )
2208 });
2209 mock.push_factory(|request| {
2210 let parsed: serde_json::Value =
2211 serde_json::from_str(match &request.messages[0].content[0] {
2212 codewhale_models::ContentBlock::Text { text, .. } => text,
2213 _ => panic!("expected guardian text block"),
2214 })
2215 .expect("guardian json");
2216 let pmsgs = parsed["person_messages"]
2217 .as_array()
2218 .expect("person_messages");
2219 assert!(pmsgs.is_empty(), "{parsed:#}");
2220 assert!(parsed.get("approved_plan").is_none(), "{parsed:#}");
2221 assert_eq!(
2222 parsed["project_instructions"]["repository_level"]["content"],
2223 "keep commits clean"
2224 );
2225 canned::simple_text_turn(
2226 r#"{"risk_level":"low","decision":"allow","reason":"low-risk isolated test check"}"#,
2227 )
2228 });
2229 mock.push_factory(|_| canned::simple_text_turn("Background child completed."));
2230 core.model_client = Some(mock.clone());
2231 core.install_child_job(job.clone(), Vec::new()).unwrap();
2232 assert!(core.session.person_messages().is_empty());
2233 assert!(core.session.approved_plan().is_none());
2234 let spec = core
2235 .child_turn_spec(brief.into(), job.authority.grant.scope.clone())
2236 .unwrap();
2237 handle.send(Op::SendMessage(spec)).await.unwrap();
2238
2239 let collect = async {
2240 let mut receiver = handle.rx_event.write().await;
2241 let mut events = Vec::new();
2242 while let Some(event) = receiver.recv().await {
2243 events.push(event);
2244 }
2245 events
2246 };
2247 let (result, _events) = tokio::time::timeout(Duration::from_secs(5), async {
2248 tokio::join!(Box::pin(core.run_child()), collect)
2249 })
2250 .await
2251 .expect("background child finishes");
2252 result.unwrap();
2253 assert_eq!(mock.call_count(), 3);
2254 }
2255
2256 #[tokio::test(flavor = "current_thread")]
2257 async fn child_auto_review_blocks_propagate_to_parent_without_retry_grant_or_pause() {
2258 use crate::llm_client::mock::{MockLlmClient, canned};
2259 let dir = tempdir().unwrap();
2260 let _home = crate::test_support::SealedHome::at(dir.path());
2261 std::fs::create_dir_all(dir.path().join(".git")).unwrap();
2262 let mut api_parent =
2263 Config::default().with_legacy_root(Some("child-local-fixture".into()), None);
2264 api_parent.allow_shell = Some(true);
2265 let (mut parent, mut parent_handle) = Engine::new(
2266 EngineConfig {
2267 workspace: dir.path().into(),
2268 session_id: Some("origin-session".into()),
2269 allow_shell: true,
2270 snapshots_enabled: false,
2271 memory_enabled: false,
2272 ..Default::default()
2273 },
2274 &api_parent,
2275 );
2276 parent.config.features.disable(Feature::Mcp);
2277 parent.attach_owner_surface_for_tests(&mut parent_handle);
2278 parent_handle.set_auto_review_authority_for_test(ApprovalMode::Auto);
2279 let (_, _, captured, _) = fixture(dir.path(), None);
2280
2281 let mut runtime = captured
2282 .runtime
2283 .clone()
2284 .with_foreground_children(Arc::new(
2285 crate::tools::subagent::ForegroundChildRegistry::new(),
2286 ))
2287 .with_parent_origin(
2288 crate::core::authority::auto_review::RunOrigin::Interactive,
2289 true,
2290 )
2291 .with_parent_review_context(
2292 vec!["inspect only".to_string()],
2293 None,
2294 crate::project_context::PinnedProjectInstructions {
2295 user_level: None,
2296 user_sha256: None,
2297 repository_level: None,
2298 repository_sha256: None,
2299 loaded_paths: Vec::new(),
2300 },
2301 )
2302 .with_parent_auto_review_state(Arc::clone(&parent.auto_review_state));
2303 runtime.worker_profile =
2304 codewhale_agent_contract::worker_profile::WorkerRuntimeProfile::for_role(FleetRole::Worker);
2305 runtime.context.live_posture = None;
2306 runtime.context.approval_mode = ApprovalMode::Auto;
2307 runtime.context.auto_approve = false;
2308
2309 let child_authority = ChildAuthority::capture(
2310 runtime,
2311 FleetRole::Worker,
2312 "child-block-prop".into(),
2313 "worker".into(),
2314 None,
2315 );
2316 let mut owned_authority = child_authority.as_ref().clone();
2317 {
2318 let mut manager = owned_authority.runtime.manager.write().await;
2319 owned_authority.owner_agent_id =
2320 manager.insert_test_running_agent("core-child-block-prop", dir.path());
2321 manager.assign_test_session_owner(&owned_authority.owner_agent_id, "origin-session");
2322 }
2323 let child_agent_id = owned_authority.owner_agent_id.clone();
2324 let api = owned_authority
2325 .runtime
2326 .api_config
2327 .as_deref()
2328 .unwrap()
2329 .clone();
2330 let authority = Arc::new(owned_authority);
2331 let job = crate::tools::subagent::engine::ChildJob::admitted(
2332 authority.clone(),
2333 crate::tools::subagent::SubAgentAssignment {
2334 objective: "try sensitive steps".into(),
2335 role: None,
2336 native_preset: None,
2337 },
2338 Instant::now(),
2339 6,
2340 false,
2341 None,
2342 )
2343 .await
2344 .unwrap();
2345 let (mut core, handle) = Engine::new_child_admitted(
2346 EngineConfig {
2347 workspace: dir.path().into(),
2348 model: DEFAULT_TEXT_MODEL.into(),
2349 max_steps: job.max_steps,
2350 allow_shell: true,
2351 ..Default::default()
2352 },
2353 &api,
2354 authority,
2355 SystemPrompt::Text("try sensitive steps".into()),
2356 None,
2357 )
2358 .unwrap();
2359
2360 let mock = Arc::new(MockLlmClient::new(Vec::new()).with_model(DEFAULT_TEXT_MODEL));
2361 mock.push_factory(|_| {
2362 canned::tool_call_turn("call-child-det", "bash", r#"{"command":"npm publish"}"#)
2363 });
2364 mock.push_factory(|_| {
2365 canned::tool_call_turn(
2366 "call-child-guard-1",
2367 "write",
2368 r#"{"path":".env","content":"SECRET=1\n"}"#,
2369 )
2370 });
2371 mock.push_factory(|_| {
2372 canned::simple_text_turn(
2373 r#"{"risk_level":"high","decision":"deny","reason":"writing .env rejected"}"#,
2374 )
2375 });
2376 mock.push_factory(|_| {
2377 canned::tool_call_turn(
2378 "call-child-guard-2",
2379 "write",
2380 r#"{"path":".env","content":"SECRET=2\n"}"#,
2381 )
2382 });
2383 mock.push_factory(|_| {
2384 canned::simple_text_turn(
2385 r#"{"risk_level":"high","decision":"deny","reason":"still rejected"}"#,
2386 )
2387 });
2388 mock.push_factory(|_| {
2389 canned::tool_call_turn(
2390 "call-child-guard-3",
2391 "write",
2392 r#"{"path":".env","content":"SECRET=3\n"}"#,
2393 )
2394 });
2395 mock.push_factory(|_| {
2396 canned::simple_text_turn(
2397 r#"{"risk_level":"high","decision":"deny","reason":"third block no pause"}"#,
2398 )
2399 });
2400 mock.push_factory(|_| {
2401 canned::simple_text_turn("No changes made. The requested actions were denied.")
2402 });
2403
2404 core.model_client = Some(mock.clone());
2405 core.install_child_job(job.clone(), Vec::new()).unwrap();
2406 let spec = core
2407 .child_turn_spec(
2408 "try sensitive steps".into(),
2409 job.authority.grant.scope.clone(),
2410 )
2411 .unwrap();
2412 handle.send(Op::SendMessage(spec)).await.unwrap();
2413
2414 let child_auto_review = Arc::clone(&core.auto_review_state);
2415 let mut receiver = handle.rx_event.write().await;
2416 let mut events = Vec::new();
2417 let child = core.run_child();
2418 tokio::pin!(child);
2419 let result = tokio::time::timeout(Duration::from_secs(30), async {
2420 loop {
2421 tokio::select! {
2422 result = &mut child => break result,
2423 Some(event) = receiver.recv() => events.push(event),
2424 }
2425 }
2426 })
2427 .await
2428 .unwrap_or_else(|_| {
2429 panic!(
2430 "child auto-review did not finish after {} model requests and {} parent blocks",
2431 mock.call_count(),
2432 parent_handle.list_auto_review_blocks().len()
2433 )
2434 })
2435 .unwrap();
2436 while let Ok(event) = receiver.try_recv() {
2437 events.push(event);
2438 }
2439 assert_eq!(
2440 result.status,
2441 crate::tools::subagent::SubAgentStatus::Failed(
2442 crate::core::engine::dispatch::FLEET_NO_PROGRESS_STOP.to_string()
2443 )
2444 );
2445 assert_eq!(mock.call_count(), 8);
2446 assert!(!dir.path().join(".env").exists());
2447
2448 assert!(child_auto_review.lock().blocked_actions().is_empty());
2449 let blocks = parent_handle.list_auto_review_blocks();
2450 assert_eq!(blocks.len(), 4, "{blocks:?}");
2451 let prefix = format!("[sub-agent {child_agent_id}] ");
2452 for block in &blocks {
2453 assert_eq!(block.agent_id.as_deref(), Some(child_agent_id.as_str()));
2454 assert!(!block.approvable, "{block:?}");
2455 assert!(block.action_summary.starts_with(&prefix), "{block:?}");
2456 assert!(matches!(
2457 parent_handle.approve_auto_review_retry(&block.receipt_id),
2458 Err(AutoReviewRetryApprovalError::InvalidTarget(_))
2459 ));
2460 }
2461 assert_eq!(
2462 parent_handle.runtime_permission_authority().approval_mode,
2463 ApprovalMode::Auto
2464 );
2465 assert!(!events.iter().any(|e| matches!(
2466 e,
2467 Event::ApprovalRequired { .. } | Event::AutoReviewPaused { .. }
2468 )));
2469 }
2470
2471 #[tokio::test(flavor = "current_thread")]
2472 async fn dropped_child_approval_decision_logs_warning_before_denying_unavailable() {
2473 struct CaptureWriter(Arc<std::sync::Mutex<Vec<u8>>>);
2474 impl std::io::Write for CaptureWriter {
2475 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
2476 self.0.lock().unwrap().extend_from_slice(bytes);
2477 Ok(bytes.len())
2478 }
2479 fn flush(&mut self) -> std::io::Result<()> {
2480 Ok(())
2481 }
2482 }
2483
2484 let dir = tempdir().unwrap();
2485 let _home = crate::test_support::SealedHome::at(dir.path());
2486 let mut api = Config::default().with_legacy_root(Some("child-local-fixture".into()), None);
2487 api.allow_shell = Some(true);
2488 let (mut parent, _parent_handle) = Engine::new(
2489 EngineConfig {
2490 workspace: dir.path().into(),
2491 session_id: Some("origin-session".into()),
2492 allow_shell: true,
2493 snapshots_enabled: false,
2494 memory_enabled: false,
2495 ..Default::default()
2496 },
2497 &api,
2498 );
2499 parent.config.features.disable(Feature::Mcp);
2500 let route = TurnRouteContext {
2501 provider: ProviderKind::Deepseek,
2502 model: DEFAULT_TEXT_MODEL.into(),
2503 capabilities: Default::default(),
2504 limits: None,
2505 client: parent.codewhale_client.clone(),
2506 api_config: Box::new(api.clone()),
2507 locale_tag: parent.config.locale_tag.clone(),
2508 role_models: HashMap::new(),
2509 auto_model: false,
2510 reasoning_effort: None,
2511 reasoning_effort_auto: false,
2512 };
2513 let policy = TurnAuthority::from_effective_fields(
2514 AppMode::Agent,
2515 true,
2516 false,
2517 false,
2518 ApprovalMode::Suggest,
2519 );
2520 let context = parent.build_tool_context_for_turn(&policy, &route);
2521 let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(32);
2522 let runtime = SubAgentRuntime::new(
2523 parent.codewhale_client.clone().unwrap(),
2524 DEFAULT_TEXT_MODEL.into(),
2525 context,
2526 true,
2527 Some(event_tx),
2528 parent.subagent_manager.clone(),
2529 )
2530 .with_api_config(api.clone())
2531 .with_approval_receipt_store(parent.approval_receipt_store.clone())
2532 .with_permission_posture(
2533 Arc::new(crate::core::authority::auto_review::AutoReviewPolicy::default()),
2534 true,
2535 );
2536 let authority = ChildAuthority::capture(
2537 runtime,
2538 FleetRole::Worker,
2539 "child-approval-err".into(),
2540 "run command".into(),
2541 None,
2542 );
2543 let (child_engine, _child_handle) = Engine::new_child_admitted(
2544 EngineConfig {
2545 workspace: dir.path().into(),
2546 model: DEFAULT_TEXT_MODEL.into(),
2547 ..Default::default()
2548 },
2549 &api,
2550 authority.clone(),
2551 SystemPrompt::Text("captured child role".into()),
2552 None,
2553 )
2554 .unwrap();
2555 let build = child_engine.acp_tool_build(&policy, &route, None);
2556 let warm: Vec<String> = build
2557 .surface
2558 .catalog
2559 .iter()
2560 .map(|tool| tool.name.clone())
2561 .collect();
2562 let mut surface = ChildSurfaceProbe::new(build.surface.catalog, &warm);
2563 let execution_id = authority.new_execution_id();
2564
2565 let manager_for_close = Arc::clone(&authority.runtime.manager);
2566 let closer = tokio::spawn(async move {
2567 tokio::time::timeout(Duration::from_secs(5), async {
2568 while let Some(event) = event_rx.recv().await {
2569 if let Event::ApprovalRequired { id, .. } = event {
2570 manager_for_close.write().await.cancel_child_approval(&id);
2571 return id;
2572 }
2573 }
2574 panic!("event channel closed before child ApprovalRequired");
2575 })
2576 .await
2577 .expect("child ApprovalRequired arrives")
2578 });
2579
2580 let buffer = Arc::new(std::sync::Mutex::new(Vec::<u8>::new()));
2581 let writer = Arc::clone(&buffer);
2582 let subscriber = tracing_subscriber::fmt()
2583 .without_time()
2584 .with_ansi(false)
2585 .with_max_level(tracing::Level::WARN)
2586 .with_writer(move || CaptureWriter(Arc::clone(&writer)))
2587 .finish();
2588 let _log_guard = tracing::subscriber::set_default(subscriber);
2589
2590 let err = Engine::probe_child_call(
2591 authority,
2592 build.surface.registry,
2593 &mut surface,
2594 ChildProbeCall {
2595 id: execution_id.clone(),
2596 execution_id,
2597 name: "bash".into(),
2598 input: json!({ "command": "echo gated" }),
2599 },
2600 )
2601 .await
2602 .expect_err("dropped approval decision must fail closed");
2603 let approval_id = closer.await.expect("closer task");
2604 drop(_log_guard);
2605
2606 assert!(
2607 matches!(
2608 err.downcast_ref::<ToolError>(),
2609 Some(ToolError::ExecutionFailed { message, .. })
2610 if message.contains("no longer current")
2611 ),
2612 "{err}"
2613 );
2614 let logs = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
2615 assert!(
2616 logs.contains("child approval decision failed; denying as unavailable"),
2617 "{logs}"
2618 );
2619 assert!(logs.contains(&approval_id), "{logs}");
2620 assert!(logs.contains("channel closed"), "{logs}");
2621 }
2622
2623 #[tokio::test(flavor = "current_thread")]
2624 async fn child_engine_inherits_parent_tools_overrides_and_excludes_disabled_tools() {
2625 let dir = tempdir().unwrap();
2626 let _home = crate::test_support::SealedHome::at(dir.path());
2627 let plugin_dir = dir.path().join("empty-plugins");
2628 std::fs::create_dir_all(&plugin_dir).unwrap();
2629
2630 let build_child =
2631 |tools: Option<codewhale_runtime::config::ToolsConfig>,
2632 child_tools: Option<codewhale_runtime::config::ToolsConfig>| {
2633 let mut api =
2634 Config::default().with_legacy_root(Some("child-local-fixture".into()), None);
2635 api.allow_shell = Some(true);
2636 api.tools = tools;
2637 let (mut parent, _parent_handle) = Engine::new(
2638 EngineConfig {
2639 workspace: dir.path().into(),
2640 session_id: Some("origin-session".into()),
2641 allow_shell: true,
2642 tools: api.tools.clone(),
2643 snapshots_enabled: false,
2644 memory_enabled: false,
2645 ..Default::default()
2646 },
2647 &api,
2648 );
2649 parent.config.features.disable(Feature::Mcp);
2650 let route = TurnRouteContext {
2651 provider: ProviderKind::Deepseek,
2652 model: DEFAULT_TEXT_MODEL.into(),
2653 capabilities: Default::default(),
2654 limits: None,
2655 client: parent.codewhale_client.clone(),
2656 api_config: Box::new(api.clone()),
2657 locale_tag: parent.config.locale_tag.clone(),
2658 role_models: HashMap::new(),
2659 auto_model: false,
2660 reasoning_effort: None,
2661 reasoning_effort_auto: false,
2662 };
2663 let policy = TurnAuthority::from_effective_fields(
2664 AppMode::Agent,
2665 true,
2666 false,
2667 false,
2668 ApprovalMode::Suggest,
2669 );
2670 let context = parent.build_tool_context_for_turn(&policy, &route);
2671 let runtime = SubAgentRuntime::new(
2672 parent.codewhale_client.clone().unwrap(),
2673 DEFAULT_TEXT_MODEL.into(),
2674 context,
2675 true,
2676 None,
2677 parent.subagent_manager.clone(),
2678 )
2679 .with_api_config(api.clone())
2680 .with_approval_receipt_store(parent.approval_receipt_store.clone());
2681 let authority = ChildAuthority::capture(
2682 runtime,
2683 FleetRole::Worker,
2684 "child-overrides".into(),
2685 "inspect".into(),
2686 None,
2687 );
2688 let (child, _child_handle) = Engine::new_child_admitted(
2689 EngineConfig {
2690 workspace: dir.path().into(),
2691 model: DEFAULT_TEXT_MODEL.into(),
2692 tools: child_tools,
2693 ..Default::default()
2694 },
2695 &api,
2696 authority,
2697 SystemPrompt::Text("captured child role".into()),
2698 None,
2699 )
2700 .unwrap();
2701 (child, policy, route)
2702 };
2703
2704 let (mut baseline_child, baseline_policy, baseline_route) = build_child(None, None);
2705 let baseline = baseline_child
2706 .build_turn_tool_registry_and_catalog(
2707 &baseline_policy,
2708 &[],
2709 None,
2710 SubAgentWiring::Inert,
2711 McpAccess::PassiveSnapshot,
2712 &[],
2713 baseline_route,
2714 "",
2715 )
2716 .await;
2717 assert!(
2718 baseline.surface.registry.names().contains(&"tui_help"),
2719 "control: worker child includes tui_help without overrides"
2720 );
2721
2722 let mut overrides = std::collections::HashMap::new();
2723 overrides.insert(
2724 "tui_help".to_string(),
2725 codewhale_runtime::config::ToolOverride::Disabled,
2726 );
2727 overrides.insert(
2728 "tasks".to_string(),
2729 codewhale_runtime::config::ToolOverride::Disabled,
2730 );
2731 let plugin_dir_str = plugin_dir.to_string_lossy().into_owned();
2732 let tools_cfg = codewhale_runtime::config::ToolsConfig {
2733 plugin_dir: Some(plugin_dir_str.clone()),
2734 overrides: Some(overrides),
2735 ..Default::default()
2736 };
2737 for child_tools in [
2738 None,
2739 Some(codewhale_runtime::config::ToolsConfig::default()),
2740 ] {
2741 let (mut restricted_child, restricted_policy, restricted_route) =
2742 build_child(Some(tools_cfg.clone()), child_tools);
2743 assert_eq!(
2744 restricted_child
2745 .config
2746 .tools
2747 .as_ref()
2748 .and_then(|t| t.plugin_dir.as_deref()),
2749 Some(plugin_dir_str.as_str())
2750 );
2751 let restricted = restricted_child
2752 .build_turn_tool_registry_and_catalog(
2753 &restricted_policy,
2754 &[],
2755 None,
2756 SubAgentWiring::Inert,
2757 McpAccess::PassiveSnapshot,
2758 &[],
2759 restricted_route,
2760 "",
2761 )
2762 .await;
2763 for disabled in ["tui_help", "tasks"] {
2764 assert!(
2765 !restricted.surface.registry.names().contains(&disabled),
2766 "child registry must exclude disabled tool {disabled}"
2767 );
2768 assert!(
2769 !restricted
2770 .surface
2771 .catalog
2772 .iter()
2773 .any(|tool| tool.name == disabled),
2774 "child catalog must exclude disabled tool {disabled}"
2775 );
2776 }
2777 }
2778 }
2779
2780 #[test]
2781 fn saved_child_posture_caps_live_switches_without_changing_the_parent() {
2782 let parent = LivePosture::for_tests(std::path::Path::new("."), ApprovalMode::Bypass);
2783 let mut child = parent.clone();
2784 child.ceiling = Some(ApprovalMode::AcceptEdits);
2785 assert_eq!(child.read().approval_mode, ApprovalMode::AcceptEdits);
2786 assert!(!child.read().auto_approve);
2787 assert_eq!(parent.read().approval_mode, ApprovalMode::Bypass);
2788 parent.switch_for_tests(ApprovalMode::Suggest);
2789 assert_eq!(child.read().approval_mode, ApprovalMode::Suggest);
2790 parent.switch_for_tests(ApprovalMode::Bypass);
2791 assert_eq!(child.read().approval_mode, ApprovalMode::AcceptEdits);
2792 }
2793
2794 #[tokio::test(flavor = "current_thread")]
2795 async fn child_engines_never_raise_the_search_card_and_honor_off() {
2796 use crate::tools::web::consent::ThirdPartySearch;
2797 use codewhale_runtime::config::SearchThirdParty;
2798
2799 let dir = tempdir().unwrap();
2800 let _home = crate::test_support::SealedHome::at(dir.path());
2801 let (mut engine, _handle, _authority, route) = fixture(dir.path(), None);
2802 engine.config.search_consent_implied = false;
2803 engine.config.search_native = Some(false);
2804 engine.turn_owner_present = true;
2805 engine.turn_run_origin = RunOrigin::Interactive;
2806 let policy = TurnAuthority::from_effective_fields(
2807 AppMode::Agent,
2808 true,
2809 false,
2810 true,
2811 ApprovalMode::Suggest,
2812 );
2813 let input = json!({"action": "search", "query": "rust"});
2814 for (saved, expected) in [
2815 (None, ThirdPartySearch::Allowed),
2816 (Some(SearchThirdParty::Ask), ThirdPartySearch::Allowed),
2817 (Some(SearchThirdParty::Off), ThirdPartySearch::Declined),
2818 (Some(SearchThirdParty::On), ThirdPartySearch::Allowed),
2819 ] {
2820 engine.config.search_third_party = saved;
2821 let context = engine.build_tool_context_for_turn(&policy, &route);
2822 assert_eq!(context.third_party_search.get(), expected, "{saved:?}");
2823 assert!(
2824 !engine.search_consent_card_needed("Web", &input, false, None),
2825 "{saved:?}"
2826 );
2827 }
2828 }
2829
2830 #[tokio::test(flavor = "current_thread")]
2831 async fn children_of_an_interactive_session_wait_for_the_persons_search_choice() {
2832 use crate::tools::spec::ToolSpec;
2833 use crate::tools::web::consent::{
2834 DECLINED_MESSAGE, ThirdPartySearch, WITHHELD_MESSAGE, search_refusal,
2835 };
2836 use codewhale_net::network_policy::{DecisionToml, NetworkPolicy, NetworkPolicyDecider};
2837 use codewhale_runtime::config::SearchThirdParty;
2838
2839 let dir = tempdir().unwrap();
2840 let _home = crate::test_support::SealedHome::at(dir.path());
2841 let (mut engine, _handle, authority, route) = fixture(dir.path(), None);
2842 engine.config.search_consent_implied = false;
2843 engine.config.search_native = Some(false);
2844 engine.config.search_provider = codewhale_runtime::config::SearchProvider::Firecrawl;
2845 let policy = TurnAuthority::from_effective_fields(
2846 AppMode::Agent,
2847 true,
2848 false,
2849 true,
2850 ApprovalMode::Suggest,
2851 );
2852 let parent = authority.runtime.context.third_party_search.clone();
2853 for (parent_state, saved, expected) in [
2854 (ThirdPartySearch::Withheld, None, ThirdPartySearch::Withheld),
2855 (
2856 ThirdPartySearch::Withheld,
2857 Some(SearchThirdParty::Ask),
2858 ThirdPartySearch::Withheld,
2859 ),
2860 (
2861 ThirdPartySearch::Withheld,
2862 Some(SearchThirdParty::Off),
2863 ThirdPartySearch::Declined,
2864 ),
2865 (
2866 ThirdPartySearch::Withheld,
2867 Some(SearchThirdParty::On),
2868 ThirdPartySearch::Allowed,
2869 ),
2870 (ThirdPartySearch::Declined, None, ThirdPartySearch::Declined),
2871 (ThirdPartySearch::Allowed, None, ThirdPartySearch::Allowed),
2872 ] {
2873 parent.set(parent_state);
2874 engine.config.search_third_party = saved;
2875 let mut context = engine.build_tool_context_for_turn(&policy, &route);
2876 assert_eq!(
2877 context.third_party_search.get(),
2878 expected,
2879 "{parent_state:?} {saved:?}"
2880 );
2881 if expected == ThirdPartySearch::Allowed {
2882 continue;
2883 }
2884 context.network_policy = Some(NetworkPolicyDecider::new(
2885 NetworkPolicy {
2886 default: DecisionToml::Deny,
2887 audit: false,
2888 ..NetworkPolicy::default()
2889 },
2890 None,
2891 ));
2892 let refusal = if expected == ThirdPartySearch::Withheld {
2893 WITHHELD_MESSAGE
2894 } else {
2895 DECLINED_MESSAGE
2896 };
2897 assert_eq!(search_refusal(&context), Some(refusal));
2898 let result = crate::tools::web_search::WebSearchTool
2899 .execute(json!({"query": "rust"}), &context)
2900 .await
2901 .expect("a withheld search is a short result, not a request");
2902 assert_eq!(result.content, refusal);
2903 }
2904 }
2905
2906 #[tokio::test(flavor = "current_thread")]
2907 async fn a_withheld_child_search_is_refused_before_its_own_card() {
2908 use crate::tools::spec::ToolSpec;
2909 use crate::tools::web::consent::{ThirdPartySearch, WITHHELD_MESSAGE};
2910
2911 let dir = tempdir().unwrap();
2912 let _home = crate::test_support::SealedHome::at(dir.path());
2913 let (mut engine, _handle, authority, route) = fixture(dir.path(), None);
2914 engine.config.search_consent_implied = false;
2915 engine.config.search_native = Some(false);
2916 engine.config.search_provider = codewhale_runtime::config::SearchProvider::Firecrawl;
2917 authority
2918 .runtime
2919 .context
2920 .third_party_search
2921 .set(ThirdPartySearch::Withheld);
2922 let policy = TurnAuthority::from_effective_fields(
2923 AppMode::Agent,
2924 true,
2925 false,
2926 true,
2927 ApprovalMode::Suggest,
2928 );
2929 let context = engine.build_tool_context_for_turn(&policy, &route);
2930 assert_eq!(context.third_party_search.get(), ThirdPartySearch::Withheld);
2931 for (tool, input) in [
2932 (
2933 Arc::new(crate::tools::web_tool::WebTool::new("Web")) as Arc<dyn ToolSpec>,
2934 json!({"action": "search", "query": "rust"}),
2935 ),
2936 (
2937 Arc::new(crate::tools::web_search::WebSearchTool),
2938 json!({"query": "rust"}),
2939 ),
2940 (
2941 Arc::new(crate::tools::web_run::WebRunTool),
2942 json!({"search_query": [{"q": "rust"}]}),
2943 ),
2944 (
2945 Arc::new(crate::tools::web_run::WebRunTool),
2946 json!({"image_query": [{"q": "whales"}]}),
2947 ),
2948 ] {
2949 let refusal = tool
2950 .refusal_before_approval(&input, &context)
2951 .unwrap_or_else(|| panic!("{} {input} asks before refusing", tool.name()));
2952 assert_eq!(refusal.content, WITHHELD_MESSAGE, "{} {input}", tool.name());
2953 }
2954 for (tool, input) in [
2955 (
2956 Arc::new(crate::tools::web_tool::WebTool::new("Web")) as Arc<dyn ToolSpec>,
2957 json!({"action": "fetch", "url": "https://example.com"}),
2958 ),
2959 (
2960 Arc::new(crate::tools::web_run::WebRunTool),
2961 json!({"open": [{"ref_id": "r1"}]}),
2962 ),
2963 ] {
2964 assert!(
2965 tool.refusal_before_approval(&input, &context).is_none(),
2966 "{} {input}",
2967 tool.name()
2968 );
2969 }
2970
2971 let mut self_hosted = context.clone();
2972 self_hosted.search_provider = codewhale_runtime::config::SearchProvider::Searxng;
2973 self_hosted.search_base_url = Some("https://searx.local".into());
2974 let web_run = crate::tools::web_run::WebRunTool;
2975 assert!(
2976 web_run
2977 .refusal_before_approval(&json!({"search_query": [{"q": "rust"}]}), &self_hosted)
2978 .is_none()
2979 );
2980 assert_eq!(
2981 web_run
2982 .refusal_before_approval(&json!({"image_query": [{"q": "whales"}]}), &self_hosted)
2983 .expect("image search always leaves the machine")
2984 .content,
2985 WITHHELD_MESSAGE
2986 );
2987 }
2988
2989 #[tokio::test(flavor = "current_thread")]
2990 async fn a_background_parent_turn_does_not_lift_the_hold_on_its_children() {
2991 use crate::tools::web::consent::ThirdPartySearch;
2992 use codewhale_runtime::config::SearchThirdParty;
2993
2994 let dir = tempdir().unwrap();
2995 let _home = crate::test_support::SealedHome::at(dir.path());
2996 let (mut child, _child_handle, _authority, route) = fixture(dir.path(), None);
2997 let (mut parent, _parent_handle) = Engine::new(
2998 EngineConfig {
2999 workspace: dir.path().into(),
3000 snapshots_enabled: false,
3001 memory_enabled: false,
3002 search_consent_implied: false,
3003 search_native: Some(false),
3004 ..Default::default()
3005 },
3006 &Config::default(),
3007 );
3008 let policy = TurnAuthority::from_effective_fields(
3009 AppMode::Agent,
3010 true,
3011 false,
3012 true,
3013 ApprovalMode::Suggest,
3014 );
3015 child.child_host.as_mut().unwrap().authority = {
3016 let parent_context = parent.build_tool_context_for_turn(&policy, &route);
3017 let mut authority = child
3018 .child_host
3019 .as_ref()
3020 .unwrap()
3021 .authority
3022 .as_ref()
3023 .clone();
3024 authority.runtime.context.third_party_search = parent_context.third_party_search.clone();
3025 Arc::new(authority)
3026 };
3027 child.config.search_consent_implied = false;
3028 child.config.search_native = Some(false);
3029 let child_permit = |child: &Engine| {
3030 child
3031 .build_tool_context_for_turn(&policy, &route)
3032 .third_party_search
3033 .get()
3034 };
3035
3036 parent.turn_owner_present = true;
3037 parent.turn_run_origin = RunOrigin::Interactive;
3038 let _ = parent.build_tool_context_for_turn(&policy, &route);
3039 assert_eq!(child_permit(&child), ThirdPartySearch::Withheld);
3040
3041 parent.turn_owner_present = false;
3042 parent.turn_run_origin = RunOrigin::Background;
3043 let background = parent.build_tool_context_for_turn(&policy, &route);
3044 assert_eq!(
3045 background.third_party_search.get(),
3046 ThirdPartySearch::Withheld,
3047 "a background turn cannot answer for the person"
3048 );
3049 assert_eq!(child_permit(&child), ThirdPartySearch::Withheld);
3050
3051 parent.record_search_consent(SearchThirdParty::On).await;
3052 assert_eq!(child_permit(&child), ThirdPartySearch::Allowed);
3053
3054 let (mut unattended, _unattended_handle) = Engine::new(
3055 EngineConfig {
3056 workspace: dir.path().into(),
3057 snapshots_enabled: false,
3058 memory_enabled: false,
3059 search_consent_implied: false,
3060 search_native: Some(false),
3061 ..Default::default()
3062 },
3063 &Config::default(),
3064 );
3065 unattended.turn_run_origin = RunOrigin::Background;
3066 assert_eq!(
3067 unattended
3068 .build_tool_context_for_turn(&policy, &route)
3069 .third_party_search
3070 .get(),
3071 ThirdPartySearch::Allowed,
3072 "a session unattended from the start still searches"
3073 );
3074 }
3075
3075 lines RUST