返回 CodeWhale
compaction.rs
根目录 / crates / engine / src / compaction.rs
1 //! Context compaction for long conversations.
2
3 use anyhow::Result;
4 use std::collections::HashMap;
5 use std::fmt::Write;
6 use std::sync::Arc;
7
8 use crate::core::model_client::ModelClient;
9 use codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL;
10 use codewhale_models::Role;
11 #[cfg(test)]
12 use codewhale_models::turn_classify::COMPACTION_SUMMARY_MARKER;
13 use codewhale_models::turn_classify::{
14 COMPACTION_CHECKPOINT_PROVENANCE, LEGACY_V2_COMPACTION_SUMMARY_MARKER,
15 is_wire_compaction_checkpoint_message,
16 };
17 use codewhale_models::{
18 CacheControl, ContentBlock, Message, MessageRequest, SystemBlock, SystemPrompt, Tool, Usage,
19 };
20 use codewhale_runtime::logging;
21
22 #[path = "compaction/last_round.rs"]
23 mod last_round;
24 #[path = "compaction/subagent_handles.rs"]
25 mod subagent_handles;
26 #[cfg(test)]
27 #[path = "compaction/survival_contract.rs"]
28 mod survival_contract;
29 pub use last_round::last_round_start;
30 pub use last_round::{
31 CompactionCoverage, CompactionKeep, CompactionPath, LastCompactionSnapshot,
32 inspect_compaction_keep, last_round_kept_count, pinned_anchors_text,
33 };
34
35 /// Configuration for conversation compaction behavior.
36 ///
37 /// v0.8.11 simplified this from the prior token-OR-message-count trigger
38 /// to a token-only trigger. The
39 /// `message_threshold` field was removed: its only purpose was to fire
40 /// compaction on long sessions of small messages, which is exactly the
41 /// case where rewriting the prefix cache is least valuable. Token
42 /// budget is the right signal; message count was a 128K-era heuristic.
43 #[derive(Debug, Clone, PartialEq)]
44 pub struct CompactionConfig {
45 pub enabled: bool,
46 pub token_threshold: usize,
47 pub model: String,
48 /// Exact route image-input fact for the summarizer's outbound history.
49 pub image_input: crate::model_profile::SupportState,
50 /// Route-effective context window. `None` preserves compatibility for
51 /// callers that have not resolved a provider route yet.
52 pub effective_context_window: Option<u32>,
53 pub cache_summary: bool,
54 /// Optional user-supplied focus for a manual `/compact <focus>`: injected
55 /// into the summary request so the checkpoint weights what the user
56 /// said matters. `None` for automatic compaction.
57 pub focus: Option<String>,
58 /// Runtime turn that owns provider calls made by this compaction pass.
59 /// `None` for the foreground TUI. This is accounting provenance only and
60 /// is never included in a provider request.
61 pub runtime_cost_owner: Option<String>,
62 /// Workspace root, used only to re-state the user's `/anchor` file after
63 /// the summary. `None` skips anchors.
64 pub workspace: Option<std::path::PathBuf>,
65 /// Standing operator instructions from `[compaction] summary_instructions`
66 /// (#5956), appended to the summarizer prompt on every pass — manual and
67 /// automatic. `None` keeps the built-in prompt byte-identical. A manual
68 /// `/compact <focus>` still composes after this text.
69 pub summary_instructions: Option<String>,
70 /// Verbatim retention budget for recent plain user messages in the
71 /// replacement history (`[compaction] retained_user_message_tokens`,
72 /// #5956). Defaults to [`COMPACT_RETAINED_USER_MESSAGE_MAX_TOKENS`].
73 pub retained_user_message_tokens: usize,
74 }
75
76 /// Host callback for user-visible progress during a compaction pass.
77 ///
78 /// Compaction runs inside the engine's provider boundary, where the engine
79 /// owns the only channel that reaches the person. Injecting a sink lets a
80 /// downgrade (re-encoding images after an HTTP 413, say) say what it is doing
81 /// while it is doing it, instead of surfacing only when the pass ends.
82 pub trait CompactionNoticeSink: Send + Sync + std::fmt::Debug {
83 /// Deliver one already-rendered, user-visible sentence.
84 fn notice(&self, message: String);
85 fn tool_projection_warning(&self, warning: codewhale_models::ToolProjectionWarning) {
86 self.notice(crate::core::events::render_tool_projection_warning(
87 &warning,
88 ));
89 }
90 /// Captured dispatch origin for a child; ordinary engines retain the existing billing path.
91 fn accounting_origin(&self) -> std::io::Result<Option<crate::cost_status::NativeUsageOrigin>> {
92 Ok(None)
93 }
94 /// Projection after the existing billing block has settled this exact response once.
95 fn settled_usage<'a>(
96 &'a self,
97 _record: &'a crate::cost_status::RuntimeUsageRecord,
98 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = std::io::Result<()>> + Send + 'a>> {
99 Box::pin(async { Ok(()) })
100 }
101 }
102
103 /// Host-prepared configuration carried from compaction eligibility through
104 /// the replacement-history commit.
105 #[derive(Clone)]
106 pub struct PreparedCompactionEnvelope {
107 pub config: CompactionConfig,
108 pub input_token_ratio: (usize, usize),
109 /// Durable handoff owner; set by the engine, never added to the stable prefix.
110 pub session_id: Option<String>,
111 /// Exact tool prefix of the interrupted request. A summary reply that
112 /// calls a tool is never executed; retaining schemas preserves cache reuse.
113 pub tools: Option<Vec<Tool>>,
114 /// Resolved reasoning tier the parent turn sends (#6540). Reasoning
115 /// routes render the effort into the head of the prompt, so a summary
116 /// request that omits it shares no cacheable prefix with the turn it
117 /// summarizes and re-bills the whole history uncached.
118 pub reasoning_effort: Option<String>,
119 pub image_cap: Option<usize>,
120 /// User-visible progress sink supplied by the host that owns the run
121 /// (the interactive engine, typically). `None` keeps every notice in the
122 /// log only — the pass itself never depends on it.
123 pub notice_sink: Option<Arc<dyn CompactionNoticeSink>>,
124 }
125
126 impl std::fmt::Debug for PreparedCompactionEnvelope {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 f.debug_struct("PreparedCompactionEnvelope")
129 .field("config", &self.config)
130 .field("input_token_ratio", &self.input_token_ratio)
131 .field("session_id", &self.session_id)
132 .field("tools", &self.tools)
133 .field("reasoning_effort", &self.reasoning_effort)
134 .field("image_cap", &self.image_cap)
135 .field("notice_sink", &self.notice_sink.as_ref().map(|_| "<sink>"))
136 .finish()
137 }
138 }
139
140 impl PartialEq for PreparedCompactionEnvelope {
141 /// The notice sink is host plumbing, not envelope content: two passes over
142 /// the same config are equal whether or not their host delivers notices.
143 fn eq(&self, other: &Self) -> bool {
144 self.config == other.config
145 && self.input_token_ratio == other.input_token_ratio
146 && self.session_id == other.session_id
147 && self.tools == other.tools
148 && self.reasoning_effort == other.reasoning_effort
149 && self.image_cap == other.image_cap
150 }
151 }
152
153 impl PreparedCompactionEnvelope {
154 #[must_use]
155 pub fn new(config: CompactionConfig) -> Self {
156 Self {
157 config,
158 input_token_ratio: (1, 1),
159 session_id: None,
160 tools: None,
161 reasoning_effort: None,
162 image_cap: None,
163 notice_sink: None,
164 }
165 }
166 }
167
168 impl Default for CompactionConfig {
169 fn default() -> Self {
170 Self {
171 // ON BY DEFAULT since v0.8.6 (#402 P0 survivability). v0.8.64
172 // resolves the user-facing default through the active model's
173 // known context window, while explicit `auto_compact = false`
174 // remains the opt-out. This fallback covers code paths that build
175 // a `CompactionConfig` directly; real per-model values are still
176 // derived through the threshold helpers.
177 enabled: true,
178 // v0.8.11: 50K was a 128K-era leftover that biased every
179 // unconfigured caller toward "compact almost immediately on large-context routes."
180 // Bumped to 800K (80% of a 1M window) so the fallback
181 // default matches the hard automatic compaction guardrail. This
182 // keeps replacement compaction a late continuity guardrail.
183 // Real call sites override this via
184 // `compaction_threshold_for_model_and_effort`.
185 token_threshold: 800_000,
186 model: DEFAULT_TEXT_MODEL.to_string(),
187 image_input: crate::model_profile::SupportState::Unknown,
188 effective_context_window: None,
189 cache_summary: true,
190 focus: None,
191 runtime_cost_owner: None,
192 workspace: None,
193 summary_instructions: None,
194 retained_user_message_tokens: COMPACT_RETAINED_USER_MESSAGE_MAX_TOKENS,
195 }
196 }
197 }
198
199 /// A provider can return HTTP success with an empty, non-text, or known
200 /// placeholder response. Committing that response would discard the useful
201 /// history while leaving only a placeholder checkpoint. Keep this deliberately
202 /// conservative: it is a corruption guard, not a prose-length or language
203 /// scorer.
204 const COMPACTION_LANGUAGE_CONTRACT: &str = "Use the natural language of the most recent \
205 substantive user message for reasoning and user-facing prose. Keep code, identifiers, paths, \
206 commands, logs, tool payloads, quotations, and the English headings verbatim. English \
207 headings are not a request to switch languages.";
208
209 /// Failure kind for compaction LLM calls (deterministic vs transient).
210 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
211 pub enum CompactionFailureKind {
212 /// Same payload will fail again — do not sleep/retry unchanged.
213 Deterministic,
214 /// May resolve on retry (network, rate limit, timeout).
215 Transient,
216 /// Context overflow — the selected summary span does not fit the route.
217 ContextOverflow,
218 }
219
220 impl CompactionFailureKind {
221 #[must_use]
222 pub fn is_transient(self) -> bool {
223 matches!(self, Self::Transient)
224 }
225 }
226
227 pub const KEEP_RECENT_MESSAGES: usize = 4;
228 const MIN_SUMMARIZE_MESSAGES: usize = 6;
229 const SUMMARY_TOOL_RESULT_SNIPPET_CHARS: usize = 240;
230 const TOOL_PRUNE_STOP_CHECK_BYTES: usize = 16 * 1024;
231 const RETAINED_TOOL_RESULT_MAX_CHARS: usize = 64 * 1024;
232 /// Token budget for the recent user messages retained verbatim in the
233 /// replacement history (Codex parity: COMPACT_USER_MESSAGE_MAX_TOKENS).
234 ///
235 /// This is now the *default* only: `[compaction] retained_user_message_tokens`
236 /// overrides it per session (#5956). Aliased to the config default so the two
237 /// names cannot drift apart.
238 pub const COMPACT_RETAINED_USER_MESSAGE_MAX_TOKENS: usize =
239 codewhale_runtime::config::DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS;
240 /// Handoff summarization prompt, appended to the live conversation as the
241 /// final user message. The headings are requested, not enforced:
242 /// `validate_compaction_summary` only rejects corrupt output, so a provider
243 /// that drifts from the layout still produces a usable note.
244 pub const COMPACT_PROMPT_OPENING: &str = "Summarize the earlier conversation so the user's \
245 task can continue alongside the retained recent messages.";
246
247 /// The note's layout, shared by the first request and the quality retry.
248 /// Each entry is a heading and what belongs under it.
249 const HANDOFF_SECTIONS: [(&str, &str); 4] = [
250 (
251 "Goal and constraints",
252 "the user's goal, corrections, decisions and explicit permissions or limits. Preserve \
253 important user wording exactly; never infer permission.",
254 ),
255 (
256 "Progress and evidence",
257 "work actually observed, with the supporting tool results and exact references. \
258 Distinguish verified results from assistant claims and earlier summary notes.",
259 ),
260 (
261 "Open work",
262 "unfinished requests, failures, unresolved decisions and processes that may still be \
263 running, with their check or stop handles when observed.",
264 ),
265 (
266 "Next steps and references",
267 "the next concrete actions and the exact paths, identifiers, commands and values \
268 needed to continue. Keep proposed actions distinct from completed work.",
269 ),
270 ];
271
272 const HANDOFF_FOLD_IN_RULE: &str = "If the history already holds an earlier handoff note, fold \
273 it in: carry forward what is still true, update what later work changed, and drop what is \
274 finished or superseded. Keep quoted user wording exact rather than paraphrasing it again. Do not \
275 copy the note's opening or closing lines or the user-pinned anchors; Codewhale adds those itself.";
276
277 const HANDOFF_CLOSING_RULE: &str = "Write about the task, not about condensing context. Be \
278 specific and brief. Copy commands, paths, commit IDs and numeric results exactly from the \
279 conversation; never invent them. A claim about tests, commits or file state needs the actual \
280 tool result, not an earlier assistant claim. Mark anything without that evidence unverified. \
281 Do not call tools.";
282
283 const HANDOFF_FOCUS_LINE: &str = "The user asked this handoff to focus on:";
284
285 fn handoff_sections_text() -> String {
286 let mut text = String::from("Use these headings and omit sections with nothing to report:");
287 for (heading, guidance) in HANDOFF_SECTIONS {
288 let _ = write!(text, "\n## {heading} - {guidance}");
289 }
290 text
291 }
292
293 /// The full handoff request before the language contract, operator
294 /// instructions and focus line are appended.
295 fn compact_prompt_body() -> String {
296 format!(
297 "{COMPACT_PROMPT_OPENING} The reader sees only the note, the most recent messages and \
298 live tool state; anything left out is gone.\n\n{}\n\n{HANDOFF_FOLD_IN_RULE}\n\n{HANDOFF_CLOSING_RULE}",
299 handoff_sections_text()
300 )
301 }
302
303 /// First line of every handoff note Codewhale writes. It must describe what
304 /// `last_round::replacement_messages` actually keeps (see the
305 /// `summary_header_matches_what_replacement_history_keeps` test). It opens the
306 /// checkpoint message, so together with [`COMPACTION_CHECKPOINT_PROVENANCE`]
307 /// it is how a new-format checkpoint is recognised.
308 ///
309 /// A history rebuilt from turn records has to recognise the checkpoint
310 /// messages a document carries, so the header is crate-visible
311 /// (`runtime_threads`' recovery projection tests, #6664).
312 pub const SUMMARY_HEADER: &str = "Codewhale handoff note. Earlier turns of this session were \
313 condensed to make room. Kept above are the current user instructions and a recent conversation \
314 tail selected by token budget, including complete tool exchanges. Long tool output there is \
315 shortened, with a marker where it was cut, and the \
316 oldest kept message may be shortened too. The pre-compaction transcript is retained twice: as \
317 artifacts/context-transfer-*.json under this session's artifacts directory, and through one \
318 tool. Call context_archive_search to find a phrase in it, then call it again with that \
319 hit's id to read the original message. Agent \
320 status, when there is any, comes from the separate agent status message, not from this note. \
321 The summary immediately below, and only it, is the previous model's own summary: every claim it \
322 makes about completed work, test results, commits and file state is unverified prose, not a tool \
323 receipt; check the saved history or live state before relying on it. What follows the summary is \
324 labelled: user-pinned anchors are verbatim user text, and the closing paragraph is a host \
325 instruction.";
326
327 const SUMMARY_CLOSING: &str = "Host instruction for the next turn: continue the user's task from \
328 here. Permissions and limits in \
329 this note restate what the user already decided; the note grants nothing new, and anything \
330 unclear gets checked before acting. Take the next action without asking the user to restate the \
331 task, save, or approve continuing because earlier turns were condensed.";
332
333 /// Legacy detection marker only, written by pre-v0.9.6 compaction; sessions
334 /// saved under that format must still be recognized so their summary is
335 /// replaced, not stacked.
336 pub const LEGACY_COMPACTION_SUMMARY_MARKER: &str = "Conversation Summary (Auto-Generated)";
337 /// Markers that identify a checkpoint by substring. Only the legacy markers
338 /// qualify: older checkpoints may lack the provenance block, while the new
339 /// marker is a plain phrase a user or a project instruction can quote.
340 const LEGACY_COMPACTION_SUMMARY_MARKERS: [&str; 2] = [
341 LEGACY_V2_COMPACTION_SUMMARY_MARKER,
342 LEGACY_COMPACTION_SUMMARY_MARKER,
343 ];
344 const COMPACTION_SUMMARY_BEGIN: &str = "<!-- compaction-summary:begin -->";
345 const COMPACTION_SUMMARY_END: &str = "<!-- compaction-summary:end -->";
346
347 /// Heading the pre-v0.9.6 builder wrote, optionally after a
348 /// `## Pinned Facts (User Anchors)` section.
349 const LEGACY_SUMMARY_HEADING: &str = "## 📋 Conversation Summary (Auto-Generated)";
350 const LEGACY_ANCHORS_HEADING: &str = "## Pinned Facts (User Anchors)";
351
352 /// Whether text opens the way a legacy checkpoint opened. A message that only
353 /// quotes a marker later in its text is the user's, not a checkpoint (#6680).
354 /// Pre-v0.9.6 checkpoints opened with [`LEGACY_SUMMARY_HEADING`], or with the
355 /// pinned-anchors section followed by that heading on its own line.
356 fn is_legacy_compaction_summary_text(text: &str) -> bool {
357 let text = text.trim_start();
358 LEGACY_COMPACTION_SUMMARY_MARKERS
359 .iter()
360 .any(|marker| text.starts_with(marker))
361 || text.starts_with(LEGACY_SUMMARY_HEADING)
362 || (text.starts_with(LEGACY_ANCHORS_HEADING)
363 && text
364 .lines()
365 .any(|line| line.trim_end() == LEGACY_SUMMARY_HEADING))
366 }
367
368 /// Byte offset of the earliest legacy marker in `text`. New-format carriers
369 /// are always wrapped in the begin/end delimiters, so a bare new marker in a
370 /// system prompt is host text (for example a project instruction quoting it)
371 /// and must not truncate the prompt.
372 fn legacy_summary_start(text: &str) -> Option<usize> {
373 LEGACY_COMPACTION_SUMMARY_MARKERS
374 .iter()
375 .filter_map(|marker| text.find(marker))
376 .min()
377 }
378
379 fn summary_section(text: &str) -> Option<&str> {
380 let begin = text.find(COMPACTION_SUMMARY_BEGIN)? + COMPACTION_SUMMARY_BEGIN.len();
381 let remainder = &text[begin..];
382 let end = remainder.find(COMPACTION_SUMMARY_END)?;
383 let summary = remainder[..end].trim();
384 (!summary.is_empty()).then_some(summary)
385 }
386
387 fn strip_summary_text(mut text: String) -> Option<String> {
388 while let Some(begin) = text.find(COMPACTION_SUMMARY_BEGIN) {
389 let after_begin = begin + COMPACTION_SUMMARY_BEGIN.len();
390 let end = text[after_begin..]
391 .find(COMPACTION_SUMMARY_END)
392 .map_or(text.len(), |offset| {
393 after_begin + offset + COMPACTION_SUMMARY_END.len()
394 });
395 text.replace_range(begin..end, "");
396 }
397 if let Some(marker) = legacy_summary_start(&text) {
398 text.truncate(marker);
399 }
400 let text = text.trim().to_string();
401 (!text.is_empty()).then_some(text)
402 }
403
404 /// Extract the persisted checkpoint payload from a legacy system-prompt
405 /// carrier. Runtime-thread storage used that carrier before checkpoints moved
406 /// into conversation history; the engine strips it before provider dispatch.
407 #[must_use]
408 pub fn extract_compaction_summary(prompt: Option<&SystemPrompt>) -> Option<SystemPrompt> {
409 match prompt? {
410 SystemPrompt::Text(text) => summary_section(text)
411 .map(str::to_string)
412 .or_else(|| legacy_summary_start(text).map(|start| text[start..].trim().to_string()))
413 .map(SystemPrompt::Text),
414 SystemPrompt::Blocks(blocks) => {
415 let blocks = blocks
416 .iter()
417 .filter_map(|block| {
418 let text = summary_section(&block.text)
419 .map(str::to_string)
420 .or_else(|| {
421 legacy_summary_start(&block.text)
422 .map(|start| block.text[start..].trim().to_string())
423 })?;
424 let mut summary = block.clone();
425 summary.text = text;
426 Some(summary)
427 })
428 .collect::<Vec<_>>();
429 (!blocks.is_empty()).then_some(SystemPrompt::Blocks(blocks))
430 }
431 }
432 }
433
434 /// Remove every committed compaction-summary block from a system prompt.
435 ///
436 /// Compaction commits exactly one live summary: the newest one replaces its
437 /// predecessors. Before this existed, each compaction appended another
438 /// summary block to the successor system prompt, so the stable prefix grew by
439 /// up to a full summary per pass — which re-latched compaction pressure and
440 /// retriggered compaction on the next turn, forever.
441 #[must_use]
442 pub fn strip_compaction_summaries(prompt: Option<&SystemPrompt>) -> Option<SystemPrompt> {
443 match prompt.cloned()? {
444 SystemPrompt::Text(text) => strip_summary_text(text).map(SystemPrompt::Text),
445 SystemPrompt::Blocks(blocks) => {
446 let blocks = blocks
447 .into_iter()
448 .filter_map(|mut block| {
449 block.text = strip_summary_text(block.text)?;
450 Some(block)
451 })
452 .collect::<Vec<_>>();
453 (!blocks.is_empty()).then_some(SystemPrompt::Blocks(blocks))
454 }
455 }
456 }
457
458 /// Flatten a committed summary prompt to the text stored in history.
459 #[must_use]
460 pub fn summary_prompt_text(prompt: &SystemPrompt) -> String {
461 match prompt {
462 SystemPrompt::Text(text) => text.clone(),
463 SystemPrompt::Blocks(blocks) => blocks
464 .iter()
465 .map(|block| block.text.as_str())
466 .collect::<Vec<_>>()
467 .join("\n\n"),
468 }
469 }
470
471 #[must_use]
472 pub fn compaction_checkpoint_message(prompt: &SystemPrompt) -> Message {
473 Message {
474 role: Role::User,
475 content: vec![
476 ContentBlock::Text {
477 text: summary_prompt_text(prompt),
478 cache_control: None,
479 },
480 ContentBlock::Text {
481 text: COMPACTION_CHECKPOINT_PROVENANCE.to_string(),
482 cache_control: None,
483 },
484 ],
485 }
486 }
487
488 /// Whether a history message is a compaction checkpoint. New-format
489 /// checkpoints are recognised only structurally (see
490 /// [`is_wire_compaction_checkpoint_message`]); substring matching is kept for
491 /// the two legacy markers, whose older checkpoints may lack provenance.
492 #[must_use]
493 pub fn is_compaction_checkpoint_message(message: &Message) -> bool {
494 is_wire_compaction_checkpoint_message(message)
495 || user_text_of(message).is_some_and(|text| is_legacy_compaction_summary_text(&text))
496 }
497
498 /// Whether this history already carries a provenance-stamped checkpoint.
499 ///
500 /// Restore uses this to prefer the stamped form for topology placement and
501 /// to resolve conflicts with the summary in the saved system prompt.
502 #[must_use]
503 pub fn history_is_post_provenance(messages: &[Message]) -> bool {
504 messages.iter().any(is_wire_compaction_checkpoint_message)
505 }
506
507 /// Checkpoint recognition for callers that supply the history's era.
508 #[must_use]
509 pub fn is_compaction_checkpoint_message_in_era(message: &Message, post_provenance: bool) -> bool {
510 if post_provenance {
511 is_wire_compaction_checkpoint_message(message)
512 } else {
513 is_compaction_checkpoint_message(message)
514 }
515 }
516
517 fn is_checkpoint_for_compaction(message: &Message) -> bool {
518 is_wire_compaction_checkpoint_message(message)
519 || matches!(
520 message.content.as_slice(),
521 [
522 ContentBlock::Text { text, cache_control: None },
523 ContentBlock::Text { text: provenance, cache_control: None }
524 ] if message.role == Role::User
525 && provenance == COMPACTION_CHECKPOINT_PROVENANCE
526 && is_legacy_compaction_summary_text(text)
527 )
528 }
529
530 /// Keep the checkpoint at its original historical boundary on session load.
531 /// Later user turns must remain after the saved compaction boundary. A
532 /// session saved before the Agent-topology placement anchor has its sidecar
533 /// moved to that anchor, so the first request after a restore is wire-legal
534 /// for strict paired chat templates; a restore without a saved checkpoint
535 /// only relocates and deletes nothing.
536 pub fn restore_compaction_checkpoint(
537 mut messages: Vec<Message>,
538 checkpoint: Option<&SystemPrompt>,
539 ) -> Vec<Message> {
540 crate::runtime_handoff::relocate_restored_compaction_topology(&mut messages);
541 let Some(checkpoint) = checkpoint else {
542 return messages;
543 };
544 let typed_position = messages.iter().position(is_checkpoint_for_compaction);
545 let checkpoint_index = if let Some(index) = typed_position {
546 messages.retain(|message| !is_checkpoint_for_compaction(message));
547 index
548 } else {
549 messages
550 .iter()
551 .position(is_compaction_checkpoint_message)
552 .unwrap_or(messages.len())
553 };
554 messages.insert(
555 checkpoint_index.min(messages.len()),
556 compaction_checkpoint_message(checkpoint),
557 );
558 messages
559 }
560
561 pub fn estimate_tokens_for_message(message: &Message, include_thinking: bool) -> usize {
562 message
563 .content
564 .iter()
565 .map(|c| match c {
566 ContentBlock::Text { text, .. } => estimate_message_text_tokens(text),
567 // Replay-capable routes retain reasoning even on text-only
568 // assistant messages and across later user turns.
569 ContentBlock::Thinking { thinking, .. } if include_thinking => {
570 estimate_message_text_tokens(thinking)
571 }
572 ContentBlock::Thinking { .. } => 0,
573 ContentBlock::ToolUse { input, .. } => estimate_json_tokens(input).unwrap_or(100),
574 ContentBlock::ToolResult {
575 content,
576 content_blocks,
577 ..
578 } => estimate_tool_result_tokens(content, content_blocks.as_deref()),
579 // An inline image is real input the model pays for; estimating it
580 // at 0 undercounts the budget and risks overflow in image-heavy
581 // sessions. Use a conservative flat per-image estimate (vision
582 // tiles are typically ~1k tokens); erring high compacts slightly
583 // early rather than overflowing.
584 ContentBlock::ImageUrl { .. } => IMAGE_TOKEN_ESTIMATE,
585 ContentBlock::ServerToolUse { input, .. } => {
586 estimate_json_tokens(input).unwrap_or_default()
587 }
588 ContentBlock::ToolSearchToolResult { content, .. }
589 | ContentBlock::CodeExecutionToolResult { content, .. }
590 | ContentBlock::WebSearchToolResult { content, .. }
591 | ContentBlock::WebFetchToolResult { content, .. } => {
592 estimate_json_tokens(content).unwrap_or_default()
593 }
594 ContentBlock::WebSearchCall {
595 sources,
596 page,
597 action,
598 ..
599 } => {
600 sources.as_ref().and_then(estimate_json_tokens).unwrap_or(0)
601 + page.as_ref().and_then(estimate_json_tokens).unwrap_or(0)
602 + action.as_ref().and_then(estimate_json_tokens).unwrap_or(0)
603 }
604 ContentBlock::ServerToolCalls { steps } => {
605 steps.iter().filter_map(estimate_json_tokens).sum()
606 }
607 ContentBlock::File { file_id } => estimate_message_text_tokens(file_id),
608 })
609 .sum::<usize>()
610 }
611
612 fn estimate_tool_result_tokens(content: &str, blocks: Option<&[serde_json::Value]>) -> usize {
613 let images = blocks
614 .unwrap_or_default()
615 .iter()
616 .filter(|block| block.get("type").and_then(serde_json::Value::as_str) == Some("image"))
617 .count();
618 estimate_message_text_tokens(content) + images * IMAGE_TOKEN_ESTIMATE
619 }
620
621 fn token_units(bytes: &[u8], ascii_per_token: usize) -> usize {
622 if bytes.is_ascii() {
623 return bytes.len();
624 }
625 bytes
626 .iter()
627 .map(|&byte| match byte {
628 0x00..=0x7f => 1,
629 0x80..=0xbf => 0,
630 _ => ascii_per_token,
631 })
632 .sum()
633 }
634
635 pub(crate) fn estimate_message_text_tokens(text: &str) -> usize {
636 token_units(text.as_bytes(), 4).div_ceil(4)
637 }
638
639 #[derive(Default)]
640 struct JsonTokenCounter(usize);
641
642 impl std::io::Write for JsonTokenCounter {
643 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
644 self.0 += token_units(bytes, 4);
645 Ok(bytes.len())
646 }
647
648 fn flush(&mut self) -> std::io::Result<()> {
649 Ok(())
650 }
651 }
652
653 pub(crate) fn estimate_json_tokens<T: serde::Serialize + ?Sized>(value: &T) -> Option<usize> {
654 let mut counter = JsonTokenCounter::default();
655 serde_json::to_writer(&mut counter, value).ok()?;
656 Some(counter.0.div_ceil(4))
657 }
658
659 /// Conservative flat token estimate for an inline image (`ContentBlock::ImageUrl`).
660 /// Vision models bill images by resized tile count; ~1k tokens is a safe
661 /// mid-range estimate that keeps the compaction trigger from under-reading an
662 /// image-heavy session.
663 const IMAGE_TOKEN_ESTIMATE: usize = 1000;
664
665 pub fn estimate_tokens(messages: &[Message]) -> usize {
666 // Count every retained reasoning
667 // block: DeepSeek/Kimi replay text-only assistant reasoning too. This
668 // route-neutral estimate cannot assume a transport will omit it.
669 messages
670 .iter()
671 .map(|message| estimate_tokens_for_message(message, true))
672 .sum()
673 }
674
675 pub fn message_has_tool_use(message: &Message) -> bool {
676 message
677 .content
678 .iter()
679 .any(|block| matches!(block, ContentBlock::ToolUse { .. }))
680 }
681
682 /// Conservative text estimate using three ASCII characters per token and one
683 /// token per non-ASCII scalar. Provider-billed prompt size still informs the
684 /// compaction trigger when the provider's tokenizer differs.
685 pub fn estimate_text_tokens_conservative(text: &str) -> usize {
686 token_units(text.as_bytes(), 3).div_ceil(3)
687 }
688
689 fn estimate_system_tokens_conservative(system: Option<&SystemPrompt>) -> usize {
690 match system {
691 Some(SystemPrompt::Text(text)) => estimate_text_tokens_conservative(text),
692 Some(SystemPrompt::Blocks(blocks)) => blocks
693 .iter()
694 .map(|block| estimate_text_tokens_conservative(&block.text))
695 .sum(),
696 None => 0,
697 }
698 }
699
700 /// Conservative estimate for full request input tokens (messages + system + framing).
701 #[must_use]
702 pub fn estimate_input_tokens_conservative(
703 messages: &[Message],
704 system: Option<&SystemPrompt>,
705 ) -> usize {
706 estimate_input_tokens_conservative_with_text(messages, system, "")
707 }
708
709 pub(crate) fn estimate_input_tokens_conservative_with_text(
710 messages: &[Message],
711 system: Option<&SystemPrompt>,
712 current_text: &str,
713 ) -> usize {
714 let has_draft = !current_text.trim().is_empty();
715 let draft_tokens = if has_draft {
716 estimate_message_text_tokens(current_text)
717 } else {
718 0
719 };
720 let message_tokens = estimate_tokens(messages)
721 .saturating_add(draft_tokens)
722 .saturating_mul(3)
723 .div_ceil(2);
724 let system_tokens = estimate_system_tokens_conservative(system);
725 let framing_overhead = messages
726 .len()
727 .saturating_add(usize::from(has_draft))
728 .saturating_mul(12)
729 .saturating_add(48);
730 message_tokens
731 .saturating_add(system_tokens)
732 .saturating_add(framing_overhead)
733 }
734
735 /// Best-effort estimate of real request input tokens, without the 1.5×
736 /// safety inflation used by overflow math.
737 ///
738 /// Compaction *pressure* compares against a threshold whose percentage means
739 /// "fraction of the context window" on the user-facing meter. Feeding the
740 /// inflated overflow estimate into that comparison made an 80% setting fire
741 /// at roughly half the real usage. Overflow protection keeps its inflated
742 /// estimator; the pressure trigger uses this one, preferring provider-billed
743 /// prompt tokens when the caller has them.
744 #[must_use]
745 pub fn estimate_input_tokens_for_pressure(
746 messages: &[Message],
747 system: Option<&SystemPrompt>,
748 ) -> usize {
749 let message_tokens = estimate_tokens(messages);
750 let system_tokens = estimate_system_tokens_conservative(system);
751 let framing_overhead = messages.len().saturating_mul(12).saturating_add(48);
752 message_tokens
753 .saturating_add(system_tokens)
754 .saturating_add(framing_overhead)
755 }
756
757 #[must_use]
758 pub fn estimate_request_input_tokens(
759 messages: &[Message],
760 system: Option<&SystemPrompt>,
761 tools: Option<&[Tool]>,
762 ) -> usize {
763 estimate_input_tokens_for_pressure(messages, system)
764 .saturating_add(tools.and_then(estimate_json_tokens).unwrap_or(0))
765 }
766
767 pub fn calibrate_token_estimate(estimate: usize, ratio: (usize, usize)) -> usize {
768 let (reported, estimated) = ratio;
769 if reported <= estimated || estimated == 0 {
770 return estimate;
771 }
772 usize::try_from((estimate as u128 * reported as u128).div_ceil(estimated as u128))
773 .unwrap_or(usize::MAX)
774 }
775
776 impl PreparedCompactionEnvelope {
777 fn retained_recent_tokens(&self, system: Option<&SystemPrompt>) -> usize {
778 let fixed = calibrate_token_estimate(
779 estimate_request_input_tokens(&[], system, self.tools.as_deref()),
780 self.input_token_ratio,
781 );
782 let budget = self
783 .config
784 .token_threshold
785 .saturating_sub(fixed)
786 .saturating_div(5)
787 .min(COMPACT_RETAINED_USER_MESSAGE_MAX_TOKENS);
788 let (reported, estimated) = self.input_token_ratio;
789 if reported <= estimated || estimated == 0 {
790 budget
791 } else {
792 usize::try_from(budget as u128 * estimated as u128 / reported as u128)
793 .unwrap_or(usize::MAX)
794 }
795 }
796 }
797
798 fn estimate_retained_floor_conservative(
799 messages: &[Message],
800 system_prompt: Option<&SystemPrompt>,
801 prepared: &PreparedCompactionEnvelope,
802 ) -> usize {
803 let config = &prepared.config;
804 let retained = last_round::replacement_messages(
805 messages,
806 config.retained_user_message_tokens,
807 prepared.retained_recent_tokens(system_prompt),
808 );
809 let retained_tokens = estimate_tokens(&retained).saturating_mul(3).div_ceil(2);
810 let framing = retained.len().saturating_mul(12).saturating_add(48);
811 let anchors = user_anchors_section(config.workspace.as_deref());
812 let summary_scaffolding_tokens =
813 estimate_text_tokens_conservative(&build_compaction_summary_block_text("", &anchors));
814
815 // Post-compaction the committed summary is REPLACED, not stacked, so prior
816 // summary blocks must not inflate the floor. Count only the exact installed
817 // scaffolding here; the model owns the concise summary length, just as it
818 // owns the answer length on an ordinary turn.
819 let retained_system_prompt = strip_compaction_summaries(system_prompt);
820 let floor = retained_tokens
821 .saturating_add(estimate_system_tokens_conservative(
822 retained_system_prompt.as_ref(),
823 ))
824 .saturating_add(framing)
825 .saturating_add(summary_scaffolding_tokens)
826 .saturating_add(estimate_request_input_tokens(
827 &[],
828 None,
829 prepared.tools.as_deref(),
830 ));
831 calibrate_token_estimate(floor, prepared.input_token_ratio)
832 }
833
834 /// Whether the current canonical request has reached the configured automatic
835 /// compaction pressure. This deliberately excludes eligibility/reclaimability:
836 /// local tool-result pruning uses it to decide when pressure has actually
837 /// cleared, even if the remaining transcript cannot support an LLM summary.
838 #[must_use]
839 pub fn compaction_pressure_reached(
840 messages: &[Message],
841 system_prompt: Option<&SystemPrompt>,
842 config: &CompactionConfig,
843 ) -> bool {
844 compaction_pressure_reached_with_billed(messages, system_prompt, config, None)
845 }
846
847 /// Pressure check that additionally honors provider-billed prompt tokens.
848 ///
849 /// Billed usage is the ground truth for how large the context actually is;
850 /// the estimator can undercount tokens and cannot see server-side
851 /// framing. Whichever signal is higher decides, so an undercounting estimate
852 /// cannot hide pressure the provider already billed for. Callers must only
853 /// pass a billed count that describes the message list being checked —
854 /// post-prune re-checks pass `None` and fall back to the estimate.
855 #[must_use]
856 pub fn compaction_pressure_reached_with_billed(
857 messages: &[Message],
858 system_prompt: Option<&SystemPrompt>,
859 config: &CompactionConfig,
860 billed_input_tokens: Option<u64>,
861 ) -> bool {
862 if !config.enabled {
863 return false;
864 }
865 let billed = billed_input_tokens
866 .and_then(|tokens| usize::try_from(tokens).ok())
867 .unwrap_or(0);
868 // Billing alone proving pressure short-circuits the walk (#perf-r5):
869 // `estimated.max(billed) >= threshold` is unconditionally true when
870 // `billed >= threshold`, so estimating cannot change the answer and the
871 // O(transcript) pass is skipped.
872 if billed >= config.token_threshold {
873 return true;
874 }
875 let estimated = estimate_input_tokens_for_pressure(messages, system_prompt);
876 estimated.max(billed) >= config.token_threshold
877 }
878
879 /// Estimate-only eligibility check ([`should_compact_with_billed`] with no
880 /// billed tokens): used by the request preview, where no provider bill exists.
881 pub fn should_compact(
882 messages: &[Message],
883 system_prompt: Option<&SystemPrompt>,
884 prepared: &PreparedCompactionEnvelope,
885 ) -> bool {
886 should_compact_with_billed(messages, system_prompt, prepared, None)
887 }
888
889 /// Why an over-pressure context still did not start an automatic pass.
890 ///
891 /// A refusal is not a bug by itself — each guard exists for a reason — but a
892 /// silent refusal is: the user watches a full context meter while
893 /// auto-compaction appears broken (#5577). Callers surface these.
894 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
895 pub enum CompactionRefusal {
896 /// Too few messages for a summary pass to mean anything.
897 TooFewMessages { count: usize },
898 /// The conservative retained floor (system prompt + kept messages +
899 /// summary allowance) cannot get below the trigger, so a pass would
900 /// recur on every step without relieving pressure.
901 RetainedFloor { floor: usize, threshold: usize },
902 }
903
904 /// Outcome of the automatic-compaction eligibility check.
905 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
906 pub enum CompactionDecision {
907 /// Disabled, or pressure not reached: nothing to do, nothing to explain.
908 NotNeeded,
909 /// Start a pass.
910 Compact,
911 /// Pressure is real but a guard declined; the reason names the guard.
912 Refused(CompactionRefusal),
913 }
914
915 /// Eligibility check that honors provider-billed prompt tokens for the
916 /// pressure gate, mirroring [`compaction_pressure_reached_with_billed`].
917 pub fn should_compact_with_billed(
918 messages: &[Message],
919 system_prompt: Option<&SystemPrompt>,
920 prepared: &PreparedCompactionEnvelope,
921 billed_input_tokens: Option<u64>,
922 ) -> bool {
923 matches!(
924 compaction_decision_with_billed(messages, system_prompt, prepared, billed_input_tokens),
925 CompactionDecision::Compact
926 )
927 }
928
929 /// Full eligibility decision, including *why* an over-pressure context was
930 /// refused, so hosts can tell the user instead of silently holding.
931 #[must_use]
932 pub fn compaction_decision_with_billed(
933 messages: &[Message],
934 system_prompt: Option<&SystemPrompt>,
935 prepared: &PreparedCompactionEnvelope,
936 billed_input_tokens: Option<u64>,
937 ) -> CompactionDecision {
938 let config = &prepared.config;
939 if !config.enabled {
940 return CompactionDecision::NotNeeded;
941 }
942 // Pressure gate + prune projection share one estimate (#perf-r5): both
943 // consume `estimate_input_tokens_for_pressure` over the same
944 // `(messages, system_prompt)`, a pure function, so it is computed at
945 // most once. `billed >= threshold` proves pressure without estimating
946 // (max is unconditionally >= threshold then); the estimate is deferred
947 // until something actually needs it — the prune projection below — so
948 // the billed-corner still reaches the TooFew and RetainedFloor guards
949 // unchanged, and skips the walk entirely when no prune candidates exist.
950 let billed = billed_input_tokens
951 .and_then(|tokens| usize::try_from(tokens).ok())
952 .unwrap_or(0);
953 let estimated: Option<usize> = if billed < config.token_threshold {
954 let estimate = calibrate_token_estimate(
955 estimate_request_input_tokens(messages, system_prompt, prepared.tools.as_deref()),
956 prepared.input_token_ratio,
957 );
958 if estimate.max(billed) < config.token_threshold {
959 return CompactionDecision::NotNeeded;
960 }
961 Some(estimate)
962 } else {
963 None
964 };
965
966 // The execution path mechanically prunes old verbose tool results before
967 // asking the model for a summary. Local pruning alone may be enough to
968 // clear pressure even when the transcript is too small for an LLM pass.
969 // Project that outcome from the measured plan — per-block deltas use the
970 // estimator's own arithmetic, so this equals re-estimating a pruned copy
971 // without cloning a multi-megabyte transcript on every step.
972 let recent_tokens = prepared.retained_recent_tokens(system_prompt);
973 let protected_window = messages
974 .len()
975 .saturating_sub(last_round::recent_tail_start(messages, recent_tokens));
976 let prune_plan = plan_tool_result_prunes(messages, protected_window);
977 if !prune_plan.is_empty() {
978 let estimate = match estimated {
979 Some(value) => value,
980 None => calibrate_token_estimate(
981 estimate_request_input_tokens(messages, system_prompt, prepared.tools.as_deref()),
982 prepared.input_token_ratio,
983 ),
984 };
985 let reclaimed_tokens: usize = prune_plan.iter().map(PlannedPrune::tokens_reclaimed).sum();
986 let projected = estimate.saturating_sub(calibrate_token_estimate(
987 reclaimed_tokens,
988 prepared.input_token_ratio,
989 ));
990 if projected < config.token_threshold.saturating_mul(4) / 5 {
991 return CompactionDecision::Compact;
992 }
993 }
994
995 if messages.len() < MIN_SUMMARIZE_MESSAGES {
996 return CompactionDecision::Refused(CompactionRefusal::TooFewMessages {
997 count: messages.len(),
998 });
999 }
1000
1001 // Reclaimability guard: do not start a pass whose replacement request
1002 // (system prompt + retained user messages + summary allowance)
1003 // cannot get below the trigger, or a large stable prefix would cause
1004 // auto-compaction on every tool step.
1005 let floor = estimate_retained_floor_conservative(messages, system_prompt, prepared);
1006 if floor >= config.token_threshold {
1007 return CompactionDecision::Refused(CompactionRefusal::RetainedFloor {
1008 floor,
1009 threshold: config.token_threshold,
1010 });
1011 }
1012 CompactionDecision::Compact
1013 }
1014
1015 /// Whether a compaction pass could shrink this history at all: enough
1016 /// messages to summarize, or old tool output to prune. A one- or two-message
1017 /// conversation that is over budget is over budget because of its fixed
1018 /// prefix or its newest message, and summarizing it only spends a model call
1019 /// before the same failure (experience mark 2).
1020 #[must_use]
1021 pub fn has_compactable_history(messages: &[Message]) -> bool {
1022 messages.len() >= MIN_SUMMARIZE_MESSAGES
1023 || !plan_tool_result_prunes(messages, KEEP_RECENT_MESSAGES).is_empty()
1024 }
1025
1026 fn truncate_chars(text: &str, max_chars: usize) -> &str {
1027 if max_chars == 0 {
1028 return "";
1029 }
1030 match text.char_indices().nth(max_chars) {
1031 Some((idx, _)) => &text[..idx],
1032 None => text,
1033 }
1034 }
1035
1036 fn tail_chars(text: &str, max_chars: usize) -> String {
1037 if max_chars == 0 {
1038 return String::new();
1039 }
1040 let total_chars = text.chars().count();
1041 if total_chars <= max_chars {
1042 return text.to_string();
1043 }
1044 let start_char = total_chars.saturating_sub(max_chars);
1045 let start_idx = text
1046 .char_indices()
1047 .nth(start_char)
1048 .map_or(0, |(idx, _)| idx);
1049 text[start_idx..].to_string()
1050 }
1051
1052 #[derive(Debug, Clone)]
1053 struct ToolUseInfo {
1054 name: String,
1055 key: String,
1056 args_preview: String,
1057 }
1058
1059 fn tool_use_key(name: &str, input: &serde_json::Value) -> String {
1060 format!(
1061 "{name}:{}",
1062 serde_json::to_string(input).unwrap_or_else(|_| input.to_string())
1063 )
1064 }
1065
1066 fn tool_args_preview(input: &serde_json::Value) -> String {
1067 let redacted = codewhale_config::persistence::redact_json_secrets(input);
1068 let raw = serde_json::to_string(&redacted).unwrap_or_else(|_| redacted.to_string());
1069 truncate_chars(&raw, 120).to_string()
1070 }
1071
1072 fn collect_tool_uses(
1073 messages: &[Message],
1074 ) -> HashMap<codewhale_models::ToolCallKey<'_>, Option<(&str, ToolUseInfo)>> {
1075 let mut tool_uses = HashMap::new();
1076 for message in messages {
1077 for block in &message.content {
1078 if let ContentBlock::ToolUse {
1079 id, name, input, ..
1080 } = block
1081 && let Some(key) = block.tool_call_key()
1082 && !key.as_str().trim().is_empty()
1083 {
1084 // Ambiguous old or malformed new history is left intact; a
1085 // later call must not supply the earlier result's metadata.
1086 tool_uses
1087 .entry(key)
1088 .and_modify(|entry| *entry = None)
1089 .or_insert_with(|| {
1090 Some((
1091 id.as_str(),
1092 ToolUseInfo {
1093 name: name.clone(),
1094 key: tool_use_key(name, input),
1095 args_preview: tool_args_preview(input),
1096 },
1097 ))
1098 });
1099 }
1100 }
1101 }
1102 tool_uses
1103 }
1104
1105 struct ToolResultPruneCandidate {
1106 message_idx: usize,
1107 block_idx: usize,
1108 key: String,
1109 tool_name: String,
1110 args_preview: String,
1111 original_len: usize,
1112 }
1113
1114 fn tool_result_content_blocks_len(content_blocks: Option<&[serde_json::Value]>) -> usize {
1115 content_blocks
1116 .and_then(|blocks| serde_json::to_vec(blocks).ok())
1117 .map_or(0, |bytes| bytes.len())
1118 }
1119
1120 #[cfg(test)]
1121 fn prune_tool_results(messages: &mut [Message], protected_window: usize) -> usize {
1122 prune_tool_results_until(messages, protected_window, |_, _| false)
1123 }
1124
1125 /// Mechanically prune old verbose tool results before paying for an LLM summary.
1126 ///
1127 /// The most recent `protected_window` messages stay byte-for-byte intact. Older
1128 /// duplicate tool results keep the freshest full body and replace earlier
1129 /// copies with one-line summaries; non-duplicate old results are summarized only
1130 /// when they exceed the normal summary snippet size.
1131 fn prune_tool_results_until<F>(
1132 messages: &mut [Message],
1133 protected_window: usize,
1134 mut should_stop: F,
1135 ) -> usize
1136 where
1137 F: FnMut(&[Message], usize) -> bool,
1138 {
1139 let plan = plan_tool_result_prunes(messages, protected_window);
1140 let mut bytes_saved = 0usize;
1141 for planned in plan {
1142 if let ContentBlock::ToolResult {
1143 content,
1144 content_blocks,
1145 ..
1146 } = &mut messages[planned.message_idx].content[planned.block_idx]
1147 {
1148 bytes_saved = bytes_saved.saturating_add(planned.bytes_reclaimed());
1149 *content = planned.summary;
1150 *content_blocks = None;
1151
1152 if should_stop(messages, bytes_saved) {
1153 break;
1154 }
1155 }
1156 }
1157 bytes_saved
1158 }
1159
1160 /// One tool-result replacement the pruner has decided on, measured up front
1161 /// so eligibility checks can project the outcome without cloning a
1162 /// multi-megabyte transcript ([`compaction_decision_with_billed`] used to
1163 /// copy the entire message list every over-pressure step just to ask "would
1164 /// pruning be enough?").
1165 struct PlannedPrune {
1166 message_idx: usize,
1167 block_idx: usize,
1168 summary: String,
1169 content_len: usize,
1170 blocks_len: usize,
1171 original_tokens: usize,
1172 }
1173
1174 impl PlannedPrune {
1175 /// Byte reduction this replacement realizes, matching the pruner's
1176 /// accounting exactly.
1177 fn bytes_reclaimed(&self) -> usize {
1178 self.content_len
1179 .saturating_sub(self.summary.len())
1180 .saturating_add(self.blocks_len)
1181 }
1182
1183 /// Estimator-token reduction, using the same per-block arithmetic as
1184 /// [`estimate_tokens_for_message`] so a projection built from these
1185 /// deltas equals re-estimating the pruned transcript.
1186 fn tokens_reclaimed(&self) -> usize {
1187 self.original_tokens
1188 .saturating_sub(estimate_message_text_tokens(&self.summary))
1189 }
1190 }
1191
1192 /// Decide, without mutating anything, which old tool results pruning would
1193 /// replace. The most recent `protected_window` messages stay untouched; older
1194 /// duplicate results keep the freshest full body; non-duplicates are replaced
1195 /// only when they exceed the summary snippet size.
1196 fn plan_tool_result_prunes(messages: &[Message], protected_window: usize) -> Vec<PlannedPrune> {
1197 let cutoff = messages.len().saturating_sub(protected_window);
1198 if cutoff == 0 {
1199 return Vec::new();
1200 }
1201
1202 let tool_uses = collect_tool_uses(messages);
1203 let mut candidates = Vec::new();
1204 let mut latest_by_key: HashMap<String, usize> = HashMap::new();
1205 let mut count_by_key: HashMap<String, usize> = HashMap::new();
1206
1207 for (message_idx, message) in messages.iter().take(cutoff).enumerate() {
1208 for (block_idx, block) in message.content.iter().enumerate() {
1209 let ContentBlock::ToolResult {
1210 tool_use_id,
1211 content,
1212 content_blocks,
1213 ..
1214 } = block
1215 else {
1216 continue;
1217 };
1218 let Some((provider_id, info)) = block
1219 .tool_call_key()
1220 .and_then(|key| tool_uses.get(&key))
1221 .and_then(Option::as_ref)
1222 else {
1223 continue;
1224 };
1225 if provider_id != &tool_use_id.as_str() {
1226 continue;
1227 }
1228 latest_by_key.insert(info.key.clone(), message_idx);
1229 *count_by_key.entry(info.key.clone()).or_insert(0) += 1;
1230 candidates.push(ToolResultPruneCandidate {
1231 message_idx,
1232 block_idx,
1233 key: info.key.clone(),
1234 tool_name: info.name.clone(),
1235 args_preview: info.args_preview.clone(),
1236 original_len: content
1237 .len()
1238 .saturating_add(tool_result_content_blocks_len(content_blocks.as_deref())),
1239 });
1240 }
1241 }
1242
1243 // The maps above are fully populated before planning completes, so the order
1244 // below only changes which message bytes are rewritten first. Planning from
1245 // newest to oldest lets the pruner stop as soon as enough bytes were saved,
1246 // preserving the earlier JSON request prefix for byte-level KV caches.
1247 candidates.reverse();
1248
1249 let mut plan = Vec::new();
1250 for candidate in candidates {
1251 let duplicate_count = count_by_key.get(&candidate.key).copied().unwrap_or(0);
1252 let is_latest_duplicate = duplicate_count > 1
1253 && latest_by_key.get(&candidate.key) == Some(&candidate.message_idx);
1254 if is_latest_duplicate {
1255 continue;
1256 }
1257 if duplicate_count <= 1 && candidate.original_len <= SUMMARY_TOOL_RESULT_SNIPPET_CHARS {
1258 continue;
1259 }
1260
1261 let summary = format!(
1262 "[{}] tool result pruned ({} bytes; args: {})",
1263 candidate.tool_name, candidate.original_len, candidate.args_preview
1264 );
1265 if summary.len() >= candidate.original_len {
1266 continue;
1267 }
1268
1269 let ContentBlock::ToolResult {
1270 content,
1271 content_blocks,
1272 ..
1273 } = &messages[candidate.message_idx].content[candidate.block_idx]
1274 else {
1275 continue;
1276 };
1277 plan.push(PlannedPrune {
1278 message_idx: candidate.message_idx,
1279 block_idx: candidate.block_idx,
1280 summary,
1281 content_len: content.len(),
1282 blocks_len: tool_result_content_blocks_len(content_blocks.as_deref()),
1283 original_tokens: estimate_tool_result_tokens(content, content_blocks.as_deref()),
1284 });
1285 }
1286 plan
1287 }
1288
1289 fn truncate_retained_block(label: &str, content: &mut String, max_chars: usize) -> bool {
1290 let char_count = content.chars().count();
1291 if char_count <= max_chars {
1292 return false;
1293 }
1294
1295 let snippet_budget = max_chars.saturating_sub(256).max(1024);
1296 let head_chars = snippet_budget / 2;
1297 let tail_chars_budget = snippet_budget.saturating_sub(head_chars);
1298 let head = truncate_chars(content, head_chars).to_string();
1299 let tail = tail_chars(content, tail_chars_budget);
1300 *content =
1301 format!("[{label} retained-history truncated from {char_count} chars]\n{head}\n…\n{tail}");
1302 true
1303 }
1304
1305 // Retained reasoning is replay protocol even without a signature (DeepSeek
1306 // tool turns). Summarize older exchanges as units; do not rewrite their peers.
1307 fn sanitize_retained_messages(mut messages: Vec<Message>) -> Vec<Message> {
1308 for message in &mut messages {
1309 for block in &mut message.content {
1310 if let ContentBlock::ToolResult {
1311 content,
1312 content_blocks,
1313 ..
1314 } = block
1315 && truncate_retained_block("tool result", content, RETAINED_TOOL_RESULT_MAX_CHARS)
1316 {
1317 *content_blocks = None;
1318 }
1319 }
1320 }
1321 messages
1322 }
1323
1324 /// Result of a compaction operation with metadata.
1325 #[derive(Debug)]
1326 pub struct CompactionResult {
1327 /// Compacted messages
1328 pub messages: Vec<Message>,
1329 /// Host-persistence copy of the history checkpoint.
1330 pub summary_prompt: Option<SystemPrompt>,
1331 /// Number of retries used before success
1332 pub retries_used: u32,
1333 /// Last-round coverage for inspector receipts.
1334 pub coverage: CompactionCoverage,
1335 }
1336
1337 #[cfg(test)]
1338 fn classify_compaction_failure(e: &anyhow::Error) -> CompactionFailureKind {
1339 if let Some(error) = llm_error_in_chain(e) {
1340 return match error {
1341 crate::llm_client::LlmError::ContextLengthError(_) => {
1342 CompactionFailureKind::ContextOverflow
1343 }
1344 crate::llm_client::LlmError::QuotaExhausted(_) => CompactionFailureKind::Deterministic,
1345 error if error.is_retryable() => CompactionFailureKind::Transient,
1346 _ => CompactionFailureKind::Deterministic,
1347 };
1348 }
1349
1350 CompactionFailureKind::Deterministic
1351 }
1352
1353 fn llm_error_in_chain(error: &anyhow::Error) -> Option<&crate::llm_client::LlmError> {
1354 error
1355 .chain()
1356 .find_map(|cause| cause.downcast_ref::<crate::llm_client::LlmError>())
1357 }
1358
1359 /// Record and render a compaction failure as actionable, credential-safe text.
1360 ///
1361 /// This classifies only the error supplied by the failed request; it never
1362 /// infers a cause from later provider failures. Unknown diagnostics stay
1363 /// visible after central secret/path redaction, and the same safe detail is
1364 /// written to the runtime log so a transient status message remains auditable.
1365 #[must_use]
1366 pub fn report_compaction_failure(
1367 prefix: &str,
1368 id: &str,
1369 auto: bool,
1370 error: &anyhow::Error,
1371 ) -> String {
1372 let raw = error.to_string();
1373 let safe_raw = codewhale_runtime::safe_label::safe_error_text(&raw);
1374 tracing::warn!(
1375 compaction_id = %id,
1376 auto,
1377 error = %safe_raw,
1378 "context compaction failed"
1379 );
1380 let detail = match llm_error_in_chain(error) {
1381 Some(crate::llm_client::LlmError::QuotaExhausted(_)) => {
1382 "provider plan quota exhausted — switch provider/model or renew the provider plan"
1383 .to_string()
1384 }
1385 Some(crate::llm_client::LlmError::RateLimited { .. }
1386 | crate::llm_client::LlmError::QuotaWindow { .. }) => {
1387 "provider rate limit blocked making room — retry after the limit resets or switch provider/model"
1388 .to_string()
1389 }
1390 Some(crate::llm_client::LlmError::AuthenticationError(_)) => {
1391 "provider authentication failed — sign in or replace the credential, then retry"
1392 .to_string()
1393 }
1394 Some(crate::llm_client::LlmError::AuthorizationError(_)) => {
1395 "provider authorization rejected making room — verify account access or switch provider/model"
1396 .to_string()
1397 }
1398 _ => match codewhale_error_taxonomy::classify_error_message(&raw) {
1399 codewhale_error_taxonomy::ErrorCategory::RateLimit => {
1400 "provider rate limit blocked making room — retry after the limit resets or switch provider/model"
1401 .to_string()
1402 }
1403 codewhale_error_taxonomy::ErrorCategory::Authentication => {
1404 "provider authentication failed — sign in or replace the credential, then retry"
1405 .to_string()
1406 }
1407 codewhale_error_taxonomy::ErrorCategory::Authorization => {
1408 "provider authorization rejected making room — verify account access or switch provider/model"
1409 .to_string()
1410 }
1411 _ => safe_raw,
1412 },
1413 };
1414
1415 format!("{prefix}: {detail}")
1416 }
1417
1418 #[cfg(test)]
1419 fn is_transient_error(e: &anyhow::Error) -> bool {
1420 classify_compaction_failure(e).is_transient()
1421 }
1422
1423 /// Compact messages for one replacement pass.
1424 ///
1425 /// # Safety
1426 /// - Never panics
1427 /// - Never corrupts the original messages (returns error instead)
1428 ///
1429 /// `invocation_usage` retains every decoded response, including rejected
1430 /// summaries, across retries and cancellation of this future.
1431 pub async fn compact_messages_safe(
1432 client: &dyn ModelClient,
1433 messages: &[Message],
1434 system_prompt: Option<&SystemPrompt>,
1435 prepared: &PreparedCompactionEnvelope,
1436 invocation_usage: &mut Usage,
1437 ) -> Result<CompactionResult> {
1438 // Persist the complete pre-compaction history before any pruning or provider
1439 // call. Failure leaves the original context intact. The model-authored
1440 // handoff is saved separately before replacement is returned to the engine.
1441 let checkpoint_id = uuid::Uuid::new_v4().to_string();
1442 if let Some(session_id) = prepared.session_id.clone() {
1443 let messages = messages.to_vec();
1444 let checkpoint_id = checkpoint_id.clone();
1445 codewhale_runtime::runtime_control::owner_work(move || {
1446 let bytes = serde_json::to_vec(&codewhale_config::persistence::redact_json_secrets(
1447 &serde_json::to_value(&messages)?,
1448 ))?;
1449 codewhale_runtime::artifacts::write_session_relative_immutable(
1450 &session_id,
1451 &std::path::PathBuf::from("artifacts")
1452 .join(format!("context-transfer-{checkpoint_id}.json")),
1453 &bytes,
1454 )?;
1455 Ok(())
1456 })
1457 .await?;
1458 }
1459
1460 let config = &prepared.config;
1461 let recent_tokens = prepared.retained_recent_tokens(system_prompt);
1462 let protected_window = messages
1463 .len()
1464 .saturating_sub(last_round::recent_tail_start(messages, recent_tokens));
1465 let estimate = |messages: &[Message]| {
1466 calibrate_token_estimate(
1467 estimate_request_input_tokens(messages, system_prompt, prepared.tools.as_deref()),
1468 prepared.input_token_ratio,
1469 )
1470 };
1471 let was_over_threshold = estimate(messages) >= config.token_threshold;
1472 // Leave room for useful work after a local prune. Clearing the trigger
1473 // by a few tokens caused another prefix rewrite on the next tool result.
1474 let prune_target = config.token_threshold.saturating_mul(4) / 5;
1475 let mut pruned_messages = messages.to_vec();
1476 let mut now_under_threshold = false;
1477 let mut next_stop_check_bytes = 0usize;
1478 let pruned_bytes = prune_tool_results_until(
1479 &mut pruned_messages,
1480 protected_window,
1481 |candidate_messages, bytes_saved| {
1482 if !was_over_threshold || bytes_saved < next_stop_check_bytes {
1483 return false;
1484 }
1485
1486 // Stop at the first suffix-side prune check that clears the target.
1487 // The check itself is a full compaction-plan pass, so bound it by saved
1488 // bytes instead of running it after every candidate in huge sessions.
1489 next_stop_check_bytes = bytes_saved.saturating_add(TOOL_PRUNE_STOP_CHECK_BYTES);
1490 now_under_threshold = estimate(candidate_messages) < prune_target;
1491 now_under_threshold
1492 },
1493 );
1494 if was_over_threshold && pruned_bytes > 0 && !now_under_threshold {
1495 // The throttled in-loop check may skip the exact candidate that clears the
1496 // budget. Do one final pass so a successful local prune still avoids LLM compaction.
1497 now_under_threshold = estimate(&pruned_messages) < prune_target;
1498 }
1499
1500 if pruned_bytes > 0 {
1501 logging::info(format!(
1502 "Local tool-result prune saved {pruned_bytes} bytes before LLM compaction"
1503 ));
1504 if was_over_threshold && now_under_threshold {
1505 let kept = sanitize_retained_messages(pruned_messages);
1506 last_round::validate_retained_coverage(messages, &kept, recent_tokens)?;
1507 let anchors_chars = match config.workspace.clone() {
1508 Some(workspace) => {
1509 codewhale_runtime::runtime_control::owner_work(move || {
1510 Ok(pinned_anchors_text(Some(&workspace))
1511 .map(|text| text.chars().count())
1512 .unwrap_or(0))
1513 })
1514 .await?
1515 }
1516 None => 0,
1517 };
1518 let coverage = last_round::measure_coverage(
1519 messages,
1520 &kept,
1521 CompactionPath::PruneOnly,
1522 anchors_chars,
1523 );
1524 return Ok(CompactionResult {
1525 messages: kept,
1526 summary_prompt: None,
1527 retries_used: 0,
1528 coverage,
1529 });
1530 }
1531 }
1532
1533 let mut quality_retries = 0u32;
1534 let (msgs, prompt, mut coverage) = compact_messages_with_metadata(
1535 client,
1536 // The selected older span uses original evidence, including prior
1537 // checkpoints. The recent tail survives separately in replacement.
1538 messages,
1539 system_prompt,
1540 prepared,
1541 &mut quality_retries,
1542 invocation_usage,
1543 )
1544 .await?;
1545 let kept = sanitize_retained_messages(msgs);
1546 last_round::validate_retained_coverage(messages, &kept, recent_tokens)?;
1547 if config.enabled && was_over_threshold && estimate(&kept) >= estimate(messages) {
1548 anyhow::bail!(
1549 "Making room did not shrink the context; the original conversation was preserved."
1550 );
1551 }
1552 let keep: CompactionKeep = inspect_compaction_keep(&kept);
1553 coverage.last_round_messages = keep.last_round_messages;
1554 coverage.last_round_tool_results = keep.last_round_tool_results;
1555 coverage.last_round_assistant = keep.last_round_assistant;
1556 if let (Some(session_id), Some(summary)) = (prepared.session_id.clone(), prompt.as_ref()) {
1557 let text = summary_prompt_text(summary);
1558 let checkpoint_id = checkpoint_id.clone();
1559 codewhale_runtime::runtime_control::owner_work(move || {
1560 let redacted = codewhale_config::persistence::redact_json_secrets(
1561 &serde_json::Value::String(text),
1562 );
1563 codewhale_runtime::artifacts::write_session_relative_immutable(
1564 &session_id,
1565 &std::path::PathBuf::from("artifacts")
1566 .join(format!("context-transfer-{checkpoint_id}.md")),
1567 redacted.as_str().unwrap_or_default().as_bytes(),
1568 )?;
1569 Ok(())
1570 })
1571 .await?;
1572 }
1573 Ok(CompactionResult {
1574 messages: kept,
1575 summary_prompt: prompt,
1576 retries_used: quality_retries,
1577 coverage,
1578 })
1579 }
1580
1581 pub fn build_compaction_summary_block_text(summary: &str, anchors: &str) -> String {
1582 let summary = summary.trim();
1583 let summary = if summary.is_empty() {
1584 "(no summary available)"
1585 } else {
1586 summary
1587 };
1588 let mut text = format!("{SUMMARY_HEADER}\n\n{summary}");
1589 text.push_str(anchors);
1590 text.push_str("\n\n");
1591 text.push_str(SUMMARY_CLOSING);
1592 text
1593 }
1594
1595 /// Codex-parity replacement history: the most recent user-role messages,
1596 /// selected newest-first within a fixed token budget and restored to
1597 /// transcript order. Content boundaries carry runtime provenance and image
1598 /// turns, so structured messages are retained whole or dropped whole. Only a
1599 /// single text block can be truncated to fit the remaining budget.
1600 /// Result blocks answer a tool call that lives in an earlier message. A
1601 /// retained older turn has already lost that call to the summary, so a kept
1602 /// result block becomes an orphan providers reject outright (#6119).
1603 fn is_orphaned_result_block(block: &ContentBlock) -> bool {
1604 matches!(
1605 block,
1606 ContentBlock::ToolResult { .. }
1607 | ContentBlock::ToolSearchToolResult { .. }
1608 | ContentBlock::CodeExecutionToolResult { .. }
1609 | ContentBlock::WebSearchToolResult { .. }
1610 | ContentBlock::WebFetchToolResult { .. }
1611 )
1612 }
1613
1614 #[cfg(any(test, feature = "test-support"))]
1615 pub fn retained_user_messages(messages: &[Message], max_tokens: usize) -> Vec<Message> {
1616 retained_user_messages_in_era(history_is_post_provenance(messages), messages, max_tokens)
1617 }
1618
1619 /// Select retained user messages using the era of the full history.
1620 pub fn retained_user_messages_in_era(
1621 post_provenance: bool,
1622 messages: &[Message],
1623 max_tokens: usize,
1624 ) -> Vec<Message> {
1625 retain_user_messages(messages, max_tokens, |message| {
1626 is_compaction_checkpoint_message_in_era(message, post_provenance)
1627 })
1628 }
1629
1630 fn retain_user_messages(
1631 messages: &[Message],
1632 max_tokens: usize,
1633 is_checkpoint: impl Fn(&Message) -> bool,
1634 ) -> Vec<Message> {
1635 let mut selected: Vec<Message> = Vec::new();
1636 let mut remaining = max_tokens;
1637 for msg in messages.iter().rev() {
1638 if remaining == 0 {
1639 break;
1640 }
1641 if msg.role != Role::User
1642 || codewhale_models::turn_classify::is_runtime_owned_user_message(msg)
1643 || is_checkpoint(msg)
1644 || (user_text_of(msg).is_none()
1645 && !msg
1646 .content
1647 .iter()
1648 .any(|block| matches!(block, ContentBlock::ImageUrl { .. })))
1649 {
1650 continue;
1651 }
1652 let tokens: usize = msg
1653 .content
1654 .iter()
1655 .map(|block| match block {
1656 ContentBlock::Text { text, .. } => estimate_text_tokens_conservative(text),
1657 ContentBlock::ImageUrl { .. } => IMAGE_TOKEN_ESTIMATE,
1658 _ => 0,
1659 })
1660 .sum();
1661 let mut retained = msg.clone();
1662 if tokens <= remaining {
1663 // Keep the text and images; never a result block whose call was
1664 // summarized away with the region around it (#6119).
1665 retained
1666 .content
1667 .retain(|block| !is_orphaned_result_block(block));
1668 remaining -= tokens;
1669 } else {
1670 let [ContentBlock::Text { text, .. }] = retained.content.as_mut_slice() else {
1671 // Never flatten or partially retain an engine metadata block:
1672 // that would turn runtime-owned traffic into a user prompt.
1673 break;
1674 };
1675 let limit = remaining.saturating_mul(3);
1676 let mut units = 0;
1677 if let Some((end, _)) = text.char_indices().find(|(_, ch)| {
1678 units += if ch.is_ascii() { 1 } else { 3 };
1679 units > limit
1680 }) {
1681 text.truncate(end);
1682 }
1683 remaining = 0;
1684 }
1685 selected.push(retained);
1686 }
1687 selected.reverse();
1688 selected
1689 }
1690
1691 /// User-pinned facts from `/anchor` (`.codewhale/anchors.md`). These are the
1692 /// user's own words, re-stated after the summary because the command promises
1693 /// they survive compaction.
1694 fn anchors_section_text(anchors: Option<&str>) -> String {
1695 match anchors {
1696 Some(contents) => format!("\n\nUser-pinned anchors (verbatim):\n{contents}"),
1697 None => String::new(),
1698 }
1699 }
1700
1701 fn user_anchors_section(workspace: Option<&std::path::Path>) -> String {
1702 anchors_section_text(pinned_anchors_text(workspace).as_deref())
1703 }
1704
1705 #[cfg(test)]
1706 async fn compact_messages(
1707 client: &dyn ModelClient,
1708 messages: &[Message],
1709 config: &CompactionConfig,
1710 ) -> Result<(Vec<Message>, Option<SystemPrompt>, Vec<Message>)> {
1711 let mut quality_retries = 0;
1712 let mut invocation_usage = Usage::default();
1713 let (messages, summary_prompt, _coverage) = compact_messages_with_metadata(
1714 client,
1715 messages,
1716 None,
1717 &PreparedCompactionEnvelope::new(config.clone()),
1718 &mut quality_retries,
1719 &mut invocation_usage,
1720 )
1721 .await?;
1722 Ok((messages, summary_prompt, Vec::new()))
1723 }
1724
1725 async fn compact_messages_with_metadata(
1726 client: &dyn ModelClient,
1727 messages: &[Message],
1728 system_prompt: Option<&SystemPrompt>,
1729 prepared: &PreparedCompactionEnvelope,
1730 quality_retries: &mut u32,
1731 invocation_usage: &mut Usage,
1732 ) -> Result<(Vec<Message>, Option<SystemPrompt>, CompactionCoverage)> {
1733 if messages.is_empty() {
1734 return Ok((Vec::new(), None, CompactionCoverage::default()));
1735 }
1736
1737 let config = &prepared.config;
1738 let recent_tokens = prepared.retained_recent_tokens(system_prompt);
1739 let summary_end = last_round::recent_tail_start(messages, recent_tokens);
1740 let mut selected_indices = (0..messages.len())
1741 .filter(|&idx| idx < summary_end || is_checkpoint_for_compaction(&messages[idx]))
1742 .collect::<Vec<_>>();
1743 if selected_indices.is_empty() {
1744 selected_indices.extend(0..messages.len());
1745 }
1746 let summary_messages = if config.image_input == crate::model_profile::SupportState::Unsupported
1747 {
1748 let mut summary_messages = selected_indices
1749 .into_iter()
1750 .map(|idx| messages[idx].clone())
1751 .collect::<Vec<_>>();
1752 let stripped_images = crate::image_attach::strip_images_when_unsupported(
1753 &mut summary_messages,
1754 config.image_input,
1755 &config.model,
1756 );
1757 if stripped_images > 0 {
1758 logging::warn(format!(
1759 "Compaction omitted {stripped_images} image block(s) unsupported by its route"
1760 ));
1761 }
1762 summary_messages
1763 } else if let Some(cap) = prepared.image_cap
1764 && codewhale_models::image_window::count_request_images(messages) > cap
1765 {
1766 let images_before_cap: usize = selected_indices
1767 .iter()
1768 .map(|&idx| {
1769 codewhale_models::image_window::count_request_images(std::slice::from_ref(
1770 &messages[idx],
1771 ))
1772 })
1773 .sum();
1774 let mut capped_messages = messages.to_vec();
1775 let window = codewhale_models::image_window::cap_request_images(&mut capped_messages, cap);
1776 let summary_messages = selected_indices
1777 .into_iter()
1778 .map(|idx| capped_messages[idx].clone())
1779 .collect::<Vec<_>>();
1780 let images_after_cap =
1781 codewhale_models::image_window::count_request_images(&summary_messages);
1782 let summary_elided = images_before_cap.saturating_sub(images_after_cap);
1783 if summary_elided > 0 {
1784 let message = format!(
1785 "Making room: the summary request sends the newest {} of {} images; {} older go as text notes (limit {} per request).",
1786 images_after_cap, images_before_cap, summary_elided, window.cap,
1787 );
1788 logging::warn(&message);
1789 deliver_compaction_notice(prepared.notice_sink.as_deref(), message);
1790 }
1791 summary_messages
1792 } else {
1793 selected_indices
1794 .into_iter()
1795 .map(|idx| messages[idx].clone())
1796 .collect::<Vec<_>>()
1797 };
1798 let summary = create_summary(
1799 client,
1800 &summary_messages,
1801 system_prompt,
1802 prepared,
1803 quality_retries,
1804 invocation_usage,
1805 )
1806 .await?;
1807 let pinned_anchors = match config.workspace.clone() {
1808 Some(workspace) => {
1809 codewhale_runtime::runtime_control::owner_work(move || {
1810 Ok(pinned_anchors_text(Some(&workspace)))
1811 })
1812 .await?
1813 }
1814 None => None,
1815 };
1816 let anchors = format!(
1817 "{}{}",
1818 subagent_handles::section(&summary_messages),
1819 anchors_section_text(pinned_anchors.as_deref())
1820 );
1821 let checkpoint_text = build_compaction_summary_block_text(&summary, &anchors);
1822 let summary_block = SystemBlock {
1823 block_type: "text".to_string(),
1824 text: checkpoint_text.clone(),
1825 cache_control: config.cache_summary.then(|| CacheControl {
1826 cache_type: "ephemeral".to_string(),
1827 }),
1828 };
1829
1830 let retained = last_round::build_replacement_history(
1831 messages,
1832 &checkpoint_text,
1833 pinned_anchors.as_deref(),
1834 config.retained_user_message_tokens,
1835 recent_tokens,
1836 )?;
1837 let mut coverage = last_round::measure_coverage(
1838 messages,
1839 &retained,
1840 CompactionPath::Summary,
1841 pinned_anchors
1842 .as_deref()
1843 .map(|text| text.chars().count())
1844 .unwrap_or(0),
1845 );
1846 // Report the tuning actually in force so the receipt shows the operator
1847 // their knobs took effect (#5956).
1848 coverage.retained_user_message_tokens = config.retained_user_message_tokens;
1849 coverage.operator_instructions_applied =
1850 operator_instructions_section(config.summary_instructions.as_deref()).is_some();
1851 Ok((
1852 retained,
1853 Some(SystemPrompt::Blocks(vec![summary_block])),
1854 coverage,
1855 ))
1856 }
1857
1858 /// Delimiters around the operator's standing summarizer instructions. The
1859 /// summarizer sees a plain user message, so the section must announce itself:
1860 /// unfenced free text reads as more conversation to summarize.
1861 const OPERATOR_INSTRUCTIONS_HEADER: &str = "--- Additional instructions from the operator ---";
1862 const OPERATOR_INSTRUCTIONS_FOOTER: &str = "--- End of additional instructions ---";
1863
1864 /// Render `[compaction] summary_instructions` as a delimited prompt suffix.
1865 ///
1866 /// `None` (unset, or whitespace-only) produces no section at all, which is
1867 /// what keeps the default prompt byte-identical to the pre-#5956 constant.
1868 /// The cap is enforced here rather than at config load so the warning fires
1869 /// once per compaction pass instead of once per turn.
1870 fn operator_instructions_section(instructions: Option<&str>) -> Option<String> {
1871 let text = instructions
1872 .map(str::trim)
1873 .filter(|text| !text.is_empty())?;
1874 let max_chars = codewhale_runtime::config::COMPACTION_SUMMARY_INSTRUCTIONS_MAX_CHARS;
1875 let text = if text.chars().count() > max_chars {
1876 logging::warn(format!(
1877 "[compaction] summary_instructions is longer than {max_chars} characters; \
1878 the summarizer prompt suffix was truncated"
1879 ));
1880 truncate_chars(text, max_chars)
1881 } else {
1882 text
1883 };
1884 Some(format!(
1885 "\n\n{OPERATOR_INSTRUCTIONS_HEADER}\n{text}\n{OPERATOR_INSTRUCTIONS_FOOTER}"
1886 ))
1887 }
1888
1889 fn compact_prompt(focus: Option<&str>, instructions: Option<&str>) -> String {
1890 with_instructions_and_focus(
1891 format!("{} {COMPACTION_LANGUAGE_CONTRACT}", compact_prompt_body()),
1892 focus,
1893 instructions,
1894 )
1895 }
1896
1897 fn compact_quality_retry_prompt(focus: Option<&str>, instructions: Option<&str>) -> String {
1898 with_instructions_and_focus(
1899 format!(
1900 "The previous reply was empty or a placeholder, so there is still no handoff note. \
1901 Write it now, with real content from this session under each heading.\n\n{}\n\n\
1902 {HANDOFF_FOLD_IN_RULE}\n\n{HANDOFF_CLOSING_RULE} Do not refuse or return a placeholder. \
1903 {COMPACTION_LANGUAGE_CONTRACT}",
1904 handoff_sections_text()
1905 ),
1906 focus,
1907 instructions,
1908 )
1909 }
1910
1911 /// Standing operator instructions first, then the one-off `/compact <focus>`.
1912 fn with_instructions_and_focus(
1913 mut prompt: String,
1914 focus: Option<&str>,
1915 instructions: Option<&str>,
1916 ) -> String {
1917 if let Some(section) = operator_instructions_section(instructions) {
1918 prompt.push_str(&section);
1919 }
1920 if let Some(focus) = focus.map(str::trim).filter(|focus| !focus.is_empty()) {
1921 let _ = write!(prompt, "\n\n{HANDOFF_FOCUS_LINE} {focus}");
1922 }
1923 prompt
1924 }
1925
1926 fn validate_compaction_summary(summary: &str) -> Result<String> {
1927 let cleaned = crate::session_manager::strip_thinking_tags(summary);
1928 let trimmed = cleaned.trim();
1929 if trimmed.is_empty() {
1930 anyhow::bail!("The summary for making room was unusable: no text was returned.");
1931 }
1932
1933 // Strip every non-word edge, not just ASCII punctuation. Providers can
1934 // return visually non-empty Unicode punctuation or emoji-only payloads;
1935 // neither is a usable continuation checkpoint. `is_alphanumeric` keeps
1936 // this language-neutral for CJK and other scripts without imposing a
1937 // prose-length heuristic.
1938 let normalized = trimmed
1939 .trim_matches(|ch: char| !ch.is_alphanumeric())
1940 .to_ascii_lowercase();
1941 if normalized.is_empty() {
1942 anyhow::bail!(
1943 "The summary for making room was unusable: only whitespace or punctuation was returned."
1944 );
1945 }
1946 if matches!(
1947 normalized.as_str(),
1948 "no summary available"
1949 | "summary unavailable"
1950 | "no summary"
1951 | "n/a"
1952 | "na"
1953 | "not available"
1954 | "i cannot provide a summary"
1955 | "i can't provide a summary"
1956 | "unable to provide a summary"
1957 ) {
1958 anyhow::bail!("The summary for making room was unusable: a placeholder was returned.");
1959 }
1960 Ok(trimmed.to_string())
1961 }
1962
1963 /// The summary request for one compaction pass: the parent turn's exact
1964 /// request inputs — model, system prompt, tools, reasoning tier, and stored
1965 /// selected older history in order — plus one trailing user instruction. Only
1966 /// per-request controls differ (output cap, streaming), so the provider's
1967 /// prefix cache covers the history the turn already paid for (#6540, #7564).
1968 ///
1969 /// Every route sends `default_tool_choice(false)` (`auto`) whenever tools are
1970 /// present so the summary does not invalidate cached message prefixes with
1971 /// `tool_choice: "none"`; a reply that calls a tool is rejected as unusable and
1972 /// retried once with `tool_choice: "none"`. Known limit: a `strict_tool_mode`
1973 /// turn on a non-thinking route sends `required`, while compaction keeps `auto`
1974 /// so it is not forced to call a tool.
1975 pub fn compaction_summary_request(
1976 history: Vec<Message>,
1977 config: &CompactionConfig,
1978 system_prompt: Option<&SystemPrompt>,
1979 tools: Option<&[Tool]>,
1980 reasoning_effort: Option<&str>,
1981 max_tokens: u32,
1982 ) -> MessageRequest {
1983 MessageRequest {
1984 model: config.model.clone(),
1985 messages: history,
1986 max_tokens,
1987 system: system_prompt.cloned(),
1988 tools: tools.map(<[Tool]>::to_vec),
1989 tool_choice: tools
1990 .filter(|tools| !tools.is_empty())
1991 .map(|_| crate::core::engine::tool_catalog::default_tool_choice(false)),
1992 metadata: None,
1993 thinking: None,
1994 reasoning_effort: reasoning_effort.map(str::to_string),
1995 stream: Some(false),
1996 // Route parity with ordinary turns: turns send no sampling
1997 // params, so every provider's own normalization/defaults apply.
1998 // A hard-coded 0.3 leaked to the wire on routes that pass
1999 // temperature through (e.g. Kimi Code membership), where the
2000 // fixed-sampling contract rejects it and the whole compaction
2001 // pass fails.
2002 temperature: None,
2003 top_p: None,
2004 safety_check: None,
2005 title: None,
2006 }
2007 }
2008
2009 async fn create_summary(
2010 client: &dyn ModelClient,
2011 messages: &[Message],
2012 system_prompt: Option<&SystemPrompt>,
2013 prepared: &PreparedCompactionEnvelope,
2014 quality_retries: &mut u32,
2015 invocation_usage: &mut Usage,
2016 ) -> Result<String> {
2017 let config = &prepared.config;
2018 let tools = prepared.tools.as_deref();
2019 let reasoning_effort = prepared.reasoning_effort.as_deref();
2020 let notice_sink = prepared.notice_sink.as_deref();
2021 let mut request_messages = messages.to_vec();
2022 request_messages.push(Message {
2023 role: Role::User,
2024 content: vec![ContentBlock::Text {
2025 text: compact_prompt(
2026 config.focus.as_deref(),
2027 config.summary_instructions.as_deref(),
2028 ),
2029 cache_control: None,
2030 }],
2031 });
2032
2033 let mut quality_retry_used = false;
2034 let mut forbid_tools_on_retry = false;
2035 // Request-size ladder: an HTTP 413 caps the request *body*, which the
2036 // token-side budget cannot predict (a flat per-image token estimate can
2037 // hide megabytes of base64). A refused summary call gets two byte-side
2038 // downgrades before it fails — re-encode the inline images smaller, then
2039 // replace them with text notes — each followed by exactly one retry.
2040 let mut size_ladder = RequestSizeLadder::Start;
2041 loop {
2042 // Codex compaction is a normal model generation over the existing
2043 // cached prefix. Do the same here: the resolved route decides how
2044 // much output the model may need instead of imposing a smaller,
2045 // compaction-only ceiling that can be consumed by hidden reasoning.
2046 let cost_route = client.effective_route_envelope(&config.model, chrono::Utc::now());
2047 let ceiling = client.effective_max_output_tokens(&cost_route.model);
2048 let summary_floor = crate::route_budget::route_output_reservation_with_window(
2049 cost_route.provider,
2050 &cost_route.model,
2051 client.route_limits(),
2052 client
2053 .effective_context_window(&cost_route.model)
2054 .or(config.effective_context_window),
2055 )
2056 .min(ceiling)
2057 / 2;
2058 let max_tokens = match crate::route_budget::request_output_cap_for_input_with_window(
2059 cost_route.provider,
2060 &cost_route.model,
2061 client.route_limits(),
2062 client
2063 .effective_context_window(&cost_route.model)
2064 .or(config.effective_context_window),
2065 ceiling,
2066 u64::try_from(calibrate_token_estimate(
2067 estimate_request_input_tokens(&request_messages, system_prompt, tools),
2068 prepared.input_token_ratio,
2069 ))
2070 .unwrap_or(u64::MAX),
2071 ) {
2072 Some(cap) if cap >= summary_floor => cap,
2073 _ => {
2074 anyhow::bail!(
2075 "The selected history leaves too little output room in this route's context window. The conversation was preserved; switch to a model with a larger context window and retry."
2076 );
2077 }
2078 };
2079 let mut request = compaction_summary_request(
2080 request_messages.clone(),
2081 config,
2082 system_prompt,
2083 tools,
2084 reasoning_effort,
2085 max_tokens,
2086 );
2087 if forbid_tools_on_retry && request.tool_choice.is_some() {
2088 request.tool_choice = Some(serde_json::json!("none"));
2089 }
2090
2091 let accounting_origin = notice_sink.and_then(|sink| match sink.accounting_origin() {
2092 Ok(origin) => origin,
2093 Err(error) => {
2094 tracing::warn!(%error, "compaction accounting origin failed; continuing with unknown cost");
2095 None
2096 }
2097 });
2098 let cost_scope = accounting_origin.as_ref().map_or_else(
2099 crate::cost_status::scope_token,
2100 crate::cost_status::NativeUsageOrigin::scope,
2101 );
2102 let native_origin = if accounting_origin.is_some() {
2103 accounting_origin
2104 } else if let Some(session_id) = prepared.session_id.as_ref() {
2105 let session_id = session_id.clone();
2106 match codewhale_runtime::runtime_control::owner_work(move || {
2107 let manager = crate::session_manager::SessionManager::default_location()?;
2108 Ok(crate::cost_status::NativeUsageOrigin::session(
2109 cost_scope,
2110 manager.sessions_dir().to_path_buf(),
2111 session_id,
2112 ))
2113 })
2114 .await
2115 {
2116 Ok(origin) => Some(origin),
2117 Err(error) => {
2118 tracing::warn!(%error, "compaction session accounting origin failed; continuing with unknown cost");
2119 None
2120 }
2121 }
2122 } else {
2123 None
2124 };
2125 let source = crate::cost_status::NativeUsageSource::capture_with_origin(
2126 format!("compaction:{}", uuid::Uuid::new_v4()),
2127 crate::cost_status::UsageSpendOwner::Auxiliary,
2128 native_origin,
2129 );
2130 let observation = match prepared.notice_sink.clone() {
2131 Some(sink) => {
2132 let mut observation = source.observation();
2133 observation.emit = Arc::new(move |message| {
2134 sink.notice(format!("Making room: {message}"));
2135 Box::pin(async {})
2136 });
2137 observation
2138 }
2139 None => source.observation(),
2140 };
2141 let wire = observation.wire_observations.clone();
2142 let response = crate::llm_client::observe_request_retries(
2143 Some(observation),
2144 client.create_message(request),
2145 )
2146 .await;
2147 let wire = wire.drain();
2148 let record = source.response_record(&cost_route, &response, &wire);
2149 if let Some(origin) = source.origin() {
2150 crate::cost_status::record_runtime_usage_async(origin.scope(), Some(origin), &record)
2151 .await;
2152 }
2153 if let Some(sink) = notice_sink
2154 && let Err(error) = sink.settled_usage(&record).await
2155 {
2156 tracing::warn!(%error, "compaction final usage notice failed; continuing");
2157 }
2158 let response = match response {
2159 Ok(response) => response,
2160 // A byte-side size rejection can also read like a length problem
2161 // (gateway HTML pages carry their own wording); the size ladder
2162 // owns it, rather than the context-window failure path.
2163 Err(err) if !is_request_too_large_error(&err) && is_context_window_error(&err) => {
2164 return Err(err.context(
2165 "The provider could not summarize the selected history within its context window. The conversation was preserved; switch to a model with a larger context window and retry."
2166 ));
2167 }
2168 Err(err) if is_request_too_large_error(&err) => match size_ladder {
2169 RequestSizeLadder::Start => {
2170 // Decoding, resizing and re-encoding megabytes of inline
2171 // images is CPU-bound work; run it off the async worker so
2172 // the engine keeps servicing events while it happens.
2173 let mut outbound = std::mem::take(&mut request_messages);
2174 let joined = tokio::task::spawn_blocking(move || {
2175 let shrunk = crate::image_attach::shrink_images_for_request(&mut outbound);
2176 (outbound, shrunk)
2177 })
2178 .await;
2179 let (outbound, shrunk) = match joined {
2180 Ok(joined) => joined,
2181 Err(join_error) => {
2182 return Err(err.context(format!(
2183 "The summary request exceeded the provider's request-body limit and re-encoding its inline images failed: {join_error}"
2184 )));
2185 }
2186 };
2187 request_messages = outbound;
2188 if shrunk.images_seen == 0 {
2189 return Err(err.context(
2190 "The summary request exceeded the provider's request-body limit and the history carries no inline images to re-encode",
2191 ));
2192 }
2193 size_ladder = RequestSizeLadder::ImagesShrunk;
2194 if shrunk.images > 0 {
2195 let message = format!(
2196 "Making room exceeded the provider's request-body limit (HTTP 413); re-encoded {} inline image(s) smaller ({} to {}) and is retrying the summary.",
2197 shrunk.images,
2198 crate::image_attach::human_bytes(shrunk.bytes_before),
2199 crate::image_attach::human_bytes(shrunk.bytes_after),
2200 );
2201 logging::warn(&message);
2202 deliver_compaction_notice(notice_sink, message);
2203 continue;
2204 }
2205 // Images are present but every one already fits its share of
2206 // the byte budget, and the body was still refused: the cap
2207 // sits below the budget. A retry would send identical bytes,
2208 // so replace the images now instead of failing the pass.
2209 if let Err(replace_error) =
2210 replace_inline_images_for_retry(&mut request_messages, notice_sink)
2211 {
2212 return Err(err.context(format!(
2213 "The summary request exceeded the provider's request-body limit; {replace_error}"
2214 )));
2215 }
2216 size_ladder = RequestSizeLadder::ImagesReplaced;
2217 continue;
2218 }
2219 RequestSizeLadder::ImagesShrunk => {
2220 if let Err(replace_error) =
2221 replace_inline_images_for_retry(&mut request_messages, notice_sink)
2222 {
2223 return Err(err.context(format!(
2224 "The summary request still exceeded the provider's request-body limit and {replace_error}"
2225 )));
2226 }
2227 size_ladder = RequestSizeLadder::ImagesReplaced;
2228 continue;
2229 }
2230 RequestSizeLadder::ImagesReplaced => {
2231 return Err(err.context(
2232 "The summary request exceeded the provider's request-body limit even after re-encoding and then replacing every inline image",
2233 ));
2234 }
2235 },
2236 Err(err) => return Err(err),
2237 };
2238
2239 // Keep the caller's total before any validation or subsequent await.
2240 // A rejected summary or canceled retry still consumed these tokens.
2241 crate::core::turn::add_usage_to(invocation_usage, &response.usage);
2242
2243 if let (Some(sink), Some(warning)) = (notice_sink, response.tool_projection_warning) {
2244 sink.tool_projection_warning(warning);
2245 }
2246
2247 // Usage above is already billed; a provider-declared incomplete
2248 // summary must still fail rather than replace the session history
2249 // with a fragment.
2250 if codewhale_models::is_incomplete_stop_reason(response.stop_reason.as_deref()) {
2251 anyhow::bail!(
2252 "The summary for making room was incomplete: provider stop reason `{}`; the partial summary was not accepted.",
2253 codewhale_models::stop_reason_detail(response.stop_reason.as_deref())
2254 );
2255 }
2256 let returned_tool_call = response
2257 .content
2258 .iter()
2259 .any(|block| matches!(block, ContentBlock::ToolUse { .. }));
2260 let summary = if returned_tool_call {
2261 Err(anyhow::anyhow!(
2262 "Making room returned a tool call instead of a summary; the original conversation was preserved."
2263 ))
2264 } else {
2265 validate_compaction_summary(
2266 &response
2267 .content
2268 .iter()
2269 .filter_map(|block| match block {
2270 ContentBlock::Text { text, .. } => Some(text.clone()),
2271 _ => None,
2272 })
2273 .collect::<Vec<_>>()
2274 .join("\n"),
2275 )
2276 };
2277 if let Err(error) = summary {
2278 if quality_retry_used {
2279 return Err(error.context(
2280 "Compaction summary remained unusable after one conservative retry; \
2281 no replacement checkpoint was committed",
2282 ));
2283 }
2284
2285 quality_retry_used = true;
2286 if returned_tool_call {
2287 forbid_tools_on_retry = true;
2288 }
2289 *quality_retries = (*quality_retries).saturating_add(1);
2290 logging::warn(
2291 "Compaction provider returned an unusable successful response; retrying once with the conservative handoff prompt",
2292 );
2293 let Some(instruction) = request_messages.last_mut() else {
2294 return Err(error.context(
2295 "Compaction summary validation failed and the retry instruction was missing",
2296 ));
2297 };
2298 instruction.content = vec![ContentBlock::Text {
2299 text: compact_quality_retry_prompt(
2300 config.focus.as_deref(),
2301 config.summary_instructions.as_deref(),
2302 ),
2303 cache_control: None,
2304 }];
2305 continue;
2306 }
2307
2308 return summary;
2309 }
2310 }
2311
2312 /// How far the request-size ladder for one summary call has descended.
2313 ///
2314 /// The ladder exists because HTTP 413 rejects the request *body* by bytes,
2315 /// which the token-side context budget that governs compaction cannot see.
2316 /// Each rung is one retry: re-encode the inline images under a byte budget,
2317 /// then replace them with text notes.
2318 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2319 enum RequestSizeLadder {
2320 /// No size downgrade applied yet.
2321 Start,
2322 /// Inline images were re-encoded smaller.
2323 ImagesShrunk,
2324 /// Inline images were replaced with text notes.
2325 ImagesReplaced,
2326 }
2327
2328 fn is_request_too_large_error(e: &anyhow::Error) -> bool {
2329 matches!(
2330 llm_error_in_chain(e),
2331 Some(crate::llm_client::LlmError::InvalidRequest { status: 413, .. })
2332 )
2333 }
2334
2335 /// Forward one user-visible progress sentence, when the host supplied a sink.
2336 fn deliver_compaction_notice(sink: Option<&dyn CompactionNoticeSink>, message: String) {
2337 if let Some(sink) = sink {
2338 sink.notice(message);
2339 }
2340 }
2341
2342 /// Replace every inline image for one retry and announce it.
2343 ///
2344 /// Shared by the two rungs that can reach the replace step: after a shrink
2345 /// pass that changed something, and directly when the images already fit the
2346 /// byte budget but the body was refused anyway.
2347 fn replace_inline_images_for_retry(
2348 messages: &mut [Message],
2349 notice_sink: Option<&dyn CompactionNoticeSink>,
2350 ) -> Result<usize> {
2351 let replaced = crate::image_attach::replace_images_with_placeholders(
2352 messages,
2353 "the summary request exceeded the provider's request-body limit (HTTP 413)",
2354 );
2355 if replaced == 0 {
2356 anyhow::bail!("no inline images were left to replace");
2357 }
2358 let message = format!(
2359 "Making room still exceeded the provider's request-body limit; replaced {replaced} inline image(s) with text notes for this summary pass and is retrying."
2360 );
2361 logging::warn(&message);
2362 deliver_compaction_notice(notice_sink, message);
2363 Ok(replaced)
2364 }
2365
2366 fn is_context_window_error(e: &anyhow::Error) -> bool {
2367 matches!(
2368 llm_error_in_chain(e),
2369 Some(crate::llm_client::LlmError::ContextLengthError(_))
2370 )
2371 }
2372
2373 /// Collect text from a user message without treating tool-result payloads
2374 /// as new user instructions.
2375 fn user_text_of(msg: &Message) -> Option<String> {
2376 if msg.role != "user" {
2377 return None;
2378 }
2379 let text = msg
2380 .content
2381 .iter()
2382 .filter_map(|block| match block {
2383 ContentBlock::Text { text, .. } => Some(text.as_str()),
2384 _ => None,
2385 })
2386 .collect::<Vec<_>>()
2387 .join("\n");
2388 let text = text.trim();
2389 (!text.is_empty()).then(|| text.to_string())
2390 }
2391
2392 #[cfg(test)]
2393 #[path = "compaction/tests.rs"]
2394 mod quota_tests;
2395
2396 #[cfg(test)]
2397 mod tests {
2398 use codewhale_models::{ImageUrlContent, Message};
2399 use std::time::Duration;
2400
2401 #[test]
2402 fn legacy_checkpoint_headings_are_recognised_but_quotes_are_not() {
2403 for text in [
2404 "## 📋 Conversation Summary (Auto-Generated)\n\nkey facts.",
2405 "## Pinned Facts (User Anchors)\n\n- keep tabs\n\n---\n\n## 📋 Conversation Summary (Auto-Generated)\n\nfacts",
2406 "Conversation Summary (Auto-Generated)\nold",
2407 "Another language model started to solve this problem\nold",
2408 ] {
2409 assert!(is_legacy_compaction_summary_text(text), "{text}");
2410 }
2411 for text in [
2412 "Explain: ## 📋 Conversation Summary (Auto-Generated)",
2413 "## Pinned Facts (User Anchors)\nsee Conversation Summary (Auto-Generated) above",
2414 "Codewhale handoff note\nnot structural",
2415 ] {
2416 assert!(!is_legacy_compaction_summary_text(text), "{text}");
2417 }
2418 }
2419
2420 #[test]
2421 fn restore_without_typed_checkpoint_preserves_user_marker_quotes() {
2422 // The current marker is recognised only structurally (header block +
2423 // provenance block), so only the legacy substring markers apply here.
2424 for marker in [
2425 LEGACY_V2_COMPACTION_SUMMARY_MARKER,
2426 LEGACY_COMPACTION_SUMMARY_MARKER,
2427 ] {
2428 let quoted = Message {
2429 role: Role::User,
2430 content: vec![ContentBlock::Text {
2431 text: format!("Explain this marker: {marker}"),
2432 cache_control: None,
2433 }],
2434 };
2435 let legacy = Message {
2436 role: Role::User,
2437 content: vec![ContentBlock::Text {
2438 text: format!("{marker}\nold summary"),
2439 cache_control: None,
2440 }],
2441 };
2442 let messages = vec![quoted.clone(), legacy.clone()];
2443 assert_eq!(
2444 restore_compaction_checkpoint(messages.clone(), None),
2445 messages
2446 );
2447
2448 let summary = SystemPrompt::Text(build_compaction_summary_block_text("Summary", ""));
2449 let later = msg("user", "keep working on the current task");
2450 let restored = restore_compaction_checkpoint(
2451 vec![quoted.clone(), legacy.clone(), later.clone()],
2452 Some(&summary),
2453 );
2454 assert_eq!(
2455 restored,
2456 vec![
2457 quoted,
2458 compaction_checkpoint_message(&summary),
2459 legacy,
2460 later
2461 ]
2462 );
2463 assert_eq!(
2464 restore_compaction_checkpoint(restored.clone(), Some(&summary)),
2465 restored
2466 );
2467 }
2468 }
2469
2470 #[test]
2471 fn restore_replaces_duplicate_generated_checkpoints_without_deleting_user_quote() {
2472 let summary = SystemPrompt::Text(build_compaction_summary_block_text("Summary", ""));
2473 let generated = compaction_checkpoint_message(&summary);
2474 let user_quote = Message {
2475 role: Role::User,
2476 content: vec![ContentBlock::Text {
2477 text: summary_prompt_text(&summary),
2478 cache_control: None,
2479 }],
2480 };
2481 assert!(!is_wire_compaction_checkpoint_message(&user_quote));
2482 let restored = restore_compaction_checkpoint(
2483 vec![generated.clone(), user_quote.clone(), generated],
2484 Some(&summary),
2485 );
2486 assert_eq!(restored.len(), 2);
2487 assert!(is_wire_compaction_checkpoint_message(&restored[0]));
2488 assert_eq!(restored[1], user_quote);
2489
2490 let legacy = Message {
2491 role: Role::User,
2492 content: vec![ContentBlock::Text {
2493 text: format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\nold summary"),
2494 cache_control: None,
2495 }],
2496 };
2497 let saved = SystemPrompt::Text(format!(
2498 "{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\nold summary"
2499 ));
2500 let legacy_restored =
2501 restore_compaction_checkpoint(vec![legacy.clone(), legacy.clone()], Some(&saved));
2502 assert_eq!(
2503 legacy_restored,
2504 vec![
2505 compaction_checkpoint_message(&saved),
2506 legacy.clone(),
2507 legacy
2508 ]
2509 );
2510 assert_eq!(
2511 restore_compaction_checkpoint(legacy_restored.clone(), Some(&saved)),
2512 legacy_restored
2513 );
2514 }
2515
2516 #[test]
2517 fn restore_anchors_at_the_real_carrier_when_a_pasted_summary_precedes_it() {
2518 // Mirror order of the duplicate-carrier test above: the pasted full
2519 // summary comes BEFORE the real provenance carrier — the order in
2520 // which a content-based anchor would land on the pasted turn's
2521 // index. Restore must anchor at the real carrier's index, replace
2522 // the carrier with the saved summary there, and keep the pasted
2523 // turn verbatim as user content. The carrier's text differs from
2524 // the saved summary so the assertions cannot pass by leaving the
2525 // history untouched.
2526 let pasted_summary = SystemPrompt::Text(build_compaction_summary_block_text(
2527 "Please analyze this text",
2528 "",
2529 ));
2530 let pasted = Message {
2531 role: Role::User,
2532 content: vec![ContentBlock::Text {
2533 text: summary_prompt_text(&pasted_summary),
2534 cache_control: None,
2535 }],
2536 };
2537 assert!(
2538 !is_wire_compaction_checkpoint_message(&pasted),
2539 "a pasted summary without the provenance block is user content"
2540 );
2541 let carrier = compaction_checkpoint_message(&SystemPrompt::Text(
2542 build_compaction_summary_block_text("Compacted summary", ""),
2543 ));
2544 let authoritative = SystemPrompt::Text(build_compaction_summary_block_text(
2545 "Authoritative summary",
2546 "",
2547 ));
2548 let restored =
2549 restore_compaction_checkpoint(vec![pasted.clone(), carrier], Some(&authoritative));
2550 assert_eq!(
2551 restored.len(),
2552 2,
2553 "restore must not drop the pasted turn: {restored:?}"
2554 );
2555 assert_eq!(
2556 restored[0], pasted,
2557 "the pasted full summary must survive restore verbatim"
2558 );
2559 assert!(
2560 is_wire_compaction_checkpoint_message(&restored[1]),
2561 "the real carrier keeps the anchor position: {restored:?}"
2562 );
2563 assert_eq!(
2564 restored[1],
2565 compaction_checkpoint_message(&authoritative),
2566 "the saved summary replaces the carrier at its index: {restored:?}"
2567 );
2568 }
2569
2570 #[test]
2571 fn restore_relocates_pre_anchor_topology_sidecar_saved_after_tool_result() {
2572 // Sessions saved by v0.9.10-v0.9.12 appended the Agent-topology
2573 // sidecar to the end of the replacement history; the placement anchor
2574 // shipped only later. A session compacted while agents were live
2575 // therefore carries `tool result, summary, sidecar`, and restoring it
2576 // rewrote the sidecar in place, leaving a user carrier directly after
2577 // a tool result — a wire strict paired chat templates reject with
2578 // HTTP 400. Restore must move the sidecar to its placement anchor
2579 // instead.
2580 let bare_summary = Message {
2581 role: Role::User,
2582 content: vec![ContentBlock::Text {
2583 text: format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\npre-anchor summary"),
2584 cache_control: None,
2585 }],
2586 };
2587 let mut messages = vec![
2588 msg("user", "Analyze the data"),
2589 tool_use("call_1", "read", json!({"path": "a.txt"})),
2590 tool_result("call_1", "ready"),
2591 bare_summary,
2592 ];
2593 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]);
2594 assert!(
2595 crate::runtime_handoff::is_agent_topology_checkpoint(messages.last().unwrap()),
2596 "the pre-anchor save appended the sidecar after the summary"
2597 );
2598 let summary = SystemPrompt::Text(build_compaction_summary_block_text("Summary", ""));
2599 let restored = restore_compaction_checkpoint(
2600 crate::runtime_handoff::project_owned_messages_for_restore(messages.clone()),
2601 Some(&summary),
2602 );
2603 let carrier_positions: Vec<usize> = restored
2604 .iter()
2605 .enumerate()
2606 .filter(|(_, message)| {
2607 crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)
2608 })
2609 .map(|(index, _)| index)
2610 .collect();
2611 assert_eq!(
2612 carrier_positions,
2613 vec![1],
2614 "the restored sidecar must sit at its placement anchor, directly \
2615 after the genuine user prompt and before the assistant/tool chain: {restored:?}"
2616 );
2617 for pair in restored.windows(2) {
2618 let follows_tool_result = pair[0]
2619 .content
2620 .iter()
2621 .any(|block| matches!(block, ContentBlock::ToolResult { .. }));
2622 assert!(
2623 !(follows_tool_result
2624 && crate::runtime_handoff::is_restored_agent_topology_checkpoint(&pair[1])),
2625 "a topology carrier must not follow a tool result: {restored:?}"
2626 );
2627 }
2628 }
2629
2630 #[test]
2631 fn restore_relocates_topology_sidecar_trailing_its_summary() {
2632 // The other shape pre-anchor releases saved: the sidecar appended
2633 // directly after the compaction summary. Restore must still move it
2634 // to the placement anchor in front of the summary's own round.
2635 let summary = SystemPrompt::Text(build_compaction_summary_block_text("Summary", ""));
2636 let mut holder: Vec<Message> = Vec::new();
2637 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut holder, &[]);
2638 let topology = holder.remove(0);
2639 let mut messages = vec![
2640 msg("user", "Analyze the data"),
2641 tool_use("call_1", "read", json!({"path": "a.txt"})),
2642 tool_result("call_1", "ready"),
2643 compaction_checkpoint_message(&summary),
2644 ];
2645 messages.push(topology);
2646 let restored = restore_compaction_checkpoint(
2647 crate::runtime_handoff::project_owned_messages_for_restore(messages),
2648 Some(&summary),
2649 );
2650 let carrier_positions: Vec<usize> = restored
2651 .iter()
2652 .enumerate()
2653 .filter(|(_, message)| {
2654 crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)
2655 })
2656 .map(|(index, _)| index)
2657 .collect();
2658 assert_eq!(
2659 carrier_positions,
2660 vec![1],
2661 "the sidecar trailing its summary must relocate to the placement anchor: {restored:?}"
2662 );
2663 }
2664
2665 #[test]
2666 fn restore_keeps_anchor_placed_topology_session_byte_identical() {
2667 // A session saved by the placement anchor already carries the sidecar
2668 // where a save would write it; restore must not shuffle it.
2669 let summary = SystemPrompt::Text(build_compaction_summary_block_text("Summary", ""));
2670 let mut messages = vec![
2671 msg("user", "Analyze the data"),
2672 tool_use("call_1", "read", json!({"path": "a.txt"})),
2673 tool_result("call_1", "ready"),
2674 compaction_checkpoint_message(&summary),
2675 ];
2676 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]);
2677 assert!(
2678 crate::runtime_handoff::is_agent_topology_checkpoint(&messages[1]),
2679 "save-time anchor places the sidecar directly after the prompt"
2680 );
2681 // The projection always rewrites the live envelope into its restored
2682 // display form; "untouched" means restore changes nothing beyond
2683 // that: the summary replaces itself and the carrier stays put.
2684 let projected = crate::runtime_handoff::project_owned_messages_for_restore(messages);
2685 let restored = restore_compaction_checkpoint(projected.clone(), Some(&summary));
2686 assert_eq!(
2687 restored, projected,
2688 "an already anchored session must restore byte-identical: {restored:?}"
2689 );
2690 }
2691
2692 #[test]
2693 fn restore_never_moves_a_pasted_summary_header_and_anchors_past_it() {
2694 // In a history that carries a provenance-stamped carrier, a user turn
2695 // that pastes a summary header is genuine content. Relocation must
2696 // leave it verbatim and anchor the sidecar after it, not treat it as
2697 // the summary boundary.
2698 let pasted_summary = SystemPrompt::Text(build_compaction_summary_block_text(
2699 "Please analyze this text",
2700 "",
2701 ));
2702 let pasted = Message {
2703 role: Role::User,
2704 content: vec![ContentBlock::Text {
2705 text: summary_prompt_text(&pasted_summary),
2706 cache_control: None,
2707 }],
2708 };
2709 assert!(!is_wire_compaction_checkpoint_message(&pasted));
2710 let summary = SystemPrompt::Text(build_compaction_summary_block_text("Summary", ""));
2711 let mut holder: Vec<Message> = Vec::new();
2712 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut holder, &[]);
2713 let topology = holder.remove(0);
2714 let mut messages = vec![
2715 msg("user", "Run the tool"),
2716 tool_use("call_1", "read", json!({"path": "a.txt"})),
2717 tool_result("call_1", "done"),
2718 pasted.clone(),
2719 compaction_checkpoint_message(&summary),
2720 ];
2721 messages.push(topology);
2722 let restored = restore_compaction_checkpoint(
2723 crate::runtime_handoff::project_owned_messages_for_restore(messages),
2724 Some(&summary),
2725 );
2726 assert_eq!(
2727 restored[3], pasted,
2728 "the pasted summary header stays verbatim in its saved position: {restored:?}"
2729 );
2730 let carrier_positions: Vec<usize> = restored
2731 .iter()
2732 .enumerate()
2733 .filter(|(_, message)| {
2734 crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)
2735 })
2736 .map(|(index, _)| index)
2737 .collect();
2738 assert_eq!(
2739 carrier_positions,
2740 vec![4],
2741 "the sidecar anchors after the pasted user turn, before the summary: {restored:?}"
2742 );
2743 }
2744
2745 #[test]
2746 fn restore_without_checkpoint_only_relocates_topology_sidecars() {
2747 // A checkpoint-less restore has no summary to replace and must not
2748 // run any carrier-deletion scan; topology relocation is safe because
2749 // it only reorders sidecars and never deletes.
2750 let bare_summary = Message {
2751 role: Role::User,
2752 content: vec![ContentBlock::Text {
2753 text: format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\npre-anchor summary"),
2754 cache_control: None,
2755 }],
2756 };
2757 let mut messages = vec![
2758 msg("user", "Analyze the data"),
2759 tool_use("call_1", "read", json!({"path": "a.txt"})),
2760 tool_result("call_1", "ready"),
2761 bare_summary,
2762 ];
2763 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]);
2764 let restored = restore_compaction_checkpoint(
2765 crate::runtime_handoff::project_owned_messages_for_restore(messages.clone()),
2766 None,
2767 );
2768 assert_eq!(
2769 restored.len(),
2770 messages.len(),
2771 "a checkpoint-less restore must delete nothing: {restored:?}"
2772 );
2773 let carrier_positions: Vec<usize> = restored
2774 .iter()
2775 .enumerate()
2776 .filter(|(_, message)| {
2777 crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)
2778 })
2779 .map(|(index, _)| index)
2780 .collect();
2781 assert_eq!(
2782 carrier_positions,
2783 vec![1],
2784 "the misplaced sidecar still relocates without a saved summary: {restored:?}"
2785 );
2786 }
2787
2788 #[test]
2789 fn restore_without_checkpoint_treats_pasted_legacy_header_as_boundary() {
2790 // The boundary reading is era-dependent, and this pins the legacy
2791 // side of it. In a pre-provenance history the loose legacy form still
2792 // identifies the compaction boundary, so a user turn that pastes a
2793 // legacy summary header is read as that boundary here — unlike a
2794 // post-provenance history, where the same paste is content (see
2795 // `restore_never_moves_a_pasted_summary_header_and_anchors_past_it`).
2796 // The checkpoint-less path must relocate the carrier relative to
2797 // that boundary and leave the pasted header text itself untouched.
2798 let pasted = Message {
2799 role: Role::User,
2800 content: vec![ContentBlock::Text {
2801 text: format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\npasted transcript header"),
2802 cache_control: None,
2803 }],
2804 };
2805 assert!(!is_wire_compaction_checkpoint_message(&pasted));
2806 assert!(is_compaction_checkpoint_message(&pasted));
2807 let mut messages = vec![
2808 msg("user", "Analyze the data"),
2809 tool_use("call_1", "read", json!({"path": "a.txt"})),
2810 tool_result("call_1", "ready"),
2811 pasted.clone(),
2812 ];
2813 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]);
2814 assert!(
2815 crate::runtime_handoff::is_agent_topology_checkpoint(messages.last().unwrap()),
2816 "the pre-anchor save appended the sidecar at the end"
2817 );
2818 let restored = restore_compaction_checkpoint(
2819 crate::runtime_handoff::project_owned_messages_for_restore(messages.clone()),
2820 None,
2821 );
2822 assert_eq!(
2823 restored.len(),
2824 messages.len(),
2825 "a checkpoint-less restore deletes nothing: {restored:?}"
2826 );
2827 assert_eq!(
2828 restored[4], pasted,
2829 "the pasted header is the era's boundary, and its text stays \
2830 verbatim, shifted behind the relocated carrier but never moved \
2831 across it: {restored:?}"
2832 );
2833 let carrier_positions: Vec<usize> = restored
2834 .iter()
2835 .enumerate()
2836 .filter(|(_, message)| {
2837 crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)
2838 })
2839 .map(|(index, _)| index)
2840 .collect();
2841 assert_eq!(
2842 carrier_positions,
2843 vec![1],
2844 "the carrier moves in front of the boundary the pasted header \
2845 was read as, not beside or after it: {restored:?}"
2846 );
2847 }
2848
2849 #[test]
2850 fn restore_prompt_scan_skips_bare_legacy_summaries() {
2851 // Pins the anchor between the round's prompt and its tool chain even
2852 // with an older bare summary earlier in the window; the scan's
2853 // distinguishing power over an era-blind rposition lives in
2854 // `restore_prompt_scan_skips_summaries_inside_the_anchor_window`.
2855 let older = Message {
2856 role: Role::User,
2857 content: vec![ContentBlock::Text {
2858 text: format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\nolder summary"),
2859 cache_control: None,
2860 }],
2861 };
2862 let newer = Message {
2863 role: Role::User,
2864 content: vec![ContentBlock::Text {
2865 text: format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\nnewer summary"),
2866 cache_control: None,
2867 }],
2868 };
2869 let mut messages = vec![
2870 older.clone(),
2871 msg("user", "Analyze the data"),
2872 tool_use("call_1", "read", json!({"path": "a.txt"})),
2873 tool_result("call_1", "ready"),
2874 newer.clone(),
2875 ];
2876 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]);
2877 let restored = restore_compaction_checkpoint(
2878 crate::runtime_handoff::project_owned_messages_for_restore(messages.clone()),
2879 None,
2880 );
2881 assert_eq!(restored.len(), messages.len());
2882 assert_eq!(
2883 restored[0], older,
2884 "the older bare summary stays verbatim: {restored:?}"
2885 );
2886 assert_eq!(
2887 restored[5], newer,
2888 "the newer bare summary stays verbatim: {restored:?}"
2889 );
2890 let carrier_positions: Vec<usize> = restored
2891 .iter()
2892 .enumerate()
2893 .filter(|(_, message)| {
2894 crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)
2895 })
2896 .map(|(index, _)| index)
2897 .collect();
2898 assert_eq!(
2899 carrier_positions,
2900 vec![2],
2901 "the carrier anchors after the genuine prompt, never directly \
2902 after an older summary: {restored:?}"
2903 );
2904 }
2905
2906 #[test]
2907 fn restore_prompt_scan_skips_summaries_inside_the_anchor_window() {
2908 // Distinguishing shape for the era-aware scan: the boundary window
2909 // ends at the newest summary, so an OLDER bare legacy summary sits
2910 // inside the window with no genuine prompt after it. The era-blind
2911 // classifier reads it as editable text and would anchor the carrier
2912 // directly after it; the era-aware scan skips it and anchors after
2913 // the genuine prompt instead.
2914 let older = Message {
2915 role: Role::User,
2916 content: vec![ContentBlock::Text {
2917 text: format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\nolder summary"),
2918 cache_control: None,
2919 }],
2920 };
2921 let newer = Message {
2922 role: Role::User,
2923 content: vec![ContentBlock::Text {
2924 text: format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\nnewer summary"),
2925 cache_control: None,
2926 }],
2927 };
2928 let mut messages = vec![
2929 msg("user", "Analyze the data"),
2930 older.clone(),
2931 newer.clone(),
2932 ];
2933 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]);
2934 let restored = restore_compaction_checkpoint(
2935 crate::runtime_handoff::project_owned_messages_for_restore(messages.clone()),
2936 None,
2937 );
2938 assert_eq!(restored.len(), messages.len());
2939 assert_eq!(
2940 restored[2], older,
2941 "the older bare summary stays verbatim: {restored:?}"
2942 );
2943 assert_eq!(
2944 restored[3], newer,
2945 "the newer bare summary stays verbatim: {restored:?}"
2946 );
2947 let carrier_positions: Vec<usize> = restored
2948 .iter()
2949 .enumerate()
2950 .filter(|(_, message)| {
2951 crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)
2952 })
2953 .map(|(index, _)| index)
2954 .collect();
2955 assert_eq!(
2956 carrier_positions,
2957 vec![1],
2958 "the carrier anchors directly after the genuine prompt, never \
2959 between the summaries or after an older one: {restored:?}"
2960 );
2961 }
2962
2963 #[test]
2964 fn restore_moves_carrier_in_front_when_summary_leads_the_window() {
2965 // Pinned empty-window behavior: a summary at index 0 gives the anchor
2966 // scan an empty window, and the carrier deliberately moves to
2967 // index 0, in front of the summary — where a save would have written
2968 // it — rather than bailing out and staying after it.
2969 let stamped = compaction_checkpoint_message(&SystemPrompt::Text(
2970 build_compaction_summary_block_text("Summary", ""),
2971 ));
2972 let mut holder: Vec<Message> = Vec::new();
2973 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut holder, &[]);
2974 let topology = holder.remove(0);
2975 let messages = vec![stamped, topology];
2976 let restored = restore_compaction_checkpoint(
2977 crate::runtime_handoff::project_owned_messages_for_restore(messages),
2978 None,
2979 );
2980 assert_eq!(
2981 restored.len(),
2982 2,
2983 "a checkpoint-less restore keeps a wire-format checkpoint: {restored:?}"
2984 );
2985 assert!(
2986 is_wire_compaction_checkpoint_message(&restored[1]),
2987 "the summary stays intact behind the carrier: {restored:?}"
2988 );
2989 let carrier_positions: Vec<usize> = restored
2990 .iter()
2991 .enumerate()
2992 .filter(|(_, message)| {
2993 crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)
2994 || crate::runtime_handoff::is_agent_topology_checkpoint(message)
2995 })
2996 .map(|(index, _)| index)
2997 .collect();
2998 assert_eq!(
2999 carrier_positions,
3000 vec![0],
3001 "the empty window anchors the carrier at index 0, in front of \
3002 the summary: {restored:?}"
3003 );
3004 }
3005
3006 #[test]
3007 fn save_after_restore_keeps_exactly_one_topology_carrier() {
3008 // A restored carrier is the projection of a sidecar a previous save
3009 // already wrote. The next compaction's save must retire it when it
3010 // installs the fresh sidecar — keeping it beside the fresh one would
3011 // persist a superseded duplicate that no later replay removes.
3012 let bare_summary = Message {
3013 role: Role::User,
3014 content: vec![ContentBlock::Text {
3015 text: format!("{LEGACY_V2_COMPACTION_SUMMARY_MARKER}\npre-anchor summary"),
3016 cache_control: None,
3017 }],
3018 };
3019 let mut messages = vec![
3020 msg("user", "Analyze the data"),
3021 tool_use("call_1", "read", json!({"path": "a.txt"})),
3022 tool_result("call_1", "ready"),
3023 bare_summary.clone(),
3024 ];
3025 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]);
3026 let summary = SystemPrompt::Text(build_compaction_summary_block_text("Summary", ""));
3027 let restored = restore_compaction_checkpoint(
3028 crate::runtime_handoff::project_owned_messages_for_restore(messages),
3029 Some(&summary),
3030 );
3031 let carrier_count = |history: &[Message]| {
3032 history
3033 .iter()
3034 .filter(|message| {
3035 crate::runtime_handoff::is_agent_topology_checkpoint(message)
3036 || crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)
3037 })
3038 .count()
3039 };
3040 assert_eq!(
3041 carrier_count(&restored),
3042 1,
3043 "the restore itself carries exactly one topology carrier: {restored:?}"
3044 );
3045 let mut recompacted = restored;
3046 crate::runtime_handoff::replace_agent_topology_checkpoint(&mut recompacted, &[]);
3047 assert_eq!(
3048 carrier_count(&recompacted),
3049 1,
3050 "the save must retire the restored carrier, not stack a fresh \
3051 one beside it: {recompacted:?}"
3052 );
3053 assert!(
3054 recompacted
3055 .last()
3056 .is_some_and(crate::runtime_handoff::is_agent_topology_checkpoint),
3057 "the fresh sidecar follows the last retained user turn: {recompacted:?}"
3058 );
3059 assert_eq!(recompacted[recompacted.len() - 2], bare_summary);
3060 }
3061
3062 #[test]
3063 fn inline_image_estimates_nonzero_tokens() {
3064 let msg = Message {
3065 role: Role::User,
3066 content: vec![ContentBlock::ImageUrl {
3067 image_url: ImageUrlContent {
3068 url: "data:image/png;base64,AAAA".to_string(),
3069 },
3070 }],
3071 };
3072 assert!(
3073 estimate_tokens_for_message(&msg, false) >= IMAGE_TOKEN_ESTIMATE,
3074 "an inline image must not estimate to 0 tokens"
3075 );
3076 }
3077
3078 use super::*;
3079 use serde_json::json;
3080
3081 fn msg(role: &str, text: &str) -> Message {
3082 Message {
3083 role: Role::from(role),
3084 content: vec![ContentBlock::Text {
3085 text: text.to_string(),
3086 cache_control: None,
3087 }],
3088 }
3089 }
3090
3091 fn prepared(config: &CompactionConfig) -> PreparedCompactionEnvelope {
3092 PreparedCompactionEnvelope::new(config.clone())
3093 }
3094
3095 fn tool_use(id: &str, name: &str, input: serde_json::Value) -> Message {
3096 Message {
3097 role: Role::Assistant,
3098 content: vec![ContentBlock::ToolUse {
3099 execution_id: None,
3100 id: id.to_string(),
3101 name: name.to_string(),
3102 input,
3103 caller: None,
3104 thought_signature: None,
3105 }],
3106 }
3107 }
3108
3109 fn tool_result(id: &str, content: &str) -> Message {
3110 Message {
3111 role: Role::User,
3112 content: vec![ContentBlock::ToolResult {
3113 execution_id: None,
3114 tool_use_id: id.to_string(),
3115 content: content.to_string(),
3116 is_error: None,
3117 content_blocks: None,
3118 }],
3119 }
3120 }
3121
3122 #[test]
3123 fn truncate_chars_respects_unicode_boundaries() {
3124 let text = "abc😀é";
3125 assert_eq!(truncate_chars(text, 0), "");
3126 assert_eq!(truncate_chars(text, 1), "a");
3127 assert_eq!(truncate_chars(text, 3), "abc");
3128 assert_eq!(truncate_chars(text, 4), "abc😀");
3129 assert_eq!(truncate_chars(text, 5), "abc😀é");
3130 }
3131
3132 #[test]
3133 fn prune_tool_results_summarizes_old_verbose_outputs() {
3134 let verbose = "x".repeat(SUMMARY_TOOL_RESULT_SNIPPET_CHARS + 80);
3135 let mut messages = vec![
3136 tool_use("call-1", "read_file", json!({"path": "Cargo.toml"})),
3137 tool_result("call-1", &verbose),
3138 msg("user", "recent question"),
3139 msg("assistant", "recent answer"),
3140 ];
3141
3142 let saved = prune_tool_results(&mut messages, 2);
3143
3144 assert!(saved > 0);
3145 let ContentBlock::ToolResult { content, .. } = &messages[1].content[0] else {
3146 panic!("expected tool result");
3147 };
3148 assert!(content.contains("[read_file] tool result pruned"));
3149 assert!(content.contains("Cargo.toml"));
3150 assert!(content.len() < verbose.len());
3151 }
3152
3153 #[test]
3154 fn prune_tool_results_preserves_protected_tail() {
3155 let verbose = "x".repeat(SUMMARY_TOOL_RESULT_SNIPPET_CHARS + 80);
3156 let mut messages = vec![
3157 msg("user", "older context"),
3158 tool_use("call-1", "read_file", json!({"path": "Cargo.toml"})),
3159 tool_result("call-1", &verbose),
3160 ];
3161
3162 let saved = prune_tool_results(&mut messages, 2);
3163
3164 assert_eq!(saved, 0);
3165 let ContentBlock::ToolResult { content, .. } = &messages[2].content[0] else {
3166 panic!("expected tool result");
3167 };
3168 assert_eq!(content, &verbose);
3169 }
3170
3171 #[test]
3172 fn prune_tool_results_preserves_prefix_bytes_when_reverse_prune_is_enough() {
3173 let older_verbose = "old ".repeat(SUMMARY_TOOL_RESULT_SNIPPET_CHARS + 40);
3174 let newer_verbose = "new ".repeat(SUMMARY_TOOL_RESULT_SNIPPET_CHARS + 40);
3175 let mut messages = vec![
3176 tool_use("call-old", "read_file", json!({"path": "old.txt"})),
3177 tool_result("call-old", &older_verbose),
3178 tool_use("call-new", "read_file", json!({"path": "new.txt"})),
3179 tool_result("call-new", &newer_verbose),
3180 msg("user", "protected tail"),
3181 ];
3182 let original = messages.clone();
3183
3184 // Simulate the caller clearing its token budget after one suffix prune.
3185 let saved = prune_tool_results_until(&mut messages, 1, |_, saved| saved > 0);
3186
3187 assert!(saved > 0);
3188 assert_eq!(&messages[..3], &original[..3]);
3189 assert_eq!(&messages[4..], &original[4..]);
3190 let ContentBlock::ToolResult { content, .. } = &messages[3].content[0] else {
3191 panic!("expected pruned tool result");
3192 };
3193 assert!(content.contains("[read_file] tool result pruned"));
3194 assert!(content.contains("new.txt"));
3195 assert!(content.len() < newer_verbose.len());
3196 }
3197
3198 #[test]
3199 fn prune_tool_results_stops_after_newest_duplicate_prune() {
3200 let oldest = "oldest ".repeat(80);
3201 let middle = "middle ".repeat(80);
3202 let latest = "latest ".repeat(80);
3203 let mut messages = vec![
3204 tool_use("call-1", "read_file", json!({"path": "Cargo.toml"})),
3205 tool_result("call-1", &oldest),
3206 tool_use("call-2", "read_file", json!({"path": "Cargo.toml"})),
3207 tool_result("call-2", &middle),
3208 tool_use("call-3", "read_file", json!({"path": "Cargo.toml"})),
3209 tool_result("call-3", &latest),
3210 msg("user", "protected tail"),
3211 ];
3212 let original = messages.clone();
3213
3214 let saved = prune_tool_results_until(&mut messages, 1, |_, saved| saved > 0);
3215
3216 assert!(saved > 0);
3217 assert_eq!(&messages[..3], &original[..3]);
3218 assert_eq!(&messages[4..], &original[4..]);
3219 let ContentBlock::ToolResult { content, .. } = &messages[3].content[0] else {
3220 panic!("expected middle duplicate to be pruned");
3221 };
3222 assert!(content.contains("[read_file] tool result pruned"));
3223 }
3224
3225 #[test]
3226 fn prune_tool_results_dedupes_identical_reads_but_keeps_latest_full_body() {
3227 let first = "first ".repeat(80);
3228 let second = "second ".repeat(80);
3229 let mut messages = vec![
3230 tool_use("call-1", "read_file", json!({"path": "Cargo.toml"})),
3231 tool_result("call-1", &first),
3232 tool_use("call-2", "read_file", json!({"path": "Cargo.toml"})),
3233 tool_result("call-2", &second),
3234 msg("user", "tail"),
3235 ];
3236
3237 let saved = prune_tool_results(&mut messages, 1);
3238
3239 assert!(saved > 0);
3240 let ContentBlock::ToolResult { content: older, .. } = &messages[1].content[0] else {
3241 panic!("expected older tool result");
3242 };
3243 assert!(older.contains("tool result pruned"));
3244 let ContentBlock::ToolResult {
3245 content: latest, ..
3246 } = &messages[3].content[0]
3247 else {
3248 panic!("expected latest tool result");
3249 };
3250 assert_eq!(latest, &second);
3251 }
3252
3253 #[tokio::test]
3254 async fn context_window_errors_are_detected_for_summary_fallback() {
3255 let _environment = crate::test_support::lock_test_env();
3256 let _canonical = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS");
3257 let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS");
3258 for msg in [
3259 "HTTP 400 Bad Request: maximum context length is 1000000 tokens",
3260 "invalid_request_error: prompt is too long for the current model",
3261 "You requested 1000001 tokens but the maximum is 1000000",
3262 "request exceeds context window",
3263 ] {
3264 assert!(
3265 !is_context_window_error(&anyhow::anyhow!(msg)),
3266 "expected context-window detection for `{msg}`",
3267 );
3268 assert!(is_context_window_error(&anyhow::Error::new(
3269 crate::llm_client::LlmError::ContextLengthError(msg.to_string())
3270 )));
3271 }
3272
3273 assert!(!is_context_window_error(&anyhow::anyhow!(
3274 "Invalid request: missing required field"
3275 )));
3276 assert!(!is_context_window_error(&anyhow::anyhow!(
3277 "503 Service Unavailable"
3278 )));
3279 // A rejected parameter names a token or a maximum without being a
3280 // length overflow; dropping history cannot fix it.
3281 for msg in [
3282 r#"Invalid request (400): {"message":"max_tokens must be <= 8192","type":"invalid_request_error"}"#,
3283 "HTTP 422: temperature exceeds maximum 2",
3284 ] {
3285 assert!(
3286 !is_context_window_error(&anyhow::anyhow!(msg)),
3287 "a non-length rejection must not be classified as overflow: `{msg}`",
3288 );
3289 }
3290
3291 let original = vec![
3292 msg("user", "Keep the original requirement."),
3293 msg("assistant", "I will preserve the requirement."),
3294 msg("user", "Continue with the last request."),
3295 ];
3296 let before = original.clone();
3297 let client = ScriptedSummaryClient::with_outcomes(vec![
3298 Err(anyhow::Error::new(
3299 crate::llm_client::LlmError::ContextLengthError(
3300 "prompt is too long for this model's context window".to_string(),
3301 ),
3302 )),
3303 Ok(summary_content()),
3304 ]);
3305 let mut usage = Usage::default();
3306 let error = compact_messages_safe(
3307 &client,
3308 &original,
3309 None,
3310 &prepared(&CompactionConfig::default()),
3311 &mut usage,
3312 )
3313 .await
3314 .expect_err("a partial-input summary must not replace the conversation");
3315 assert!(error.to_string().contains("conversation was preserved"));
3316 {
3317 let requests = client.requests.lock().expect("requests");
3318 assert_eq!(requests.len(), 1);
3319 assert_eq!(&requests[0].messages[..original.len()], original.as_slice());
3320 }
3321 assert_eq!(original, before);
3322
3323 let mut limited = ScriptedSummaryClient::new(vec![summary_content()]);
3324 limited.limits = Some(codewhale_config::route::RouteLimits {
3325 context_tokens: Some(4_096),
3326 output_tokens: Some(8_192),
3327 output_declared: true,
3328 ..Default::default()
3329 });
3330 let large = vec![msg("user", &"a".repeat(100_000))];
3331 let before = large.clone();
3332 let error = compact_messages_safe(
3333 &limited,
3334 &large,
3335 None,
3336 &prepared(&CompactionConfig::default()),
3337 &mut usage,
3338 )
3339 .await
3340 .expect_err("an overfull summary must not omit the oldest history");
3341 assert!(error.to_string().contains("too little output room"));
3342 assert!(limited.requests.lock().expect("requests").is_empty());
3343 assert_eq!(large, before);
3344 }
3345
3346 #[test]
3347 fn tool_args_preview_redacts_sensitive_first_without_dropping_siblings() {
3348 let input: serde_json::Value = serde_json::from_str(
3349 r#"{"api_key":"sk-tool-secret-value","command":"cargo test -p auth"}"#,
3350 )
3351 .unwrap();
3352
3353 let preview: serde_json::Value = serde_json::from_str(&tool_args_preview(&input)).unwrap();
3354
3355 assert_eq!(preview["api_key"], codewhale_config::persistence::REDACTED);
3356 assert_eq!(preview["command"], "cargo test -p auth");
3357 }
3358
3359 #[test]
3360 fn tool_args_preview_redacts_sensitive_later_without_touching_earlier_fields() {
3361 let input: serde_json::Value =
3362 serde_json::from_str(r#"{"command":"cargo test","api_key":"plain-secret-value"}"#)
3363 .unwrap();
3364
3365 let preview: serde_json::Value = serde_json::from_str(&tool_args_preview(&input)).unwrap();
3366
3367 assert_eq!(preview["command"], "cargo test");
3368 assert_eq!(preview["api_key"], codewhale_config::persistence::REDACTED);
3369 }
3370
3371 #[test]
3372 fn tool_args_preview_redacts_nested_sensitive_values_recursively() {
3373 let input: serde_json::Value = serde_json::from_str(
3374 r#"{"meta":{"token":"nested-secret","keep":"yes"},"steps":[{"password":"pw","name":"a"}]}"#,
3375 )
3376 .unwrap();
3377
3378 let preview: serde_json::Value = serde_json::from_str(&tool_args_preview(&input)).unwrap();
3379
3380 assert_eq!(
3381 preview["meta"]["token"],
3382 codewhale_config::persistence::REDACTED
3383 );
3384 assert_eq!(preview["meta"]["keep"], "yes");
3385 assert_eq!(
3386 preview["steps"][0]["password"],
3387 codewhale_config::persistence::REDACTED
3388 );
3389 assert_eq!(preview["steps"][0]["name"], "a");
3390 }
3391
3392 #[test]
3393 fn tool_args_preview_redacts_complete_multi_word_secret_value() {
3394 let input: serde_json::Value =
3395 serde_json::from_str(r#"{"command":"run this","password":"hunter two words"}"#)
3396 .unwrap();
3397
3398 let serialized = tool_args_preview(&input);
3399 let preview: serde_json::Value = serde_json::from_str(&serialized).unwrap();
3400
3401 assert_eq!(preview["command"], "run this");
3402 assert_eq!(preview["password"], codewhale_config::persistence::REDACTED);
3403 assert!(!serialized.contains("hunter"));
3404 assert!(!serialized.contains("two words"));
3405 }
3406
3407 struct FixedSummaryClient {
3408 request: std::sync::Mutex<Option<MessageRequest>>,
3409 provider: &'static str,
3410 model: &'static str,
3411 summary: &'static str,
3412 }
3413
3414 impl Default for FixedSummaryClient {
3415 fn default() -> Self {
3416 Self {
3417 request: std::sync::Mutex::new(None),
3418 provider: "test",
3419 model: "test-model",
3420 summary: FIXED_SUMMARY,
3421 }
3422 }
3423 }
3424
3425 impl FixedSummaryClient {
3426 fn for_route(provider: &'static str, model: &'static str) -> Self {
3427 Self {
3428 provider,
3429 model,
3430 ..Self::default()
3431 }
3432 }
3433 }
3434
3435 const FIXED_SUMMARY: &str = "1. Primary request and intent — migrate the session store. \
3436 2. Key technical concepts — sqlite. 7. Pending tasks — finish the fixed clock. \
3437 8. Current work — rerunning the session tests.";
3438
3439 const LEGACY_SUMMARY_PREAMBLE: &str = "Another language model started to solve this problem and produced \
3440 a summary of its thinking process. You also have access to the state of the tools that were used \
3441 by that language model. Use this to build on the work that has already been done and avoid \
3442 duplicating work. Here is the summary produced by the other language model, use the information \
3443 in this summary to assist with your own analysis:";
3444
3445 /// A real PNG whose bytes are worth shrinking. Noise defeats compression,
3446 /// which is the point: the shrink ladder must actually re-encode.
3447 fn noisy_png_bytes(width: u32, height: u32) -> Vec<u8> {
3448 use image::ImageEncoder as _;
3449 let mut pixels = image::RgbImage::new(width, height);
3450 for (x, y, pixel) in pixels.enumerate_pixels_mut() {
3451 *pixel = image::Rgb([
3452 (x.wrapping_mul(31) ^ y.wrapping_mul(17)) as u8,
3453 (x.wrapping_mul(7) ^ y.wrapping_mul(29)) as u8,
3454 (x.wrapping_add(y).wrapping_mul(13)) as u8,
3455 ]);
3456 }
3457 let mut bytes = Vec::new();
3458 image::codecs::png::PngEncoder::new_with_quality(
3459 &mut bytes,
3460 image::codecs::png::CompressionType::Fast,
3461 image::codecs::png::FilterType::NoFilter,
3462 )
3463 .write_image(
3464 pixels.as_raw(),
3465 width,
3466 height,
3467 image::ExtendedColorType::Rgb8,
3468 )
3469 .expect("encode fixture png");
3470 bytes
3471 }
3472
3473 fn png_data_url(width: u32, height: u32) -> String {
3474 use base64::Engine as _;
3475 format!(
3476 "data:image/png;base64,{}",
3477 base64::engine::general_purpose::STANDARD.encode(noisy_png_bytes(width, height))
3478 )
3479 }
3480
3481 fn user_image_message(data_url: &str) -> Message {
3482 Message {
3483 role: Role::User,
3484 content: vec![
3485 ContentBlock::Text {
3486 text: "look at this screenshot".to_string(),
3487 cache_control: None,
3488 },
3489 ContentBlock::ImageUrl {
3490 image_url: ImageUrlContent {
3491 url: data_url.to_string(),
3492 },
3493 },
3494 ],
3495 }
3496 }
3497
3498 /// Total inline-image URL bytes a request carries, the byte side an HTTP
3499 /// 413 boundary actually measures.
3500 fn inline_image_bytes(request: &MessageRequest) -> usize {
3501 request
3502 .messages
3503 .iter()
3504 .flat_map(|message| message.content.iter())
3505 .map(|block| match block {
3506 ContentBlock::ImageUrl { image_url } => image_url.url.len(),
3507 ContentBlock::ToolResult { content_blocks, .. } => {
3508 content_blocks.as_ref().map_or(0, |blocks| {
3509 blocks.iter().fold(0, |sum, block| {
3510 let nested = block
3511 .get("data")
3512 .and_then(serde_json::Value::as_str)
3513 .map_or(0, str::len);
3514 sum + nested
3515 })
3516 })
3517 }
3518 _ => 0,
3519 })
3520 .sum()
3521 }
3522
3523 fn summary_content() -> Vec<ContentBlock> {
3524 vec![ContentBlock::Text {
3525 text: "1. Primary request: keep working on the session store. \
3526 7. Pending: rerun the tests."
3527 .to_string(),
3528 cache_control: None,
3529 }]
3530 }
3531
3532 fn request_body_413() -> anyhow::Error {
3533 crate::llm_client::LlmError::from_http_response(413, "request rejected").into()
3534 }
3535
3536 /// The same boundary stated by a fronting gateway (openresty) instead of
3537 /// the API's own body reader. Reported on 2026-09-26; the ladder must
3538 /// treat it as the same byte-side rejection.
3539 fn request_body_413_html_gateway() -> anyhow::Error {
3540 crate::llm_client::LlmError::from_http_response(
3541 413,
3542 "413 Request Entity Too Large openresty",
3543 )
3544 .into()
3545 }
3546
3547 #[derive(Debug, Default)]
3548 struct RecordingNoticeSink {
3549 messages: std::sync::Mutex<Vec<String>>,
3550 }
3551
3552 impl RecordingNoticeSink {
3553 fn messages(&self) -> Vec<String> {
3554 self.messages.lock().expect("notice sink").clone()
3555 }
3556 }
3557
3558 impl CompactionNoticeSink for RecordingNoticeSink {
3559 fn notice(&self, message: String) {
3560 self.messages.lock().expect("notice sink").push(message);
3561 }
3562 }
3563
3564 /// A 900x900 noise PNG exceeds the 2 MiB inline-image budget, so the
3565 /// ladder must actually rewrite it.
3566 fn body_413_retry_envelope(
3567 sink: std::sync::Arc<RecordingNoticeSink>,
3568 ) -> PreparedCompactionEnvelope {
3569 let mut envelope = prepared(&CompactionConfig {
3570 enabled: false,
3571 ..CompactionConfig::default()
3572 });
3573 envelope.notice_sink = Some(sink);
3574 envelope
3575 }
3576
3577 #[tokio::test]
3578 async fn request_body_413_reencodes_images_smaller_and_retries() {
3579 let _environment = crate::test_support::lock_test_env();
3580 let messages = vec![
3581 msg("user", "context before the screenshots"),
3582 user_image_message(&png_data_url(900, 900)),
3583 ];
3584 let client = ScriptedSummaryClient::with_outcomes(vec![
3585 Err(request_body_413()),
3586 Ok(summary_content()),
3587 ]);
3588 let sink = std::sync::Arc::new(RecordingNoticeSink::default());
3589 let envelope = body_413_retry_envelope(sink.clone());
3590 let mut usage = Usage::default();
3591
3592 let result = compact_messages_safe(&client, &messages, None, &envelope, &mut usage).await;
3593 assert!(result.is_ok(), "the retry after shrinking must succeed");
3594
3595 let requests = client.requests.lock().expect("requests").clone();
3596 assert_eq!(requests.len(), 2, "one rejection, one retry");
3597 let first = inline_image_bytes(&requests[0]);
3598 let second = inline_image_bytes(&requests[1]);
3599 assert!(first > 0, "the fixture must carry the image");
3600 assert!(
3601 second > 0 && second < first,
3602 "the retry must carry smaller image bytes ({second} < {first})"
3603 );
3604 let notices = sink.messages();
3605 assert_eq!(notices.len(), 1, "one notice per downgrade: {notices:?}");
3606 assert!(
3607 notices[0].contains("re-encoded") && notices[0].contains("413"),
3608 "the notice must name the downgrade: {notices:?}"
3609 );
3610 }
3611
3612 #[tokio::test]
3613 async fn request_body_413_after_shrinking_replaces_images_with_notes() {
3614 let _environment = crate::test_support::lock_test_env();
3615 let messages = vec![
3616 msg("user", "context before the screenshots"),
3617 user_image_message(&png_data_url(900, 900)),
3618 ];
3619 let client = ScriptedSummaryClient::with_outcomes(vec![
3620 Err(request_body_413()),
3621 Err(request_body_413()),
3622 Ok(summary_content()),
3623 ]);
3624 let sink = std::sync::Arc::new(RecordingNoticeSink::default());
3625 let envelope = body_413_retry_envelope(sink.clone());
3626 let mut usage = Usage::default();
3627
3628 let result = compact_messages_safe(&client, &messages, None, &envelope, &mut usage).await;
3629 assert!(
3630 result.is_ok(),
3631 "the retry after replacing images must succeed"
3632 );
3633
3634 let requests = client.requests.lock().expect("requests").clone();
3635 assert_eq!(requests.len(), 3, "reject, shrink retry, replace retry");
3636 let first = inline_image_bytes(&requests[0]);
3637 let second = inline_image_bytes(&requests[1]);
3638 let third = inline_image_bytes(&requests[2]);
3639 assert!(second > 0 && second < first);
3640 assert_eq!(third, 0, "the last rung carries no image bytes");
3641 let note_present = requests[2].messages.iter().any(|message| {
3642 message.content.iter().any(|block| match block {
3643 ContentBlock::Text { text, .. } => text.contains("omitted from this summary pass"),
3644 _ => false,
3645 })
3646 });
3647 assert!(note_present, "the summarizer is told what was there");
3648 let notices = sink.messages();
3649 assert_eq!(notices.len(), 2, "one notice per rung: {notices:?}");
3650 assert!(notices[1].contains("replaced"), "{notices:?}");
3651 }
3652
3653 #[tokio::test]
3654 async fn request_body_413_from_a_gateway_html_page_enters_the_same_ladder() {
3655 let _environment = crate::test_support::lock_test_env();
3656 let messages = vec![
3657 msg("user", "context before the screenshots"),
3658 user_image_message(&png_data_url(900, 900)),
3659 ];
3660 let client = ScriptedSummaryClient::with_outcomes(vec![
3661 Err(request_body_413_html_gateway()),
3662 Ok(summary_content()),
3663 ]);
3664 let sink = std::sync::Arc::new(RecordingNoticeSink::default());
3665 let envelope = body_413_retry_envelope(sink.clone());
3666 let mut usage = Usage::default();
3667
3668 let result = compact_messages_safe(&client, &messages, None, &envelope, &mut usage).await;
3669 assert!(
3670 result.is_ok(),
3671 "the gateway-page rejection must enter the ladder"
3672 );
3673 let requests = client.requests.lock().expect("requests").clone();
3674 assert_eq!(requests.len(), 2, "one rejection, one retry");
3675 assert!(
3676 inline_image_bytes(&requests[1]) < inline_image_bytes(&requests[0]),
3677 "the retry must carry smaller image bytes"
3678 );
3679 let notices = sink.messages();
3680 assert_eq!(
3681 notices.len(),
3682 1,
3683 "the user hears about the downgrade: {notices:?}"
3684 );
3685 assert!(notices[0].contains("413"), "{notices:?}");
3686 }
3687
3688 #[tokio::test]
3689 async fn request_body_413_with_in_budget_images_skips_the_noop_retry_and_replaces() {
3690 // The images fit their share of the 2 MiB budget, yet the endpoint
3691 // refused the body: the cap sits below the budget. The ladder must not
3692 // report "no images" (which would fail the pass outright) and must not
3693 // resend identical bytes — it goes straight to the replace rung.
3694 let _environment = crate::test_support::lock_test_env();
3695 let messages = vec![
3696 msg("user", "context before the screenshot"),
3697 user_image_message(&png_data_url(64, 64)),
3698 ];
3699 let client = ScriptedSummaryClient::with_outcomes(vec![
3700 Err(request_body_413()),
3701 Ok(summary_content()),
3702 ]);
3703 let sink = std::sync::Arc::new(RecordingNoticeSink::default());
3704 let envelope = body_413_retry_envelope(sink.clone());
3705 let mut usage = Usage::default();
3706
3707 let result = compact_messages_safe(&client, &messages, None, &envelope, &mut usage).await;
3708 assert!(
3709 result.is_ok(),
3710 "in-budget images must still let the ladder finish"
3711 );
3712 let requests = client.requests.lock().expect("requests").clone();
3713 assert_eq!(requests.len(), 2, "replace directly, no identical retry");
3714 assert!(
3715 inline_image_bytes(&requests[0]) > 0,
3716 "the fixture carried the image"
3717 );
3718 assert_eq!(
3719 inline_image_bytes(&requests[1]),
3720 0,
3721 "the retry carries notes, not bytes"
3722 );
3723 let notices = sink.messages();
3724 assert_eq!(
3725 notices.len(),
3726 1,
3727 "one notice for the replace rung: {notices:?}"
3728 );
3729 assert!(notices[0].contains("replaced"), "{notices:?}");
3730 }
3731
3732 #[tokio::test]
3733 async fn request_body_413_without_inline_images_fails_with_context() {
3734 let _environment = crate::test_support::lock_test_env();
3735 let messages = vec![msg("user", "no images anywhere in this history")];
3736 let client = ScriptedSummaryClient::with_outcomes(vec![Err(request_body_413())]);
3737 let sink = std::sync::Arc::new(RecordingNoticeSink::default());
3738 let envelope = body_413_retry_envelope(sink.clone());
3739 let mut usage = Usage::default();
3740
3741 let error = compact_messages_safe(&client, &messages, None, &envelope, &mut usage)
3742 .await
3743 .expect_err("nothing left to shrink, the pass must fail");
3744 let text = format!("{error:#}");
3745 assert!(
3746 text.contains("request-body limit"),
3747 "the failure must name the boundary: {text}"
3748 );
3749 let requests = client.requests.lock().expect("requests").clone();
3750 assert_eq!(requests.len(), 1, "no pointless identical retry");
3751 assert!(sink.messages().is_empty(), "nothing was downgraded");
3752 }
3753
3754 #[tokio::test]
3755 async fn request_body_413_after_replacements_fails_with_the_full_ladder() {
3756 let _environment = crate::test_support::lock_test_env();
3757 let messages = vec![
3758 msg("user", "context before the screenshots"),
3759 user_image_message(&png_data_url(900, 900)),
3760 ];
3761 let client = ScriptedSummaryClient::with_outcomes(vec![
3762 Err(request_body_413()),
3763 Err(request_body_413()),
3764 Err(request_body_413()),
3765 ]);
3766 let sink = std::sync::Arc::new(RecordingNoticeSink::default());
3767 let envelope = body_413_retry_envelope(sink.clone());
3768 let mut usage = Usage::default();
3769
3770 let error = compact_messages_safe(&client, &messages, None, &envelope, &mut usage)
3771 .await
3772 .expect_err("every rung refused, the pass must fail");
3773 let text = format!("{error:#}");
3774 assert!(
3775 text.contains("even after re-encoding and then replacing"),
3776 "the failure must report the full ladder: {text}"
3777 );
3778 let requests = client.requests.lock().expect("requests").clone();
3779 assert_eq!(requests.len(), 3, "two retries, then stop");
3780 assert_eq!(sink.messages().len(), 2, "both rungs announced");
3781 }
3782
3783 struct ScriptedSummaryClient {
3784 responses: std::sync::Mutex<std::collections::VecDeque<anyhow::Result<Vec<ContentBlock>>>>,
3785 requests: std::sync::Mutex<Vec<MessageRequest>>,
3786 retry_started: Option<std::sync::Arc<tokio::sync::Notify>>,
3787 limits: Option<codewhale_config::route::RouteLimits>,
3788 }
3789
3790 impl ScriptedSummaryClient {
3791 fn new(responses: Vec<Vec<ContentBlock>>) -> Self {
3792 Self::with_outcomes(responses.into_iter().map(Ok).collect())
3793 }
3794
3795 fn with_outcomes(responses: Vec<anyhow::Result<Vec<ContentBlock>>>) -> Self {
3796 Self {
3797 responses: std::sync::Mutex::new(responses.into()),
3798 requests: std::sync::Mutex::new(Vec::new()),
3799 retry_started: None,
3800 limits: None,
3801 }
3802 }
3803 }
3804
3805 #[async_trait::async_trait]
3806 impl crate::core::model_client::ModelClient for ScriptedSummaryClient {
3807 fn provider_name(&self) -> &str {
3808 "test"
3809 }
3810
3811 fn model(&self) -> &str {
3812 "test-model"
3813 }
3814
3815 fn route_limits(&self) -> Option<codewhale_config::route::RouteLimits> {
3816 self.limits
3817 }
3818
3819 async fn create_message(
3820 &self,
3821 request: MessageRequest,
3822 ) -> anyhow::Result<codewhale_models::MessageResponse> {
3823 self.requests
3824 .lock()
3825 .expect("capture scripted summary request")
3826 .push(request);
3827 let outcome = self
3828 .responses
3829 .lock()
3830 .expect("read scripted summary response")
3831 .pop_front();
3832 if outcome.is_none()
3833 && let Some(retry_started) = &self.retry_started
3834 {
3835 retry_started.notify_one();
3836 return std::future::pending().await;
3837 }
3838 let content = outcome
3839 .ok_or_else(|| anyhow::anyhow!("scripted summary responses exhausted"))??;
3840 Ok(codewhale_models::MessageResponse {
3841 tool_projection_warning: None,
3842 id: "summary-scripted".to_string(),
3843 r#type: "message".to_string(),
3844 role: "assistant".to_string(),
3845 content,
3846 model: "test-model".to_string(),
3847 stop_reason: None,
3848 stop_sequence: None,
3849 container: None,
3850 title: None,
3851 stop_details: None,
3852 refusal: None,
3853 usage: Usage {
3854 input_tokens: 17,
3855 output_tokens: 3,
3856 prompt_cache_hit_tokens: Some(5),
3857 reasoning_tokens: Some(2),
3858 ..Usage::default()
3859 },
3860 })
3861 }
3862
3863 async fn create_message_stream(
3864 &self,
3865 _request: MessageRequest,
3866 ) -> anyhow::Result<crate::llm_client::StreamEventBox> {
3867 anyhow::bail!("streaming is unused by compaction")
3868 }
3869
3870 async fn health_check(&self) -> anyhow::Result<bool> {
3871 Ok(true)
3872 }
3873 }
3874
3875 #[async_trait::async_trait]
3876 impl crate::core::model_client::ModelClient for FixedSummaryClient {
3877 fn provider_name(&self) -> &str {
3878 self.provider
3879 }
3880
3881 fn model(&self) -> &str {
3882 self.model
3883 }
3884
3885 async fn create_message(
3886 &self,
3887 request: MessageRequest,
3888 ) -> anyhow::Result<codewhale_models::MessageResponse> {
3889 *self.request.lock().expect("capture summary request") = Some(request);
3890 Ok(codewhale_models::MessageResponse {
3891 tool_projection_warning: None,
3892 id: "summary-fixture".to_string(),
3893 r#type: "message".to_string(),
3894 role: "assistant".to_string(),
3895 content: vec![ContentBlock::Text {
3896 text: self.summary.to_string(),
3897 cache_control: None,
3898 }],
3899 model: self.model.to_string(),
3900 stop_reason: None,
3901 stop_sequence: None,
3902 container: None,
3903 usage: codewhale_models::Usage::default(),
3904 title: None,
3905 stop_details: None,
3906 refusal: None,
3907 })
3908 }
3909
3910 async fn create_message_stream(
3911 &self,
3912 _request: MessageRequest,
3913 ) -> anyhow::Result<crate::llm_client::StreamEventBox> {
3914 anyhow::bail!("streaming is unused by compaction")
3915 }
3916
3917 async fn health_check(&self) -> anyhow::Result<bool> {
3918 Ok(true)
3919 }
3920 }
3921
3922 #[tokio::test]
3923 async fn compaction_persists_original_and_model_handoff_before_returning_replacement() {
3924 let _environment = crate::test_support::lock_test_env();
3925 let root = tempfile::tempdir().unwrap();
3926 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.path());
3927 let original = (0..12)
3928 .map(|i| {
3929 msg(
3930 if i % 2 == 0 { "user" } else { "assistant" },
3931 &format!("Work item {i}"),
3932 )
3933 })
3934 .collect::<Vec<_>>();
3935 let mut envelope = prepared(&CompactionConfig::default());
3936 envelope.session_id = Some("handoff-test".into());
3937 let client = FixedSummaryClient::default();
3938 let mut usage = Usage::default();
3939 let result = compact_messages_safe(&client, &original, None, &envelope, &mut usage)
3940 .await
3941 .unwrap();
3942 assert!(result.summary_prompt.is_some());
3943 let files = std::fs::read_dir(root.path().join("sessions/handoff-test/artifacts"))
3944 .unwrap()
3945 .map(|entry| entry.unwrap().path())
3946 .collect::<Vec<_>>();
3947 let json = files
3948 .iter()
3949 .find(|path| path.extension().is_some_and(|ext| ext == "json"))
3950 .unwrap();
3951 let restored: Vec<Message> = serde_json::from_slice(&std::fs::read(json).unwrap()).unwrap();
3952 assert_eq!(restored, original);
3953 let markdown = files
3954 .iter()
3955 .find(|path| path.extension().is_some_and(|ext| ext == "md"))
3956 .unwrap();
3957 assert!(
3958 std::fs::read_to_string(markdown)
3959 .unwrap()
3960 .contains("migrate the session store")
3961 );
3962 // An unwritable artifact destination must abort before a provider call.
3963 envelope.session_id = Some("blocked-handoff".into());
3964 std::fs::write(
3965 root.path().join("sessions/blocked-handoff"),
3966 b"not a directory",
3967 )
3968 .unwrap();
3969 let blocked = FixedSummaryClient::default();
3970 assert!(
3971 compact_messages_safe(&blocked, &original, None, &envelope, &mut usage)
3972 .await
3973 .is_err()
3974 );
3975 assert!(blocked.request.lock().unwrap().is_none());
3976 }
3977
3978 #[tokio::test]
3979 async fn compaction_commits_summary_and_retains_recent_user_messages() {
3980 let messages = vec![
3981 msg(
3982 "user",
3983 "Objective: migrate the session store to sqlite without breaking existing logins",
3984 ),
3985 msg("assistant", "Working on it."),
3986 tool_use(
3987 "t1",
3988 "Bash",
3989 json!({"command": "cargo test -p session-store"}),
3990 ),
3991 tool_result("t1", "test session_store::roundtrip ... ok\nexit code 0"),
3992 msg("user", "Sounds good, do it"),
3993 msg("assistant", "Nearly done, rerunning the suite."),
3994 ];
3995 let config = CompactionConfig {
3996 model: "test-model".to_string(),
3997 cache_summary: false,
3998 ..Default::default()
3999 };
4000 let client = FixedSummaryClient::default();
4001
4002 let (retained, summary_prompt, _) =
4003 compact_messages(&client, &messages, &config).await.unwrap();
4004
4005 let request = client
4006 .request
4007 .lock()
4008 .expect("read summary request")
4009 .clone()
4010 .expect("summary request was captured");
4011 assert_eq!(&request.messages[..messages.len()], messages.as_slice());
4012 assert_eq!(request.messages.len(), messages.len() + 1);
4013 let ContentBlock::Text { text, .. } = &request.messages.last().unwrap().content[0] else {
4014 panic!("final compaction instruction must be text");
4015 };
4016 assert!(!text.contains(COMPACTION_SUMMARY_MARKER));
4017 assert_eq!(request.temperature, None);
4018 assert_eq!(request.top_p, None);
4019 assert_eq!(
4020 request.max_tokens,
4021 crate::route_budget::effective_max_output_tokens_for_route(
4022 codewhale_config::ProviderKind::Custom,
4023 "test-model",
4024 None,
4025 )
4026 );
4027
4028 let Some(SystemPrompt::Blocks(blocks)) = summary_prompt else {
4029 panic!("compaction must produce a summary system block");
4030 };
4031 let text = &blocks[0].text;
4032 assert!(text.contains(FIXED_SUMMARY));
4033 assert!(text.starts_with(COMPACTION_SUMMARY_MARKER));
4034
4035 // Replacement history keeps older user turns, then the open round
4036 // verbatim (user + assistant + tools), then one checkpoint.
4037 assert!(retained.iter().any(|message| {
4038 user_text_of(message).is_some_and(|text| text.contains("Objective: migrate"))
4039 }));
4040 assert!(
4041 retained
4042 .iter()
4043 .any(|message| { user_text_of(message).as_deref() == Some("Sounds good, do it") })
4044 );
4045 assert!(retained.iter().any(|message| {
4046 message.role.is_assistant_like()
4047 && message.content.iter().any(|block| {
4048 matches!(
4049 block,
4050 ContentBlock::Text { text, .. }
4051 if text.contains("Nearly done, rerunning the suite.")
4052 )
4053 })
4054 }));
4055 assert!(retained.iter().any(|message| {
4056 message.content.iter().any(|block| {
4057 matches!(
4058 block,
4059 ContentBlock::ToolResult { content, .. }
4060 if content.contains("session_store::roundtrip")
4061 )
4062 })
4063 }));
4064 assert!(is_compaction_checkpoint_message(retained.last().unwrap()));
4065 assert!(is_wire_compaction_checkpoint_message(
4066 retained.last().unwrap()
4067 ));
4068 assert!(matches!(
4069 &retained.last().unwrap().content[0],
4070 ContentBlock::Text { text: checkpoint, .. } if checkpoint == text
4071 ));
4072 last_round::validate_retained_coverage(&messages, &retained[..retained.len() - 1], 20_000)
4073 .unwrap();
4074 }
4075
4076 #[tokio::test]
4077 async fn compaction_preserves_legacy_header_user_message_across_passes() {
4078 let pasted = msg(
4079 "user",
4080 &format!("{LEGACY_SUMMARY_PREAMBLE}\n\nPlease keep my original words."),
4081 );
4082 let later = msg("user", "Check the remaining work.");
4083 let call = tool_use("check", "File", json!({"path": "session.rs"}));
4084 let result = tool_result("check", "Found the session store.");
4085 let mut messages = vec![
4086 pasted.clone(),
4087 msg("assistant", "I can explain that text."),
4088 later.clone(),
4089 call.clone(),
4090 result.clone(),
4091 ];
4092 let prepared = PreparedCompactionEnvelope::new(CompactionConfig {
4093 token_threshold: 250,
4094 retained_user_message_tokens: 256,
4095 ..CompactionConfig::default()
4096 });
4097 let client = FixedSummaryClient::default();
4098 let mut quality_retries = 0;
4099 let mut usage = Usage::default();
4100 for pass in 1..=2 {
4101 assert!(
4102 last_round::recent_tail_start(&messages, prepared.retained_recent_tokens(None)) > 0
4103 );
4104 let (retained, summary, _) = compact_messages_with_metadata(
4105 &client,
4106 &messages,
4107 None,
4108 &prepared,
4109 &mut quality_retries,
4110 &mut usage,
4111 )
4112 .await
4113 .unwrap();
4114 assert_eq!(
4115 retained
4116 .iter()
4117 .filter(|message| *message == &pasted)
4118 .count(),
4119 1,
4120 "pass {pass} must retain one verbatim copy of the pasted header"
4121 );
4122 assert_eq!(
4123 retained
4124 .iter()
4125 .filter(|message| is_wire_compaction_checkpoint_message(message))
4126 .count(),
4127 1,
4128 "pass {pass} must install one stamped checkpoint"
4129 );
4130 assert_eq!(
4131 retained.last(),
4132 Some(&compaction_checkpoint_message(&summary.unwrap()))
4133 );
4134 assert!(
4135 retained
4136 .windows(3)
4137 .any(|window| window == [&later, &call, &result].map(Clone::clone))
4138 );
4139 if let Some(previous) = messages
4140 .last()
4141 .filter(|message| is_wire_compaction_checkpoint_message(message))
4142 {
4143 let request = client.request.lock().unwrap();
4144 assert!(request.as_ref().unwrap().messages.contains(previous));
4145 }
4146 messages = retained;
4147 }
4148 }
4149
4150 #[tokio::test]
4151 async fn compaction_safe_legacy_paste_shrinks_twice_with_complete_tool_pairs() {
4152 let first = msg("user", "Keep investigating.");
4153 let pasted = msg(
4154 "user",
4155 &format!("{LEGACY_SUMMARY_PREAMBLE}\n\nPlease keep my original words."),
4156 );
4157 let large_call = |id| {
4158 let mut call = tool_use(id, "File", json!({"path": id}));
4159 call.content
4160 .extend(msg("assistant", &"x".repeat(8_000)).content);
4161 call
4162 };
4163 let mut mixed = tool_result("old", "Old evidence.");
4164 mixed.content.extend(pasted.content.clone());
4165 let older_exchange = [large_call("old"), mixed];
4166 let mut messages = vec![first.clone()];
4167 messages.extend(older_exchange.clone());
4168 let prepared = PreparedCompactionEnvelope::new(CompactionConfig {
4169 token_threshold: 1_024,
4170 retained_user_message_tokens: 256,
4171 ..CompactionConfig::default()
4172 });
4173
4174 for (id, summary) in [
4175 ("first", "First check complete."),
4176 ("second", "Second check complete."),
4177 ] {
4178 let previous = messages
4179 .last()
4180 .filter(|message| is_checkpoint_for_compaction(message))
4181 .cloned();
4182 if previous.is_some() {
4183 messages.extend([
4184 large_call("reclaim"),
4185 tool_result("reclaim", "More evidence."),
4186 ]);
4187 }
4188 let call = tool_use(id, "File", json!({"path": id}));
4189 let result = tool_result(id, &"y".repeat(800));
4190 messages.extend([call.clone(), result.clone()]);
4191 let before = estimate_request_input_tokens(&messages, None, None);
4192 assert!(before >= prepared.config.token_threshold);
4193 let client = FixedSummaryClient {
4194 summary,
4195 ..FixedSummaryClient::default()
4196 };
4197 let kept =
4198 compact_messages_safe(&client, &messages, None, &prepared, &mut Usage::default())
4199 .await
4200 .unwrap();
4201 assert_eq!(kept.coverage.path, CompactionPath::Summary);
4202 let after = estimate_request_input_tokens(&kept.messages, None, None);
4203 assert!(after < before, "{id}: {before} -> {after}");
4204 let next = compaction_checkpoint_message(&SystemPrompt::Text(
4205 build_compaction_summary_block_text(summary, ""),
4206 ));
4207 assert_eq!(
4208 kept.messages,
4209 [first.clone(), pasted.clone(), call, result, next]
4210 );
4211
4212 let request = client.request.into_inner().unwrap().unwrap();
4213 if let Some(previous) = previous {
4214 assert!(request.messages.contains(&previous));
4215 assert!(!kept.messages.contains(&previous));
4216 } else {
4217 assert!(
4218 request
4219 .messages
4220 .windows(2)
4221 .any(|pair| pair == older_exchange)
4222 );
4223 }
4224 messages = kept.messages;
4225 }
4226 }
4227
4228 #[tokio::test]
4229 async fn compaction_safe_legacy_tail_requires_a_saved_checkpoint_to_shrink() {
4230 let legacy = format!("{LEGACY_SUMMARY_PREAMBLE}\n\n{}", "z".repeat(8_000));
4231 let original = [
4232 msg("user", "Please continue."),
4233 msg("assistant", &"a".repeat(400)),
4234 msg("user", &legacy),
4235 ];
4236 let messages = original.clone();
4237 let prepared = PreparedCompactionEnvelope::new(CompactionConfig {
4238 token_threshold: 1_024,
4239 ..CompactionConfig::default()
4240 });
4241 let before = estimate_request_input_tokens(&messages, None, None);
4242 assert!(before >= prepared.config.token_threshold);
4243 let client = FixedSummaryClient::default();
4244 let mut usage = Usage::default();
4245 let error = compact_messages_safe(&client, &messages, None, &prepared, &mut usage)
4246 .await
4247 .unwrap_err();
4248 assert_eq!(
4249 error.to_string(),
4250 "Making room did not shrink the context; the original conversation was preserved."
4251 );
4252 assert_eq!(messages, original);
4253
4254 let saved = SystemPrompt::Text(format!(
4255 "{COMPACTION_SUMMARY_BEGIN}\n{legacy}\n{COMPACTION_SUMMARY_END}"
4256 ));
4257 let summary = extract_compaction_summary(Some(&saved)).unwrap();
4258 let checkpoint = compaction_checkpoint_message(&summary);
4259 let restored = restore_compaction_checkpoint(original.to_vec(), Some(&summary));
4260 assert_eq!(
4261 restored,
4262 [
4263 original[0].clone(),
4264 original[1].clone(),
4265 checkpoint.clone(),
4266 original[2].clone(),
4267 ]
4268 );
4269 let result = compact_messages_safe(&client, &restored, None, &prepared, &mut usage)
4270 .await
4271 .unwrap();
4272 assert_eq!(result.coverage.path, CompactionPath::Summary);
4273 assert!(
4274 estimate_request_input_tokens(&result.messages, None, None)
4275 < estimate_request_input_tokens(&restored, None, None)
4276 );
4277 let request = client.request.into_inner().unwrap().unwrap();
4278 assert!(request.messages.contains(&checkpoint));
4279 assert!(!result.messages.contains(&checkpoint));
4280 assert_eq!(
4281 result
4282 .messages
4283 .iter()
4284 .filter(|msg| *msg == &original[2])
4285 .count(),
4286 1
4287 );
4288 assert_eq!(
4289 result
4290 .messages
4291 .iter()
4292 .filter(|message| is_checkpoint_for_compaction(message))
4293 .count(),
4294 1
4295 );
4296 }
4297
4298 #[tokio::test]
4299 async fn uninterrupted_task_compacts_repeatedly_with_original_prefix_and_recent_tool_pairs() {
4300 let system = SystemPrompt::Text("stable project instructions and permissions".into());
4301 let mut prepared = PreparedCompactionEnvelope::new(CompactionConfig {
4302 token_threshold: 40_000,
4303 model: "test-model".into(),
4304 ..Default::default()
4305 });
4306 prepared.tools = Some(vec![
4307 serde_json::from_value(json!({
4308 "name": "File", "description": "Read a file", "input_schema": {"type": "object"}
4309 }))
4310 .unwrap(),
4311 ]);
4312 let client = FixedSummaryClient::default();
4313 let mut messages = vec![msg(
4314 "user",
4315 "Finish the migration. Preserve logins; do not publish.",
4316 )];
4317 for epoch in 0..3 {
4318 for step in 0..20 {
4319 let id = format!("{epoch}-{step}");
4320 let mut call = tool_use(&id, "File", json!({"path":"session.rs"}));
4321 call.content.insert(
4322 0,
4323 ContentBlock::Text {
4324 text: format!("Evidence {id}: {}", "x".repeat(12_000)),
4325 cache_control: None,
4326 },
4327 );
4328 if step == 19 {
4329 call.content.insert(
4330 0,
4331 ContentBlock::Thinking {
4332 thinking: "retained reasoning ".repeat(2000),
4333 signature: None,
4334 state: None,
4335 redacted_data: None,
4336 },
4337 );
4338 }
4339 messages.push(call);
4340 messages.push(tool_result(
4341 &id,
4342 &format!("Observed {id}: {}", "e".repeat(1000)),
4343 ));
4344 }
4345 let original = messages.clone();
4346 let mut usage = Usage::default();
4347 let result =
4348 compact_messages_safe(&client, &messages, Some(&system), &prepared, &mut usage)
4349 .await
4350 .unwrap();
4351 let request = client.request.lock().unwrap().clone().unwrap();
4352 assert_eq!(request.system.as_ref(), Some(&system));
4353 assert_eq!(request.tools, prepared.tools);
4354 assert_eq!(
4355 request.tool_choice,
4356 Some(crate::core::engine::tool_catalog::default_tool_choice(
4357 false
4358 ))
4359 );
4360 let tail_start = last_round::recent_tail_start(
4361 &original,
4362 prepared.retained_recent_tokens(Some(&system)),
4363 );
4364 let summary_history = original
4365 .iter()
4366 .enumerate()
4367 .filter(|(idx, message)| *idx < tail_start || is_checkpoint_for_compaction(message))
4368 .map(|(_, message)| message.clone())
4369 .collect::<Vec<_>>();
4370 assert_eq!(
4371 &request.messages[..summary_history.len()],
4372 summary_history.as_slice(),
4373 "summary must see the original older span and prior checkpoint"
4374 );
4375 assert_eq!(request.messages.len(), summary_history.len() + 1);
4376 assert!(estimate_tokens(&result.messages) < estimate_tokens(&original) / 2);
4377 assert_eq!(
4378 result
4379 .messages
4380 .iter()
4381 .filter(|m| is_checkpoint_for_compaction(m))
4382 .count(),
4383 1
4384 );
4385 for expected in &original[tail_start..] {
4386 if is_checkpoint_for_compaction(expected) {
4387 continue;
4388 }
4389 assert!(
4390 result.messages.contains(expected),
4391 "selected recent messages, including calls and reasoning, must survive unchanged"
4392 );
4393 }
4394 assert_eq!(result.messages[0], original[0]);
4395 messages = result.messages;
4396 }
4397 }
4398
4399 #[test]
4400 fn coverage_floor_rejects_a_replacement_that_drops_last_round_assistant() {
4401 let original = vec![
4402 msg("user", "What failed?"),
4403 msg("assistant", "session_store::roundtrip panics on reload."),
4404 ];
4405 let gutting = vec![msg("user", "What failed?")];
4406 let error = last_round::validate_retained_coverage(&original, &gutting, 20_000)
4407 .expect_err("dropping last-round assistant text must fail closed");
4408 assert!(error.to_string().contains("assistant"), "{error}");
4409 }
4410
4411 #[tokio::test]
4412 async fn compaction_preserves_runtime_provenance_and_saved_user_title() {
4413 let runtime = crate::runtime_handoff::operate_contract_runtime_message();
4414 let mut user = msg("user", "Build a focus timer");
4415 user.content.push(ContentBlock::Text {
4416 text: "<turn_meta>\nInput provenance: external_user\nInput authority: external_current_turn\n</turn_meta>".to_string(),
4417 cache_control: None,
4418 });
4419 let messages = vec![
4420 runtime.clone(),
4421 msg("assistant", "Ready."),
4422 user.clone(),
4423 msg("assistant", "Building the timer."),
4424 msg("user", "Keep the controls simple"),
4425 msg("assistant", "Adding start and stop."),
4426 ];
4427 let (retained, summary, _) = compact_messages(
4428 &FixedSummaryClient::default(),
4429 &messages,
4430 &CompactionConfig::default(),
4431 )
4432 .await
4433 .unwrap();
4434 assert_eq!(retained.first(), Some(&runtime));
4435 assert!(retained.contains(&user));
4436 assert!(crate::runtime_handoff::is_operate_contract_message(
4437 &retained[0]
4438 ));
4439 let saved = crate::session_manager::create_saved_session_with_mode(
4440 &retained,
4441 "test-model",
4442 std::path::Path::new("."),
4443 0,
4444 summary.as_ref(),
4445 None,
4446 );
4447 let restored: crate::session_manager::SavedSession =
4448 serde_json::from_slice(&serde_json::to_vec(&saved).unwrap()).unwrap();
4449 assert_eq!(restored.metadata.title, "Build a focus timer");
4450 assert_eq!(restored.messages, retained);
4451 }
4452
4453 #[test]
4454 fn retained_literal_runtime_xml_remains_user_authored() {
4455 let runtime = crate::runtime_handoff::operate_contract_runtime_message();
4456 // A user may paste the exact bytes, including a metadata example, in
4457 // one ordinary text block. Compaction must not split it into authority.
4458 let literal = user_text_of(&runtime).unwrap();
4459 let user = msg("user", &literal);
4460 let retained = retained_user_messages(std::slice::from_ref(&user), usize::MAX);
4461 assert_eq!(retained, vec![user]);
4462 assert_eq!(
4463 codewhale_models::turn_classify::classify_user_turn_prompt(&retained[0]),
4464 codewhale_models::turn_classify::UserTurnPromptKind::Editable,
4465 );
4466 assert_eq!(
4467 crate::session_manager::conversation_title_prompt(&retained),
4468 Some(literal.as_str()),
4469 );
4470 assert!(!crate::runtime_handoff::is_operate_contract_message(
4471 &retained[0]
4472 ));
4473 }
4474
4475 #[test]
4476 fn retained_image_turn_and_structured_content_keep_their_boundaries() {
4477 let image = Message {
4478 role: Role::User,
4479 content: vec![ContentBlock::ImageUrl {
4480 image_url: ImageUrlContent {
4481 url: "data:image/png;base64,AAAA".to_string(),
4482 },
4483 }],
4484 };
4485 let mut mixed = msg("user", "Compare these views");
4486 mixed.content.extend(image.content.clone());
4487 mixed.content.push(ContentBlock::Text {
4488 text: "Keep the original colors".to_string(),
4489 cache_control: Some(CacheControl {
4490 cache_type: "ephemeral".to_string(),
4491 }),
4492 });
4493 let messages = vec![image, mixed];
4494 let retained = retained_user_messages(&messages, 3_000);
4495 assert_eq!(retained, messages);
4496 let saved = crate::session_manager::create_saved_session_with_mode(
4497 &retained,
4498 "test-model",
4499 std::path::Path::new("."),
4500 0,
4501 None,
4502 None,
4503 );
4504 assert_eq!(
4505 saved.metadata.title,
4506 crate::session_manager::DEFAULT_SESSION_TITLE
4507 );
4508 assert!(retained_user_messages(&messages[..1], IMAGE_TOKEN_ESTIMATE - 1).is_empty());
4509 }
4510
4511 #[test]
4512 fn retained_budget_never_partially_promotes_structural_metadata() {
4513 let runtime = crate::runtime_handoff::operate_contract_runtime_message();
4514 let text = msg("user", "αβγδεζηθικ");
4515 let retained = retained_user_messages(&[runtime.clone(), text.clone()], 10);
4516 assert_eq!(retained, vec![text]);
4517 assert!(retained_user_messages(&[runtime], 1).is_empty());
4518 assert_eq!(
4519 user_text_of(&retained_user_messages(&[msg("user", "αβγδεζηθικ")], 2)[0]).as_deref(),
4520 Some("αβ"),
4521 );
4522 }
4523
4524 #[test]
4525 fn retained_older_turn_drops_result_blocks_whose_call_was_summarized() {
4526 // #6119: a host-supplied user message can mix text with a tool
4527 // result; the tool_use it answers lives in the summarized region, so
4528 // the retained copy must keep the text and drop the orphaned result.
4529 let mut mixed = msg("user", "Please keep this context.");
4530 mixed.content.push(ContentBlock::ToolResult {
4531 execution_id: None,
4532 tool_use_id: "toolu_orphan_1".to_string(),
4533 content: "{\"ok\":true}".to_string(),
4534 is_error: None,
4535 content_blocks: None,
4536 });
4537 let retained = retained_user_messages(std::slice::from_ref(&mixed), usize::MAX);
4538 assert_eq!(retained.len(), 1);
4539 assert!(
4540 !retained[0]
4541 .content
4542 .iter()
4543 .any(|block| matches!(block, ContentBlock::ToolResult { .. })),
4544 "the retained copy must not keep an orphaned tool_result"
4545 );
4546 assert_eq!(
4547 user_text_of(&retained[0]).as_deref(),
4548 Some("Please keep this context.")
4549 );
4550 // Insufficient budget still refuses to partially retain a multi-block
4551 // turn; the structural-metadata guard is unchanged.
4552 assert!(retained_user_messages(std::slice::from_ref(&mixed), 1).is_empty());
4553 }
4554
4555 #[test]
4556 fn summary_quality_gate_rejects_empty_and_known_placeholder_text() {
4557 for summary in [
4558 "",
4559 " \n\t ",
4560 "...",
4561 "。。。",
4562 "🫧",
4563 "N/A",
4564 "(no summary available)",
4565 "I cannot provide a summary.",
4566 "</think>",
4567 "<think>Only private reasoning.</think>",
4568 "<THINK>Unfinished private reasoning",
4569 "<analysis>Hidden analysis</analysis>",
4570 ] {
4571 let error = validate_compaction_summary(summary)
4572 .expect_err("degenerate summary must fail closed");
4573 assert!(error.to_string().contains("unusable"), "{error}");
4574 }
4575 validate_compaction_summary(FIXED_SUMMARY)
4576 .expect("a substantive continuation handoff must be accepted");
4577 validate_compaction_summary(
4578 "目的: #4394の空要約を防止。完了: 検証と実装。制約: 履歴を変更しない。次: テスト実行。",
4579 )
4580 .expect("a concise multilingual handoff must not be rejected by prose length");
4581 assert_eq!(
4582 validate_compaction_summary(
4583 "<think>private</think> Continue the session store migration.",
4584 )
4585 .unwrap(),
4586 "Continue the session store migration."
4587 );
4588 validate_compaction_summary(
4589 "Next: run `cargo test` and inspect `/new/migration.rs`; results remain unverified.",
4590 )
4591 .expect("planned actions must not be mistaken for fabricated evidence");
4592 }
4593
4594 #[tokio::test]
4595 async fn empty_successful_summary_retries_once_without_replacing_history() {
4596 let original = vec![
4597 msg(
4598 "user",
4599 "Keep the migration transactional and preserve existing sessions.",
4600 ),
4601 msg(
4602 "assistant",
4603 "I am updating the session store and its fixtures.",
4604 ),
4605 ];
4606 let client = ScriptedSummaryClient::new(vec![
4607 vec![ContentBlock::Text {
4608 text: "</think>".to_string(),
4609 cache_control: None,
4610 }],
4611 vec![ContentBlock::Text {
4612 text: FIXED_SUMMARY.to_string(),
4613 cache_control: None,
4614 }],
4615 ]);
4616 let config = CompactionConfig {
4617 model: "test-model".to_string(),
4618 cache_summary: false,
4619 ..Default::default()
4620 };
4621
4622 let mut invocation_usage = Usage::default();
4623 let result = compact_messages_safe(
4624 &client,
4625 &original,
4626 None,
4627 &prepared(&config),
4628 &mut invocation_usage,
4629 )
4630 .await
4631 .expect("the conservative retry should recover a usable summary");
4632 assert_eq!(invocation_usage.input_tokens, 34);
4633 assert_eq!(invocation_usage.output_tokens, 6);
4634 assert_eq!(invocation_usage.prompt_cache_hit_tokens, Some(10));
4635 assert_eq!(invocation_usage.reasoning_tokens, Some(4));
4636
4637 let requests = client
4638 .requests
4639 .lock()
4640 .expect("read scripted summary requests");
4641 assert_eq!(requests.len(), 2, "quality failure retries exactly once");
4642 let ContentBlock::Text { text, .. } = &requests[1]
4643 .messages
4644 .last()
4645 .expect("retry instruction")
4646 .content[0]
4647 else {
4648 panic!("retry instruction must be text");
4649 };
4650 assert!(text.contains("previous reply was empty or a placeholder"));
4651 drop(requests);
4652
4653 assert_eq!(
4654 result.retries_used, 1,
4655 "quality retry must reach diagnostics"
4656 );
4657 assert_eq!(original[0].role, "user", "source history remains untouched");
4658 assert!(result.messages.iter().any(is_compaction_checkpoint_message));
4659 let Some(SystemPrompt::Blocks(blocks)) = result.summary_prompt else {
4660 panic!("recovered summary must be committed");
4661 };
4662 assert!(blocks[0].text.contains(FIXED_SUMMARY));
4663 assert!(!blocks[0].text.contains("(no summary available)"));
4664 }
4665
4666 #[tokio::test]
4667 async fn tool_call_only_summary_is_unusable_and_retried_once() {
4668 let tool_call = || {
4669 vec![ContentBlock::ToolUse {
4670 execution_id: None,
4671 id: "summary-read".to_string(),
4672 name: "read_file".to_string(),
4673 input: serde_json::json!({"path": "src/session_store.rs"}),
4674 caller: None,
4675 thought_signature: None,
4676 }]
4677 };
4678 let config = CompactionConfig {
4679 model: "test-model".to_string(),
4680 cache_summary: false,
4681 ..Default::default()
4682 };
4683 let mut envelope = prepared(&config);
4684 envelope.tools = Some(vec![
4685 serde_json::from_value(json!({
4686 "name": "read_file",
4687 "description": "Read a file",
4688 "input_schema": {"type": "object"}
4689 }))
4690 .unwrap(),
4691 ]);
4692 let original = vec![
4693 msg("user", "Keep the session store migration transactional."),
4694 msg(
4695 "assistant",
4696 "I am updating the session store and its fixtures.",
4697 ),
4698 ];
4699
4700 let client = ScriptedSummaryClient::new(vec![
4701 tool_call(),
4702 vec![ContentBlock::Text {
4703 text: FIXED_SUMMARY.to_string(),
4704 cache_control: None,
4705 }],
4706 ]);
4707 let result =
4708 compact_messages_safe(&client, &original, None, &envelope, &mut Usage::default())
4709 .await
4710 .expect("a tool-only reply is retried like any unusable summary");
4711 {
4712 let requests = client.requests.lock().unwrap();
4713 assert_eq!(requests.len(), 2);
4714 assert_eq!(
4715 requests[0].tool_choice,
4716 Some(crate::core::engine::tool_catalog::default_tool_choice(
4717 false
4718 ))
4719 );
4720 assert_eq!(requests[1].tool_choice, Some(json!("none")));
4721 }
4722 assert_eq!(result.retries_used, 1);
4723 let Some(SystemPrompt::Blocks(blocks)) = result.summary_prompt else {
4724 panic!("recovered summary must be committed");
4725 };
4726 assert!(blocks[0].text.contains(FIXED_SUMMARY));
4727
4728 let client = ScriptedSummaryClient::new(vec![tool_call(), tool_call()]);
4729 let error =
4730 compact_messages_safe(&client, &original, None, &envelope, &mut Usage::default())
4731 .await
4732 .expect_err("two tool-only replies leave history unchanged");
4733 {
4734 let requests = client.requests.lock().unwrap();
4735 assert_eq!(requests.len(), 2);
4736 assert_eq!(
4737 requests[0].tool_choice,
4738 Some(crate::core::engine::tool_catalog::default_tool_choice(
4739 false
4740 ))
4741 );
4742 assert_eq!(requests[1].tool_choice, Some(json!("none")));
4743 }
4744 assert!(
4745 format!("{error:#}").contains("tool call instead of a summary"),
4746 "{error:#}"
4747 );
4748 }
4749
4750 #[tokio::test]
4751 async fn compaction_caps_images_against_full_history_before_slicing_tail() {
4752 fn image_user_message(label: &str, url: &str) -> Message {
4753 Message {
4754 role: Role::User,
4755 content: vec![
4756 ContentBlock::Text {
4757 text: label.to_string(),
4758 cache_control: None,
4759 },
4760 ContentBlock::ImageUrl {
4761 image_url: ImageUrlContent {
4762 url: url.to_string(),
4763 },
4764 },
4765 ],
4766 }
4767 }
4768 fn image_tool_result(id: &str, label: &str, data: &str) -> Message {
4769 Message {
4770 role: Role::User,
4771 content: vec![ContentBlock::ToolResult {
4772 execution_id: None,
4773 tool_use_id: id.to_string(),
4774 content: label.to_string(),
4775 is_error: None,
4776 content_blocks: Some(vec![json!({
4777 "type": "image",
4778 "source": {
4779 "type": "base64",
4780 "media_type": "image/png",
4781 "data": data,
4782 }
4783 })]),
4784 }],
4785 }
4786 }
4787
4788 let padding = "evidence ".repeat(1_500);
4789 let messages = vec![
4790 image_user_message(
4791 &format!("Older screenshot 0: {padding}"),
4792 "data:image/png;base64,IMG0",
4793 ),
4794 tool_use("shot-1", "read_file", json!({"path": "shot1.png"})),
4795 image_tool_result(
4796 "shot-1",
4797 &format!("Older tool screenshot 1: {padding}"),
4798 "IMG1",
4799 ),
4800 msg("assistant", &format!("Analyzed shot 1. {padding}")),
4801 image_user_message(
4802 &format!("Older screenshot 2: {padding}"),
4803 "data:image/png;base64,IMG2",
4804 ),
4805 msg("assistant", &format!("Analyzed shot 2. {padding}")),
4806 image_user_message("Recent tail screenshot 3", "data:image/png;base64,IMG3"),
4807 msg("assistant", "Analyzed shot 3."),
4808 image_user_message("Recent tail screenshot 4", "data:image/png;base64,IMG4"),
4809 msg("assistant", "Analyzed shot 4."),
4810 image_user_message("Recent tail screenshot 5", "data:image/png;base64,IMG5"),
4811 msg("assistant", "Analyzed shot 5."),
4812 ];
4813
4814 let config = CompactionConfig {
4815 model: "test-model".to_string(),
4816 token_threshold: 20_000,
4817 image_input: crate::model_profile::SupportState::Supported,
4818 cache_summary: false,
4819 ..Default::default()
4820 };
4821 let mut envelope = prepared(&config);
4822 envelope.image_cap = Some(4);
4823
4824 let summary_end =
4825 last_round::recent_tail_start(&messages, envelope.retained_recent_tokens(None));
4826 assert!(summary_end > 0 && summary_end < messages.len());
4827 let older_images =
4828 codewhale_models::image_window::count_request_images(&messages[..summary_end]);
4829 let tail_images =
4830 codewhale_models::image_window::count_request_images(&messages[summary_end..]);
4831 assert!(
4832 older_images > 0 && older_images <= 4 && older_images + tail_images > 4,
4833 "fixture must exceed cap only when the dropped tail is counted: older={older_images}, tail={tail_images}"
4834 );
4835
4836 let mut parent_messages = messages.clone();
4837 codewhale_models::image_window::cap_request_images(&mut parent_messages, 4);
4838
4839 let client = FixedSummaryClient::default();
4840 let result =
4841 compact_messages_safe(&client, &messages, None, &envelope, &mut Usage::default())
4842 .await
4843 .expect("compaction succeeds");
4844
4845 let request = client
4846 .request
4847 .lock()
4848 .unwrap()
4849 .clone()
4850 .expect("summary request");
4851 assert_eq!(request.messages.len(), summary_end + 1);
4852 assert_eq!(
4853 &request.messages[..summary_end],
4854 &parent_messages[..summary_end],
4855 "summary prefix must match the parent turn's full-history image elision"
4856 );
4857 assert_eq!(
4858 codewhale_models::image_window::count_request_images(&request.messages[..summary_end]),
4859 codewhale_models::image_window::count_request_images(&parent_messages[..summary_end]),
4860 );
4861 for retained_tail_msg in &messages[summary_end..] {
4862 assert!(
4863 result.messages.contains(retained_tail_msg),
4864 "retained recent tail must keep original inline images intact"
4865 );
4866 }
4867
4868 let mut with_tail_checkpoint = messages.clone();
4869 let checkpoint = Message {
4870 role: Role::User,
4871 content: vec![
4872 ContentBlock::Text {
4873 text: format!(
4874 "{SUMMARY_HEADER}\n\nPrior handoff summary.\n\n{SUMMARY_CLOSING}"
4875 ),
4876 cache_control: None,
4877 },
4878 ContentBlock::Text {
4879 text: COMPACTION_CHECKPOINT_PROVENANCE.to_string(),
4880 cache_control: None,
4881 },
4882 ],
4883 };
4884 assert!(is_checkpoint_for_compaction(&checkpoint));
4885 let checkpoint_idx = with_tail_checkpoint.len() - 2;
4886 with_tail_checkpoint.insert(checkpoint_idx, checkpoint.clone());
4887 let checkpoint_summary_end = last_round::recent_tail_start(
4888 &with_tail_checkpoint,
4889 envelope.retained_recent_tokens(None),
4890 );
4891 assert!(
4892 checkpoint_summary_end > 0 && checkpoint_summary_end <= checkpoint_idx,
4893 "checkpoint at {checkpoint_idx} must sit inside the retained tail starting at {checkpoint_summary_end}"
4894 );
4895 let mut parent_with_checkpoint = with_tail_checkpoint.clone();
4896 codewhale_models::image_window::cap_request_images(&mut parent_with_checkpoint, 4);
4897 let checkpoint_client = FixedSummaryClient::default();
4898 compact_messages_safe(
4899 &checkpoint_client,
4900 &with_tail_checkpoint,
4901 None,
4902 &envelope,
4903 &mut Usage::default(),
4904 )
4905 .await
4906 .expect("compaction with tail checkpoint succeeds");
4907 let checkpoint_request = checkpoint_client
4908 .request
4909 .lock()
4910 .unwrap()
4911 .clone()
4912 .expect("checkpoint summary request");
4913 assert_eq!(
4914 checkpoint_request.messages.len(),
4915 checkpoint_summary_end + 2
4916 );
4917 assert_eq!(
4918 &checkpoint_request.messages[..checkpoint_summary_end],
4919 &parent_with_checkpoint[..checkpoint_summary_end],
4920 );
4921 assert_eq!(
4922 checkpoint_request.messages[checkpoint_summary_end],
4923 checkpoint
4924 );
4925 }
4926
4927 #[tokio::test]
4928 async fn transient_failure_after_a_quality_retry_stops_without_replacement() {
4929 let client = ScriptedSummaryClient::with_outcomes(vec![
4930 Ok(vec![ContentBlock::Text {
4931 text: "...".to_string(),
4932 cache_control: None,
4933 }]),
4934 Err(crate::llm_client::LlmError::RateLimited {
4935 message: "rate limited".into(),
4936 retry_after: Some(Duration::ZERO),
4937 }
4938 .into()),
4939 ]);
4940 let config = CompactionConfig {
4941 model: "test-model".to_string(),
4942 cache_summary: false,
4943 ..Default::default()
4944 };
4945
4946 let mut invocation_usage = Usage::default();
4947 let error = compact_messages_safe(
4948 &client,
4949 &[msg("user", "Preserve the current migration state.")],
4950 None,
4951 &prepared(&config),
4952 &mut invocation_usage,
4953 )
4954 .await
4955 .expect_err("a transient failure after the quality retry must stop the pass");
4956 assert!(format!("{error:#}").contains("Rate limit"), "{error:#}");
4957 assert_eq!(invocation_usage.input_tokens, 17);
4958 assert_eq!(invocation_usage.output_tokens, 3);
4959 assert_eq!(invocation_usage.prompt_cache_hit_tokens, Some(5));
4960 assert_eq!(invocation_usage.reasoning_tokens, Some(2));
4961
4962 assert_eq!(
4963 client
4964 .requests
4965 .lock()
4966 .expect("read scripted summary requests")
4967 .len(),
4968 2,
4969 "the client owns transport retries; the pass must not add a third call"
4970 );
4971 }
4972
4973 #[tokio::test]
4974 async fn compaction_usage_survives_cancellation_during_quality_retry() {
4975 let _cost_scope = crate::cost_status::test_scope();
4976 let retry_started = std::sync::Arc::new(tokio::sync::Notify::new());
4977 let mut client = ScriptedSummaryClient::new(vec![vec![ContentBlock::Text {
4978 text: "...".to_string(),
4979 cache_control: None,
4980 }]]);
4981 client.retry_started = Some(std::sync::Arc::clone(&retry_started));
4982 let messages = vec![msg("user", "Preserve the migration state.")];
4983 let prepared = prepared(&CompactionConfig::default());
4984 let mut invocation_usage = Usage::default();
4985 {
4986 let compaction =
4987 compact_messages_safe(&client, &messages, None, &prepared, &mut invocation_usage);
4988 tokio::pin!(compaction);
4989 tokio::select! {
4990 result = &mut compaction => panic!("retry must remain pending: {result:?}"),
4991 _ = retry_started.notified() => {},
4992 _ = tokio::time::sleep(Duration::from_secs(10)) => panic!("quality retry did not start"),
4993 }
4994 }
4995 assert_eq!(invocation_usage.input_tokens, 17);
4996 assert_eq!(invocation_usage.output_tokens, 3);
4997 assert_eq!(invocation_usage.prompt_cache_hit_tokens, Some(5));
4998 assert_eq!(invocation_usage.reasoning_tokens, Some(2));
4999 assert_eq!(client.requests.lock().unwrap().len(), 2);
5000 }
5001
5002 #[tokio::test]
5003 async fn non_text_summary_failure_preserves_history_after_one_retry() {
5004 let original = vec![
5005 msg(
5006 "user",
5007 "Do not lose the current branch or the failing test name.",
5008 ),
5009 msg("assistant", "The failing test is session_store::roundtrip."),
5010 ];
5011 let client = ScriptedSummaryClient::new(vec![
5012 vec![ContentBlock::thinking("internal-only response")],
5013 vec![ContentBlock::thinking("still no user-visible handoff")],
5014 ]);
5015 let config = CompactionConfig {
5016 model: "test-model".to_string(),
5017 cache_summary: false,
5018 ..Default::default()
5019 };
5020
5021 let mut invocation_usage = Usage::default();
5022 let error = compact_messages_safe(
5023 &client,
5024 &original,
5025 None,
5026 &prepared(&config),
5027 &mut invocation_usage,
5028 )
5029 .await
5030 .expect_err("two non-text responses must not replace history");
5031 assert_eq!(invocation_usage.input_tokens, 34);
5032 assert_eq!(invocation_usage.output_tokens, 6);
5033 assert_eq!(invocation_usage.prompt_cache_hit_tokens, Some(10));
5034 assert_eq!(invocation_usage.reasoning_tokens, Some(4));
5035
5036 assert!(
5037 error
5038 .to_string()
5039 .contains("remained unusable after one conservative retry"),
5040 "{error}"
5041 );
5042 assert_eq!(
5043 client
5044 .requests
5045 .lock()
5046 .expect("read scripted summary requests")
5047 .len(),
5048 2,
5049 "quality failure gets one retry, not the transient retry ladder"
5050 );
5051 assert_eq!(
5052 original,
5053 vec![
5054 msg(
5055 "user",
5056 "Do not lose the current branch or the failing test name."
5057 ),
5058 msg("assistant", "The failing test is session_store::roundtrip."),
5059 ],
5060 "borrowed source history must remain byte-for-byte unchanged"
5061 );
5062 }
5063 #[tokio::test]
5064 async fn compaction_uses_the_resolved_route_output_allowance() {
5065 for (route_label, provider, model) in [
5066 (
5067 "thinking-default route",
5068 codewhale_config::ProviderKind::Deepseek,
5069 "deepseek-v4-flash",
5070 ),
5071 (
5072 "fixed-sampling route",
5073 codewhale_config::ProviderKind::Moonshot,
5074 "k3",
5075 ),
5076 ] {
5077 let client = FixedSummaryClient::for_route(provider.as_str(), model);
5078 let config = CompactionConfig {
5079 model: model.to_string(),
5080 cache_summary: false,
5081 ..Default::default()
5082 };
5083 compact_messages(&client, &[msg("user", "summarize this task")], &config)
5084 .await
5085 .expect("route compaction should complete");
5086
5087 let request = client
5088 .request
5089 .lock()
5090 .expect("read summary request")
5091 .clone()
5092 .expect("summary request was captured");
5093 assert_eq!(
5094 request.max_tokens,
5095 crate::route_budget::effective_max_output_tokens_for_route(provider, model, None),
5096 "{route_label} must use the ordinary route output policy"
5097 );
5098 assert_eq!(request.temperature, None);
5099 assert_eq!(request.top_p, None);
5100 }
5101 }
5102
5103 struct TruncatedSummaryClient;
5104
5105 #[async_trait::async_trait]
5106 impl crate::core::model_client::ModelClient for TruncatedSummaryClient {
5107 fn provider_name(&self) -> &str {
5108 "test"
5109 }
5110
5111 fn model(&self) -> &str {
5112 "test-model"
5113 }
5114
5115 async fn create_message(
5116 &self,
5117 _request: MessageRequest,
5118 ) -> anyhow::Result<codewhale_models::MessageResponse> {
5119 Ok(codewhale_models::MessageResponse {
5120 tool_projection_warning: None,
5121 id: "summary-truncated".to_string(),
5122 r#type: "message".to_string(),
5123 role: "assistant".to_string(),
5124 content: vec![ContentBlock::Text {
5125 text: "1. Primary request and intent — mig".to_string(),
5126 cache_control: None,
5127 }],
5128 model: "test-model".to_string(),
5129 stop_reason: Some("max_tokens".to_string()),
5130 stop_sequence: None,
5131 container: None,
5132 usage: codewhale_models::Usage::default(),
5133 title: None,
5134 stop_details: None,
5135 refusal: None,
5136 })
5137 }
5138
5139 async fn create_message_stream(
5140 &self,
5141 _request: MessageRequest,
5142 ) -> anyhow::Result<crate::llm_client::StreamEventBox> {
5143 anyhow::bail!("streaming is unused by compaction")
5144 }
5145
5146 async fn health_check(&self) -> anyhow::Result<bool> {
5147 Ok(true)
5148 }
5149 }
5150
5151 /// A provider-truncated summary must fail compaction instead of replacing
5152 /// session history with a fragment.
5153 #[tokio::test]
5154 async fn truncated_summary_response_fails_compaction() {
5155 let messages: Vec<Message> = (0..40)
5156 .map(|index| {
5157 msg(
5158 if index % 2 == 0 { "user" } else { "assistant" },
5159 &format!("padding message {index} with enough text to compact"),
5160 )
5161 })
5162 .collect();
5163 let config = CompactionConfig {
5164 model: "test-model".to_string(),
5165 cache_summary: false,
5166 ..Default::default()
5167 };
5168
5169 let error = compact_messages(&TruncatedSummaryClient, &messages, &config)
5170 .await
5171 .expect_err("a truncated summary must not be committed");
5172 let text = error.to_string();
5173 assert!(text.contains("incomplete"), "{text}");
5174 assert!(text.contains("max_tokens"), "{text}");
5175 }
5176
5177 #[test]
5178 fn estimate_tokens_empty_messages() {
5179 let messages: Vec<Message> = vec![];
5180 assert_eq!(estimate_tokens(&messages), 0);
5181 }
5182
5183 #[test]
5184 fn estimate_tokens_with_text() {
5185 let messages = vec![Message {
5186 role: Role::User,
5187 content: vec![ContentBlock::Text {
5188 text: "Hello, world!".to_string(), // 13 chars = ~3 tokens
5189 cache_control: None,
5190 }],
5191 }];
5192 let tokens = estimate_tokens(&messages);
5193 assert!(tokens > 0 && tokens < 10);
5194 }
5195
5196 #[test]
5197 fn mixed_script_input_counts_toward_compaction_and_retention_budgets() {
5198 let text = "code中文かな한글".repeat(200);
5199 let messages = [msg("user", &text)];
5200 assert_eq!(estimate_tokens(&messages), 1_400);
5201 assert_eq!(estimate_text_tokens_conservative(&text), 1_467);
5202 assert_eq!(estimate_text_tokens_conservative(&"a".repeat(300)), 100);
5203 assert_eq!(estimate_tokens(&[msg("user", &"a".repeat(300))]), 75);
5204 let config = CompactionConfig {
5205 token_threshold: 1_400,
5206 ..CompactionConfig::default()
5207 };
5208 assert!(compaction_pressure_reached(&messages, None, &config));
5209 let system = SystemPrompt::Text(text.clone());
5210 assert!(compaction_pressure_reached(&[], Some(&system), &config));
5211
5212 let json = json!({"input": text});
5213 let call = tool_use("read", "File", json.clone());
5214 assert_eq!(
5215 estimate_tokens_for_message(&call, true),
5216 estimate_message_text_tokens(&json.to_string())
5217 );
5218 let result = tool_result("read", &text);
5219 let mut history = vec![call, result];
5220 let plan = plan_tool_result_prunes(&history, 0);
5221 assert_eq!(plan.len(), 1);
5222 let before = estimate_tokens(&history);
5223 let reclaimed = plan[0].tokens_reclaimed();
5224 assert!(prune_tool_results(&mut history, 0) > 0);
5225 assert_eq!(before - estimate_tokens(&history), reclaimed);
5226
5227 assert_eq!(
5228 retained_user_messages(&messages, 4),
5229 [msg("user", "code中文")]
5230 );
5231 }
5232
5233 #[test]
5234 fn pressure_counts_text_only_reasoning_and_server_tool_payloads() {
5235 let payload = "retained evidence ".repeat(1000);
5236 let blocks = vec![
5237 ContentBlock::thinking(payload.clone()),
5238 ContentBlock::ServerToolUse {
5239 id: "server-call".into(),
5240 name: "code_execution".into(),
5241 input: json!({"code": payload}),
5242 kind: None,
5243 caller: None,
5244 },
5245 ContentBlock::CodeExecutionToolResult {
5246 tool_use_id: "server-call".into(),
5247 content: json!({"stdout": payload}),
5248 },
5249 ContentBlock::ToolSearchToolResult {
5250 tool_use_id: "search-call".into(),
5251 content: json!({"description": payload}),
5252 },
5253 ];
5254 for block in blocks {
5255 let messages = vec![Message {
5256 role: Role::Assistant,
5257 content: vec![block],
5258 }];
5259 assert!(estimate_tokens(&messages) >= payload.len() / 4);
5260 assert!(estimate_input_tokens_for_pressure(&messages, None) >= payload.len() / 4);
5261 }
5262 }
5263
5264 #[test]
5265 fn estimate_tokens_counts_tool_round_thinking_across_turns() {
5266 // Per DeepSeek thinking-mode rules, any assistant message that
5267 // performed a tool call keeps its reasoning_content in the request
5268 // forever, including across new user turns. Token estimates must
5269 // count those bytes.
5270 let thinking = "reasoning ".repeat(800);
5271 let current_messages = vec![
5272 Message {
5273 role: Role::User,
5274 content: vec![ContentBlock::Text {
5275 text: "Use a tool".to_string(),
5276 cache_control: None,
5277 }],
5278 },
5279 Message {
5280 role: Role::Assistant,
5281 content: vec![
5282 ContentBlock::Thinking {
5283 signature: None,
5284 state: None,
5285 redacted_data: None,
5286 thinking: thinking.clone(),
5287 },
5288 ContentBlock::ToolUse {
5289 execution_id: None,
5290 id: "tool-1".to_string(),
5291 name: "read_file".to_string(),
5292 input: serde_json::json!({"path": "Cargo.toml"}),
5293 caller: None,
5294 thought_signature: None,
5295 },
5296 ],
5297 },
5298 Message {
5299 role: Role::User,
5300 content: vec![ContentBlock::ToolResult {
5301 execution_id: None,
5302 tool_use_id: "tool-1".to_string(),
5303 content: "manifest".to_string(),
5304 is_error: None,
5305 content_blocks: None,
5306 }],
5307 },
5308 ];
5309 let historical_messages = {
5310 let mut messages = current_messages.clone();
5311 messages.push(Message {
5312 role: Role::Assistant,
5313 content: vec![ContentBlock::Text {
5314 text: "Done.".to_string(),
5315 cache_control: None,
5316 }],
5317 });
5318 messages.push(Message {
5319 role: Role::User,
5320 content: vec![ContentBlock::Text {
5321 text: "Next question.".to_string(),
5322 cache_control: None,
5323 }],
5324 });
5325 messages
5326 };
5327 let completed_messages = {
5328 let mut messages = current_messages.clone();
5329 messages.push(Message {
5330 role: Role::Assistant,
5331 content: vec![ContentBlock::Text {
5332 text: "Done.".to_string(),
5333 cache_control: None,
5334 }],
5335 });
5336 messages
5337 };
5338
5339 let lower_bound = thinking.len() / 5;
5340 assert!(estimate_tokens(&current_messages) > lower_bound);
5341 assert!(estimate_tokens(&completed_messages) > lower_bound);
5342 assert!(estimate_tokens(&historical_messages) > lower_bound);
5343 }
5344
5345 #[test]
5346 fn should_compact_respects_enabled_flag() {
5347 let config = CompactionConfig {
5348 enabled: false,
5349 ..Default::default()
5350 };
5351 // Even with many messages, disabled compaction should return false
5352 let messages: Vec<Message> = (0..100)
5353 .map(|_| Message {
5354 role: Role::User,
5355 content: vec![ContentBlock::Text {
5356 text: "test".to_string(),
5357 cache_control: None,
5358 }],
5359 })
5360 .collect();
5361 assert!(!should_compact(&messages, None, &prepared(&config)));
5362 }
5363
5364 /// The #5577 acceptance case: a session whose provider bills 842K prompt
5365 /// tokens on a 1M window (threshold 800K) MUST compact even when the
5366 /// local estimate is far lower — the bounded working list undercounts
5367 /// what the provider actually saw, and billed truth wins.
5368 #[test]
5369 fn billed_842k_on_a_1m_window_compacts_despite_a_small_estimate() {
5370 let config = CompactionConfig {
5371 enabled: true,
5372 token_threshold: 800_000,
5373 ..Default::default()
5374 };
5375 let messages: Vec<Message> = (0..40)
5376 .map(|i| Message {
5377 role: if i % 2 == 0 {
5378 Role::User
5379 } else {
5380 Role::Assistant
5381 },
5382 content: vec![ContentBlock::Text {
5383 text: format!("short message {i}"),
5384 cache_control: None,
5385 }],
5386 })
5387 .collect();
5388 // Estimate alone stays far under the trigger…
5389 assert!(!should_compact(&messages, None, &prepared(&config)));
5390 // …but the provider's billed prompt total decides.
5391 assert_eq!(
5392 compaction_decision_with_billed(&messages, None, &prepared(&config), Some(842_000)),
5393 CompactionDecision::Compact
5394 );
5395 }
5396
5397 /// A refusal under real pressure must name its guard so the host can
5398 /// tell the user, instead of the silent hold that reads as a broken
5399 /// auto-compactor (#5577).
5400 #[test]
5401 fn refusals_under_pressure_name_their_guard() {
5402 let config = CompactionConfig {
5403 enabled: true,
5404 token_threshold: 100,
5405 ..Default::default()
5406 };
5407 // Too few messages to summarize: over-pressure, short transcript.
5408 let few: Vec<Message> = (0..3)
5409 .map(|i| Message {
5410 role: Role::User,
5411 content: vec![ContentBlock::Text {
5412 text: format!("message {i} {}", "x".repeat(300)),
5413 cache_control: None,
5414 }],
5415 })
5416 .collect();
5417 assert_eq!(
5418 compaction_decision_with_billed(&few, None, &prepared(&config), None),
5419 CompactionDecision::Refused(CompactionRefusal::TooFewMessages { count: few.len() })
5420 );
5421
5422 // Retained floor above the trigger: a giant system prompt no pass
5423 // can reclaim. The refusal carries the numbers the user needs.
5424 let many: Vec<Message> = (0..12)
5425 .map(|i| Message {
5426 role: if i % 2 == 0 {
5427 Role::User
5428 } else {
5429 Role::Assistant
5430 },
5431 content: vec![ContentBlock::Text {
5432 text: format!("message {i} {}", "y".repeat(200)),
5433 cache_control: None,
5434 }],
5435 })
5436 .collect();
5437 let system = SystemPrompt::Text("s".repeat(4_000));
5438 match compaction_decision_with_billed(&many, Some(&system), &prepared(&config), None) {
5439 CompactionDecision::Refused(CompactionRefusal::RetainedFloor { floor, threshold }) => {
5440 assert_eq!(threshold, 100);
5441 assert!(floor >= threshold, "floor {floor} must be over {threshold}");
5442 }
5443 other => panic!("expected a retained-floor refusal, got {other:?}"),
5444 }
5445 }
5446
5447 /// v0.8.11: message-count is no longer a compaction trigger. Long
5448 /// chats of small messages stay uncompacted because rewriting the
5449 /// prefix cache for a tiny budget reclaim is net-negative. Only token
5450 /// pressure (and the explicit `/compact` slash command) trigger
5451 /// compaction.
5452 #[test]
5453 fn message_count_no_longer_triggers_compaction() {
5454 let config = CompactionConfig {
5455 enabled: true,
5456 token_threshold: 1_000_000,
5457 ..Default::default()
5458 };
5459
5460 // 200 tiny messages, well above the prior message threshold.
5461 let many_messages: Vec<Message> = (0..200)
5462 .map(|_| Message {
5463 role: Role::User,
5464 content: vec![ContentBlock::Text {
5465 text: "x".to_string(),
5466 cache_control: None,
5467 }],
5468 })
5469 .collect();
5470 // Token total stays minuscule so the token threshold is not hit;
5471 // without the prior message-count trigger, no compaction.
5472 assert!(!should_compact(&many_messages, None, &prepared(&config)));
5473 }
5474
5475 // ========================================================================
5476 // Additional Compaction Trigger Tests
5477 // ========================================================================
5478
5479 #[test]
5480 fn full_request_pressure_crosses_token_threshold() {
5481 let config = CompactionConfig {
5482 enabled: true,
5483 token_threshold: 20_000,
5484 ..Default::default()
5485 };
5486
5487 // Create messages that exceed token threshold
5488 let messages: Vec<Message> = (0..20).map(|_| msg("user", &"x".repeat(5_000))).collect();
5489
5490 assert!(compaction_pressure_reached(&messages, None, &config));
5491 }
5492
5493 #[test]
5494 fn auto_compaction_uses_full_request_pressure_across_context_sizes() {
5495 for (window, output_reserve) in [
5496 (128_000_u64, 4_096_u64),
5497 (272_000, 4_096),
5498 // Large windows use the same ordinary request reservation; there
5499 // is no second, non-wire reasoning allowance.
5500 (1_000_000, 65_536),
5501 ] {
5502 let budget =
5503 codewhale_runtime::context_budget::ContextBudget::new(window, 0, output_reserve);
5504 let threshold = usize::try_from(budget.compaction_trigger_for_percent(80.0))
5505 .expect("test threshold fits usize");
5506 let raw_target = threshold.saturating_mul(7) / 10;
5507 let chars_per_message = raw_target.saturating_mul(4) / 14;
5508 let messages: Vec<Message> = (0..14)
5509 .map(|index| {
5510 msg(
5511 if index % 2 == 0 { "user" } else { "assistant" },
5512 &"x".repeat(chars_per_message),
5513 )
5514 })
5515 .collect();
5516 let raw = estimate_tokens(&messages);
5517 let full = estimate_input_tokens_for_pressure(&messages, None);
5518 let config = CompactionConfig {
5519 enabled: true,
5520 token_threshold: threshold,
5521 ..Default::default()
5522 };
5523
5524 assert!(
5525 raw < threshold,
5526 "raw message estimator alone must not cross {window}"
5527 );
5528 // The pressure estimate adds per-message framing on top of the
5529 // raw message tokens; billed usage from the provider can also
5530 // cross the trigger on its own.
5531 assert!(
5532 full < threshold,
5533 "70%-filled fixture must stay under the {window} trigger: {full} >= {threshold}"
5534 );
5535 assert!(
5536 crate::compaction::compaction_pressure_reached_with_billed(
5537 &messages,
5538 None,
5539 &config,
5540 Some(threshold as u64),
5541 ),
5542 "billed prompt tokens at the trigger must reach pressure for {window}"
5543 );
5544 assert!(
5545 crate::compaction::should_compact_with_billed(
5546 &messages,
5547 None,
5548 &prepared(&config),
5549 Some(threshold as u64),
5550 ),
5551 "billed pressure must trigger eligibility for a {window}-token route"
5552 );
5553 }
5554 }
5555
5556 #[test]
5557 fn auto_compaction_skips_pressure_that_cannot_be_reclaimed_below_trigger() {
5558 let messages: Vec<Message> = (0..20)
5559 .map(|index| {
5560 msg(
5561 if index % 2 == 0 { "user" } else { "assistant" },
5562 &"x".repeat(500),
5563 )
5564 })
5565 .collect();
5566 let system = SystemPrompt::Text("s".repeat(24_000));
5567 let config = CompactionConfig {
5568 enabled: true,
5569 token_threshold: 10_000,
5570 ..Default::default()
5571 };
5572
5573 assert!(
5574 estimate_input_tokens_conservative(&messages, Some(&system)) >= config.token_threshold,
5575 "fixture must be under full-request pressure"
5576 );
5577 assert!(
5578 !should_compact(&messages, Some(&system), &prepared(&config)),
5579 "a pinned/system floor above the trigger would loop every tool step"
5580 );
5581 }
5582
5583 #[test]
5584 fn full_request_threshold_is_inclusive() {
5585 let messages: Vec<Message> = (0..10)
5586 .map(|index| msg(if index % 2 == 0 { "user" } else { "assistant" }, "payload"))
5587 .collect();
5588 let threshold = estimate_input_tokens_for_pressure(&messages, None);
5589 let config = CompactionConfig {
5590 enabled: true,
5591 token_threshold: threshold,
5592 ..Default::default()
5593 };
5594
5595 assert!(compaction_pressure_reached(&messages, None, &config));
5596 }
5597
5598 #[test]
5599 fn test_should_compact_below_token_threshold() {
5600 let config = CompactionConfig {
5601 enabled: true,
5602 token_threshold: 1000,
5603 ..Default::default()
5604 };
5605
5606 // Create short messages
5607 let messages: Vec<Message> = (0..5).map(|_| msg("user", "short")).collect();
5608
5609 assert!(!should_compact(&messages, None, &prepared(&config)));
5610 }
5611
5612 #[test]
5613 fn auto_compaction_uses_token_threshold_without_fixed_floor() {
5614 let config = CompactionConfig {
5615 enabled: true,
5616 token_threshold: 20_000,
5617 ..Default::default()
5618 };
5619
5620 // Long sessions are dominated by assistant/tool output; the retained
5621 // user tail stays small, so the pass is reclaimable.
5622 let messages: Vec<Message> = (0..20)
5623 .map(|index| {
5624 if index % 2 == 0 {
5625 msg("user", &"x".repeat(100))
5626 } else {
5627 msg("assistant", &"x".repeat(10_000))
5628 }
5629 })
5630 .collect();
5631 assert!(should_compact(&messages, None, &prepared(&config)));
5632 }
5633
5634 #[test]
5635 fn test_compaction_result_retries_used() {
5636 // This test verifies the CompactionResult structure
5637 let result = CompactionResult {
5638 messages: vec![],
5639 summary_prompt: None,
5640 retries_used: 2,
5641 coverage: CompactionCoverage::default(),
5642 };
5643
5644 assert_eq!(result.retries_used, 2);
5645 assert!(result.messages.is_empty());
5646 }
5647 }
5648
5648 lines RUST