返回 CodeWhale
last_round.rs
根目录 / crates / engine / src / compaction / last_round.rs
1 //! Recent-history coverage floor for compaction replacement history.
2 //!
3 //! Compaction summarizes older turns while retaining a token-budgeted tail
4 //! and the current user instructions. Tool exchanges stay paired and retained
5 //! output is bounded. See [`SURVIVAL_CONTRACT.md`].
6
7 use anyhow::Result;
8 use std::{borrow::Cow, collections::HashSet};
9
10 use codewhale_models::{ContentBlock, Message, SystemPrompt};
11
12 use super::{
13 compaction_checkpoint_message, is_checkpoint_for_compaction, is_orphaned_result_block,
14 retain_user_messages, truncate_retained_block, user_text_of,
15 };
16
17 const LAST_ROUND_TOOL_RESULT_MAX_CHARS: usize = 8 * 1024;
18
19 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20 pub enum CompactionPath {
21 #[default]
22 Summary,
23 PruneOnly,
24 }
25
26 #[derive(Debug, Clone, PartialEq, Eq, Default)]
27 pub struct CompactionCoverage {
28 pub path: CompactionPath,
29 pub last_round_messages: usize,
30 pub last_round_tool_results: usize,
31 pub last_round_assistant: bool,
32 pub dropped_messages: usize,
33 pub anchors_chars: usize,
34 /// Effective `[compaction] retained_user_message_tokens` budget this pass
35 /// spent on verbatim user messages (#5956). `0` on the prune-only path,
36 /// which never builds a replacement history.
37 pub retained_user_message_tokens: usize,
38 /// Whether `[compaction] summary_instructions` was appended to the
39 /// summarizer prompt on this pass (#5956).
40 pub operator_instructions_applied: bool,
41 }
42
43 impl CompactionCoverage {
44 #[must_use]
45 pub fn receipt_clause(&self) -> String {
46 let path = match self.path {
47 CompactionPath::Summary => "summary",
48 CompactionPath::PruneOnly => "prune-only",
49 };
50 let assistant = if self.last_round_assistant {
51 ", assistant"
52 } else {
53 ""
54 };
55 let mut clause = format!(
56 "{path}; last round kept: {} messages ({} tool results{assistant})",
57 self.last_round_messages, self.last_round_tool_results
58 );
59 if self.anchors_chars > 0 {
60 clause.push_str(&format!("; anchors {} chars", self.anchors_chars));
61 }
62 // Name the tuning knobs so an operator who set them can tell they took
63 // effect without reading the log (#5956). The prune-only path builds no
64 // replacement history, so it reports no budget.
65 if self.retained_user_message_tokens > 0 {
66 clause.push_str(&format!(
67 "; verbatim user budget {} tokens",
68 self.retained_user_message_tokens
69 ));
70 }
71 if self.operator_instructions_applied {
72 clause.push_str("; operator instructions applied");
73 }
74 clause
75 }
76 }
77
78 #[derive(Debug, Clone, PartialEq, Eq)]
79 pub struct LastCompactionSnapshot {
80 pub auto: bool,
81 pub coverage: CompactionCoverage,
82 pub messages_before: usize,
83 pub messages_after: usize,
84 }
85
86 #[derive(Debug, Clone, PartialEq, Eq, Default)]
87 pub struct CompactionKeep {
88 pub has_checkpoint: bool,
89 pub last_round_messages: usize,
90 pub last_round_tool_results: usize,
91 pub last_round_assistant: bool,
92 }
93
94 #[must_use]
95 pub fn inspect_compaction_keep(messages: &[Message]) -> CompactionKeep {
96 let last_round = last_round_slice(messages);
97 CompactionKeep {
98 has_checkpoint: messages.iter().any(is_checkpoint_for_compaction),
99 last_round_messages: last_round.len(),
100 last_round_tool_results: last_round.iter().flat_map(tool_result_ids).count(),
101 last_round_assistant: last_round
102 .iter()
103 .any(|message| message.role.is_assistant_like()),
104 }
105 }
106
107 /// Workspace anchors are passive model input; only user-configured trust admits
108 /// them. Missing, linked, unreadable, or empty anchors contribute no text.
109 #[must_use]
110 pub fn pinned_anchors_text(workspace: Option<&std::path::Path>) -> Option<String> {
111 let workspace = workspace?;
112 if !codewhale_runtime::config::is_workspace_trusted(workspace) {
113 return None;
114 }
115 let primary = workspace.join(".codewhale").join("anchors.md");
116 let path = if primary.symlink_metadata().is_ok() || workspace.join(".codewhale").is_symlink() {
117 primary
118 } else {
119 workspace.join(".deepseek").join("anchors.md")
120 };
121 codewhale_util::fs_confined::read_to_string(workspace, &path)
122 .ok()
123 .map(|contents| contents.trim().to_string())
124 .filter(|contents| !contents.is_empty())
125 }
126
127 fn is_plain_user_text(message: &Message) -> bool {
128 !is_checkpoint_for_compaction(message)
129 && !codewhale_models::turn_classify::is_runtime_owned_user_message(message)
130 && user_text_of(message).is_some()
131 }
132
133 fn user_prompt_text_of(message: &Message) -> Option<String> {
134 is_plain_user_text(message)
135 .then(|| user_text_of(message))
136 .flatten()
137 }
138
139 fn last_plain_user_index(messages: &[Message], end: usize) -> Option<usize> {
140 messages[..end]
141 .iter()
142 .enumerate()
143 .rev()
144 .find_map(|(idx, message)| is_plain_user_text(message).then_some(idx))
145 }
146
147 fn slice_has_tool_result(messages: &[Message], start: usize) -> bool {
148 messages[start..].iter().any(|message| {
149 message
150 .content
151 .iter()
152 .any(|block| matches!(block, ContentBlock::ToolResult { .. }))
153 })
154 }
155
156 #[must_use]
157 pub fn last_round_start(messages: &[Message]) -> usize {
158 let Some(last_user) = last_plain_user_index(messages, messages.len()) else {
159 return 0;
160 };
161 if slice_has_tool_result(messages, last_user) {
162 return last_user;
163 }
164 // Trailing toolless user/assistant turns still need the previous
165 // tool-bearing round; otherwise those results vanish behind the summary.
166 // If no tool round exists, keep only the latest user turn so chat-only
167 // sessions can still summarize older text.
168 let mut candidate = last_user;
169 loop {
170 let Some(prev) = last_plain_user_index(messages, candidate) else {
171 return last_user;
172 };
173 if slice_has_tool_result(messages, prev) {
174 return prev;
175 }
176 candidate = prev;
177 }
178 }
179
180 #[must_use]
181 pub fn last_round_range(messages: &[Message]) -> (usize, usize) {
182 let start = last_round_start(messages).min(messages.len());
183 // A previous checkpoint can sit in the middle of an uninterrupted task.
184 // Stopping at that marker hid every tool step after the first compact
185 // from the next pass's survival checks.
186 let end = messages.len().saturating_sub(usize::from(
187 messages.last().is_some_and(is_checkpoint_for_compaction),
188 ));
189 (start, end)
190 }
191
192 /// How many messages of the open round sit in `messages` before a checkpoint.
193 #[must_use]
194 pub fn last_round_kept_count(messages: &[Message]) -> Option<usize> {
195 let checkpoint = messages.iter().rposition(is_checkpoint_for_compaction)?;
196 if checkpoint == 0 {
197 return None;
198 }
199 let start = last_round_start(&messages[..checkpoint]);
200 Some(checkpoint.saturating_sub(start))
201 }
202
203 fn last_round_slice(messages: &[Message]) -> &[Message] {
204 let (start, end) = last_round_range(messages);
205 &messages[start..end]
206 }
207
208 pub(super) fn recent_tail_start(messages: &[Message], recent_tokens: usize) -> usize {
209 let mut tokens = 0usize;
210 let mut start = messages.len();
211 for (idx, message) in messages.iter().enumerate().rev() {
212 if is_checkpoint_for_compaction(message) {
213 continue;
214 }
215 tokens = tokens.saturating_add(
216 super::estimate_tokens(std::slice::from_ref(message)).saturating_add(12),
217 );
218 start = idx;
219 if tokens >= recent_tokens {
220 break;
221 }
222 }
223 let mut pending = HashSet::new();
224 let mut boundaries = vec![0];
225 for (idx, message) in messages.iter().enumerate() {
226 if pending.is_empty() {
227 boundaries.push(idx);
228 }
229 pending.extend(tool_use_ids(message));
230 for id in tool_result_ids(message) {
231 pending.remove(&id);
232 }
233 }
234 boundaries
235 .into_iter()
236 .rfind(|&idx| idx <= start)
237 .unwrap_or(0)
238 }
239
240 fn protected_messages(messages: &[Message], recent_tokens: usize) -> Vec<Cow<'_, Message>> {
241 let start = recent_tail_start(messages, recent_tokens);
242 let round_start = last_round_start(messages);
243 messages
244 .iter()
245 .enumerate()
246 .filter_map(|(idx, message)| {
247 if is_checkpoint_for_compaction(message) {
248 return None;
249 }
250 if idx >= start {
251 return Some(Cow::Borrowed(message));
252 }
253 if idx < round_start || !is_plain_user_text(message) {
254 return None;
255 }
256 let mut retained = Cow::Borrowed(message);
257 if message.content.iter().any(is_orphaned_result_block) {
258 retained
259 .to_mut()
260 .content
261 .retain(|block| !is_orphaned_result_block(block));
262 }
263 Some(retained)
264 })
265 .collect()
266 }
267
268 pub(super) fn replacement_messages(
269 messages: &[Message],
270 retained_user_message_tokens: usize,
271 recent_tokens: usize,
272 ) -> Vec<Message> {
273 let start = last_round_start(messages).min(recent_tail_start(messages, recent_tokens));
274 let mut retained = retain_user_messages(
275 &messages[..start],
276 retained_user_message_tokens,
277 is_checkpoint_for_compaction,
278 );
279 let round = protected_messages(messages, recent_tokens)
280 .into_iter()
281 .map(Cow::into_owned)
282 .collect();
283 retained.extend(bound_last_round(round));
284 // The Operate contract applies to the current tool loop as well as later
285 // turns. It must survive compaction even when old-user retention is full.
286 let current_contract = messages
287 .iter()
288 .rev()
289 .find(|message| crate::runtime_handoff::is_current_operate_contract_message(message));
290 let contract = current_contract.or_else(|| {
291 messages
292 .iter()
293 .rev()
294 .find(|message| crate::runtime_handoff::is_operate_contract_message(message))
295 });
296 if let Some(contract) = contract {
297 retained.retain(|message| !crate::runtime_handoff::is_operate_contract_message(message));
298 retained.insert(0, contract.clone());
299 }
300 // Contributions are captured once per turn. Preserve the complete latest
301 // snapshot, including a withdrawal, rather than summarizing or truncating
302 // instructions that still apply to this tool loop.
303 if let Some(snapshot) = messages.iter().rev().find(|message| {
304 crate::runtime_handoff::extension_prompt_contributions_display(message).is_some()
305 }) {
306 retained.retain(|message| {
307 crate::runtime_handoff::extension_prompt_contributions_display(message).is_none()
308 });
309 retained.insert(0, snapshot.clone());
310 }
311 if let Some(snapshot) = messages
312 .iter()
313 .rev()
314 .find(|message| crate::runtime_handoff::constitution_display(message).is_some())
315 {
316 retained.retain(|message| crate::runtime_handoff::constitution_display(message).is_none());
317 retained.insert(0, snapshot.clone());
318 }
319 retained
320 }
321
322 fn bound_last_round(mut round: Vec<Message>) -> Vec<Message> {
323 for message in &mut round {
324 for block in &mut message.content {
325 if let ContentBlock::ToolResult {
326 content,
327 content_blocks,
328 ..
329 } = block
330 && truncate_retained_block("tool result", content, LAST_ROUND_TOOL_RESULT_MAX_CHARS)
331 {
332 *content_blocks = None;
333 }
334 }
335 }
336 round
337 }
338
339 fn tool_result_ids(message: &Message) -> Vec<(codewhale_models::ToolCallKey<'_>, &str)> {
340 message
341 .content
342 .iter()
343 .filter_map(|block| match block {
344 ContentBlock::ToolResult { tool_use_id, .. } => {
345 block.tool_call_key().map(|key| (key, tool_use_id.as_str()))
346 }
347 _ => None,
348 })
349 .collect()
350 }
351
352 fn has_tool_result_id(message: &Message, id: &(codewhale_models::ToolCallKey<'_>, &str)) -> bool {
353 if id.0.as_str().trim().is_empty() {
354 return false;
355 }
356 message.content.iter().any(|block| {
357 matches!(
358 block,
359 ContentBlock::ToolResult { tool_use_id, .. } if block.tool_call_key() == Some(id.0) && tool_use_id == id.1
360 )
361 })
362 }
363
364 fn tool_use_ids(message: &Message) -> Vec<(codewhale_models::ToolCallKey<'_>, &str)> {
365 message
366 .content
367 .iter()
368 .filter_map(|block| match block {
369 ContentBlock::ToolUse { id, .. } => block.tool_call_key().map(|key| (key, id.as_str())),
370 _ => None,
371 })
372 .collect()
373 }
374
375 fn has_tool_use_id(message: &Message, id: &(codewhale_models::ToolCallKey<'_>, &str)) -> bool {
376 if id.0.as_str().trim().is_empty() {
377 return false;
378 }
379 message.content.iter().any(|block| {
380 matches!(
381 block,
382 ContentBlock::ToolUse { id: provider, .. } if block.tool_call_key() == Some(id.0) && provider == id.1
383 )
384 })
385 }
386
387 fn tool_call_identity_label(id: &(codewhale_models::ToolCallKey<'_>, &str)) -> String {
388 match id.0 {
389 codewhale_models::ToolCallKey::Execution(execution_id) => {
390 format!("execution {execution_id} (provider call {})", id.1)
391 }
392 codewhale_models::ToolCallKey::LegacyProvider(provider_id) => provider_id.to_string(),
393 }
394 }
395
396 fn assistant_text_of(message: &Message) -> Option<String> {
397 if !message.role.is_assistant_like() {
398 return None;
399 }
400 let text = message
401 .content
402 .iter()
403 .filter_map(|block| match block {
404 ContentBlock::Text { text, .. } => Some(text.as_str()),
405 _ => None,
406 })
407 .collect::<Vec<_>>()
408 .join("\n");
409 let text = text.trim();
410 (!text.is_empty()).then(|| text.to_string())
411 }
412
413 /// A retained copy may be truncated (`bound_last_round` caps oversized blocks),
414 /// so a prefix either way counts as survival -- but nothing weaker does.
415 fn survives(text: &str, replacement: &[Message], of: impl Fn(&Message) -> Option<String>) -> bool {
416 replacement.iter().any(|message| {
417 of(message)
418 .is_some_and(|kept| kept == text || text.starts_with(&kept) || kept.starts_with(text))
419 })
420 }
421
422 pub fn validate_retained_coverage(
423 original: &[Message],
424 replacement: &[Message],
425 recent_tokens: usize,
426 ) -> Result<()> {
427 let protected = protected_messages(original, recent_tokens);
428 if protected.is_empty() {
429 return Ok(());
430 }
431 let last_round = || protected.iter().map(Cow::as_ref);
432 // Every user turn in the round, not the first one `find_map` happens to
433 // reach. `last_round_start` walks back past a toolless tail to the previous
434 // tool-bearing turn, so the round routinely spans two user messages -- and
435 // checking only the earliest let a rewrite drop the *latest* one, which is
436 // the turn this whole contract exists to keep.
437 for text in last_round().filter_map(user_prompt_text_of) {
438 if !survives(&text, replacement, user_prompt_text_of) {
439 anyhow::bail!(
440 "Making room stopped: a last-round user message was dropped; history was not replaced."
441 );
442 }
443 }
444 for id in last_round().flat_map(tool_result_ids) {
445 if !replacement
446 .iter()
447 .any(|message| has_tool_result_id(message, &id))
448 {
449 let label = tool_call_identity_label(&id);
450 anyhow::bail!(
451 "Making room stopped: last-round tool result {label} was dropped; history was not replaced."
452 );
453 }
454 }
455 // The call, not just its result. Keeping a tool_result whose tool_use was
456 // summarized away leaves an orphaned result that providers reject outright.
457 for id in last_round().flat_map(tool_use_ids) {
458 if !replacement
459 .iter()
460 .any(|message| has_tool_use_id(message, &id))
461 {
462 let label = tool_call_identity_label(&id);
463 anyhow::bail!(
464 "Making room stopped: last-round tool call {label} was dropped; history was not replaced."
465 );
466 }
467 }
468 // Match the assistant's actual output. An existential "some assistant
469 // message survived" check passed on a replacement whose only assistant
470 // message was the summary the rewrite had just written.
471 for text in last_round().filter_map(assistant_text_of) {
472 if !survives(&text, replacement, assistant_text_of) {
473 anyhow::bail!(
474 "Making room stopped: last-round assistant output was dropped; history was not replaced."
475 );
476 }
477 }
478 if last_round().any(|message| message.role.is_assistant_like())
479 && !replacement
480 .iter()
481 .any(|message| message.role.is_assistant_like())
482 {
483 anyhow::bail!(
484 "Making room stopped: last-round assistant output was dropped; history was not replaced."
485 );
486 }
487 Ok(())
488 }
489
490 pub fn require_text_survives(replacement: &[Message], needle: &str, label: &str) -> Result<()> {
491 let needle = needle.trim();
492 if needle.is_empty() {
493 return Ok(());
494 }
495 let kept = replacement.iter().any(|message| {
496 message.content.iter().any(|block| match block {
497 ContentBlock::Text { text, .. } => text.contains(needle),
498 ContentBlock::ToolResult { content, .. } => content.contains(needle),
499 _ => false,
500 })
501 });
502 if !kept {
503 anyhow::bail!("Making room stopped: {label} was dropped; history was not replaced.");
504 }
505 Ok(())
506 }
507
508 pub fn validate_survival_contract(
509 original: &[Message],
510 replacement: &[Message],
511 anchors: Option<&str>,
512 recent_tokens: usize,
513 ) -> Result<()> {
514 validate_retained_coverage(original, replacement, recent_tokens)?;
515 let checkpoints = replacement
516 .iter()
517 .filter(|message| is_checkpoint_for_compaction(message))
518 .count();
519 if checkpoints == 0 {
520 anyhow::bail!(
521 "Making room stopped: checkpoint receipt was dropped; history was not replaced."
522 );
523 }
524 if checkpoints > 1 {
525 anyhow::bail!(
526 "Making room stopped: prior summaries were duplicated; history was not replaced."
527 );
528 }
529 if let Some(anchors) = anchors {
530 require_text_survives(replacement, anchors, "pinned /anchor text")?;
531 }
532 Ok(())
533 }
534
535 pub(super) fn measure_coverage(
536 original: &[Message],
537 replacement: &[Message],
538 path: CompactionPath,
539 anchors_chars: usize,
540 ) -> CompactionCoverage {
541 let last_round = last_round_slice(replacement);
542 CompactionCoverage {
543 path,
544 last_round_messages: last_round.len(),
545 last_round_tool_results: last_round.iter().flat_map(tool_result_ids).count(),
546 last_round_assistant: last_round
547 .iter()
548 .any(|message| message.role.is_assistant_like()),
549 dropped_messages: original.len().saturating_sub(replacement.len()),
550 anchors_chars,
551 // Tuning provenance is owned by the caller that holds the
552 // `CompactionConfig`; measurement over two message lists cannot know it.
553 retained_user_message_tokens: 0,
554 operator_instructions_applied: false,
555 }
556 }
557
558 /// Build the post-compaction history: recent plain user messages kept
559 /// verbatim within `retained_user_message_tokens`, the bounded recent tail, and
560 /// the checkpoint. The budget is `[compaction] retained_user_message_tokens`
561 /// (#5956); it was a hard-coded 20 000 before that key existed.
562 pub(super) fn build_replacement_history(
563 messages: &[Message],
564 checkpoint_text: &str,
565 anchors: Option<&str>,
566 retained_user_message_tokens: usize,
567 recent_tokens: usize,
568 ) -> Result<Vec<Message>> {
569 let mut retained = replacement_messages(messages, retained_user_message_tokens, recent_tokens);
570 retained.push(compaction_checkpoint_message(&SystemPrompt::Text(
571 checkpoint_text.to_string(),
572 )));
573 validate_survival_contract(messages, &retained, anchors, recent_tokens)?;
574 Ok(retained)
575 }
576
577 #[cfg(test)]
578 mod tests {
579 use super::*;
580 use crate::compaction::compaction_checkpoint_message;
581 use codewhale_models::turn_classify::{
582 COMPACTION_SUMMARY_MARKER, LEGACY_V2_COMPACTION_SUMMARY_MARKER,
583 };
584 use codewhale_models::{ContentBlock, Role};
585 use serde_json::json;
586
587 #[test]
588 fn coverage_requires_the_original_execution_and_provider_pair() {
589 let original: Vec<Message> = serde_json::from_value(json!([
590 {"role":"user","content":[{"type":"text","text":"keep this exchange"}]},
591 {"role":"assistant","content":[{"type":"tool_use","id":"wire","execution_id":"local","name":"read","input":{}}]},
592 {"role":"user","content":[{"type":"tool_result","tool_use_id":"wire","execution_id":"local","content":"kept"}]}
593 ])).unwrap();
594 assert!(validate_retained_coverage(&original, &original, 20_000).is_ok());
595 for identity in [None, Some("different")] {
596 let mut replacement = original.clone();
597 for block in replacement
598 .iter_mut()
599 .flat_map(|message| &mut message.content)
600 {
601 match block {
602 ContentBlock::ToolUse { execution_id, .. }
603 | ContentBlock::ToolResult { execution_id, .. } => {
604 *execution_id = identity.map(str::to_string)
605 }
606 _ => {}
607 }
608 }
609 assert!(validate_retained_coverage(&original, &replacement, 20_000).is_err());
610 }
611 let mut replacement = original.clone();
612 if let ContentBlock::ToolResult { tool_use_id, .. } = &mut replacement[2].content[0] {
613 *tool_use_id = "wrong-wire".to_string();
614 }
615 let error = validate_retained_coverage(&original, &replacement, 20_000).unwrap_err();
616 assert_eq!(
617 error.to_string(),
618 "Making room stopped: last-round tool result execution local (provider call wire) was dropped; history was not replaced."
619 );
620 let mut replacement = original.clone();
621 if let ContentBlock::ToolUse { id, .. } = &mut replacement[1].content[0] {
622 *id = "wrong-wire".to_string();
623 }
624 let error = validate_retained_coverage(&original, &replacement, 20_000).unwrap_err();
625 assert_eq!(
626 error.to_string(),
627 "Making room stopped: last-round tool call execution local (provider call wire) was dropped; history was not replaced."
628 );
629 }
630
631 #[test]
632 fn confined_pinned_anchors_require_workspace_trust() {
633 use crate::test_support::{EnvVarGuard, lock_test_env};
634 let _lock = lock_test_env();
635 let workspace = tempfile::tempdir().unwrap();
636 let config = tempfile::tempdir().unwrap();
637 let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config.path().join("config.toml"));
638 let legacy = workspace.path().join(".deepseek");
639 std::fs::create_dir(&legacy).unwrap();
640 std::fs::write(legacy.join("anchors.md"), " legacy anchor \n").unwrap();
641 std::fs::write(legacy.join("trusted"), "true").unwrap();
642 assert_eq!(pinned_anchors_text(None), None);
643 assert_eq!(pinned_anchors_text(Some(workspace.path())), None);
644
645 codewhale_runtime::config::save_workspace_trust(workspace.path()).unwrap();
646 assert!(codewhale_runtime::config::is_workspace_trusted(
647 workspace.path()
648 ));
649 assert_eq!(
650 pinned_anchors_text(Some(workspace.path())).as_deref(),
651 Some("legacy anchor")
652 );
653 let primary = workspace.path().join(".codewhale");
654 std::fs::create_dir(&primary).unwrap();
655 std::fs::write(primary.join("anchors.md"), " primary anchor \n").unwrap();
656 assert_eq!(
657 pinned_anchors_text(Some(workspace.path())).as_deref(),
658 Some("primary anchor")
659 );
660 std::fs::write(primary.join("anchors.md"), " \n").unwrap();
661 assert_eq!(pinned_anchors_text(Some(workspace.path())), None);
662 }
663
664 #[cfg(unix)]
665 #[test]
666 fn confined_pinned_anchors_refuse_linked_files_and_directories() {
667 use crate::test_support::{EnvVarGuard, lock_test_env};
668 use std::os::unix::fs::symlink;
669 let _lock = lock_test_env();
670 let config = tempfile::tempdir().unwrap();
671 let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config.path().join("config.toml"));
672 for directory in [".codewhale", ".deepseek"] {
673 for linked_directory in [false, true] {
674 let workspace = tempfile::tempdir().unwrap();
675 let outside = tempfile::tempdir().unwrap();
676 codewhale_runtime::config::save_workspace_trust(workspace.path()).unwrap();
677 assert!(codewhale_runtime::config::is_workspace_trusted(
678 workspace.path()
679 ));
680 let target = outside.path().join("anchors.md");
681 std::fs::write(&target, "separate anchor").unwrap();
682 let parent = workspace.path().join(directory);
683 if linked_directory {
684 symlink(outside.path(), &parent).unwrap();
685 } else {
686 std::fs::create_dir(&parent).unwrap();
687 symlink(&target, parent.join("anchors.md")).unwrap();
688 }
689 assert_eq!(pinned_anchors_text(Some(workspace.path())), None);
690 // A dangling preferred path must not select legacy content.
691 if directory == ".codewhale" {
692 let legacy = workspace.path().join(".deepseek");
693 std::fs::create_dir(&legacy).unwrap();
694 std::fs::write(legacy.join("anchors.md"), "legacy anchor").unwrap();
695 }
696 std::fs::remove_file(&target).unwrap();
697 assert_eq!(pinned_anchors_text(Some(workspace.path())), None);
698 }
699 }
700 }
701
702 fn msg(role: &str, text: &str) -> Message {
703 Message {
704 role: Role::from(role),
705 content: vec![ContentBlock::Text {
706 text: text.to_string(),
707 cache_control: None,
708 }],
709 }
710 }
711
712 fn tool_use(id: &str, name: &str, input: serde_json::Value) -> Message {
713 Message {
714 role: Role::Assistant,
715 content: vec![ContentBlock::ToolUse {
716 execution_id: None,
717 id: id.to_string(),
718 name: name.to_string(),
719 input,
720 caller: None,
721 thought_signature: None,
722 }],
723 }
724 }
725
726 fn tool_result(id: &str, content: &str) -> Message {
727 Message {
728 role: Role::User,
729 content: vec![ContentBlock::ToolResult {
730 execution_id: None,
731 tool_use_id: id.to_string(),
732 content: content.to_string(),
733 is_error: None,
734 content_blocks: None,
735 }],
736 }
737 }
738
739 fn checkpoint(summary: &str) -> Message {
740 compaction_checkpoint_message(&SystemPrompt::Text(format!(
741 "{COMPACTION_SUMMARY_MARKER}: {summary}"
742 )))
743 }
744
745 #[test]
746 fn replacement_keeps_only_latest_complete_prompt_snapshot_and_withdrawal() {
747 use crate::runtime_handoff::{
748 extension_prompt_contributions_display, extension_prompt_contributions_runtime_message,
749 };
750 let old = extension_prompt_contributions_runtime_message(Some("old instructions"));
751 let current_text = "current instructions ".repeat(400);
752 for current in [
753 extension_prompt_contributions_runtime_message(Some(&current_text)),
754 extension_prompt_contributions_runtime_message(None),
755 ] {
756 let quoted = msg(
757 "user",
758 &user_text_of(&current).expect("runtime snapshot has text"),
759 );
760 let original = vec![
761 old.clone(),
762 quoted.clone(),
763 current.clone(),
764 msg("user", "Continue this task."),
765 tool_use("first", "Read", json!({"path": "first"})),
766 tool_result("first", "first output"),
767 tool_use("second", "Read", json!({"path": "second"})),
768 tool_result("second", "second output"),
769 tool_use("third", "Read", json!({"path": "third"})),
770 tool_result("third", "third output"),
771 ];
772 let kept = replacement_messages(&original, 20_000, 20_000);
773 let snapshots: Vec<_> = kept
774 .iter()
775 .filter(|message| extension_prompt_contributions_display(message).is_some())
776 .collect();
777 assert_eq!(snapshots, [&current]);
778 assert!(
779 kept.contains(&quoted),
780 "a person's quote is ordinary user text"
781 );
782 assert_eq!(
783 replacement_messages(&kept, 20_000, 20_000)
784 .iter()
785 .filter(|message| extension_prompt_contributions_display(message).is_some())
786 .count(),
787 1,
788 "repeated compaction must not accumulate snapshots"
789 );
790 }
791 }
792
793 /// The handoff header tells the next turn what survived. It must match
794 /// what the replacement history keeps: only the last steps of a long
795 /// round, with long tool output shortened and marked.
796 #[test]
797 fn profile_constitution_compaction_keeps_only_the_complete_latest_snapshot() {
798 use crate::runtime_handoff::{constitution_display, constitution_runtime_message};
799 let old = constitution_runtime_message(Some("old instructions"));
800 let current_text = "current instructions ".repeat(400);
801 for current in [
802 constitution_runtime_message(Some(&current_text)),
803 constitution_runtime_message(None),
804 ] {
805 let quoted = msg(
806 "user",
807 &user_text_of(&current).expect("runtime snapshot has text"),
808 );
809 let original = vec![
810 old.clone(),
811 quoted.clone(),
812 current.clone(),
813 msg("user", "Continue this task."),
814 tool_use("first", "Read", json!({"path": "first"})),
815 tool_result("first", "first output"),
816 tool_use("second", "Read", json!({"path": "second"})),
817 tool_result("second", "second output"),
818 tool_use("third", "Read", json!({"path": "third"})),
819 tool_result("third", "third output"),
820 ];
821 let kept = replacement_messages(&original, 20_000, 20_000);
822 let snapshots: Vec<_> = kept
823 .iter()
824 .filter(|message| constitution_display(message).is_some())
825 .collect();
826 assert_eq!(snapshots, [&current]);
827 assert!(
828 kept.contains(&quoted),
829 "a person's quote is ordinary user text"
830 );
831 assert_eq!(
832 replacement_messages(&kept, 20_000, 20_000)
833 .iter()
834 .filter(|message| constitution_display(message).is_some())
835 .count(),
836 1,
837 "repeated compaction must not accumulate snapshots"
838 );
839 }
840 }
841
842 /// The handoff header tells the next turn what survived. It must match
843 /// what the replacement history keeps: only the last steps of a long
844 /// round, with long tool output shortened and marked.
845 #[test]
846 fn summary_header_matches_what_replacement_history_keeps() {
847 let long_output = "x".repeat(LAST_ROUND_TOOL_RESULT_MAX_CHARS * 2);
848 let original = vec![
849 msg("user", "Fix the build."),
850 tool_use("first", "Bash", json!({"command": "cargo check"})),
851 tool_result("first", "first step output"),
852 tool_use("second", "Bash", json!({"command": "cargo build"})),
853 tool_result("second", "second step output"),
854 tool_use("third", "Bash", json!({"command": "cargo test"})),
855 tool_result("third", &long_output),
856 ];
857 let recent_tokens =
858 crate::compaction::estimate_tokens(&original[3..]) + original[3..].len() * 12;
859 let kept = replacement_messages(&original, 20_000, recent_tokens);
860 let kept_ids: Vec<&str> = kept
861 .iter()
862 .flat_map(tool_result_ids)
863 .map(|(_, wire)| wire)
864 .collect();
865 assert_eq!(kept_ids, ["second", "third"], "earlier steps are dropped");
866 assert!(
867 kept.iter()
868 .any(|m| user_text_of(m).as_deref() == Some("Fix the build."))
869 );
870 let shortened = kept
871 .iter()
872 .flat_map(|m| &m.content)
873 .find_map(|block| match block {
874 ContentBlock::ToolResult {
875 tool_use_id,
876 content,
877 ..
878 } if tool_use_id == "third" => Some(content.clone()),
879 _ => None,
880 })
881 .expect("the last tool result is kept");
882 assert!(shortened.len() < long_output.len());
883 assert!(shortened.starts_with("[tool result retained-history truncated from"));
884
885 let header = crate::compaction::SUMMARY_HEADER;
886 assert!(header.contains("current user instructions"), "{header}");
887 assert!(header.contains("tail selected by token budget"), "{header}");
888 assert!(
889 header.contains("Long tool output there is shortened"),
890 "{header}"
891 );
892 assert!(
893 header.contains("with a marker where it was cut"),
894 "{header}"
895 );
896 assert!(!header.contains("as they were"), "{header}");
897 }
898
899 #[test]
900 fn coverage_floor_rejects_a_replacement_that_drops_last_round_tools() {
901 let original = vec![
902 msg("user", "Run the failing test."),
903 msg("assistant", "Running."),
904 tool_use("live", "Bash", json!({"command": "cargo test"})),
905 tool_result("live", "test session_store::roundtrip ... FAILED"),
906 ];
907 let gutting = vec![
908 msg("user", "Run the failing test."),
909 checkpoint("and kept going"),
910 ];
911 let error = validate_retained_coverage(&original, &gutting, 20_000)
912 .expect_err("dropping the last tool result must fail the coverage floor");
913 assert!(error.to_string().contains("tool result live"), "{error}");
914 assert!(validate_retained_coverage(&original, &original, 20_000).is_ok());
915 }
916
917 #[test]
918 fn coverage_floor_rejects_a_replacement_that_drops_last_round_assistant() {
919 let original = vec![
920 msg("user", "What failed?"),
921 msg("assistant", "session_store::roundtrip panics on reload."),
922 ];
923 let error = validate_retained_coverage(&original, &[msg("user", "What failed?")], 20_000)
924 .expect_err("dropping last-round assistant text must fail closed");
925 assert!(error.to_string().contains("assistant"), "{error}");
926 }
927
928 /// The round spans the tool-bearing turn *and* the toolless tail after it,
929 /// because `last_round_start` walks back for the tools. Checking only the
930 /// first user text it found meant a rewrite could keep the older question
931 /// and drop the one the person actually just asked.
932 #[test]
933 fn coverage_floor_rejects_a_replacement_that_drops_the_latest_user_turn() {
934 let original = vec![
935 msg("user", "Run the suite."),
936 msg("assistant", "Running."),
937 tool_use("live", "Bash", json!({"command": "cargo test"})),
938 tool_result("live", "ok"),
939 msg("user", "Now ship it."),
940 msg("assistant", "Shipping."),
941 ];
942 assert_eq!(last_round_start(&original), 0, "round must span both turns");
943
944 let drops_latest = vec![
945 msg("user", "Run the suite."),
946 msg("assistant", "Running."),
947 tool_use("live", "Bash", json!({"command": "cargo test"})),
948 tool_result("live", "ok"),
949 checkpoint("then shipped"),
950 ];
951 let error = validate_retained_coverage(&original, &drops_latest, 20_000)
952 .expect_err("dropping the latest user turn must fail the coverage floor");
953 assert!(error.to_string().contains("user message"), "{error}");
954 assert!(validate_retained_coverage(&original, &original, 20_000).is_ok());
955 }
956
957 /// A surviving `tool_result` whose `tool_use` was summarized away is an
958 /// orphan the provider rejects, so the floor must cover the call too.
959 #[test]
960 fn coverage_floor_rejects_a_replacement_that_drops_the_tool_call() {
961 let original = vec![
962 msg("user", "Run the failing test."),
963 msg("assistant", "Running."),
964 tool_use("live", "Bash", json!({"command": "cargo test"})),
965 tool_result("live", "FAILED"),
966 ];
967 let orphaned = vec![
968 msg("user", "Run the failing test."),
969 msg("assistant", "Running."),
970 tool_result("live", "FAILED"),
971 checkpoint("and it failed"),
972 ];
973 let error = validate_retained_coverage(&original, &orphaned, 20_000)
974 .expect_err("dropping the tool call must fail the coverage floor");
975 assert!(error.to_string().contains("tool call live"), "{error}");
976 }
977
978 /// "Some assistant message survived" was satisfied by the summary the
979 /// rewrite had just written, so the round's real output could vanish.
980 #[test]
981 fn coverage_floor_rejects_assistant_output_replaced_by_a_summary() {
982 let original = vec![
983 msg("user", "What failed?"),
984 msg("assistant", "session_store::roundtrip panics on reload."),
985 ];
986 let summarized = vec![
987 msg("user", "What failed?"),
988 msg("assistant", "Earlier we discussed several test failures."),
989 ];
990 let error = validate_retained_coverage(&original, &summarized, 20_000)
991 .expect_err("substituting a summary for the round's output must fail closed");
992 assert!(error.to_string().contains("assistant"), "{error}");
993 }
994
995 #[test]
996 fn survival_contract_rejects_dropped_anchors_and_receipts() {
997 let original = vec![msg("user", "Keep the pin."), msg("assistant", "Anchored.")];
998 let without_receipt = vec![msg("user", "Keep the pin."), msg("assistant", "Anchored.")];
999 let error =
1000 validate_survival_contract(&original, &without_receipt, Some("ship 0.9.12"), 20_000)
1001 .expect_err("missing checkpoint receipt must fail closed");
1002 assert!(error.to_string().contains("receipt"), "{error}");
1003
1004 let without_anchor = vec![
1005 msg("user", "Keep the pin."),
1006 msg("assistant", "Anchored."),
1007 checkpoint("progress without the pin"),
1008 ];
1009 let error =
1010 validate_survival_contract(&original, &without_anchor, Some("ship 0.9.12"), 20_000)
1011 .expect_err("dropped /anchor text must fail closed");
1012 assert!(error.to_string().contains("anchor"), "{error}");
1013 }
1014
1015 #[test]
1016 fn last_round_starts_at_the_latest_plain_user_message() {
1017 let messages = vec![
1018 msg("user", "older"),
1019 msg("assistant", "working"),
1020 tool_result("old", "stale"),
1021 msg("user", "Run the suite now."),
1022 msg("assistant", "Rerunning."),
1023 tool_use("live", "Bash", json!({"command": "cargo test"})),
1024 tool_result("live", "ok"),
1025 ];
1026 assert_eq!(last_round_start(&messages), 3); // last user with tools
1027 let (start, end) = last_round_range(&messages);
1028 let kept = bound_last_round(messages[start..end].to_vec());
1029 assert!(kept.iter().any(|message| {
1030 message.content.iter().any(|block| {
1031 matches!(
1032 block,
1033 ContentBlock::ToolResult { tool_use_id, content, .. }
1034 if tool_use_id == "live" && content == "ok"
1035 )
1036 })
1037 }));
1038 }
1039
1040 #[test]
1041 fn second_compaction_keeps_long_user_question_and_tool_pair_past_retention_budget() {
1042 const PRODUCTION_MIN_RETAINED_TOKENS: usize = 2_000;
1043 let long_question = format!(
1044 "{}?",
1045 "Analyze every step of this case carefully. ".repeat(400)
1046 );
1047 assert!(long_question.len() > PRODUCTION_MIN_RETAINED_TOKENS * 3);
1048 let original = vec![
1049 msg("user", &long_question),
1050 tool_use("call_1", "Bash", json!({"command": "echo ready"})),
1051 tool_result("call_1", "ready"),
1052 ];
1053 let first_summary =
1054 crate::compaction::build_compaction_summary_block_text("First pass complete", "");
1055 let mut first = build_replacement_history(
1056 &original,
1057 &first_summary,
1058 None,
1059 PRODUCTION_MIN_RETAINED_TOKENS,
1060 20_000,
1061 )
1062 .expect("first compaction");
1063 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut first, &[]);
1064 assert_eq!(last_round_start(&first), 0);
1065 let topology = first
1066 .iter()
1067 .find(|message| crate::runtime_handoff::is_agent_topology_checkpoint(message))
1068 .expect("first compaction topology checkpoint")
1069 .clone();
1070 assert!(
1071 crate::compaction::retained_user_messages(
1072 std::slice::from_ref(&topology),
1073 PRODUCTION_MIN_RETAINED_TOKENS,
1074 )
1075 .is_empty(),
1076 "runtime topology must not consume the older-user retention budget"
1077 );
1078
1079 let second_summary =
1080 crate::compaction::build_compaction_summary_block_text("Second pass complete", "");
1081 let second = build_replacement_history(
1082 &first,
1083 &second_summary,
1084 None,
1085 PRODUCTION_MIN_RETAINED_TOKENS,
1086 20_000,
1087 )
1088 .expect("second compaction");
1089 assert!(
1090 second.iter().any(|message| {
1091 user_text_of(message).as_deref() == Some(long_question.as_str())
1092 })
1093 );
1094 assert!(second.iter().any(|message| has_tool_use_id(
1095 message,
1096 &(
1097 codewhale_models::ToolCallKey::LegacyProvider("call_1"),
1098 "call_1"
1099 )
1100 )));
1101 assert!(second.iter().any(|message| has_tool_result_id(
1102 message,
1103 &(
1104 codewhale_models::ToolCallKey::LegacyProvider("call_1"),
1105 "call_1"
1106 )
1107 )));
1108 let without_question = second
1109 .iter()
1110 .filter(|message| user_text_of(message).as_deref() != Some(long_question.as_str()))
1111 .cloned()
1112 .collect::<Vec<_>>();
1113 assert!(validate_retained_coverage(&first, &without_question, 20_000).is_err());
1114 }
1115
1116 #[test]
1117 fn runtime_text_cannot_satisfy_real_user_coverage() {
1118 let runtime = crate::runtime_handoff::operate_contract_runtime_message();
1119 let copied_text = user_text_of(&runtime).expect("runtime text");
1120 let original = vec![msg("user", &copied_text), msg("assistant", "Acknowledged")];
1121 let replacement = vec![runtime, msg("assistant", "Acknowledged")];
1122 assert!(
1123 validate_retained_coverage(&original, &replacement, 20_000).is_err(),
1124 "runtime-owned text must not stand in for the user's actual prompt"
1125 );
1126 }
1127
1128 #[test]
1129 fn operate_contract_survives_compaction_without_spending_user_budget() {
1130 let contract = crate::runtime_handoff::operate_contract_runtime_message();
1131 let original = vec![
1132 contract.clone(),
1133 msg("user", "First task"),
1134 msg("assistant", "Working"),
1135 msg("user", "Continue the same task"),
1136 msg("assistant", "Continuing"),
1137 ];
1138 let replaced = build_replacement_history(
1139 &original,
1140 &format!("{COMPACTION_SUMMARY_MARKER}: work continues"),
1141 None,
1142 1,
1143 20_000,
1144 )
1145 .expect("compaction must retain the active Operate contract");
1146 assert_eq!(replaced.first(), Some(&contract));
1147 assert_eq!(
1148 replaced
1149 .iter()
1150 .filter(|message| **message == contract)
1151 .count(),
1152 1
1153 );
1154 }
1155
1156 #[test]
1157 fn compaction_prefers_current_operate_contract_over_legacy() {
1158 let legacy = crate::runtime_handoff::legacy_operate_contract_runtime_message();
1159 let current = crate::runtime_handoff::operate_contract_runtime_message();
1160 let original = vec![
1161 legacy.clone(),
1162 current.clone(),
1163 msg("user", "Continue"),
1164 msg("assistant", "Working"),
1165 ];
1166 let replaced = build_replacement_history(
1167 &original,
1168 &format!("{COMPACTION_SUMMARY_MARKER}: work continues"),
1169 None,
1170 1,
1171 20_000,
1172 )
1173 .expect("current contract must survive compaction");
1174 assert_eq!(replaced.first(), Some(&current));
1175 assert!(!replaced.contains(&legacy));
1176 assert_eq!(
1177 replaced
1178 .iter()
1179 .filter(|message| crate::runtime_handoff::is_operate_contract_message(message))
1180 .count(),
1181 1
1182 );
1183 }
1184
1185 #[test]
1186 fn compaction_replaces_v0_10_0_operate_contract_with_current() {
1187 // A v0.10.0 session that entered Operate after a tool round, resumed on
1188 // a later build: the protected round reaches back past both contracts.
1189 let shipped = crate::runtime_handoff::v0_10_0_operate_contract_runtime_message();
1190 let current = crate::runtime_handoff::operate_contract_runtime_message();
1191 let original = vec![
1192 msg("user", "Run the failing test."),
1193 tool_use("live", "Bash", json!({"command": "cargo test"})),
1194 tool_result("live", "test session_store::roundtrip ... FAILED"),
1195 shipped.clone(),
1196 msg("user", "Fix it."),
1197 msg("assistant", "Fixed."),
1198 current.clone(),
1199 msg("user", "Continue"),
1200 msg("assistant", "Working"),
1201 ];
1202 assert_eq!(last_round_start(&original), 0);
1203 let replaced = build_replacement_history(
1204 &original,
1205 &format!("{COMPACTION_SUMMARY_MARKER}: work continues"),
1206 None,
1207 1,
1208 20_000,
1209 )
1210 .expect("current contract must survive compaction");
1211 assert_eq!(replaced.first(), Some(&current));
1212 assert!(
1213 !replaced.contains(&shipped),
1214 "the v0.10.0 contract contradicts the current one about goals"
1215 );
1216 assert_eq!(
1217 replaced
1218 .iter()
1219 .filter(|message| crate::runtime_handoff::is_operate_contract_message(message))
1220 .count(),
1221 1
1222 );
1223
1224 // Until an Operate turn on the new build appends the current wording,
1225 // the saved contract is the only one and is kept once, at the front.
1226 let only_shipped = vec![
1227 shipped.clone(),
1228 msg("user", "Continue"),
1229 msg("assistant", "Working"),
1230 ];
1231 let replaced = build_replacement_history(
1232 &only_shipped,
1233 &format!("{COMPACTION_SUMMARY_MARKER}: work continues"),
1234 None,
1235 1,
1236 20_000,
1237 )
1238 .expect("saved contract must survive compaction");
1239 assert_eq!(replaced.first(), Some(&shipped));
1240 assert_eq!(
1241 replaced
1242 .iter()
1243 .filter(|message| **message == shipped)
1244 .count(),
1245 1
1246 );
1247 }
1248
1249 #[test]
1250 fn last_round_walks_back_through_toolless_tails_to_the_tool_round() {
1251 let original = vec![
1252 msg("user", "Run the failing test."),
1253 msg("assistant", "Running."),
1254 tool_use("live", "Bash", json!({"command": "cargo test"})),
1255 tool_result("live", "test session_store::roundtrip ... FAILED"),
1256 msg("user", "ok thanks"),
1257 msg("assistant", "you're welcome"),
1258 msg("user", "one more thing"),
1259 msg("assistant", "sure"),
1260 ];
1261 assert_eq!(last_round_start(&original), 0);
1262 let next = format!("{COMPACTION_SUMMARY_MARKER}: keep the failing test result");
1263 let replaced = build_replacement_history(
1264 &original,
1265 &next,
1266 None,
1267 crate::compaction::COMPACT_RETAINED_USER_MESSAGE_MAX_TOKENS,
1268 20_000,
1269 )
1270 .expect("toolless tails must not drop the last tool result");
1271 assert!(replaced.iter().any(|message| {
1272 message.content.iter().any(|block| {
1273 matches!(
1274 block,
1275 ContentBlock::ToolResult { tool_use_id, content, .. }
1276 if tool_use_id == "live" && content.contains("FAILED")
1277 )
1278 })
1279 }));
1280 }
1281
1282 #[test]
1283 fn chat_only_history_keeps_the_latest_user_round() {
1284 let messages = vec![
1285 msg("user", "hello"),
1286 msg("assistant", "hi"),
1287 msg("user", "how are you"),
1288 msg("assistant", "fine"),
1289 ];
1290 assert_eq!(last_round_start(&messages), 2);
1291 }
1292
1293 /// In a history that carries the stamped carrier, a user turn pasting a
1294 /// bare legacy summary header is content: it anchors the round, survives
1295 /// the replacement, and the receipt count stays 1 instead of rejecting
1296 /// the rewrite as a duplicated summary.
1297 #[test]
1298 fn pasted_legacy_header_turn_is_content_in_a_post_provenance_history() {
1299 let pasted = format!(
1300 "{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\n\nEarlier turns of another session, pasted."
1301 );
1302 let original = vec![
1303 msg("user", "Run the suite now."),
1304 tool_use("live", "Bash", json!({"command": "cargo test"})),
1305 tool_result("live", "ok"),
1306 checkpoint("suite finished"),
1307 msg("assistant", "done"),
1308 msg("user", &pasted),
1309 ];
1310 assert!(
1311 !is_checkpoint_for_compaction(&msg("user", &pasted)),
1312 "the pasted turn alone carries no provenance block"
1313 );
1314 assert_eq!(
1315 last_round_start(&original),
1316 0,
1317 "the pasted turn must anchor like any other user turn"
1318 );
1319
1320 let retained = retain_user_messages(&original, 10_000, is_checkpoint_for_compaction);
1321 assert!(
1322 retained
1323 .iter()
1324 .any(|message| user_text_of(message).as_deref() == Some(pasted.as_str())),
1325 "the pasted turn must be retained verbatim: {retained:?}"
1326 );
1327
1328 let replacement = vec![
1329 checkpoint("second summary"),
1330 msg("user", "Run the suite now."),
1331 tool_use("live", "Bash", json!({"command": "cargo test"})),
1332 tool_result("live", "ok"),
1333 msg("assistant", "done"),
1334 msg("user", &pasted),
1335 ];
1336 validate_survival_contract(&original, &replacement, None, 20_000)
1337 .expect("a retained pasted-header turn must not break or lose the round");
1338
1339 let mut dropped = replacement.clone();
1340 dropped.pop();
1341 let error = validate_survival_contract(&original, &dropped, None, 20_000)
1342 .expect_err("dropping the pasted turn must fail the coverage floor");
1343 assert!(
1344 error.to_string().contains("user message was dropped"),
1345 "{error}"
1346 );
1347 }
1348
1349 #[test]
1350 fn compaction_retains_mixed_user_text_within_tool_pair_boundaries() {
1351 let first = msg("user", "Keep investigating.");
1352 let pasted = msg(
1353 "user",
1354 &format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\n\nMy exact wording."),
1355 );
1356 let mut old_call = tool_use("old", "File", json!({"path":"old"}));
1357 old_call
1358 .content
1359 .extend(msg("assistant", &"x".repeat(8_000)).content);
1360 let mut mixed = tool_result("old", "old output");
1361 mixed.content.extend(pasted.content.clone());
1362 let new_call = tool_use("new", "File", json!({"path":"new"}));
1363 let new_result = tool_result("new", "new output");
1364 let original = [
1365 first.clone(),
1366 old_call,
1367 mixed,
1368 new_call.clone(),
1369 new_result.clone(),
1370 ];
1371 let text = format!("{COMPACTION_SUMMARY_MARKER}: recent work");
1372
1373 assert_eq!(recent_tail_start(&original, 26), 3);
1374 let narrow = build_replacement_history(&original, &text, None, 256, 26).unwrap();
1375 assert_eq!(
1376 narrow,
1377 [
1378 first,
1379 pasted,
1380 new_call,
1381 new_result,
1382 checkpoint("recent work")
1383 ]
1384 );
1385
1386 let wide = build_replacement_history(&original, &text, None, 256, 10_000).unwrap();
1387 assert_eq!(&wide[..original.len()], original.as_slice());
1388 assert_eq!(wide.last(), Some(&checkpoint("recent work")));
1389 }
1390
1391 #[test]
1392 fn legacy_summary_requires_checkpoint_provenance() {
1393 use crate::compaction::retained_user_messages_in_era;
1394
1395 let text = "Conversation Summary (Auto-Generated)\n\nCondensed progress.";
1396 let user = msg("user", text);
1397 let carrier = compaction_checkpoint_message(&SystemPrompt::Text(text.into()));
1398 let history = [user.clone(), carrier];
1399 assert!(retained_user_messages_in_era(false, &history, 1_000).is_empty());
1400 assert_eq!(
1401 retained_user_messages_in_era(true, &history, 1_000),
1402 history
1403 );
1404 assert_eq!(
1405 retain_user_messages(&history, 1_000, is_checkpoint_for_compaction).as_slice(),
1406 std::slice::from_ref(&user)
1407 );
1408 assert_eq!(last_round_kept_count(&history), Some(1));
1409 assert!(!inspect_compaction_keep(std::slice::from_ref(&user)).has_checkpoint);
1410
1411 let text = format!("{COMPACTION_SUMMARY_MARKER}: new handoff");
1412 let replaced = build_replacement_history(&history, &text, None, 1_000, 1_000).unwrap();
1413 assert_eq!(replaced, [user, checkpoint("new handoff")]);
1414 }
1415
1416 #[derive(serde::Deserialize)]
1417 struct FixtureMatrix {
1418 schema_version: u32,
1419 cases: Vec<FixtureCase>,
1420 }
1421
1422 #[derive(serde::Deserialize)]
1423 struct FixtureCase {
1424 id: String,
1425 expect: String,
1426 #[serde(default)]
1427 anchors: Option<String>,
1428 original: Vec<Message>,
1429 replacement: Vec<Message>,
1430 #[serde(default)]
1431 last_round_start: Option<usize>,
1432 recent_tokens: usize,
1433 }
1434
1435 #[test]
1436 fn fixture_matrix_enforces_survival_contract() {
1437 let matrix: FixtureMatrix =
1438 serde_json::from_str(include_str!("fixtures/matrix.json")).expect("matrix.json");
1439 assert_eq!(matrix.schema_version, 2);
1440 assert!(
1441 matrix.cases.len() >= 8,
1442 "fixture matrix must cover last-round, toolless-tail, chat-only, anchor, and receipt cases"
1443 );
1444 for case in &matrix.cases {
1445 if let Some(start) = case.last_round_start {
1446 assert_eq!(
1447 last_round_start(&case.original),
1448 start,
1449 "{} last_round_start",
1450 case.id
1451 );
1452 }
1453 let result = validate_survival_contract(
1454 &case.original,
1455 &case.replacement,
1456 case.anchors.as_deref(),
1457 case.recent_tokens,
1458 );
1459 match case.expect.as_str() {
1460 "pass" => {
1461 result.unwrap_or_else(|error| panic!("{} should pass: {error}", case.id));
1462 }
1463 "fail" => {
1464 result.expect_err(&format!("{} should fail closed", case.id));
1465 }
1466 other => panic!("{}: unknown expect {other}", case.id),
1467 }
1468 }
1469 }
1470
1471 #[test]
1472 fn second_compact_does_not_duplicate_prior_summaries() {
1473 let first = vec![
1474 msg("user", "older"),
1475 msg("user", "Run the suite now."),
1476 msg("assistant", "Rerunning."),
1477 tool_use("live", "Bash", json!({"command": "cargo test"})),
1478 tool_result("live", "ok"),
1479 checkpoint("first handoff: suite still running"),
1480 ];
1481 let next = format!(
1482 "{COMPACTION_SUMMARY_MARKER}: second handoff with User-pinned anchors (verbatim):\nship 0.9.12"
1483 );
1484 let replaced = build_replacement_history(
1485 &first,
1486 &next,
1487 Some("ship 0.9.12"),
1488 crate::compaction::COMPACT_RETAINED_USER_MESSAGE_MAX_TOKENS,
1489 20_000,
1490 )
1491 .expect("second compact must keep last round and one receipt");
1492 let checkpoints = replaced
1493 .iter()
1494 .filter(|message| is_checkpoint_for_compaction(message))
1495 .count();
1496 assert_eq!(checkpoints, 1, "{replaced:?}");
1497 assert!(replaced.iter().any(|message| {
1498 message.content.iter().any(|block| {
1499 matches!(
1500 block,
1501 ContentBlock::ToolResult { tool_use_id, .. } if tool_use_id == "live"
1502 )
1503 })
1504 }));
1505 require_text_survives(&replaced, "ship 0.9.12", "pinned /anchor text").unwrap();
1506 }
1507 }
1508
1508 lines RUST