返回 CodeWhale
test_cases_15.rs
根目录 / crates / engine / src / core / engine / tests / test_cases_15.rs
1 #[test]
2 fn subagent_results_are_summarized_before_parent_context_insertion() {
3 let long_result = "verified detail\n".repeat(1_000);
4 let output = ToolResult::success(
5 json!({
6 "agent_id": "agent_1234abcd",
7 "agent_type": "explore",
8 "assignment": {
9 "objective": "Inspect the RLM rendering path and report the smallest fix."
10 },
11 "model": "deepseek-v4-flash",
12 "status": "Completed",
13 "result": long_result,
14 "steps_taken": 12,
15 "duration_ms": 3456
16 })
17 .to_string(),
18 );
19
20 let context = compact_tool_result_for_context("deepseek-v4-pro", "agent", &output);
21
22 assert!(context.contains("[sub-agent result summarized for parent context]"));
23 assert!(context.contains("agent_1234abcd (explore) status=Completed"));
24 assert!(context.contains("Inspect the RLM rendering path"));
25 assert!(context.contains("steps=12"));
26 assert!(context.len() < output.content.len());
27 assert!(context.contains("self-report"));
28 assert!(context.contains("verify side effects"));
29 assert!(context.contains("verify side effects with `read`"));
30 assert!(!context.contains("read_file") && !context.contains("list_dir"));
31 assert!(context.contains("handle_read"));
32 // #6747: the guidance names only callable tools (no hidden `File`).
33 crate::tools::canonical_action_test_support::assert_text_names_only_callable_tools(
34 "sub-agent summary guidance",
35 &super::context::subagent_summary_guidance(),
36 );
37 }
38
39 #[test]
40 fn wait_payloads_survive_parent_context_compaction() {
41 let raw = json!({
42 "action": "wait",
43 "until": "all",
44 "all_settled": true,
45 "settled": [{"agent_id": "agent_1234abcd", "status": "Completed"}],
46 "still_running": [],
47 "waited_ms": 1234,
48 "timed_out": false,
49 "note": "joined the fan-out"
50 })
51 .to_string();
52 let output = ToolResult::success(raw.clone());
53
54 let context = compact_tool_result_for_context("deepseek-v4-pro", "agent", &output);
55
56 assert!(
57 !context.contains("status=unknown"),
58 "a wait envelope must not be projected as an unknown snapshot: {context}"
59 );
60 assert!(context.contains("agent_1234abcd"));
61 assert!(context.contains("still_running"));
62 assert!(context.contains("waited_ms"));
63 assert_eq!(
64 context, raw,
65 "small coordination payloads pass through verbatim"
66 );
67 }
68
69 #[test]
70 fn run_verifiers_results_are_structured_before_context_insertion() {
71 let noisy_failure = "node lint failure detail\n".repeat(300);
72 let noisy_success = "successful check output\n".repeat(300);
73 let output = ToolResult::success(
74 json!({
75 "success": false,
76 "profile": "auto",
77 "level": "quick",
78 "workspace": "/repo",
79 "gate_count": 3,
80 "passed": 1,
81 "failed": 1,
82 "skipped": 1,
83 "summary": "1 passed, 1 failed, 1 skipped",
84 "gates": [
85 {
86 "name": "rust-check",
87 "ecosystem": "rust",
88 "status": "passed",
89 "command": "cargo check --workspace --locked",
90 "cwd": "/repo",
91 "exit_code": 0,
92 "duration_ms": 110,
93 "stdout": noisy_success.clone(),
94 "stderr": "",
95 "stdout_truncated": false,
96 "stderr_truncated": false,
97 "skipped_reason": null
98 },
99 {
100 "name": "node-lint",
101 "ecosystem": "node",
102 "status": "failed",
103 "command": "npm run lint",
104 "cwd": "/repo",
105 "exit_code": 1,
106 "duration_ms": 220,
107 "stdout": "",
108 "stderr": noisy_failure,
109 "stdout_truncated": false,
110 "stderr_truncated": false,
111 "skipped_reason": null
112 },
113 {
114 "name": "python-pytest",
115 "ecosystem": "python",
116 "status": "skipped",
117 "command": "",
118 "cwd": "/repo",
119 "exit_code": null,
120 "duration_ms": 0,
121 "stdout": "",
122 "stderr": "",
123 "stdout_truncated": false,
124 "stderr_truncated": false,
125 "skipped_reason": "pytest is not installed"
126 }
127 ]
128 })
129 .to_string(),
130 );
131
132 let context = compact_tool_result_for_context("deepseek-v4-pro", "run_verifiers", &output);
133
134 assert!(context.contains("[run_verifiers result summarized for context]"));
135 assert!(context.contains("summary: 1 passed, 1 failed, 1 skipped"));
136 assert!(context.contains("selection: profile=auto, level=quick"));
137 assert!(context.contains("- node-lint (node): failed exit=1"));
138 assert!(context.contains("command: npm run lint"));
139 assert!(context.contains("- python-pytest (python): skipped"));
140 assert!(context.contains("pytest is not installed"));
141 assert!(context.contains("- rust-check (rust): passed exit=0"));
142 assert!(context.len() < output.content.len());
143 assert!(
144 !context.contains(&noisy_success),
145 "successful gate stdout should not be copied into parent context"
146 );
147 }
148
149 #[test]
150 fn mixed_run_verifiers_results_keep_failures_and_running_jobs_in_context() {
151 let output = ToolResult::success(
152 json!({
153 "success": false,
154 "summary": "1 passed, 1 failed, 0 skipped; 1 verifier gate(s) running in the background.",
155 "completed_gates": [
156 {"name": "a-pass", "ecosystem": "rust", "status": "passed", "exit_code": 0},
157 {
158 "name": "b-fail",
159 "ecosystem": "rust",
160 "status": "failed",
161 "exit_code": 1,
162 "stdout": "format diff"
163 }
164 ],
165 "jobs": [
166 {"name": "slow", "ecosystem": "go", "status": "running", "task_id": "shell_1"}
167 ]
168 })
169 .to_string(),
170 );
171
172 let context = compact_tool_result_for_context("deepseek-v4-pro", "run_verifiers", &output);
173
174 let failed = context
175 .find("- b-fail (rust): failed exit=1")
176 .expect("failure");
177 let passed = context
178 .find("- a-pass (rust): passed exit=0")
179 .expect("pass");
180 assert!(failed < passed, "{context}");
181 assert!(context.contains("detail: format diff"));
182 assert!(context.contains("- slow (go): running task_id=shell_1"));
183 }
184
185 #[test]
186 fn run_tests_results_are_structured_before_context_insertion() {
187 let stdout = "running test suite\n".repeat(500);
188 let stderr = "error[E0425]: cannot find value `missing`\n".repeat(500);
189 let output = ToolResult::success(
190 json!({
191 "success": false,
192 "exit_code": 101,
193 "stdout": stdout,
194 "stderr": stderr,
195 "command": "(cd /repo && cargo test --workspace --all-features)"
196 })
197 .to_string(),
198 );
199
200 let context = compact_tool_result_for_context("deepseek-v4-pro", "run_tests", &output);
201
202 assert!(context.contains("[run_tests result summarized for context]"));
203 assert!(context.contains("status: failed, exit_code: 101"));
204 assert!(context.contains("cargo test --workspace --all-features"));
205 assert!(context.contains("error[E0425]"));
206 assert!(context.contains("running test suite"));
207 assert!(context.len() < output.content.len());
208 }
209
210 #[test]
211 fn task_gate_run_results_are_structured_before_context_insertion() {
212 let output = ToolResult::success(
213 json!({
214 "gate": {
215 "id": "gate_abcd1234",
216 "gate": "clippy",
217 "command": "cargo clippy -p codewhale-tui --all-targets --all-features --locked -- -D warnings",
218 "cwd": "/repo",
219 "exit_code": 1,
220 "status": "failed",
221 "classification": "compile_failure",
222 "duration_ms": 5000,
223 "summary": "warning promoted to error in verifier.rs",
224 "log_path": "/repo/.codewhale/runtime/gate.log",
225 "recorded_at": "2026-06-01T12:00:00Z"
226 },
227 "stdout_summary": "",
228 "stderr_summary": "warning promoted to error"
229 })
230 .to_string(),
231 );
232
233 let context = compact_tool_result_for_context("deepseek-v4-pro", "task_gate_run", &output);
234
235 assert!(context.contains("[task_gate_run result summarized for context]"));
236 assert!(context.contains("gate: clippy, status: failed, exit_code: 1"));
237 assert!(context.contains("cargo clippy -p codewhale-tui"));
238 assert!(context.contains("summary: warning promoted to error"));
239 assert!(context.contains("log_path: /repo/.codewhale/runtime/gate.log"));
240 }
241
242 #[test]
243 fn refresh_system_prompt_leaves_working_set_out_of_system_prompt() {
244 let tmp = tempdir().expect("tempdir");
245 fs::create_dir_all(tmp.path().join("src")).expect("mkdir");
246 fs::write(tmp.path().join("src/lib.rs"), "pub fn sample() {}").expect("write");
247
248 let config = EngineConfig {
249 workspace: tmp.path().to_path_buf(),
250 ..Default::default()
251 };
252 let (mut engine, _handle) = Engine::new(config, &Config::default());
253 engine
254 .session
255 .working_set
256 .observe_user_message("please inspect src/lib.rs", tmp.path());
257
258 engine.refresh_system_prompt();
259
260 let prompt = match &engine.session.system_prompt {
261 Some(SystemPrompt::Text(text)) => text.clone(),
262 Some(SystemPrompt::Blocks(blocks)) => blocks
263 .iter()
264 .map(|block| block.text.as_str())
265 .collect::<Vec<_>>()
266 .join("\n"),
267 None => panic!("expected system prompt"),
268 };
269 assert!(!prompt.contains(WORKING_SET_SUMMARY_MARKER));
270 }
271
272 #[test]
273 fn working_set_reaches_model_as_turn_metadata() {
274 let tmp = tempdir().expect("tempdir");
275 fs::create_dir_all(tmp.path().join("src")).expect("mkdir");
276 fs::write(tmp.path().join("src/lib.rs"), "pub fn sample() {}").expect("write");
277
278 let config = EngineConfig {
279 workspace: tmp.path().to_path_buf(),
280 ..Default::default()
281 };
282 let (mut engine, _handle) = Engine::new(config, &Config::default());
283 engine
284 .session
285 .working_set
286 .observe_user_message("please inspect src/lib.rs", tmp.path());
287 let user_msg =
288 engine.user_text_message_with_turn_metadata("please inspect src/lib.rs".to_string());
289 engine.session.add_message(user_msg);
290
291 let messages = engine.messages_with_turn_metadata();
292 let last_block = messages
293 .first()
294 .and_then(|message| message.content.last())
295 .expect("turn metadata block");
296 let ContentBlock::Text { text, .. } = last_block else {
297 panic!("expected text metadata block");
298 };
299 assert!(text.starts_with("<turn_meta>\n"));
300 assert!(text.contains(WORKING_SET_SUMMARY_MARKER));
301 assert!(text.contains("src/lib.rs"));
302 }
303
304 #[test]
305 fn turn_metadata_includes_git_workspace_snapshot_in_repo() {
306 use codewhale_dependencies::ExternalTool;
307
308 if !codewhale_dependencies::Git::available() {
309 return;
310 }
311 let tmp = tempfile::tempdir().expect("tempdir");
312 let root = tmp.path();
313 let init = codewhale_dependencies::Git::output(&["init", "-q"], root);
314 if init.is_err() || !init.unwrap().status.success() {
315 return;
316 }
317
318 let config = EngineConfig {
319 workspace: root.to_path_buf(),
320 ..Default::default()
321 };
322 let (engine, _handle) = Engine::new(config, &Config::default());
323 let user_msg = engine.user_text_message_with_turn_metadata("inspect repo state".to_string());
324 let last_block = user_msg.content.last().expect("turn metadata block");
325 let ContentBlock::Text { text, .. } = last_block else {
326 panic!("expected text metadata block");
327 };
328
329 if let Some(snapshot) = crate::git_status::collect(root) {
330 assert!(
331 text.contains(&format!("Git workspace: {snapshot}")),
332 "turn_meta should include git snapshot: {text}"
333 );
334 }
335 }
336
337 /// #5187 (k3-gap F3): the git snapshot line is emitted only when it actually
338 /// changes — an unchanged workspace must not re-emit the line (churning the
339 /// block's bytes and priming caution), a changed one must re-emit it once.
340 #[test]
341 fn turn_metadata_git_snapshot_emitted_only_on_change() {
342 use codewhale_dependencies::ExternalTool;
343
344 if !codewhale_dependencies::Git::available() {
345 return;
346 }
347 let tmp = tempfile::tempdir().expect("tempdir");
348 let root = tmp.path();
349 let init = codewhale_dependencies::Git::output(&["init", "-q"], root);
350 if init.is_err() || !init.unwrap().status.success() {
351 return;
352 }
353 if crate::git_status::collect(root).is_none() {
354 return;
355 }
356
357 let config = EngineConfig {
358 workspace: root.to_path_buf(),
359 ..Default::default()
360 };
361 let (engine, _handle) = Engine::new(config, &Config::default());
362 let meta_of = |msg: Message| -> String {
363 let ContentBlock::Text { text, .. } = msg.content.last().expect("turn metadata block")
364 else {
365 panic!("expected text metadata block");
366 };
367 text.clone()
368 };
369
370 let first = meta_of(engine.user_text_message_with_turn_metadata("first turn".to_string()));
371 assert!(
372 first.contains("Git workspace:"),
373 "first turn must emit the git snapshot: {first}"
374 );
375
376 let second = meta_of(engine.user_text_message_with_turn_metadata("second turn".to_string()));
377 assert!(
378 !second.contains("Git workspace:"),
379 "unchanged git state must not re-emit the snapshot line: {second}"
380 );
381
382 // Dirty the workspace: the snapshot changes, so the line is emitted once.
383 std::fs::write(root.join("turn-meta-gating.txt"), "changed").expect("write file");
384 let third = meta_of(engine.user_text_message_with_turn_metadata("third turn".to_string()));
385 assert!(
386 third.contains("Git workspace:"),
387 "changed git state must re-emit the snapshot line: {third}"
388 );
389
390 let fourth = meta_of(engine.user_text_message_with_turn_metadata("fourth turn".to_string()));
391 assert!(
392 !fourth.contains("Git workspace:"),
393 "the re-emitted snapshot must be cached again: {fourth}"
394 );
395 }
396
397 #[test]
398 fn turn_metadata_includes_current_local_date_without_working_set() {
399 let tmp = tempdir().expect("tempdir");
400 let config = EngineConfig {
401 model: "deepseek-v4-flash".to_string(),
402 workspace: tmp.path().to_path_buf(),
403 ..Default::default()
404 };
405 let (mut engine, _handle) = Engine::new(config, &Config::default());
406 let user_msg = engine.user_text_message_with_turn_metadata("what is today's date?".to_string());
407 engine.session.add_message(user_msg);
408
409 let messages = engine.messages_with_turn_metadata();
410 let last_block = messages
411 .first()
412 .and_then(|message| message.content.last())
413 .expect("turn metadata block");
414 let ContentBlock::Text { text, .. } = last_block else {
415 panic!("expected text metadata block");
416 };
417
418 let today = chrono::Local::now().format("%Y-%m-%d").to_string();
419 assert!(text.starts_with("<turn_meta>\n"));
420 assert!(text.contains(&format!("Current local date: {today}")));
421 assert!(
422 text.contains(&format!("Current workspace: {}", tmp.path().display())),
423 "workspace must remain in the block: {text}"
424 );
425 assert!(
426 text.contains("Current permission posture: Ask"),
427 "the active posture must remain model-visible: {text}"
428 );
429 // Turn-meta diet: no telemetry may re-enter the per-turn block.
430 for telemetry in [
431 "Current model:",
432 "Current mode:",
433 "Input provenance:",
434 "Input authority:",
435 "Auto model route:",
436 "Auto reasoning effort:",
437 "Session token usage:",
438 "Active goal resource usage:",
439 "Active goal token budget:",
440 ] {
441 assert!(
442 !text.contains(telemetry),
443 "{telemetry} leaked into turn_meta: {text}"
444 );
445 }
446 }
447
448 #[test]
449 fn turn_metadata_surfaces_goal_budget_only_while_goal_active() {
450 let tmp = tempdir().expect("tempdir");
451 let config = EngineConfig {
452 model: "deepseek-v4-flash".to_string(),
453 workspace: tmp.path().to_path_buf(),
454 ..Default::default()
455 };
456 let (mut engine, _handle) = Engine::new(config, &Config::default());
457 // Even with session usage recorded, the per-turn block must not surface
458 // it: totals/cache figures are UI telemetry, not model steering signal.
459 engine.session.total_usage.add(&Usage {
460 input_tokens: 1_200,
461 output_tokens: 300,
462 prompt_cache_hit_tokens: Some(800),
463 prompt_cache_miss_tokens: Some(400),
464 prompt_cache_write_tokens: Some(400),
465 ..Default::default()
466 });
467 {
468 let mut goal = engine.config.goal_state.lock().expect("goal lock");
469 goal.create("Finish telemetry visibility".to_string(), Some(2_000))
470 .expect("create goal");
471 goal.record_usage(1_000, 100, std::time::Instant::now());
472 }
473
474 let user_msg = engine
475 .user_text_message_with_turn_metadata("continue the long-running release task".to_string());
476 let last_block = user_msg.content.last().expect("turn metadata block");
477 let ContentBlock::Text { text, .. } = last_block else {
478 panic!("expected text metadata block");
479 };
480
481 // The goal budget stays (model pacing), and only while the goal is active.
482 assert!(
483 text.contains("Active goal token budget: 2000"),
484 "goal budget should be model-visible: {text}"
485 );
486 // Usage/time deltas, rates, and continuation counts are telemetry.
487 for telemetry in [
488 "Session token usage:",
489 "cache hits",
490 "cache writes",
491 "Active goal resource usage:",
492 "tok/s",
493 "continuations",
494 "50% budget",
495 ] {
496 assert!(
497 !text.contains(telemetry),
498 "{telemetry} leaked into turn_meta: {text}"
499 );
500 }
501
502 // Without an active goal the budget line must vanish entirely.
503 let tmp = tempdir().expect("tempdir");
504 let config = EngineConfig {
505 model: "deepseek-v4-flash".to_string(),
506 workspace: tmp.path().to_path_buf(),
507 ..Default::default()
508 };
509 let (engine, _handle) = Engine::new(config, &Config::default());
510 let user_msg = engine.user_text_message_with_turn_metadata("no goal".to_string());
511 let ContentBlock::Text { text, .. } = user_msg.content.last().expect("turn metadata block")
512 else {
513 panic!("expected text metadata block");
514 };
515 assert!(
516 !text.contains("Active goal token budget:"),
517 "budget must not be emitted when no goal is active: {text}"
518 );
519 }
520
521 #[test]
522 fn context_pressure_message_emits_only_at_warning_and_critical_thresholds() {
523 const WARNING: &str = "Context pressure: warning — ESCALATED: prefer /compact, narrow scope, or finish the current task";
524 const CRITICAL: &str = "Context pressure: critical — CRITICAL: stop expanding scope; run /compact immediately or finish the current task";
525
526 assert_eq!(context_pressure_message(84.99), None);
527 assert_eq!(context_pressure_message(85.0), Some(WARNING));
528 assert_eq!(context_pressure_message(94.99), Some(WARNING));
529 assert_eq!(context_pressure_message(95.0), Some(CRITICAL));
530 assert_eq!(context_pressure_message(100.0), Some(CRITICAL));
531
532 // Threshold labels steer a decision without exposing a continuously
533 // changing percentage, token count, or headroom value.
534 for line in [WARNING, CRITICAL] {
535 assert!(!line.contains('%'), "{line}");
536 assert!(!line.contains("tokens"), "{line}");
537 assert!(!line.contains("headroom"), "{line}");
538 }
539 }
540
541 #[test]
542 fn runtime_turn_metadata_condenses_non_authoritative_provenance_to_one_line() {
543 let tmp = tempdir().expect("tempdir");
544 let config = EngineConfig {
545 workspace: tmp.path().to_path_buf(),
546 ..Default::default()
547 };
548 let (engine, _handle) = Engine::new(config, &Config::default());
549 let msg = engine.runtime_text_message_with_turn_metadata(
550 "改吧".to_string(),
551 UserInputProvenance::AssistantGenerated,
552 );
553 let last_block = msg.content.last().expect("turn metadata block");
554 let ContentBlock::Text { text, .. } = last_block else {
555 panic!("expected text metadata block");
556 };
557
558 // Reduced authority on a non-external turn is the sole signal: one
559 // condensed line, not the former two-line provenance/authority pair.
560 assert!(
561 text.contains("Input provenance: assistant_generated (non-authoritative)"),
562 "{text}"
563 );
564 assert!(!text.contains("Input authority:"), "{text}");
565 assert!(!text.contains("Input provenance: external_user"), "{text}");
566 }
567
568 #[test]
569 fn turn_metadata_omits_route_and_reasoning_effort_telemetry() {
570 let tmp = tempdir().expect("tempdir");
571 let config = EngineConfig {
572 workspace: tmp.path().to_path_buf(),
573 ..Default::default()
574 };
575 let (engine, _handle) = Engine::new(config, &Config::default());
576
577 let user_msg = engine.user_text_message_with_turn_metadata_for_route(
578 "debug this regression".to_string(),
579 "deepseek-v4-pro",
580 true,
581 Some("max"),
582 true,
583 );
584 let last_block = user_msg.content.last().expect("turn metadata block");
585 let ContentBlock::Text { text, .. } = last_block else {
586 panic!("expected text metadata block");
587 };
588
589 // Model, auto-route, and auto-reasoning-effort lines were pure telemetry
590 // and must never re-enter the per-turn block.
591 assert!(!text.contains("Current model:"), "{text}");
592 assert!(!text.contains("Auto model route:"), "{text}");
593 assert!(!text.contains("Auto reasoning effort:"), "{text}");
594 assert!(!text.contains("debug this regression"));
595 assert!(
596 text.starts_with(
597 "<turn_meta>
598 Current local date:"
599 ),
600 "{text}"
601 );
602 }
603
604 #[test]
605 fn turn_metadata_keeps_stable_fields_while_pressure_reports_live_estimates() {
606 // Live estimates belong in appended turn metadata, never in the pinned
607 // system prefix. Unrelated metadata remains stable as the transcript grows.
608 let tmp = tempdir().expect("tempdir");
609 let config = EngineConfig {
610 model: "deepseek-v4-flash".to_string(),
611 workspace: tmp.path().to_path_buf(),
612 ..Default::default()
613 };
614 let (mut engine, _handle) = Engine::new(config, &Config::default());
615
616 // Use explicit route limits so the fixture exercises the critical band
617 // without depending on a model catalog entry or provider default.
618 engine.session.messages.push(Message {
619 role: Role::User,
620 content: vec![ContentBlock::Text {
621 text: "x".repeat(100_000),
622 cache_control: None,
623 }],
624 });
625 let prompt_context = NextTurnPromptContext::for_planned_turn(
626 ProviderKind::Deepseek,
627 "deepseek-v4-flash".to_string(),
628 Some(codewhale_config::route::RouteLimits {
629 context_tokens: Some(10_000),
630 input_tokens: None,
631 output_tokens: Some(512),
632 output_declared: false,
633 }),
634 AppMode::Agent,
635 None,
636 crate::tools::goal::GoalStatus::Active,
637 None,
638 false,
639 None,
640 );
641
642 let meta_of = |msg: &Message| -> String {
643 let ContentBlock::Text { text, .. } = msg.content.last().expect("turn metadata block")
644 else {
645 panic!("expected text metadata block");
646 };
647 text.clone()
648 };
649 let message_for = |engine: &Engine| {
650 engine.user_text_message_from_snapshot(
651 "stable input".to_string(),
652 &prompt_context.model,
653 false,
654 None,
655 false,
656 UserInputProvenance::ExternalUser,
657 TurnMetadataSnapshot {
658 planned_compaction: None,
659 prompt_context: &prompt_context,
660 system_prompt: None,
661 approval_mode: engine.session.approval_mode,
662 working_set: &engine.session.working_set,
663 messages: &engine.session.messages,
664 policy_narrowing: None,
665 },
666 )
667 };
668
669 let first = message_for(&engine);
670 let first_meta = meta_of(&first);
671 assert!(
672 !first_meta.contains("Context pressure:"),
673 "automatic continuity must not ask the user to manage context: {first_meta}"
674 );
675 assert!(first_meta.contains("Estimated conversation input:"));
676 assert!(!first_meta.contains("/compact"));
677 engine.config.compaction.enabled = false;
678 let first = message_for(&engine);
679 let first_meta = meta_of(&first);
680 assert!(
681 first_meta.contains("Context pressure: critical"),
682 "fixture must exercise the pressure line: {first_meta}"
683 );
684
685 engine.session.add_message(first);
686 let second = message_for(&engine);
687 let second_meta = meta_of(&second);
688 let without_pressure = |metadata: &str| {
689 metadata
690 .lines()
691 .filter(|line| !line.contains("Context pressure:"))
692 .collect::<Vec<_>>()
693 .join("\n")
694 };
695 assert_eq!(
696 without_pressure(&first_meta),
697 without_pressure(&second_meta)
698 );
699 assert!(second_meta.contains("Estimated conversation input:"));
700 assert!(second_meta.contains("Making room automatically is off"));
701 }
702
703 #[tokio::test]
704 async fn interrupted_turn_names_surviving_background_shell_jobs() {
705 // DGF-03 (dogfood 2026-08-02): Esc says "Turn interrupted" while
706 // detached background shells keep writing files. The interrupt path
707 // must name the survivors so the copy stops lying about what stopped.
708 let tmp = tempdir().expect("tempdir");
709 let marker = tmp.path().join("survivor-marker.txt");
710 let shell_manager = crate::tools::shell::new_shared_shell_manager(tmp.path().to_path_buf());
711
712 let runtime_services = crate::tools::spec::RuntimeToolServices {
713 shell_manager: Some(shell_manager.clone()),
714 ..crate::tools::spec::RuntimeToolServices::default()
715 };
716 let engine_config = EngineConfig {
717 model: "deepseek-v4-flash".to_string(),
718 workspace: tmp.path().to_path_buf(),
719 snapshots_enabled: false,
720 terminal_chrome_enabled: false,
721 runtime_services,
722 ..EngineConfig::default()
723 };
724 let (engine, handle) = Engine::new(engine_config, &Config::default());
725
726 // Background sleep-then-write: still running at interrupt time, and its
727 // write lands only after the UI would have said "interrupted". Stamp the
728 // engine's immutable session owner so a replacement session cannot see or
729 // control it.
730 let task_id = {
731 let mut manager = shell_manager.lock().expect("shell manager");
732 let result = manager
733 .execute_with_options_env_for_session(
734 &format!("sleep 5 && touch '{}'", marker.display()),
735 None,
736 60_000,
737 true,
738 None,
739 false,
740 None,
741 HashMap::new(),
742 &engine.session.id,
743 )
744 .expect("spawn background job");
745 result.task_id.expect("background task id")
746 };
747 assert!(
748 !marker.exists(),
749 "marker must not exist before the interrupt"
750 );
751
752 engine.emit_interrupted_survivor_status().await;
753
754 let mut events = handle.rx_event.write().await;
755 let mut survivor_line = None;
756 while let Ok(event) = events.try_recv() {
757 if let Event::Status { message } = event
758 && message.contains("background shell job")
759 {
760 survivor_line = Some(message);
761 }
762 }
763 let survivor_line = survivor_line.expect("interrupt must name surviving background jobs");
764 assert!(survivor_line.contains(&task_id), "{survivor_line}");
765 assert!(
766 survivor_line.contains("may still write files"),
767 "{survivor_line}"
768 );
769 assert!(
770 !marker.exists(),
771 "the honesty line must fire while the job is still running"
772 );
773
774 // Cleanup: don't leave the sleeper running after the test.
775 let _ = shell_manager.lock().expect("shell manager").kill(&task_id);
776 }
777
778 /// R6 injection-size regression: the per-turn `<turn_meta>` block, built
779 /// (never sent) from the same snapshot path production uses. The context
780 /// estimate and compaction posture brought the measured block to 396 bytes
781 /// on macOS on 2026-11-01. The ceiling retains the 10% growth allowance.
782 const TURN_META_BYTE_CEILING: usize = 436;
783
784 #[test]
785 fn turn_meta_block_stays_within_measured_ceiling() {
786 let tmp = tempdir().expect("tempdir");
787 let config = EngineConfig {
788 model: "deepseek-v4-flash".to_string(),
789 workspace: tmp.path().to_path_buf(),
790 ..Default::default()
791 };
792 let (engine, _handle) = Engine::new(config, &Config::default());
793 let prompt_context = NextTurnPromptContext::for_planned_turn(
794 ProviderKind::Deepseek,
795 "deepseek-v4-flash".to_string(),
796 None,
797 AppMode::Agent,
798 None,
799 crate::tools::goal::GoalStatus::Active,
800 None,
801 false,
802 None,
803 );
804 let message = engine.user_text_message_from_snapshot(
805 "hello".to_string(),
806 &prompt_context.model,
807 false,
808 None,
809 false,
810 UserInputProvenance::ExternalUser,
811 TurnMetadataSnapshot {
812 planned_compaction: None,
813 prompt_context: &prompt_context,
814 system_prompt: None,
815 approval_mode: engine.session.approval_mode,
816 working_set: &engine.session.working_set,
817 messages: &engine.session.messages,
818 policy_narrowing: None,
819 },
820 );
821 let ContentBlock::Text { text, .. } = message.content.last().expect("turn metadata block")
822 else {
823 panic!("expected text metadata block");
824 };
825 assert!(
826 text.len() <= TURN_META_BYTE_CEILING,
827 "turn_meta grew past its reviewed ceiling: {}B > {TURN_META_BYTE_CEILING}B. If deliberate, re-measure and raise the ceiling in the same commit.",
828 text.len()
829 );
830 }
831
832 #[test]
833 fn turn_metadata_names_the_effective_sandbox_posture() {
834 // DGF-02 (dogfood 2026-08-02): the model must know its own sandbox
835 // posture, derived from the same resolver tool execution uses, so an
836 // approved-then-sandbox-blocked write never reads as a mystery failure.
837 let tmp = tempdir().expect("tempdir");
838 let config = EngineConfig {
839 model: "deepseek-v4-flash".to_string(),
840 workspace: tmp.path().to_path_buf(),
841 ..Default::default()
842 };
843 let (mut engine, _handle) = Engine::new(config, &Config::default());
844
845 let meta_for_mode = |engine: &Engine, mode: AppMode| -> String {
846 let prompt_context = NextTurnPromptContext::for_planned_turn(
847 ProviderKind::Deepseek,
848 "deepseek-v4-flash".to_string(),
849 None,
850 mode,
851 None,
852 crate::tools::goal::GoalStatus::Active,
853 None,
854 false,
855 None,
856 );
857 let message = engine.user_text_message_from_snapshot(
858 "hello".to_string(),
859 &prompt_context.model,
860 false,
861 None,
862 false,
863 UserInputProvenance::ExternalUser,
864 TurnMetadataSnapshot {
865 planned_compaction: None,
866 prompt_context: &prompt_context,
867 system_prompt: None,
868 approval_mode: engine.session.approval_mode,
869 working_set: &engine.session.working_set,
870 messages: &engine.session.messages,
871 policy_narrowing: None,
872 },
873 );
874 let ContentBlock::Text { text, .. } = message.content.last().expect("turn metadata block")
875 else {
876 panic!("expected text metadata block");
877 };
878 text.clone()
879 };
880
881 let agent_meta = meta_for_mode(&engine, AppMode::Agent);
882 assert!(
883 agent_meta.contains("Current sandbox posture: workspace-write"),
884 "{agent_meta}"
885 );
886
887 // Plan mode must surface the read-only clamp without promising that this
888 // non-interactive posture can open an escalation prompt.
889 let plan_meta = meta_for_mode(&engine, AppMode::Plan);
890 assert!(
891 plan_meta.contains(
892 "Current sandbox posture: read-only (shell writes are blocked; ordinary approval does not change this)"
893 ),
894 "{plan_meta}"
895 );
896
897 // Pin deterministic states instead of branching on the CI host. The
898 // production value is also captured once at engine construction.
899 engine.sandbox_enforcement = codewhale_sandbox::policy::SandboxEnforcement::LocalOs;
900 let local_meta = meta_for_mode(&engine, AppMode::Agent);
901 assert!(
902 local_meta.contains("local OS sandbox applied"),
903 "{local_meta}"
904 );
905
906 engine.sandbox_enforcement = codewhale_sandbox::policy::SandboxEnforcement::Unavailable;
907 let unavailable_meta = meta_for_mode(&engine, AppMode::Agent);
908 assert!(
909 unavailable_meta.contains("policy only; no execution sandbox available"),
910 "{unavailable_meta}"
911 );
912
913 engine.sandbox_enforcement = codewhale_sandbox::policy::SandboxEnforcement::ExternalBackend;
914 let external_meta = meta_for_mode(&engine, AppMode::Agent);
915 assert!(
916 external_meta.contains("workspace-write policy"),
917 "{external_meta}"
918 );
919 assert!(
920 external_meta.contains("external execution backend configured"),
921 "{external_meta}"
922 );
923 assert!(
924 external_meta.contains("isolation unverified by Codewhale"),
925 "{external_meta}"
926 );
927 assert!(
928 !external_meta.contains("writes inside the workspace"),
929 "{external_meta}"
930 );
931 }
932
933 #[test]
934 fn provenance_gate_preserves_standing_yolo_for_runtime_and_subagent_continuations() {
935 let all_provenances = [
936 UserInputProvenance::ExternalUser,
937 UserInputProvenance::Runtime,
938 UserInputProvenance::SubAgentHandoff,
939 UserInputProvenance::ImportedTranscript,
940 UserInputProvenance::MemoryRecall,
941 UserInputProvenance::AssistantGenerated,
942 ];
943 let inheriting_provenances = [
944 UserInputProvenance::ExternalUser,
945 UserInputProvenance::Runtime,
946 UserInputProvenance::SubAgentHandoff,
947 ];
948
949 for provenance in all_provenances {
950 let policy = effective_input_policy(
951 provenance,
952 AppMode::Agent,
953 "continue",
954 true,
955 true,
956 true,
957 ApprovalMode::Auto,
958 );
959
960 if inheriting_provenances.contains(&provenance) {
961 assert_eq!(policy.mode, AppMode::Agent, "{provenance:?}");
962 assert!(policy.allow_shell, "{provenance:?}");
963 assert!(policy.trust_mode, "{provenance:?}");
964 assert!(policy.auto_approve, "{provenance:?}");
965 assert_eq!(policy.approval_mode, ApprovalMode::Auto, "{provenance:?}");
966 assert!(policy.status().is_none(), "{provenance:?}");
967 } else {
968 assert_eq!(policy.mode, AppMode::Agent, "{provenance:?}");
969 assert!(policy.allow_shell, "{provenance:?}");
970 assert!(!policy.trust_mode, "{provenance:?}");
971 assert!(!policy.auto_approve, "{provenance:?}");
972 assert_eq!(
973 policy.approval_mode,
974 ApprovalMode::Suggest,
975 "{provenance:?}"
976 );
977 assert!(
978 policy.status().as_deref().is_some_and(
979 |status| status.contains("cannot inherit standing auto-approval authority")
980 ),
981 "{provenance:?}"
982 );
983 }
984 }
985 }
986
987 #[test]
988 fn provenance_gate_never_invents_auto_authority_for_non_yolo_sessions() {
989 let all_provenances = [
990 UserInputProvenance::ExternalUser,
991 UserInputProvenance::Runtime,
992 UserInputProvenance::SubAgentHandoff,
993 UserInputProvenance::ImportedTranscript,
994 UserInputProvenance::MemoryRecall,
995 UserInputProvenance::AssistantGenerated,
996 ];
997
998 for provenance in all_provenances {
999 let policy = effective_input_policy(
1000 provenance,
1001 AppMode::Agent,
1002 "continue",
1003 true,
1004 false,
1005 false,
1006 ApprovalMode::Suggest,
1007 );
1008
1009 assert_eq!(policy.mode, AppMode::Agent, "{provenance:?}");
1010 assert!(policy.allow_shell, "{provenance:?}");
1011 assert!(!policy.trust_mode, "{provenance:?}");
1012 assert!(!policy.auto_approve, "{provenance:?}");
1013 assert_eq!(
1014 policy.approval_mode,
1015 ApprovalMode::Suggest,
1016 "{provenance:?}"
1017 );
1018 assert!(policy.status().is_none(), "{provenance:?}");
1019 }
1020 }
1021
1022 #[test]
1023 fn full_access_posture_normalizes_a_stale_auto_approve_bit() {
1024 let policy = effective_input_policy(
1025 UserInputProvenance::SubAgentHandoff,
1026 AppMode::Agent,
1027 "continue",
1028 true,
1029 true,
1030 false,
1031 ApprovalMode::Bypass,
1032 );
1033
1034 assert_eq!(policy.mode, AppMode::Agent);
1035 assert_eq!(policy.approval_mode, ApprovalMode::Bypass);
1036 assert!(policy.auto_approve);
1037 assert!(policy.status().is_none());
1038 }
1039
1040 #[test]
1041 fn self_generated_fake_approvals_cannot_authorize_work() {
1042 let non_authoritative_origins = [
1043 UserInputProvenance::ImportedTranscript,
1044 UserInputProvenance::MemoryRecall,
1045 UserInputProvenance::AssistantGenerated,
1046 ];
1047
1048 for provenance in non_authoritative_origins {
1049 for content in ["改吧", "嗯"] {
1050 let policy = effective_input_policy(
1051 provenance,
1052 AppMode::Agent,
1053 content,
1054 true,
1055 true,
1056 true,
1057 ApprovalMode::Bypass,
1058 );
1059
1060 assert_eq!(policy.mode, AppMode::Agent, "{provenance:?} {content}");
1061 assert!(policy.allow_shell, "{provenance:?} {content}");
1062 assert!(!policy.trust_mode, "{provenance:?} {content}");
1063 assert!(!policy.auto_approve, "{provenance:?} {content}");
1064 assert_eq!(
1065 policy.approval_mode,
1066 ApprovalMode::Suggest,
1067 "{provenance:?} {content}"
1068 );
1069 assert!(
1070 policy.status().as_deref().is_some_and(
1071 |status| status.contains("cannot inherit standing auto-approval authority")
1072 ),
1073 "{provenance:?} {content}"
1074 );
1075 }
1076 }
1077 }
1078
1079 #[test]
1080 fn external_prompt_wording_never_changes_effective_mode_or_authority() {
1081 let cases = [
1082 (
1083 AppMode::Agent,
1084 ApprovalMode::Suggest,
1085 false,
1086 false,
1087 "你在帮我看看 外卖部分还哪里没有使用多语言",
1088 ),
1089 (
1090 AppMode::Agent,
1091 ApprovalMode::Bypass,
1092 true,
1093 true,
1094 "check the failing tests and review the logs",
1095 ),
1096 (
1097 AppMode::Agent,
1098 ApprovalMode::Suggest,
1099 false,
1100 false,
1101 "检查外卖模块并修复缺少的多语言注入",
1102 ),
1103 ];
1104
1105 for (requested_mode, approval_mode, trust_mode, auto_approve, content) in cases {
1106 let policy = effective_input_policy(
1107 UserInputProvenance::ExternalUser,
1108 requested_mode,
1109 content,
1110 true,
1111 trust_mode,
1112 auto_approve,
1113 approval_mode,
1114 );
1115
1116 assert_eq!(policy.mode, requested_mode, "{content}");
1117 assert_eq!(policy.trust_mode, trust_mode, "{content}");
1118 assert_eq!(policy.auto_approve, auto_approve, "{content}");
1119 assert_eq!(policy.approval_mode, approval_mode, "{content}");
1120 assert!(policy.allow_shell, "{content}");
1121 assert!(policy.status().is_none(), "{content}");
1122 }
1123 }
1124
1125 #[test]
1126 fn external_user_wording_does_not_downgrade_standing_authority() {
1127 let review_wording = effective_input_policy(
1128 UserInputProvenance::ExternalUser,
1129 AppMode::Agent,
1130 "你在帮我看看 外卖部分还哪里没有使用多语言 我看看要不要加",
1131 true,
1132 true,
1133 true,
1134 ApprovalMode::Bypass,
1135 );
1136 assert_eq!(review_wording.mode, AppMode::Agent);
1137 assert!(review_wording.allow_shell);
1138 assert!(review_wording.trust_mode);
1139 assert!(review_wording.auto_approve);
1140 assert_eq!(review_wording.approval_mode, ApprovalMode::Bypass);
1141 assert!(
1142 review_wording.status().is_none(),
1143 "external user wording must not content-downgrade standing authority"
1144 );
1145
1146 let later_user_instruction = effective_input_policy(
1147 UserInputProvenance::ExternalUser,
1148 AppMode::Agent,
1149 "需要修复下",
1150 true,
1151 true,
1152 true,
1153 ApprovalMode::Bypass,
1154 );
1155 assert_eq!(later_user_instruction.mode, AppMode::Agent);
1156 assert!(later_user_instruction.allow_shell);
1157 assert!(later_user_instruction.trust_mode);
1158 assert!(later_user_instruction.auto_approve);
1159 assert_eq!(later_user_instruction.approval_mode, ApprovalMode::Bypass);
1160 assert!(
1161 later_user_instruction.status().is_none(),
1162 "a fresh external write instruction must not inherit the prior review-only downgrade"
1163 );
1164 }
1165
1166 #[test]
1167 fn turn_metadata_leaves_mode_entirely_to_runtime_policy() {
1168 // Mode permissions and capabilities are already concrete in runtime policy
1169 // and the live tool catalog. Prompt prose must not create a parallel mode.
1170 let tmp = tempdir().expect("tempdir");
1171 let config = EngineConfig {
1172 workspace: tmp.path().to_path_buf(),
1173 ..Default::default()
1174 };
1175 let (mut engine, _handle) = Engine::new(config, &Config::default());
1176 engine.current_mode = AppMode::Plan;
1177
1178 let user_msg = engine.user_text_message_with_turn_metadata_for_route(
1179 "explain the refactor plan before editing".to_string(),
1180 "deepseek-v4-flash",
1181 false,
1182 None,
1183 false,
1184 );
1185 let last_block = user_msg.content.last().expect("turn metadata block");
1186 let ContentBlock::Text { text, .. } = last_block else {
1187 panic!("expected text metadata block");
1188 };
1189
1190 assert!(!text.contains("Current mode:"), "got: {text}");
1191 assert!(
1192 !text.contains("Current mode policy"),
1193 "mode doctrine must not re-enter turn_meta: {text}"
1194 );
1195 assert!(
1196 !text.contains("##### Mode: Plan"),
1197 "mode overlay text must not re-enter turn_meta: {text}"
1198 );
1199 assert!(
1200 !text.contains("All writes, patches, shell commands,"),
1201 "mode doctrine must not re-enter turn_meta: {text}"
1202 );
1203 }
1204
1205 #[test]
1206 fn turn_metadata_projects_permission_posture_as_fact_only() {
1207 // #4780 + turn-meta diet: the active posture remains an actionable fact.
1208 // Never adds one actionable constraint so the model cannot waste a turn
1209 // asking for an approval the host is configured not to provide.
1210 use ApprovalMode;
1211
1212 let cases = [
1213 (ApprovalMode::Suggest, "Ask"),
1214 (ApprovalMode::Auto, "Auto-Review"),
1215 (ApprovalMode::Bypass, "Full Access"),
1216 (ApprovalMode::Never, "Never"),
1217 ];
1218
1219 for (approval_mode, posture) in cases {
1220 let tmp = tempdir().expect("tempdir");
1221 let config = EngineConfig {
1222 workspace: tmp.path().to_path_buf(),
1223 ..Default::default()
1224 };
1225 let (mut engine, _handle) = Engine::new(config, &Config::default());
1226 engine.session.approval_mode = approval_mode;
1227
1228 let message = engine.user_text_message_with_turn_metadata("continue".to_string());
1229 let ContentBlock::Text { text, .. } = message
1230 .content
1231 .last()
1232 .expect("turn metadata must be present")
1233 else {
1234 panic!("expected text turn metadata");
1235 };
1236
1237 assert!(
1238 text.contains(&format!("Current permission posture: {posture}")),
1239 "{posture}: {text}"
1240 );
1241 assert!(
1242 !text.contains("Current permission policy source"),
1243 "{posture}: doctrine must not re-enter turn_meta: {text}"
1244 );
1245 assert!(
1246 !text.contains("Current question discipline"),
1247 "{posture}: question discipline must not re-enter turn_meta: {text}"
1248 );
1249 assert_eq!(
1250 text.contains(
1251 "Approval prompts are disabled; do not request escalation for this turn."
1252 ),
1253 approval_mode == ApprovalMode::Never,
1254 "{posture}: {text}"
1255 );
1256 }
1257 }
1258
1259 #[test]
1260 fn turn_metadata_preserves_standing_full_access_for_subagent_handoff() {
1261 use ApprovalMode;
1262
1263 let tmp = tempdir().expect("tempdir");
1264 let config = EngineConfig {
1265 workspace: tmp.path().to_path_buf(),
1266 ..Default::default()
1267 };
1268 let (mut engine, _handle) = Engine::new(config, &Config::default());
1269 let authority = effective_input_policy(
1270 UserInputProvenance::SubAgentHandoff,
1271 AppMode::Agent,
1272 "continue from child",
1273 true,
1274 true,
1275 true,
1276 ApprovalMode::Bypass,
1277 );
1278 engine.apply_runtime_mode_policy(&authority);
1279
1280 let message = engine.runtime_text_message_with_turn_metadata(
1281 "continue from child".to_string(),
1282 UserInputProvenance::SubAgentHandoff,
1283 );
1284 let ContentBlock::Text { text, .. } = message
1285 .content
1286 .last()
1287 .expect("turn metadata must be present")
1288 else {
1289 panic!("expected text turn metadata");
1290 };
1291
1292 // A child handoff cannot grant new authority, but it retains the standing
1293 // posture and names its reduced provenance in one condensed line.
1294 assert!(!text.contains("Current mode:"), "{text}");
1295 assert!(
1296 text.contains("Current permission posture: Full Access"),
1297 "{text}"
1298 );
1299 assert!(
1300 text.contains("Input provenance: subagent_handoff (non-authoritative)"),
1301 "{text}"
1302 );
1303 }
1304
1305 #[test]
1306 fn current_mode_field_assignment_takes_effect_synchronously() {
1307 // Basic unit-level invariant: the current_mode field mutates as expected.
1308 // Op::ChangeMode dispatch through the run loop is exercised by the
1309 // integration test change_mode_op_updates_current_mode_and_emits_status.
1310 let tmp = tempdir().expect("tempdir");
1311 let config = EngineConfig {
1312 workspace: tmp.path().to_path_buf(),
1313 model: "deepseek-v4-pro".to_string(),
1314 ..Default::default()
1315 };
1316 let (mut engine, _handle) = Engine::new(config, &Config::default());
1317 assert_eq!(engine.current_mode, AppMode::Agent);
1318
1319 engine.current_mode = AppMode::Plan;
1320 assert_eq!(engine.current_mode, AppMode::Plan);
1321 }
1322
1323 #[test]
1324 fn user_text_message_keeps_current_turn_input_after_turn_metadata() {
1325 let tmp = tempdir().expect("tempdir");
1326 let config = EngineConfig {
1327 workspace: tmp.path().to_path_buf(),
1328 ..Default::default()
1329 };
1330 let (engine, _handle) = Engine::new(config, &Config::default());
1331
1332 let user_msg =
1333 engine.user_text_message_with_turn_metadata("explain the cache metrics".to_string());
1334
1335 // User text is now at position 0, turn_meta at position 1.
1336 let first_text = user_msg
1337 .content
1338 .iter()
1339 .find_map(|block| {
1340 if let ContentBlock::Text { text, .. } = block {
1341 Some(text.as_str())
1342 } else {
1343 None
1344 }
1345 })
1346 .expect("user text block");
1347 assert_eq!(first_text, "explain the cache metrics");
1348 }
1349
1350 #[test]
1351 fn messages_with_turn_metadata_preserves_stored_messages_for_prefix_cache() {
1352 let tmp = tempdir().expect("tempdir");
1353 fs::create_dir_all(tmp.path().join("src")).expect("mkdir");
1354 fs::write(tmp.path().join("src/lib.rs"), "pub fn sample() {}").expect("write");
1355
1356 let config = EngineConfig {
1357 workspace: tmp.path().to_path_buf(),
1358 ..Default::default()
1359 };
1360 let (mut engine, _handle) = Engine::new(config, &Config::default());
1361 engine
1362 .session
1363 .working_set
1364 .observe_user_message("inspect src/lib.rs", tmp.path());
1365
1366 let first_user = engine.user_text_message_with_turn_metadata("inspect src/lib.rs".to_string());
1367 engine.session.add_message(first_user.clone());
1368 let first_request = engine.messages_with_turn_metadata();
1369 assert_eq!(
1370 &first_request[..engine.session.messages.len()],
1371 &engine.session.messages[..]
1372 );
1373 assert_eq!(first_request.len(), engine.session.messages.len());
1374 assert_eq!(first_request.first(), Some(&first_user));
1375 assert_eq!(
1376 first_request.last().map(|message| message.role.as_str()),
1377 Some("user")
1378 );
1379
1380 engine.session.add_message(Message {
1381 role: Role::Assistant,
1382 content: vec![ContentBlock::Text {
1383 text: "I inspected it.".to_string(),
1384 cache_control: None,
1385 }],
1386 });
1387 engine
1388 .session
1389 .working_set
1390 .observe_user_message("now summarize it", tmp.path());
1391 let second_user = engine.user_text_message_with_turn_metadata("now summarize it".to_string());
1392 engine.session.add_message(second_user);
1393
1394 let second_request = engine.messages_with_turn_metadata();
1395 assert_eq!(
1396 &second_request[..engine.session.messages.len()],
1397 &engine.session.messages[..]
1398 );
1399 assert_eq!(second_request.len(), engine.session.messages.len());
1400 assert_eq!(second_request.first(), Some(&first_user));
1401 assert_eq!(second_request.last(), engine.session.messages.last());
1402 }
1403
1404 /// v0.8.11 regression: tool-result messages serialize to role="tool" on
1405 /// the wire but are stored as role="user" internally. `<turn_meta>` must
1406 /// be stored only on actual user-text messages. Request-time runtime metadata
1407 /// must not mutate tool-result messages.
1408 #[test]
1409 fn turn_metadata_skips_tool_result_messages() {
1410 let tmp = tempdir().expect("tempdir");
1411 fs::create_dir_all(tmp.path().join("src")).expect("mkdir");
1412 fs::write(tmp.path().join("src/lib.rs"), "pub fn sample() {}").expect("write");
1413
1414 let config = EngineConfig {
1415 workspace: tmp.path().to_path_buf(),
1416 ..Default::default()
1417 };
1418 let (mut engine, _handle) = Engine::new(config, &Config::default());
1419 engine
1420 .session
1421 .working_set
1422 .observe_user_message("inspect src/lib.rs", tmp.path());
1423
1424 // Real user message — should be eligible for injection.
1425 let user_msg = engine.user_text_message_with_turn_metadata("inspect src/lib.rs".to_string());
1426 engine.session.add_message(user_msg);
1427 // Assistant tool-call.
1428 engine.session.add_message(Message {
1429 role: Role::Assistant,
1430 content: vec![ContentBlock::ToolUse {
1431 execution_id: None,
1432 id: "call_42".to_string(),
1433 name: "read_file".to_string(),
1434 input: serde_json::json!({"path": "src/lib.rs"}),
1435 caller: None,
1436 thought_signature: None,
1437 }],
1438 });
1439 // Tool result, stored as role="user" internally.
1440 engine.session.add_message(Message {
1441 role: Role::User,
1442 content: vec![ContentBlock::ToolResult {
1443 execution_id: None,
1444 tool_use_id: "call_42".to_string(),
1445 content: "pub fn sample() {}".to_string(),
1446 is_error: None,
1447 content_blocks: None,
1448 }],
1449 });
1450
1451 let messages = engine.messages_with_turn_metadata();
1452
1453 // The stored trailing message is the tool result and MUST be untouched —
1454 // no Text block sneaking in front of the ToolResult block.
1455 let trailing = messages.last().expect("stored trailing message");
1456 assert_eq!(trailing.role, "user");
1457 assert_eq!(trailing.content.len(), 1);
1458 assert!(matches!(
1459 trailing.content.first(),
1460 Some(ContentBlock::ToolResult { .. })
1461 ));
1462
1463 // The earlier real user message carries user text first, turn_meta last.
1464 let real_user = messages.first().expect("first user message");
1465 assert_eq!(real_user.role, "user");
1466 let ContentBlock::Text { text, .. } = real_user.content.first().expect("user text content")
1467 else {
1468 panic!("expected Text block on real user message");
1469 };
1470 assert_eq!(text, "inspect src/lib.rs");
1471 // turn_meta is at the tail of the content array.
1472 let last_block = real_user.content.last().expect("turn_meta block");
1473 let ContentBlock::Text { text: meta, .. } = last_block else {
1474 panic!("expected Text block for turn_meta at tail");
1475 };
1476 assert!(meta.starts_with("<turn_meta>\n"));
1477 assert!(meta.contains("src/lib.rs"));
1478 }
1479
1480 /// User text must appear before turn_meta in the content array so that
1481 /// the leading bytes of each user message stay stable across date changes.
1482 /// DeepSeek's KV prefix cache matches byte sequences from the start of
1483 /// each message; placing the volatile date-bearing turn_meta at position
1484 /// 0 would invalidate the entire user message prefix at every date
1485 /// boundary. Moving it to the tail preserves the user-input prefix.
1486 #[test]
1487 fn user_message_turn_meta_is_appended_not_prepended() {
1488 let tmp = tempdir().expect("tempdir");
1489 let config = EngineConfig {
1490 workspace: tmp.path().to_path_buf(),
1491 ..Default::default()
1492 };
1493 let (engine, _handle) = Engine::new(config, &Config::default());
1494
1495 let msg = engine.user_text_message_with_turn_metadata("hello world".to_string());
1496 assert_eq!(msg.role, "user");
1497 assert_eq!(msg.content.len(), 2);
1498
1499 // First content block: user text.
1500 let ContentBlock::Text { text, .. } = &msg.content[0] else {
1501 panic!("expected Text block at position 0");
1502 };
1503 assert_eq!(text, "hello world");
1504
1505 // Second content block: turn_meta.
1506 let ContentBlock::Text { text: meta, .. } = &msg.content[1] else {
1507 panic!("expected Text block for turn_meta at position 1");
1508 };
1509 assert!(
1510 meta.starts_with("<turn_meta>\n"),
1511 "turn_meta must be at the tail"
1512 );
1513 assert!(
1514 meta.contains("Current local date:"),
1515 "turn_meta must contain the date"
1516 );
1517 }
1518
1519 /// When the turn is mid-execution and the trailing user message is a
1520 /// tool result, no turn_meta is injected into that tool-result message. The
1521 /// working_set surfaces again on the next stored user-text message.
1522 #[test]
1523 fn turn_metadata_skips_when_only_tool_results_trail() {
1524 let tmp = tempdir().expect("tempdir");
1525 fs::create_dir_all(tmp.path().join("src")).expect("mkdir");
1526 fs::write(tmp.path().join("src/lib.rs"), "pub fn sample() {}").expect("write");
1527
1528 let config = EngineConfig {
1529 workspace: tmp.path().to_path_buf(),
1530 ..Default::default()
1531 };
1532 let (mut engine, _handle) = Engine::new(config, &Config::default());
1533 engine
1534 .session
1535 .working_set
1536 .observe_user_message("inspect src/lib.rs", tmp.path());
1537
1538 // Only a tool-result message in history — simulates the corner case
1539 // where the prior real user message has already been compacted away
1540 // but a tool-result is still pending. We must not retroactively
1541 // inject.
1542 engine.session.add_message(Message {
1543 role: Role::User,
1544 content: vec![ContentBlock::ToolResult {
1545 execution_id: None,
1546 tool_use_id: "call_42".to_string(),
1547 content: "pub fn sample() {}".to_string(),
1548 is_error: None,
1549 content_blocks: None,
1550 }],
1551 });
1552
1553 let messages = engine.messages_with_turn_metadata();
1554
1555 // Stored tool-result message is unchanged: no Text prefix, content length == 1.
1556 let only = messages.first().expect("stored tool result message");
1557 assert_eq!(only.content.len(), 1);
1558 assert!(matches!(
1559 only.content.first(),
1560 Some(ContentBlock::ToolResult { .. })
1561 ));
1562 assert_eq!(messages.len(), 1);
1563 }
1564
1565 #[test]
1566 fn declared_refresh_sets_pending_prefix_change_reason() {
1567 let _lock = lock_test_env();
1568 let tmp = tempdir().expect("tempdir");
1569 let config = EngineConfig {
1570 workspace: tmp.path().to_path_buf(),
1571 ..Default::default()
1572 };
1573 let (mut engine, _handle) = Engine::new(config, &Config::default());
1574 // Construction pins the initial prompt; clear any construction-time flag.
1575 engine.session.pending_prefix_change_reason = None;
1576
1577 // A no-op refresh (unchanged bytes) declares nothing.
1578 engine.refresh_system_prompt_with_reason("system");
1579 assert_eq!(engine.session.pending_prefix_change_reason, None);
1580
1581 // A refresh that actually changes the bytes records the declared reason.
1582 engine.config.goal_objective = Some("ship the release".to_string());
1583 engine.config.goal_status = crate::tools::goal::GoalStatus::Active;
1584 engine.refresh_system_prompt_with_reason("goal");
1585 assert_eq!(
1586 engine.session.pending_prefix_change_reason.as_deref(),
1587 Some("goal")
1588 );
1589 }
1590
1591 #[test]
1592 fn workspace_file_change_never_moves_the_frozen_prefix() {
1593 // The old bug: the tool loop recomposed the system prompt from disk on
1594 // every step, so an agent writing a file changed the project pack and
1595 // busted DeepSeek's KV prefix cache mid-turn. The header is now frozen
1596 // for the session: only an explicit refresh (a declared header change)
1597 // recomposes it, and the tool loop no longer calls one.
1598 let _lock = lock_test_env();
1599 let tmp = tempdir().expect("tempdir");
1600 let config = EngineConfig {
1601 workspace: tmp.path().to_path_buf(),
1602 project_context_pack_enabled: true,
1603 ..Default::default()
1604 };
1605 let (mut engine, _handle) = Engine::new(config, &Config::default());
1606 let frozen_prompt = engine.session.system_prompt.clone();
1607 engine.session.pending_prefix_change_reason = None;
1608
1609 // Simulate the agent writing a file into the workspace mid-turn.
1610 fs::write(tmp.path().join("NEWFILE.md"), "brand new content").expect("write");
1611
1612 // What a fresh compose WOULD produce now differs — the bug precondition.
1613 let recomposed =
1614 engine.compose_stable_system_prompt(&engine.installed_next_turn_prompt_context());
1615 assert_ne!(
1616 recomposed, frozen_prompt,
1617 "a workspace file change must change what a fresh compose would produce"
1618 );
1619
1620 // But the session's pinned prompt is untouched and nothing was declared,
1621 // because the tool loop performs no mid-loop refresh.
1622 assert_eq!(engine.session.system_prompt, frozen_prompt);
1623 assert_eq!(engine.session.pending_prefix_change_reason, None);
1624 }
1625
1625 lines RUST