返回 CodeWhale
test_cases_13.rs
根目录 / crates / engine / src / core / engine / tests / test_cases_13.rs
1 #[test]
2 fn agent_mode_elevates_writes_without_granting_network() {
3 // #273 elevated Agent mode's sandbox so `curl`, package managers, and
4 // similar shell commands worked, and justified it by saying the
5 // application-level NetworkPolicy would remain "the only outbound
6 // boundary". That premise did not hold: NetworkPolicy governs
7 // fetch_url/web_search/MCP HTTP and never constrained shell subprocesses,
8 // so workspace-write turns had unrestricted egress with no boundary at
9 // all. Writing to the workspace is now decoupled from reaching the
10 // network: the write elevation stays, the network grant does not.
11 // Network comes from `sandbox_network_access`, from a danger-full-access
12 // posture, or from the post-denial elevation prompt.
13 let (engine, _handle) = Engine::new(EngineConfig::default(), &Config::default());
14
15 let agent_ctx = engine.build_tool_context(AppMode::Agent, false);
16 let agent_policy = agent_ctx
17 .elevated_sandbox_policy
18 .as_ref()
19 .expect("Agent mode should elevate the sandbox policy");
20 assert!(
21 !agent_policy.has_network_access(),
22 "Agent mode must not grant shell network access by default; got {agent_policy:?}",
23 );
24 assert!(
25 !agent_policy
26 .get_writable_roots(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
27 .is_empty(),
28 "Agent mode must still elevate workspace writes; got {agent_policy:?}",
29 );
30
31 let full_access_ctx = engine.build_tool_context(AppMode::Agent, true);
32 let full_access_policy = full_access_ctx
33 .elevated_sandbox_policy
34 .as_ref()
35 .expect("Full Access should elevate the sandbox policy");
36 assert!(full_access_policy.has_network_access());
37 // v0.8.11: Full Access drops to DangerFullAccess (no sandbox) so the
38 // user is not bounced through approval round-trips for legitimate
39 // outside-workspace writes (package installs, sub-agent
40 // workspaces, ~/.cache mutations, etc.). Full Access is opt-in and
41 // already enables trust mode + auto-approve; the sandbox was the
42 // last guardrail and contradicts the contract.
43 assert!(
44 matches!(
45 full_access_policy,
46 codewhale_sandbox::SandboxPolicy::DangerFullAccess
47 ),
48 "Full Access must use DangerFullAccess (no sandbox); got {full_access_policy:?}",
49 );
50
51 // Plan mode (#1077): the sandbox must actually deny workspace writes.
52 // The previous WorkspaceWrite-with-empty-network policy whitelisted the
53 // workspace as writable, so `python -c "open('f','w').write('x')"`
54 // mutated files inside the workspace despite Plan-mode's intent. Lock
55 // it to ReadOnly: no writes anywhere, no network. The shell tool stays
56 // exposed for read-only inspection (`ls`, `git log`, `grep`, …) and
57 // the per-platform sandbox enforces the rest.
58 let plan_ctx = engine.build_tool_context(AppMode::Plan, false);
59 let plan_policy = plan_ctx
60 .elevated_sandbox_policy
61 .as_ref()
62 .expect("Plan mode should make the shell sandbox policy explicit");
63 assert!(
64 matches!(plan_policy, codewhale_sandbox::SandboxPolicy::ReadOnly { .. }),
65 "Plan mode must use ReadOnly sandbox to deny workspace writes (#1077); got {plan_policy:?}",
66 );
67 assert!(!plan_policy.has_network_access());
68 assert!(!plan_policy.has_full_disk_write_access());
69 assert!(
70 plan_policy
71 .get_writable_roots(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
72 .is_empty(),
73 "ReadOnly policy must enumerate zero writable roots; got {plan_policy:?}",
74 );
75 assert!(
76 plan_ctx
77 .shell_network_denied_hint
78 .as_deref()
79 .is_some_and(|hint| hint.contains("Plan mode") && hint.contains("read-only")),
80 );
81 }
82
83 #[test]
84 fn sandbox_policy_for_turn_returns_correct_default_policy_per_mode() {
85 use crate::core::authority::{SandboxNetworkAccess, sandbox_policy_for_turn};
86 use ApprovalMode;
87 use codewhale_sandbox::SandboxPolicy;
88
89 let workspace = PathBuf::from("/tmp/example-workspace");
90
91 // Plan: ReadOnly. The whole point of #1077.
92 assert!(matches!(
93 sandbox_policy_for_turn(
94 AppMode::Plan,
95 ApprovalMode::Suggest,
96 None,
97 &workspace,
98 SandboxNetworkAccess::Restricted,
99 ),
100 SandboxPolicy::ReadOnly { .. }
101 ));
102
103 // Agent: WorkspaceWrite with workspace as writable root, network OFF.
104 match sandbox_policy_for_turn(
105 AppMode::Agent,
106 ApprovalMode::Suggest,
107 None,
108 &workspace,
109 SandboxNetworkAccess::Restricted,
110 ) {
111 SandboxPolicy::WorkspaceWrite {
112 writable_roots,
113 network_access,
114 ..
115 } => {
116 assert_eq!(writable_roots, vec![workspace.clone()]);
117 assert!(
118 !network_access,
119 "workspace-write must not imply shell network access"
120 );
121 }
122 other => panic!("Agent mode should be WorkspaceWrite; got {other:?}"),
123 }
124
125 // Agent with the explicit opt-in: same posture, network on.
126 match sandbox_policy_for_turn(
127 AppMode::Agent,
128 ApprovalMode::Suggest,
129 None,
130 &workspace,
131 SandboxNetworkAccess::Allowed,
132 ) {
133 SandboxPolicy::WorkspaceWrite { network_access, .. } => {
134 assert!(
135 network_access,
136 "sandbox_network_access = true must grant shell network access"
137 );
138 }
139 other => panic!("Agent mode should be WorkspaceWrite; got {other:?}"),
140 }
141
142 // Bypass posture: DangerFullAccess.
143 assert!(matches!(
144 sandbox_policy_for_turn(
145 AppMode::Agent,
146 ApprovalMode::Bypass,
147 None,
148 &workspace,
149 SandboxNetworkAccess::Restricted,
150 ),
151 SandboxPolicy::DangerFullAccess
152 ));
153 }
154
155 #[tokio::test]
156 async fn session_update_preserves_reasoning_tool_only_turn() {
157 let (mut engine, handle) = Engine::new(EngineConfig::default(), &Config::default());
158 let assistant = Message {
159 role: Role::Assistant,
160 content: vec![
161 ContentBlock::Thinking {
162 signature: None,
163 state: None,
164 redacted_data: None,
165 thinking: "Need a tool before answering.".to_string(),
166 },
167 ContentBlock::ToolUse {
168 execution_id: None,
169 id: "tool-1".to_string(),
170 name: "read_file".to_string(),
171 input: json!({"path": "Cargo.toml"}),
172 caller: None,
173 thought_signature: None,
174 },
175 ],
176 };
177
178 engine.add_session_message(assistant.clone()).await;
179
180 let event = {
181 let mut rx = handle.rx_event.write().await;
182 rx.recv().await.expect("session update event")
183 };
184 let Event::SessionUpdated {
185 source: _,
186 messages, .. } = event else {
187 panic!("expected session update event");
188 };
189
190 assert_eq!(*messages, vec![assistant]);
191 }
192
193 #[tokio::test]
194 async fn set_model_reloads_instruction_sources_and_updates_session_prompt() {
195 let tmp = tempdir().expect("tempdir");
196 let instructions = tmp.path().join("instructions.md");
197 fs::write(&instructions, "FLASH_INSTRUCTIONS_MARKER").expect("write instructions");
198 let config = EngineConfig {
199 workspace: tmp.path().to_path_buf(),
200 model: "deepseek-v4-flash".to_string(),
201 instructions: vec![instructions.clone().into()],
202 ..Default::default()
203 };
204 let (engine, handle) = Engine::new(config, &Config::default());
205 fs::write(&instructions, "PRO_INSTRUCTIONS_MARKER").expect("rewrite instructions");
206
207 let run = tokio::spawn(engine.run());
208 handle
209 .send(Op::SetModel {
210 model: "deepseek-v4-pro".to_string(),
211 mode: AppMode::Agent,
212 route_limits: None,
213 })
214 .await
215 .expect("send set model");
216
217 let (model, prompt, assembly_block) = {
218 let mut rx = handle.rx_event.write().await;
219 loop {
220 let event = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
221 .await
222 .expect("session update after model switch")
223 .expect("event");
224 if let Event::SessionUpdated {
225 model,
226 system_prompt,
227 instruction_assembly,
228 ..
229 } = event
230 {
231 let prompt = match system_prompt.expect("system prompt") {
232 SystemPrompt::Text(text) => text,
233 SystemPrompt::Blocks(blocks) => blocks
234 .into_iter()
235 .map(|block| block.text)
236 .collect::<Vec<_>>()
237 .join("\n"),
238 };
239 let assembly_block = instruction_assembly
240 .and_then(|assembly| assembly.block.clone())
241 .unwrap_or_default();
242 break (model, prompt, assembly_block);
243 }
244 }
245 };
246 run.abort();
247
248 assert_eq!(model, "deepseek-v4-pro");
249 assert!(assembly_block.contains("PRO_INSTRUCTIONS_MARKER"));
250 assert!(!assembly_block.contains("FLASH_INSTRUCTIONS_MARKER"));
251 assert!(!prompt.contains("PRO_INSTRUCTIONS_MARKER"));
252 }
253
254 #[tokio::test]
255 async fn change_mode_refreshes_session_prompt_and_updates_session() {
256 let tmp = tempdir().expect("tempdir");
257 let config = EngineConfig {
258 workspace: tmp.path().to_path_buf(),
259 model: "deepseek-v4-pro".to_string(),
260 ..Default::default()
261 };
262 let (engine, handle) = Engine::new(config, &Config::default());
263
264 let run = tokio::spawn(engine.run());
265 handle
266 .send(Op::ChangeMode {
267 mode: AppMode::Agent,
268 allow_shell: true,
269 trust_mode: true,
270 auto_approve: true,
271 approval_mode: ApprovalMode::Bypass,
272 configured_sandbox_mode: None,
273 })
274 .await
275 .expect("send change mode");
276
277 let (_prompt, messages) = {
278 let mut rx = handle.rx_event.write().await;
279 loop {
280 let event = tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())
281 .await
282 .expect("session update after mode switch")
283 .expect("event");
284 if let Event::SessionUpdated {
285 system_prompt,
286 messages,
287 ..
288 } = event
289 {
290 let prompt = match system_prompt.expect("system prompt") {
291 SystemPrompt::Text(text) => text,
292 SystemPrompt::Blocks(blocks) => blocks
293 .into_iter()
294 .map(|block| block.text)
295 .collect::<Vec<_>>()
296 .join("\n"),
297 };
298 break (prompt, messages);
299 }
300 }
301 };
302 run.abort();
303
304 assert!(
305 messages.iter().all(|message| message.role != "system"),
306 "mode switch must not persist appended system messages: {messages:?}"
307 );
308 }
309
310 /// A posture change announces itself in product words (§19): Permissions,
311 /// then Plan / Work / Operate. A republished identical posture says nothing.
312 #[tokio::test]
313 async fn posture_change_status_uses_permissions_and_work() {
314 let tmp = tempdir().expect("tempdir");
315 let config = EngineConfig {
316 workspace: tmp.path().to_path_buf(),
317 ..Default::default()
318 };
319 let (mut engine, handle) = Engine::new(config, &Config::default());
320 let publish = |handle: &EngineHandle| {
321 handle
322 .try_send(Op::ChangeMode {
323 mode: AppMode::Agent,
324 allow_shell: true,
325 trust_mode: false,
326 auto_approve: true,
327 approval_mode: ApprovalMode::Bypass,
328 configured_sandbox_mode: None,
329 })
330 .expect("publish live runtime authority");
331 };
332 publish(&handle);
333 assert!(engine.apply_pending_runtime_authority().await);
334 publish(&handle);
335 assert!(!engine.apply_pending_runtime_authority().await);
336 handle
337 .try_send(Op::ChangeMode {
338 mode: AppMode::Plan,
339 allow_shell: false,
340 trust_mode: false,
341 auto_approve: false,
342 approval_mode: ApprovalMode::Suggest,
343 configured_sandbox_mode: None,
344 })
345 .expect("publish plan runtime authority");
346 assert!(engine.apply_pending_runtime_authority().await);
347
348 let mut statuses = Vec::new();
349 let mut rx = handle.rx_event.write().await;
350 while let Ok(event) = rx.try_recv() {
351 if let Event::Status { message } = event {
352 statuses.push(message);
353 }
354 }
355 assert_eq!(
356 statuses,
357 vec![
358 "Permissions: Full Access · Work".to_string(),
359 "Permissions: Plan (read only)".to_string(),
360 ]
361 );
362 }
363
364 #[tokio::test]
365 async fn live_runtime_authority_applies_latest_posture_and_sandbox_before_tools() {
366 use ApprovalMode;
367 use codewhale_sandbox::SandboxPolicy;
368
369 let tmp = tempdir().expect("tempdir");
370 let config = EngineConfig {
371 workspace: tmp.path().to_path_buf(),
372 ..Default::default()
373 };
374 let (mut engine, handle) = Engine::new(config, &Config::default());
375 let registry = ToolRegistryBuilder::new()
376 .build(engine.build_tool_context(engine.current_mode, engine.session.auto_approve));
377
378 for (mode, posture, auto_approve, sandbox_mode, expected_sandbox) in [
379 (
380 AppMode::Agent,
381 ApprovalMode::Auto,
382 false,
383 Some("read-only".to_string()),
384 SandboxPolicy::read_only(),
385 ),
386 (
387 AppMode::Agent,
388 ApprovalMode::Bypass,
389 true,
390 None,
391 SandboxPolicy::DangerFullAccess,
392 ),
393 (
394 AppMode::Agent,
395 ApprovalMode::Suggest,
396 false,
397 None,
398 SandboxPolicy::WorkspaceWrite {
399 writable_roots: vec![tmp.path().to_path_buf()],
400 network_access: false,
401 exclude_tmpdir: false,
402 exclude_slash_tmp: false,
403 },
404 ),
405 ] {
406 handle
407 .try_send(Op::ChangeMode {
408 mode,
409 allow_shell: true,
410 trust_mode: false,
411 auto_approve,
412 approval_mode: posture,
413 configured_sandbox_mode: sandbox_mode,
414 })
415 .expect("publish live runtime authority");
416
417 let published = handle.runtime_permission_authority();
418 assert_eq!(published.approval_mode, posture);
419 assert_eq!(published.auto_approve, auto_approve);
420 assert!(engine.apply_pending_runtime_authority().await);
421 assert_eq!(engine.current_mode, mode);
422 assert_eq!(engine.session.approval_mode, posture);
423 assert_eq!(engine.session.auto_approve, auto_approve);
424 assert_eq!(
425 engine
426 .live_tool_context(Some(&registry))
427 .expect("live registry context")
428 .elevated_sandbox_policy,
429 Some(expected_sandbox),
430 );
431 // Tools carry the posture the turn resolved, so a task they create can
432 // pin the authority it was actually granted.
433 assert_eq!(
434 engine
435 .live_tool_context(Some(&registry))
436 .expect("live registry context")
437 .approval_mode,
438 posture,
439 );
440 }
441 }
442
443 #[test]
444 fn turn_approval_mode_prefers_auto_approve_flag() {
445 use ApprovalMode;
446
447 assert_eq!(
448 agent_approval_mode_for_turn(true, ApprovalMode::Suggest),
449 ApprovalMode::Bypass
450 );
451 assert_eq!(
452 agent_approval_mode_for_turn(true, ApprovalMode::Never),
453 ApprovalMode::Bypass
454 );
455 }
456
457 #[test]
458 fn messages_with_turn_metadata_returns_stored_session_messages() {
459 use ApprovalMode;
460
461 let tmp = tempdir().expect("tempdir");
462 let config = EngineConfig {
463 workspace: tmp.path().to_path_buf(),
464 ..Default::default()
465 };
466 let (mut engine, _handle) = Engine::new(config, &Config::default());
467 engine.current_mode = AppMode::Plan;
468 engine.session.approval_mode = ApprovalMode::Suggest;
469 engine.session.messages = vec![Message {
470 role: Role::User,
471 content: vec![ContentBlock::Text {
472 text: "summary after compaction".to_string(),
473 cache_control: None,
474 }],
475 }]
476 .into();
477 let stored = engine.session.messages.clone();
478
479 let request_messages = engine.messages_with_turn_metadata();
480
481 assert_eq!(&*engine.session.messages, &*stored);
482 assert_eq!(request_messages.len(), stored.len());
483 assert!(
484 request_messages
485 .iter()
486 .all(|message| message.role != "system"),
487 "model request projection must not create appended system messages"
488 );
489 }
490
491 // === To-do state reaches the model through its own tool results ===
492 //
493 // Codewhale has one To-do list. The model learns what is on it the way it
494 // learns anything else: from its own `work_update` call and the short receipt
495 // it returned, which are ordinary persisted history. No request re-states the list, on any
496 // step. The complete list stays visible in the UI, which is a different
497 // surface from the request.
498
499 fn todo_engine() -> (
500 Engine,
501 EngineHandle,
502 crate::tools::todo::SharedTodoList,
503 crate::work_graph::SharedWorkRuntime,
504 tempfile::TempDir,
505 ) {
506 let tmp = tempdir().expect("tempdir");
507 let todos = crate::tools::todo::new_shared_todo_list();
508 let plan = crate::tools::plan::new_shared_plan_state();
509 let work = crate::work_graph::new_shared_work_runtime(todos.clone(), plan.clone());
510 let config = EngineConfig {
511 workspace: tmp.path().to_path_buf(),
512 todos: todos.clone(),
513 plan_state: plan,
514 runtime_services: crate::tools::spec::RuntimeToolServices {
515 work: Some(work.clone()),
516 ..Default::default()
517 },
518 ..Default::default()
519 };
520 let (mut engine, handle) = Engine::new(config, &Config::default());
521 engine.session.messages = vec![Message {
522 role: Role::User,
523 content: vec![ContentBlock::Text {
524 text: "land the To-do seam".to_string(),
525 cache_control: None,
526 }],
527 }]
528 .into();
529 (engine, handle, todos, work, tmp)
530 }
531
532 fn message_text_of(message: &Message) -> String {
533 message
534 .content
535 .iter()
536 .filter_map(|block| match block {
537 ContentBlock::Text { text, .. } => Some(text.as_str()),
538 _ => None,
539 })
540 .collect::<Vec<_>>()
541 .join("\n")
542 }
543
544 /// Run the real `work_update` tool against the attached graph — not a direct
545 /// mutation of the legacy list, which is exactly the state the fork seam must
546 /// stop trusting.
547 async fn run_graph_backed_work_update(
548 todos: &crate::tools::todo::SharedTodoList,
549 work: &crate::work_graph::SharedWorkRuntime,
550 items: serde_json::Value,
551 ) {
552 use crate::tools::spec::ToolSpec as _;
553 let mut context = crate::tools::spec::ToolContext::new(std::env::temp_dir());
554 context.runtime.work = Some(work.clone());
555 crate::tools::todo::TodoWriteTool::new(todos.clone())
556 .execute(json!({ "todos": items }), &context)
557 .await
558 .expect("graph-backed todo_write");
559 }
560
561 /// A non-empty To-do adds nothing to the messages a request is built from.
562 #[tokio::test]
563 async fn a_non_empty_todo_adds_nothing_to_the_request_messages() {
564 let (engine, _handle, todos, work, _tmp) = todo_engine();
565 let stored = engine.session.messages.clone();
566
567 run_graph_backed_work_update(
568 &todos,
569 &work,
570 json!([
571 { "content": "read the runtime seam", "status": "completed" },
572 { "content": "write the renderer", "status": "in_progress" }
573 ]),
574 )
575 .await;
576
577 let request = engine.messages_with_turn_metadata();
578
579 assert_eq!(request.len(), stored.len(), "nothing may be appended");
580 assert_eq!(&*engine.session.messages, &*stored, "history is untouched");
581 for message in &request {
582 let text = message_text_of(message);
583 assert!(
584 !text.contains("To-do ("),
585 "request re-stated the list: {text}"
586 );
587 assert!(
588 !text.contains("write the renderer"),
589 "request re-stated an item: {text}"
590 );
591 assert!(!text.contains("codewhale:work"), "{text}");
592 }
593 }
594
595 /// The outbound payload itself, across a whole turn and the turn after it:
596 /// with work on the list, no provider request body mentions it.
597 #[tokio::test]
598 #[allow(clippy::await_holding_lock)]
599 async fn provider_request_bodies_never_carry_the_todo_list() {
600 use wiremock::matchers::{method, path};
601 use wiremock::{Mock, MockServer, ResponseTemplate};
602
603 let _lock = lock_test_env();
604 let workspace = tempdir().expect("tempdir");
605 let server = MockServer::start().await;
606 let done_sse = concat!(
607 "data: {\"id\":\"chatcmpl-todo\",\"choices\":[{\"index\":0,",
608 "\"delta\":{\"content\":\"noted.\"},\"finish_reason\":null}]}\n\n",
609 "data: {\"id\":\"chatcmpl-todo\",\"choices\":[{\"index\":0,",
610 "\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n",
611 "data: [DONE]\n\n",
612 );
613 Mock::given(method("POST"))
614 .and(path("/v1/chat/completions"))
615 .respond_with(
616 ResponseTemplate::new(200)
617 .insert_header("content-type", "text/event-stream")
618 .set_body_string(done_sse),
619 )
620 .mount(&server)
621 .await;
622
623 let api_config = Config::default()
624 .with_legacy_root(Some("test-key".to_string()), Some(server.uri()));
625 let todos = crate::tools::todo::new_shared_todo_list();
626 let plan = crate::tools::plan::new_shared_plan_state();
627 let work = crate::work_graph::new_shared_work_runtime(todos.clone(), plan.clone());
628 let engine_config = EngineConfig {
629 workspace: workspace.path().to_path_buf(),
630 snapshots_enabled: false,
631 subagents_enabled: false,
632 todos: todos.clone(),
633 plan_state: plan,
634 runtime_services: crate::tools::spec::RuntimeToolServices {
635 work: Some(work.clone()),
636 ..Default::default()
637 },
638 ..EngineConfig::default()
639 };
640 run_graph_backed_work_update(
641 &todos,
642 &work,
643 json!([{ "content": "ship the outbound payload test", "status": "in_progress" }]),
644 )
645 .await;
646
647 let (engine, handle) = Engine::new(engine_config, &api_config);
648 let task = tokio::spawn(engine.run());
649
650 for prompt in ["first turn", "second turn"] {
651 handle
652 .send(external_user_message_op(
653 prompt,
654 AppMode::Agent,
655 &api_config,
656 ))
657 .await
658 .expect("send turn");
659 let mut rx = handle.rx_event.write().await;
660 while let Some(event) = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
661 .await
662 .expect("timed out waiting for turn completion")
663 {
664 match event {
665 Event::Error { envelope, .. } => panic!("turn errored: {envelope:?}"),
666 Event::TurnComplete { status, error, .. } => {
667 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
668 break;
669 }
670 _ => {}
671 }
672 }
673 }
674
675 let requests = server
676 .received_requests()
677 .await
678 .expect("recorded provider requests");
679 assert!(requests.len() >= 2, "expected one request per turn");
680 for request in &requests {
681 let body = String::from_utf8_lossy(&request.body);
682 assert!(
683 !body.contains("ship the outbound payload test"),
684 "a provider request restated the To-do list: {body}"
685 );
686 assert!(!body.contains("To-do ("), "{body}");
687 assert!(!body.contains("codewhale:work"), "{body}");
688 }
689
690 handle.send(Op::Shutdown).await.expect("shutdown engine");
691 task.await.expect("engine task");
692 }
693
694 /// The turn-start structured state is deliberately To-do-free: the list moves
695 /// during a turn, so it is resolved at the fork seam instead.
696 #[test]
697 fn turn_start_structured_state_carries_no_todo_section() {
698 let state = StructuredState {
699 mode_label: "Agent".to_string(),
700 workspace: PathBuf::from("/workspace/codewhale"),
701 cwd: None,
702 working_set_summary: None,
703 subagent_snapshots: Vec::new(),
704 };
705
706 let block = state.to_system_block().expect("fork state block");
707
708 assert!(
709 !block.contains(crate::todo_snapshot::FORK_TODO_SECTION_HEADING),
710 "stable capture must not pin a To-do section: {block}"
711 );
712 assert!(!block.contains("To-do ("));
713 }
714
715 /// The fork handoff and `/relay` show the same To-do snapshot body. Relay
716 /// parity is asserted in `commands::tests`.
717 #[tokio::test]
718 async fn fork_state_block_reuses_the_snapshot_body() {
719 let (engine, _handle, todos, work, _tmp) = todo_engine();
720 run_graph_backed_work_update(
721 &todos,
722 &work,
723 json!([
724 { "content": "Wire Fleet progress projection", "status": "in_progress" },
725 { "content": "Run focused gates", "status": "pending" }
726 ]),
727 )
728 .await;
729 let snapshot = engine.todo_source().snapshot().await;
730 let body = crate::todo_snapshot::todo_snapshot_body(&snapshot).expect("body");
731
732 let state = StructuredState {
733 mode_label: "Agent".to_string(),
734 workspace: PathBuf::from("/workspace/codewhale"),
735 cwd: None,
736 working_set_summary: None,
737 subagent_snapshots: Vec::new(),
738 };
739 let fork_context = crate::tools::subagent::SubAgentForkContext {
740 messages: engine.messages_with_turn_metadata(),
741 structured_state_block: state.to_system_block(),
742 work_source: Some(engine.todo_source()),
743 };
744
745 let resolved = fork_context
746 .with_resolved_state_block()
747 .await
748 .structured_state_block
749 .expect("resolved fork state block");
750
751 assert!(resolved.contains(&body), "fork body drifted: {resolved}");
752 }
753
754 /// `update_plan` is conversational reasoning, not a second list: plan-only
755 /// state must not produce a To-do snapshot.
756 #[tokio::test]
757 async fn plan_only_state_produces_no_todo_snapshot() {
758 let (engine, _handle, _todos, _work, _tmp) = todo_engine();
759 {
760 let mut plan = engine.config.plan_state.lock().await;
761 plan.update(crate::tools::plan::UpdatePlanArgs {
762 objective: Some("Ship the To-do seam".to_string()),
763 plan: vec![crate::tools::plan::PlanItemArg {
764 step: "draft the renderer".to_string(),
765 status: crate::tools::plan::StepStatus::InProgress,
766 }],
767 ..crate::tools::plan::UpdatePlanArgs::default()
768 });
769 assert!(!plan.snapshot().is_empty());
770 }
771
772 assert!(
773 engine.todo_source().body().await.is_none(),
774 "legacy plan-only state must not become a To-do snapshot"
775 );
776 }
777
778 /// A real graph-backed `work_update` stages the new projection in the
779 /// `WorkRuntime` and publishes into `config.todos` only later, asynchronously,
780 /// from the UI. The fork seam must read the staged projection, not the
781 /// pre-write legacy view.
782 #[tokio::test]
783 async fn fork_seam_reflects_a_graph_backed_work_update() {
784 let (engine, _handle, todos, work, _tmp) = todo_engine();
785 assert!(
786 engine.todo_source().is_graph_backed(),
787 "this engine must read the graph, not the legacy view"
788 );
789
790 run_graph_backed_work_update(
791 &todos,
792 &work,
793 json!([
794 { "content": "read the runtime seam", "status": "completed" },
795 { "content": "hand the child the live list", "status": "in_progress" }
796 ]),
797 )
798 .await;
799
800 // The staleness this test exists for: the legacy view is still empty here.
801 assert!(
802 todos.lock().await.snapshot().is_empty(),
803 "precondition: work_update stages in the graph and publishes later"
804 );
805
806 let body = engine.todo_source().body().await.expect("body");
807 assert!(body.contains("[x] #1 read the runtime seam"), "{body}");
808 assert!(
809 body.contains("[~] #2 hand the child the live list"),
810 "{body}"
811 );
812 }
813
814 /// A compaction checkpoint is history, never a second To-do surface or a
815 /// stable-system-prefix mutation.
816 #[tokio::test]
817 async fn compaction_keeps_todos_out_of_the_prefix() {
818 let (mut engine, _handle, todos, work, _tmp) = todo_engine();
819 run_graph_backed_work_update(
820 &todos,
821 &work,
822 json!([{ "content": "staged graph-only todo", "status": "in_progress" }]),
823 )
824 .await;
825 assert!(
826 todos.lock().await.snapshot().is_empty(),
827 "precondition: the compatibility list is still stale"
828 );
829
830 let stable_before = engine.session.system_prompt.clone();
831 engine.commit_compaction_checkpoint(Some(SystemPrompt::Text(format!(
832 "{COMPACTION_SUMMARY_MARKER}\nsummary"
833 ))));
834 assert_eq!(engine.session.system_prompt, stable_before);
835 let checkpoint = engine.rendered_compaction_summary().expect("checkpoint");
836 assert!(
837 !checkpoint.contains("staged graph-only todo"),
838 "{checkpoint}"
839 );
840 assert!(!checkpoint.contains("### Todos"), "{checkpoint}");
841 }
842
843 #[tokio::test]
844 async fn compaction_completed_reports_complete_post_input_tokens() {
845 let _env = crate::test_support::lock_test_env();
846 let tmp = tempdir().expect("tempdir");
847 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path());
848 let config = EngineConfig {
849 workspace: tmp.path().to_path_buf(),
850 ..Default::default()
851 };
852 let (mut engine, handle) = Engine::new(config, &Config::default());
853 engine.session.system_prompt = Some(SystemPrompt::Text("stable system context ".repeat(400)));
854 engine.session.replace_messages(vec![Message {
855 role: Role::User,
856 content: vec![ContentBlock::Text {
857 text: "post-compaction message".to_string(),
858 cache_control: None,
859 }],
860 }]);
861 engine.commit_compaction_checkpoint(Some(SystemPrompt::Text(format!(
862 "{COMPACTION_SUMMARY_MARKER}\npost-compaction summary"
863 ))));
864
865 let messages_only =
866 crate::compaction::estimate_input_tokens_for_pressure(&engine.session.messages, None);
867 let expected = engine.estimated_input_tokens();
868 assert!(expected > messages_only);
869 engine.active_context_window = Some(crate::route_runtime::ContextWindowResolution {
870 tokens: 1_000_000,
871 source: crate::route_runtime::ContextWindowSource::Configured,
872 });
873
874 engine
875 .emit_compaction_completed(
876 "compact_test".to_string(),
877 false,
878 "Made room".to_string(),
879 super::compaction::CompactionPass {
880 trigger: "manual",
881 path: Some(crate::compaction::CompactionPath::Summary),
882 messages_before: 4,
883 messages_after: Some(1),
884 tokens_before: 9000,
885 threshold_tokens: 8000,
886 configured_threshold_tokens: 8000,
887 usage: Usage {
888 input_tokens: 120,
889 output_tokens: 15,
890 ..Default::default()
891 },
892 elapsed_ms: 42,
893 reported_input_tokens: Some(8_500),
894 gate_input_tokens: None,
895 calibration: (2, 1),
896 compaction_window_tokens: Some(1_000_000),
897 },
898 )
899 .await;
900
901 let event = handle
902 .rx_event
903 .write()
904 .await
905 .recv()
906 .await
907 .expect("compaction completed event");
908 let Event::CompactionCompleted {
909 post_input_tokens, ..
910 } = event
911 else {
912 panic!("expected CompactionCompleted, got {event:?}");
913 };
914 assert_eq!(post_input_tokens, Some(expected as u64));
915 let log = std::fs::read_to_string(tmp.path().join("audit.log")).unwrap();
916 let records = log
917 .lines()
918 .map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
919 .filter(|row| row["event"] == "compaction.completed")
920 .collect::<Vec<_>>();
921 assert_eq!(records.len(), 1);
922 let details = &records[0]["details"];
923 assert_eq!(details["messages_before"], 4);
924 assert_eq!(details["messages_after"], 1);
925 assert_eq!(details["reduction_ratio"], 0.75);
926 assert_eq!(details["estimated_tokens_before"], 9000);
927 assert_eq!(details["estimated_tokens_after"], expected);
928 assert_eq!(details["threshold_tokens"], 8000);
929 assert_eq!(details["configured_threshold_tokens"], 8000);
930 assert_eq!(details["summarizer_usage"]["input_tokens"], 120);
931 assert_eq!(details["trigger"], "manual");
932 assert_eq!(details["path"], "summary");
933 assert_eq!(details["outcome"], "success");
934 assert_eq!(details["elapsed_ms"], 42);
935 assert_eq!(details["reported_input_tokens"], 8_500);
936 assert_eq!(details["gate_input_tokens"], Value::Null);
937 assert_eq!(details["calibration"]["numerator"], 2);
938 assert_eq!(details["calibration"]["denominator"], 1);
939 assert_eq!(details["compaction_window_tokens"], 1_000_000);
940 assert_eq!(details["effective_context_window_tokens"], 1_000_000);
941 assert_eq!(details["effective_context_window_source"], "configured");
942 assert_eq!(
943 details["route_model"],
944 Value::String(engine.session.model.clone())
945 );
946 assert!(!log.contains("post-compaction message"));
947 engine
948 .record_compaction_event(
949 "compaction.refused",
950 serde_json::json!({
951 "trigger": "auto", "reason": "retained_floor", "threshold_tokens": 8000,
952 }),
953 )
954 .await;
955 assert!(
956 std::fs::read_to_string(tmp.path().join("audit.log"))
957 .unwrap()
958 .contains("compaction.refused")
959 );
960 }
961
962 /// `fork_context` is captured once at turn start, so a `work_update` followed
963 /// by an `agent` spawn *in the same turn* must still hand the child the
964 /// current snapshot. Only the To-do portion is refreshed; the inherited
965 /// transcript and stable state text are unchanged.
966 #[tokio::test]
967 async fn same_turn_fork_carries_the_updated_todo() {
968 let (engine, _handle, todos, work, _tmp) = todo_engine();
969
970 // Turn start: capture the fork context, before any work exists.
971 let stable_block = StructuredState {
972 mode_label: "Agent".to_string(),
973 workspace: engine.config.workspace.clone(),
974 cwd: None,
975 working_set_summary: None,
976 subagent_snapshots: Vec::new(),
977 }
978 .to_system_block();
979 let fork_context = crate::tools::subagent::SubAgentForkContext {
980 messages: engine.messages_with_turn_metadata(),
981 structured_state_block: stable_block.clone(),
982 work_source: Some(engine.todo_source()),
983 };
984 let captured_messages = fork_context.messages.clone();
985 assert!(
986 !fork_context
987 .with_resolved_state_block()
988 .await
989 .structured_state_block
990 .expect("stable block")
991 .contains("To-do ("),
992 "no work yet, so no To-do section"
993 );
994
995 // Mid-turn: the model calls work_update, then spawns an agent.
996 run_graph_backed_work_update(
997 &todos,
998 &work,
999 json!([{ "content": "hand the child the live list", "status": "in_progress" }]),
1000 )
1001 .await;
1002
1003 let resolved = fork_context.with_resolved_state_block().await;
1004 let block = resolved
1005 .structured_state_block
1006 .as_deref()
1007 .expect("resolved block");
1008 let snapshot = engine.todo_source().snapshot().await;
1009 let body = crate::todo_snapshot::todo_snapshot_body(&snapshot).expect("body");
1010
1011 assert!(
1012 block.contains(&body),
1013 "same-turn fork must carry the current body: {block}"
1014 );
1015 assert!(
1016 block.contains("[~] #1 hand the child the live list"),
1017 "{block}"
1018 );
1019 // Stable history semantics are untouched.
1020 assert_eq!(resolved.messages, captured_messages);
1021 assert!(
1022 block.starts_with(stable_block.as_deref().expect("stable").trim()),
1023 "the stable capture must stay a byte-identical prefix: {block}"
1024 );
1025 }
1026
1027 /// U1: hosts resend the compaction config on every model, route or session
1028 /// sync. Neither a session sync nor a config whose switch did not move should
1029 /// produce a status line: it would overwrite a real error (the missing-key
1030 /// notice) or the host's confirmed "Resumed:" receipt in the footer.
1031 #[tokio::test]
1032 async fn unchanged_compaction_config_is_acknowledged_silently() {
1033 let tmp = tempdir().expect("tempdir");
1034 let (engine, handle) = Engine::new(
1035 EngineConfig {
1036 workspace: tmp.path().to_path_buf(),
1037 ..Default::default()
1038 },
1039 &Config::default(),
1040 );
1041 let current = engine.config.compaction.clone();
1042 let restored_messages = vec![Message {
1043 role: Role::User,
1044 content: vec![ContentBlock::Text {
1045 text: "Restored conversation proof".to_string(),
1046 cache_control: None,
1047 }],
1048 }];
1049 let run = tokio::spawn(engine.run());
1050 handle
1051 .send(Op::SyncSession {
1052 expected: None,
1053 control: crate::core::ops::SessionControlId::new(),
1054 session_id: Some("resumed-session".to_string()),
1055 messages: restored_messages.clone(),
1056 system_prompt: None,
1057 system_prompt_override: false,
1058 model: current.model.clone(),
1059 workspace: tmp.path().to_path_buf(),
1060 mode: AppMode::Agent,
1061 agent_preset: None,
1062 })
1063 .await
1064 .expect("sync restored session");
1065 handle
1066 .send(Op::SetCompaction {
1067 config: current.clone(),
1068 })
1069 .await
1070 .expect("send unchanged config");
1071 // A session restore resyncs the model and window with the switch as it
1072 // was: applied, but not news.
1073 let mut resynced = current.clone();
1074 resynced.model = format!("{}-resynced", current.model);
1075 resynced.effective_context_window = Some(64_000);
1076 handle
1077 .send(Op::SetCompaction {
1078 config: resynced.clone(),
1079 })
1080 .await
1081 .expect("send resynced config");
1082 let mut changed = resynced;
1083 changed.enabled = !changed.enabled;
1084 let expected = if changed.enabled {
1085 "Make room automatically: on"
1086 } else {
1087 "Make room automatically: off"
1088 };
1089 handle
1090 .send(Op::SetCompaction { config: changed })
1091 .await
1092 .expect("send changed config");
1093
1094 let mut rx = handle.rx_event.write().await;
1095 let mut session_updated = false;
1096 let first_status = loop {
1097 let event = tokio::time::timeout(Duration::from_secs(2), rx.recv())
1098 .await
1099 .expect("status after a real change")
1100 .expect("event");
1101 match event {
1102 Event::SessionUpdated {
1103 session_id,
1104 messages,
1105 model,
1106 workspace,
1107 ..
1108 } => {
1109 assert_eq!(session_id, "resumed-session");
1110 assert_eq!(*messages, restored_messages);
1111 assert_eq!(model, current.model);
1112 assert_eq!(workspace, tmp.path());
1113 session_updated = true;
1114 }
1115 Event::Status { message } => break message,
1116 _ => {}
1117 }
1118 };
1119 assert!(
1120 session_updated,
1121 "session sync still publishes its authoritative update"
1122 );
1123 assert_eq!(
1124 first_status, expected,
1125 "session sync and unchanged/resynced configs produced no status; only the switch did"
1126 );
1127 drop(rx);
1128 run.abort();
1129 }
1130
1131 #[tokio::test]
1132 async fn change_mode_op_updates_current_mode_and_emits_status() {
1133 let tmp = tempdir().expect("tempdir");
1134 let mut config = EngineConfig {
1135 workspace: tmp.path().to_path_buf(),
1136 model: "deepseek-v4-pro".to_string(),
1137 ..Default::default()
1138 };
1139 config.features.disable(Feature::Mcp);
1140 let (engine, handle) = Engine::new(config, &Config::default());
1141
1142 let run = tokio::spawn(engine.run());
1143 handle
1144 .send(Op::ChangeMode {
1145 mode: AppMode::Agent,
1146 allow_shell: true,
1147 trust_mode: true,
1148 auto_approve: true,
1149 approval_mode: ApprovalMode::Bypass,
1150 configured_sandbox_mode: None,
1151 })
1152 .await
1153 .expect("send change mode");
1154
1155 // Expect a SessionUpdated event confirming the mode change.
1156 let mut rx = handle.rx_event.write().await;
1157 let session_updated = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
1158 .await
1159 .expect("session update after mode switch")
1160 .expect("event");
1161 let Event::SessionUpdated {
1162 source: _,
1163 messages, .. } = session_updated else {
1164 panic!("should emit SessionUpdated after mode change, got: {session_updated:?}");
1165 };
1166 assert!(
1167 messages.iter().all(|message| message.role != "system"),
1168 "mode switch must not persist synthetic system messages: {messages:?}"
1169 );
1170
1171 // Also expect a status event
1172 let status = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
1173 .await
1174 .expect("status after mode switch")
1175 .expect("event");
1176 assert!(
1177 matches!(status, Event::Status { .. }),
1178 "should emit Status after mode change, got: {status:?}"
1179 );
1180
1181 run.abort();
1182 }
1183
1184 #[test]
1185 fn runtime_mode_policy_updates_engine_session_mirrors() {
1186 let tmp = tempdir().expect("tempdir");
1187 let config = EngineConfig {
1188 workspace: tmp.path().to_path_buf(),
1189 model: "deepseek-v4-pro".to_string(),
1190 allow_shell: false,
1191 trust_mode: false,
1192 ..Default::default()
1193 };
1194 let (mut engine, _handle) = Engine::new(config, &Config::default());
1195 engine.current_mode = AppMode::Plan;
1196 engine.session.allow_shell = false;
1197 engine.session.trust_mode = false;
1198 engine.session.auto_approve = false;
1199 engine.session.approval_mode = ApprovalMode::Suggest;
1200
1201 let agent_authority = crate::core::authority::TurnAuthority::from_effective_fields(
1202 AppMode::Agent,
1203 true,
1204 false,
1205 false,
1206 ApprovalMode::Never,
1207 );
1208 engine.apply_runtime_mode_policy(&agent_authority);
1209
1210 assert_eq!(engine.current_mode, AppMode::Agent);
1211 assert!(engine.session.allow_shell);
1212 assert!(engine.config.allow_shell);
1213 assert!(!engine.session.trust_mode);
1214 assert!(!engine.config.trust_mode);
1215 assert!(!engine.session.auto_approve);
1216 assert_eq!(engine.session.approval_mode, ApprovalMode::Never);
1217
1218 let full_access_authority = crate::core::authority::TurnAuthority::from_effective_fields(
1219 AppMode::Agent,
1220 true,
1221 true,
1222 true,
1223 ApprovalMode::Bypass,
1224 );
1225 engine.apply_runtime_mode_policy(&full_access_authority);
1226
1227 assert_eq!(engine.current_mode, AppMode::Agent);
1228 assert!(engine.session.allow_shell);
1229 assert!(engine.session.trust_mode);
1230 assert!(engine.config.trust_mode);
1231 assert!(engine.session.auto_approve);
1232 assert_eq!(engine.session.approval_mode, ApprovalMode::Bypass);
1233 }
1234
1235 #[tokio::test]
1236 async fn sync_session_restores_current_mode() {
1237 let tmp = tempdir().expect("tempdir");
1238 let config = EngineConfig {
1239 workspace: tmp.path().to_path_buf(),
1240 model: "deepseek-v4-pro".to_string(),
1241 ..Default::default()
1242 };
1243 let (engine, handle) = Engine::new(config, &Config::default());
1244
1245 let run = tokio::spawn(engine.run());
1246 handle
1247 .send(Op::SyncSession {
1248 expected: None,
1249 control: crate::core::ops::SessionControlId::new(),
1250 session_id: Some("plan-session".to_string()),
1251 messages: Vec::new(),
1252 system_prompt: None,
1253 system_prompt_override: false,
1254 model: "deepseek-v4-pro".to_string(),
1255 workspace: tmp.path().to_path_buf(),
1256 mode: AppMode::Plan,
1257 agent_preset: None,
1258 })
1259 .await
1260 .expect("sync session");
1261
1262 let (tx, rx) = tokio::sync::oneshot::channel();
1263 handle
1264 .send(Op::GetSessionSnapshot {
1265 tx: std::sync::Arc::new(std::sync::Mutex::new(Some(tx))),
1266 })
1267 .await
1268 .expect("request snapshot");
1269 let snapshot = tokio::time::timeout(Duration::from_secs(2), rx)
1270 .await
1271 .expect("snapshot response")
1272 .expect("snapshot");
1273
1274 assert_eq!(snapshot.mode, "plan");
1275
1276 run.abort();
1277 }
1278
1279 #[tokio::test]
1280 async fn sync_session_without_prompt_repins_full_system_prompt_on_next_turn() {
1281 use crate::llm_client::mock::{MockLlmClient, canned};
1282
1283 const WORKSPACE_RULE: &str = "SYNC_SESSION_FULL_PROMPT_PROOF";
1284
1285 async fn wait_for_completed_turn(handle: &EngineHandle) {
1286 let mut rx = handle.rx_event.write().await;
1287 loop {
1288 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
1289 .await
1290 .expect("timed out waiting for turn completion")
1291 .expect("engine event channel closed before turn completion");
1292 if let Event::TurnComplete { status, error, .. } = event {
1293 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1294 break;
1295 }
1296 }
1297 }
1298
1299 let workspace = tempdir().expect("tempdir");
1300 fs::write(
1301 workspace.path().join("AGENTS.md"),
1302 format!("# Rules\n\nAlways preserve {WORKSPACE_RULE}.\n"),
1303 )
1304 .expect("write AGENTS.md fixture");
1305 let config = Config::default();
1306 let mock = std::sync::Arc::new(MockLlmClient::new(vec![canned::simple_text_turn(
1307 "Turn complete.",
1308 )]));
1309 let client: crate::core::model_client::SharedModelClient = mock.clone();
1310 let (mut engine, handle) = Engine::new_with_model_client(
1311 deterministic_engine_config(workspace.path()),
1312 &config,
1313 client,
1314 );
1315 let established_context = engine.installed_next_turn_prompt_context();
1316 assert_eq!(
1317 engine
1318 .refresh_pinned_header_for_turn(&established_context)
1319 .unwrap(),
1320 None
1321 );
1322 assert_eq!(
1323 engine.session.pinned_prompt_context.as_ref(),
1324 Some(&established_context),
1325 "precondition: the outgoing conversation has an established prompt pin"
1326 );
1327 let task = tokio::spawn(engine.run());
1328
1329 handle
1330 .send(Op::SyncSession {
1331 expected: None,
1332 control: crate::core::ops::SessionControlId::new(),
1333 session_id: Some("fresh-session".to_string()),
1334 messages: Vec::new(),
1335 system_prompt: None,
1336 system_prompt_override: false,
1337 model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(),
1338 workspace: workspace.path().to_path_buf(),
1339 mode: AppMode::Agent,
1340 agent_preset: None,
1341 })
1342 .await
1343 .expect("sync fresh session without a persisted prompt");
1344 let synced = handle
1345 .get_session_snapshot()
1346 .await
1347 .expect("drain session sync");
1348 assert!(
1349 synced.system_prompt.is_none(),
1350 "SyncSession must install the persisted prompt exactly before the next turn"
1351 );
1352
1353 handle
1354 .send(external_user_message_op(
1355 "Start the newly synchronized conversation.",
1356 AppMode::Agent,
1357 &config,
1358 ))
1359 .await
1360 .expect("send first turn after sync");
1361 wait_for_completed_turn(&handle).await;
1362
1363 let requests = mock.captured_requests();
1364 assert_eq!(requests.len(), 1);
1365 let repinned = requests[0]
1366 .system
1367 .clone()
1368 .map(system_prompt_text)
1369 .expect("the first turn after SyncSession must send a full system prompt");
1370 assert!(
1371 !repinned.contains(WORKSPACE_RULE),
1372 "workspace instructions travel as history, not in the pinned prompt: {repinned}"
1373 );
1374 assert!(
1375 requests[0].messages.iter().any(|message| {
1376 crate::runtime_handoff::project_instructions_display(message)
1377 .is_some_and(|body| body.contains(WORKSPACE_RULE))
1378 }),
1379 "the first turn must carry the workspace rule as a history message: {:?}",
1380 requests[0].messages
1381 );
1382 assert!(
1383 requests[0].messages.iter().all(|message| {
1384 message.content.iter().all(|block| {
1385 !matches!(
1386 block,
1387 ContentBlock::Text { text, .. } if text.starts_with("<context_update>")
1388 )
1389 })
1390 }),
1391 "the fresh session must not inherit a context-update delta: {:?}",
1392 requests[0].messages
1393 );
1394
1395 let refreshed = handle
1396 .get_session_snapshot()
1397 .await
1398 .expect("snapshot refreshed session");
1399 let refreshed_prompt = refreshed
1400 .system_prompt
1401 .map(system_prompt_text)
1402 .expect("refreshed session prompt");
1403 assert!(!refreshed_prompt.contains(WORKSPACE_RULE));
1404 assert!(
1405 refreshed.messages.iter().any(|message| {
1406 crate::runtime_handoff::project_instructions_display(message)
1407 .is_some_and(|body| body.contains(WORKSPACE_RULE))
1408 }),
1409 "the refreshed session keeps the workspace rule in history"
1410 );
1411 handle.send(Op::Shutdown).await.expect("shutdown engine");
1412 task.await.expect("engine task");
1413 }
1414
1415 #[tokio::test]
1416 async fn sync_session_same_id_does_not_finalize_live_worker() {
1417 let tmp = tempdir().expect("tempdir");
1418 let workspace = tmp.path().to_path_buf();
1419 let config = EngineConfig {
1420 workspace: workspace.clone(),
1421 model: "deepseek-v4-pro".to_string(),
1422 ..Default::default()
1423 };
1424 let (engine, handle) = Engine::new(config, &Config::default());
1425 let manager = engine.subagent_manager.clone();
1426
1427 let run = tokio::spawn(engine.run());
1428 // Install the conversation identity first so the manager is not
1429 // finalized by the very first identity transition away from the
1430 // construction-time UUID.
1431 handle
1432 .send(Op::SyncSession {
1433 expected: None,
1434 control: crate::core::ops::SessionControlId::new(),
1435 session_id: Some("session-keep".to_string()),
1436 messages: Vec::new(),
1437 system_prompt: None,
1438 system_prompt_override: false,
1439 model: "deepseek-v4-pro".to_string(),
1440 workspace: workspace.clone(),
1441 mode: AppMode::Agent,
1442 agent_preset: None,
1443 })
1444 .await
1445 .expect("install session");
1446 handle.get_session_snapshot().await.expect("drain install");
1447
1448 let agent_id = {
1449 let mut manager = manager.write().await;
1450 manager.insert_test_running_agent("keep", &workspace)
1451 };
1452
1453 // A same-id re-sync is a reload, not a conversation boundary.
1454 handle
1455 .send(Op::SyncSession {
1456 expected: None,
1457 control: crate::core::ops::SessionControlId::new(),
1458 session_id: Some("session-keep".to_string()),
1459 messages: Vec::new(),
1460 system_prompt: None,
1461 system_prompt_override: false,
1462 model: "deepseek-v4-pro".to_string(),
1463 workspace: workspace.clone(),
1464 mode: AppMode::Agent,
1465 agent_preset: None,
1466 })
1467 .await
1468 .expect("re-sync same session");
1469 handle.get_session_snapshot().await.expect("drain re-sync");
1470
1471 let record = manager
1472 .read()
1473 .await
1474 .get_worker_record(&agent_id)
1475 .expect("live worker record");
1476 assert!(
1477 !record.status.is_terminal(),
1478 "same-id re-sync must not finalize the worker: {:?}",
1479 record.status
1480 );
1481
1482 run.abort();
1483 }
1484
1485 #[tokio::test]
1486 async fn sync_session_different_id_finalizes_live_worker() {
1487 let tmp = tempdir().expect("tempdir");
1488 let workspace = tmp.path().to_path_buf();
1489 let config = EngineConfig {
1490 workspace: workspace.clone(),
1491 model: "deepseek-v4-pro".to_string(),
1492 ..Default::default()
1493 };
1494 let (engine, handle) = Engine::new(config, &Config::default());
1495 let manager = engine.subagent_manager.clone();
1496
1497 let run = tokio::spawn(engine.run());
1498 handle
1499 .send(Op::SyncSession {
1500 expected: None,
1501 control: crate::core::ops::SessionControlId::new(),
1502 session_id: Some("session-a".to_string()),
1503 messages: Vec::new(),
1504 system_prompt: None,
1505 system_prompt_override: false,
1506 model: "deepseek-v4-pro".to_string(),
1507 workspace: workspace.clone(),
1508 mode: AppMode::Agent,
1509 agent_preset: None,
1510 })
1511 .await
1512 .expect("install session-a");
1513 handle.get_session_snapshot().await.expect("drain install");
1514
1515 let agent_id = {
1516 let mut manager = manager.write().await;
1517 let agent_id = manager.insert_test_running_agent("close", &workspace);
1518 manager.assign_test_session_owner(&agent_id, "session-a");
1519 agent_id
1520 };
1521
1522 // A different id is a conversation boundary: the live worker must be
1523 // finalized with the session-closed reason.
1524 handle
1525 .send(Op::SyncSession {
1526 expected: None,
1527 control: crate::core::ops::SessionControlId::new(),
1528 session_id: Some("session-b".to_string()),
1529 messages: Vec::new(),
1530 system_prompt: None,
1531 system_prompt_override: false,
1532 model: "deepseek-v4-pro".to_string(),
1533 workspace: workspace.clone(),
1534 mode: AppMode::Agent,
1535 agent_preset: None,
1536 })
1537 .await
1538 .expect("switch to session-b");
1539 handle.get_session_snapshot().await.expect("drain switch");
1540
1541 let record = manager
1542 .read()
1543 .await
1544 .get_worker_record(&agent_id)
1545 .expect("worker record after close");
1546 assert!(
1547 record.status.is_terminal(),
1548 "different-id switch must finalize the worker: {:?}",
1549 record.status
1550 );
1551 assert_eq!(
1552 record.status,
1553 crate::tools::subagent::AgentWorkerStatus::Interrupted
1554 );
1555 let reason = record.latest_message.as_deref().unwrap_or("");
1556 assert!(
1557 reason.contains("parent session closed"),
1558 "session-closed reason missing: {reason}"
1559 );
1560
1561 run.abort();
1562 }
1563
1564 #[tokio::test]
1565 async fn sync_session_migrates_one_checkpoint_and_strips_its_system_carrier() {
1566 let tmp = tempdir().expect("tempdir");
1567 let config = EngineConfig {
1568 workspace: tmp.path().to_path_buf(),
1569 model: "deepseek-v4-pro".to_string(),
1570 ..Default::default()
1571 };
1572 let (engine, handle) = Engine::new(config, &Config::default());
1573 let carrier = SystemPrompt::Text(format!(
1574 "stable host prompt\n\n<!-- compaction-summary:begin -->\n{COMPACTION_SUMMARY_MARKER}\nnew checkpoint\n<!-- compaction-summary:end -->"
1575 ));
1576 let old_checkpoint = crate::compaction::compaction_checkpoint_message(&SystemPrompt::Text(
1577 format!("{COMPACTION_SUMMARY_MARKER}\nold checkpoint"),
1578 ));
1579
1580 let run = tokio::spawn(engine.run());
1581 let mut messages = vec![old_checkpoint];
1582 for round in 0..2 {
1583 handle
1584 .send(Op::SyncSession {
1585 expected: None,
1586 control: crate::core::ops::SessionControlId::new(),
1587 session_id: Some("compacted-session".to_string()),
1588 messages,
1589 system_prompt: Some(carrier.clone()),
1590 system_prompt_override: true,
1591 model: "deepseek-v4-pro".to_string(),
1592 workspace: tmp.path().to_path_buf(),
1593 mode: AppMode::Agent,
1594 agent_preset: None,
1595 })
1596 .await
1597 .expect("sync compacted session");
1598
1599 let (tx, rx) = tokio::sync::oneshot::channel();
1600 handle
1601 .send(Op::GetSessionSnapshot {
1602 tx: std::sync::Arc::new(std::sync::Mutex::new(Some(tx))),
1603 })
1604 .await
1605 .expect("request snapshot");
1606 let snapshot = tokio::time::timeout(Duration::from_secs(2), rx)
1607 .await
1608 .expect("snapshot response")
1609 .expect("snapshot");
1610
1611 let checkpoints = snapshot
1612 .messages
1613 .iter()
1614 .filter(|message| crate::compaction::is_compaction_checkpoint_message(message))
1615 .collect::<Vec<_>>();
1616 assert_eq!(checkpoints.len(), 1, "round {round}: {checkpoints:?}");
1617 let checkpoint_text = message_text_of(checkpoints[0]);
1618 assert!(
1619 checkpoint_text.contains("new checkpoint"),
1620 "{checkpoint_text}"
1621 );
1622 assert!(
1623 !checkpoint_text.contains("old checkpoint"),
1624 "{checkpoint_text}"
1625 );
1626 assert_eq!(
1627 snapshot.system_prompt,
1628 Some(SystemPrompt::Text("stable host prompt".to_string()))
1629 );
1630 messages = snapshot.messages;
1631 }
1632
1633 run.abort();
1634 }
1635
1635 lines RUST