| 1 | # Compaction survival contract |
| 2 | |
| 3 | Schema version 2. |
| 4 | |
| 5 | The protected history means the current user instructions and a recent |
| 6 | conversation tail selected by token budget, including assistant output. |
| 7 | The tail receives one fifth of the compaction threshold remaining after the |
| 8 | fixed system and tool prefix, capped at 20,000 estimated tokens. Provider |
| 9 | usage calibration applies to both that allowance and the request guard. |
| 10 | One complete exchange can exceed the allowance; pairing takes precedence. |
| 11 | Older completed steps within a long uninterrupted task may be summarized. |
| 12 | Tool-call batches and their results are never split, and unresolved calls |
| 13 | prevent a split across them. Original history is saved before any rewrite. |
| 14 | |
| 15 | Language-invariant schema for session-tree journal entry types. Compaction |
| 16 | may summarize older turns; it must not drop the fields marked **survive** |
| 17 | below. The B1 strategy (Rust `codewhale-tui` compaction path) enforces this |
| 18 | over the live journal / API transcript. |
| 19 | |
| 20 | Failed compact must not replace live history. A successful summary pass |
| 21 | replaces verified prior checkpoints with one new stamped checkpoint in |
| 22 | history, outside the cacheable system and tool prefix. Internal protocol |
| 23 | placeholders (`(no summary available)`, refusal-only text) are never durable |
| 24 | transcript content. |
| 25 | |
| 26 | Live repository, tool, and GitHub state is distinguished from summarized |
| 27 | facts: background-work handles and the exact branch/worktree identity |
| 28 | survive here or are re-read from live state before consequential work. |
| 29 | |
| 30 | ## Entry types |
| 31 | |
| 32 | Journal kinds are the protocol `kind` strings (`header`, `user`, |
| 33 | `assistant`, `tool_result`, `compaction`, `branch_summary`). Session-tree |
| 34 | `message` / `system` entries carry the same payload on `SessionEntryKind`. |
| 35 | |
| 36 | | kind | payload location | survive | summarized | pruned | not retained | |
| 37 | | --- | --- | --- | --- | --- | --- | |
| 38 | | `header` | `payload` identity, `id`, `created_at` | always | — | — | secrets | |
| 39 | | `user` | `payload` text / `SessionEntryKind::User.text` / `Message` text blocks | last-round verbatim (bounded token budget for older user text) | older user turns | obsolete narration | secrets, raw dumps | |
| 40 | | `assistant` | `payload` text / `SessionEntryKind::Assistant.text` / `Message` text + `tool_use` | protected last-round verbatim | older assistant text and reasoning | — | internal placeholders | |
| 41 | | `tool_result` | `payload.tool_use_id`, `content`, `is_error`, `content_blocks` | last-round bounded (8KiB) | older results | nested images, oversized blocks | secrets, raw large outputs | |
| 42 | | `compaction` | `payload.summary`, `tokens_before`, `tokens_after`, `model`, coverage receipt | one stamped checkpoint after a summary pass | verified prior checkpoints supplied to the summarizer | superseded verified checkpoints | placeholder-only summaries | |
| 43 | | `branch_summary` | `payload.branch_id`, `summary`, `parent_branch_id` | always (not rewritten by compact) | — | — | — | |
| 44 | | `message` | flattened `Message.role` + `Message.content[]` | see content-block table | older turns | see prune rules | see never-durable | |
| 45 | | `system` | `SessionEntryKind::System.content` | constitution / repo-law identity when present | duplicated policy | — | unsupported completion claims | |
| 46 | |
| 47 | ## Content blocks on `message` entries |
| 48 | |
| 49 | | block `type` | fields that must survive | bound / notes | |
| 50 | | --- | --- | --- | |
| 51 | | `text` | `text` on the last user round | older user text may truncate to the retained-user token budget | |
| 52 | | `tool_use` | `id`, `name`, `input`, `thought_signature` | last-round only; `id` is the join key for `tool_result` | |
| 53 | | `tool_result` | `tool_use_id`, `content`, `is_error` | last-round; `content` truncated at 8KiB, `content_blocks` dropped if truncated | |
| 54 | | `thinking` | `thinking`, `signature` (byte-for-byte) | all retained reasoning is replay protocol; older exchanges may be summarized as complete units | |
| 55 | | `image_url` | last-round images | older images may be pruned with tool results | |
| 56 | | `server_tool_use` / `*_tool_result` | last-round ids | older blocks may be summarized | |
| 57 | |
| 58 | ## Fields restated from live state (not the summary) |
| 59 | |
| 60 | These must remain usable after compact. They live outside free-form summary |
| 61 | text; if the journal copy is missing they are re-read before consequential |
| 62 | work. |
| 63 | |
| 64 | | field | where it lives | after compact | |
| 65 | | --- | --- | --- | |
| 66 | | `/anchor` pin | `.codewhale/anchors.md` (legacy `.deepseek/anchors.md`) | restated verbatim on the checkpoint user message | |
| 67 | | compaction path + coverage | `CompactionCoverage` on the result / `/context` inspector | named as `summary` or `prune-only` plus last-round counts | |
| 68 | | compaction receipt | stamped `user` checkpoint with a summary block and a separate provenance block, with a TUI receipt in `HistoryCell::System` | a successful summary pass writes one new stamped checkpoint. Failed compaction preserves live history. | |
| 69 | | billed parent prompt tokens | `TurnContext.latest_parent_input_tokens` / session-carried copy | survive the turn boundary; cleared on history rewrite | |
| 70 | | branch / worktree identity | live git / workspace | re-read from live state | |
| 71 | | background-work / WorkRef handles | session + worker registry | survive or re-read from live state; sub-agent ids seen in condensed `agent` calls and results, and in prior checkpoints, are restated on the checkpoint with their last seen status | |
| 72 | | child usage / cumulative tool steps | turn billing totals | must not create false compaction pressure | |
| 73 | |
| 74 | ## Enforcement |
| 75 | |
| 76 | Rust now: |
| 77 | |
| 78 | - `last_round::build_replacement_history` keeps the bounded selected tail, |
| 79 | current user instructions, older user text within its configured budget, |
| 80 | and one checkpoint receipt. The summary request contains the older selected |
| 81 | span plus previous checkpoints, so retained messages do not need to be |
| 82 | paraphrased and prior state is carried forward. |
| 83 | - `validate_retained_coverage` uses the same selection and refuses the rewrite |
| 84 | if its user texts, tool-call ids, tool-result ids, or assistant texts would vanish. |
| 85 | Every user turn in the round is checked, not just the first: the round spans |
| 86 | a tool-bearing turn plus the toolless tail after it, so checking one would |
| 87 | let the latest turn -- the one this contract exists for -- be dropped. The |
| 88 | assistant check compares text, because "some assistant message survived" is |
| 89 | satisfied by the summary the rewrite itself just wrote. |
| 90 | - `validate_survival_contract` also refuses a missing checkpoint receipt, |
| 91 | duplicated prior summaries, dropped `/anchor` text, or a placeholder-only |
| 92 | checkpoint. |
| 93 | - Production summary compaction uses the same checkpoint predicate for |
| 94 | summary selection, retention, and receipt validation. A history checkpoint |
| 95 | requires a `user` message with exactly two uncached text blocks. The first |
| 96 | carries a recognized summary header, and the second is the checkpoint |
| 97 | provenance marker. Restore can install an independently saved summary as a |
| 98 | stamped history checkpoint. Bare user text follows the ordinary recent-tail |
| 99 | and older-user retention budgets even when it starts with a complete legacy |
| 100 | summary header. |
| 101 | |
| 102 | This includes normal v0.9.12 TUI saves that store the old summary solely in |
| 103 | one history text block. When compaction is enabled and the input estimate is |
| 104 | at or above the threshold, `compact_messages_safe` requires a summary pass |
| 105 | to reduce that estimate. Keeping a long old summary can cause that check to |
| 106 | reject the pass and preserve live history. A below-threshold manual pass can |
| 107 | keep the old text and append a stamped checkpoint, even if the input estimate |
| 108 | grows. |
| 109 | |
| 110 | The published `retained_user_messages_in_era` API keeps its original |
| 111 | behavior. `false` includes legacy header matching, and `true` uses only |
| 112 | wire-format stamped checkpoints. Production calls the shared retention |
| 113 | implementation directly with its strict checkpoint predicate. |
| 114 | - `compact_messages_safe` never mutates the caller's live history; the host |
| 115 | commits only after `Ok`. |
| 116 | |
| 117 | The language-invariant fixture matrix is |
| 118 | `crates/engine/src/compaction/fixtures/matrix.json`. Rust loads it in |
| 119 | `last_round` tests, with each fixture's recent token allowance. The Rust |
| 120 | validator is the single enforcement path. |
| 121 | |
| 122 | `/context` names the compaction path and `/anchor` survival. |
| 123 | |
| 124 | ## Summary and budget integrity |
| 125 | |
| 126 | Reasoning-only or placeholder replies cannot become checkpoints. An unusable reply gets one quality retry before the pass fails with its original history preserved. Incomplete replies and tool calls are rejected. Generated prose is explicitly unverified; retained tool receipts and live state remain the evidence for tests, commits and file state. The complete pre-compaction history is saved before a provider call. An automatic summary failure stops the turn instead of continuing from a full window or retrying the same broken summary through emergency recovery. |
| 127 | |
| 128 | The parent turn learns its highest observed input-token ratio from actual request usage and applies it to subsequent request sizing, suffix growth, summary sizing and emergency recovery. Replacing history clears stale billed sizes while retaining that turn's calibration. After two compaction attempts, refilling within two model steps stops the turn with an explicit recovery message. Calibration is scoped to the current turn and cannot predict a tokenizer before a provider supplies usage. Summaries continue on the selected route; no implicit provider escalation or new spend is authorized. |
| 129 | |
| 130 | Disabling automatic compaction also disables preflight and provider-overflow recovery before any summary request or replacement. The turn reports that refusal and keeps its original history. Explicit manual compaction remains available. Both overflow paths use the same typed failure reporter, so a rejected recovery request retains its own cause instead of falling back to the original overflow error. |
| 131 |