# Compaction

- **Stored**: ROOT, A, B, C, K1, K2; HEAD stays on K2
- **Summary**: S: predecessor ROOT, `covers_ids` A, B, C
- **Sent**: system prompt, S as user input, kept tail verbatim, new user message

A summary stands in for the turns it covers on every chain that holds them all, and each chain reads its own. One rule, `active_summary_for_chain` (`state/store/session/reading/summaries.py`), serves the render, the compaction input and the graph builder, so they never disagree. The capsule that draws a summary: [DAG rendering §9](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/rendering.html).

## Summary node

| Field | Value |
| --- | --- |
| `id` | `summary_<hex>` |
| `role` | `llm`, `name = "context/summary"` |
| `output` | `The earlier part of this conversation was compacted into this summary:\n<text>`. A node written before this prefix keeps `[Previous conversation summary]\n` and renders as it did |
| `predecessor` | Predecessor of the first covered node |
| `metadata.covers_ids` | Ordered ids of the chain nodes it replaces |
| `metadata.render_role` | `user` for every new node; a node without it is an assistant message |
| `metadata.restored_state`, `restored_files` | The working state written after the summary, and the path lists the next compaction adds to ([What a compaction restores](#restores)) |
| `metadata.carried_tool_names` | Deferred tools the covered turns loaded |
| Facts | `trigger` (`manual`, `auto`, `reactive`, `mid_turn`, `model_downshift`), `model`, `tokens_before`, `tokens_after`, `summarised_count`, `compacted_at`; written with the node |

- **Append-only.** One node written, complete, in one write: no cloned tail, no edge rewrites, no head movement, no metadata stamped afterwards, no session field naming it. Ignoring the summary reconstructs the original view.
- **Ids, not seq intervals.** Sibling branches interleave seqs, so an interval would drag in dead forks and change with HEAD.
- **`covers_ids` is a contiguous segment of real turns.** It never names a summary: re-compaction extends the old segment by the new turns.

## Which summary

Of the summaries whose covered turns all lie on a chain, the chain reads the one whose coverage reaches furthest along it; `seq` breaks a tie. A rolling summary covers the one before it plus newer turns, so it wins on its chain and the older one serves only chains that branch off earlier.

| Case | Chain reads |
| --- | --- |
| Two branches compacted one after the other | Each its own summary. Switching between them renders each with its own and writes nothing |
| A summary written before the fork point | Both branches |
| A rewind retracts turns in place | A retracted message is not on the chain and a retracted summary does not exist, so a rewind into a summary's range falls back to an earlier summary still wholly on the chain, or to the raw turns |
| Edit, retry or fork inside a covered segment | The new branch lacks part of the segment: it reads an earlier summary that fits, or raw |
| Two branches that loaded different tools | Each summary carries its own `carried_tool_names` |

**Why this design**

- **A summary per chain**: Follows Pi: the last compaction on the path from the leaf. Compared: one newest summary per conversation (Claude Code, Codex, with one linear history), which leaves every other branch raw to compact again. Branches here run in parallel, so the summary belongs to the chain.
- **Rewind falls back**: Codex drops a compaction when the rollback goes behind it; the same rule here keeps a retracted summary from naming turns the chain no longer holds.

## Rendering rule

`render_context` in `context/session_dag/nodes.py` decides what the model reads. With S the chain's summary and L its `covers_ids`: drop L and admit S at its position, as one user message (summary, then restored state); on Anthropic it joins the next user message.

| Case | Result |
| --- | --- |
| Compacted branch | `[ROOT, S, kept tail…]` |
| Covered turns that loaded deferred tools | Left out with their turns. S carries the tools' names (`carried_tool_names`, written with S: most recently loaded or called first, cut where the definitions would pass 5% of the window), so every request still loads them |
| The carried tools, on openai-codex | One `tool_search_call` / `tool_search_output` pair just before S, with the definitions the conversation first sent; the tools array stays as it was. Any other provider offers them in its tools array, and the request opens on S. A bounded background tail keeps only S of the covered part |
| Any checkout, any time | Deterministic from data; nothing depends on where HEAD was |
| Summaries no chain reads | Never elide anything |

The DAG capsule folds by the same rule over the same `covers_ids`.

## Pipeline

Three callers run `engine.compact` on a chain they name by its tip:

| Caller | Chain | Stop signal |
| --- | --- | --- |
| `/compact` (`trigger_compaction`) | The session head as it reads it | Not passed |
| Auto-compact (budget at `context.auto_compact_percent`, default 80%, before a turn and between a turn's steps) | The turn's own branch | The turn's |
| Overflow recovery | The turn's own branch | The turn's |

| Step | Rule |
| --- | --- |
| 1. Freeze the chain's rendered input | `compaction.view.load_compaction_view` uses `render_context` and `render_dag_messages`, with tool results, expose and spill references. Top-level turns define coverage; visible child calls count toward input and budgets |
| 2. Select whole turns | Retain 10% of the window, bounded to 8,000–40,000 tokens (an explicit override wins). Prefer at least four conversational messages at a user boundary; a posted report is a boundary too. Below target: no-op. If the last two turns exceed the target, or no boundary leaves four messages behind it (one giant turn followed by a short one), the cut can advance to the latest user boundary. That latest turn stays intact unless only reports follow it |
| 3. Summarize the whole covered prefix | With the summary prompt ([Summary prompt and role](#summary-prompt)): every replaced turn, the initial request, the chain's previous summary, rendered child calls. Non-text media becomes a reference notice |
| 4. Validate before writing | Reject empty, failed, cancelled, incomplete, capped or non-reducing summaries; a candidate, rendered in memory the same way, must be strictly smaller. After the model call, recheck the chain's rendered nodes; a change is a retryable no-op, other branches and a head moved elsewhere do not count. Provider failure keeps the history, with no lossy structural fallback |
| 5. Persist and report | One write, with the restored state; `covers_ids` expands any previous summary to real turn ids. Before: the context panel's reading of the chain; after: that reading less what the candidate saves. No-ops write nothing and do not count |

### How large a request is

One rule (`runtime/context/token_accounting/measure.py`) answers it for the compaction before a turn, the one between its steps, the gate before each request and the context ring, so they never disagree.

| Part | Rule |
| --- | --- |
| Size | The provider's count of the conversation's last request on the same model (input, cache reads and cache writes), plus the local estimate of what changed since. Without one, the estimate alone |
| What counts as a count | Only a reply that measured one request. A reply that ran provider-side tools (a web search) reports its passes summed; a failed or stopped reply; a count over the window, or over twice the request's own estimate plus 8,000: none of them is used, and the previous count stays |
| Added, not multiplied | The count's difference from its own estimate is added to later estimates. It never takes more than half an estimate away |
| The estimate | The rendered request, reasoning sent back to the model that wrote it included: its summary and its payload |

**Why this design**

- **Last count plus the change**: Follows Claude Code (`tokenCountWithEstimation`) and Codex (`get_total_token_usage`). Compared: a ratio of count to estimate applied to every later estimate. A Grok reply that searched the web twice reported 339k for a 109k prompt; the ratio of 3.95 refused every later request of that turn although it fit.
- **Provider tools excluded**: Claude Code reads the last of Anthropic's `usage.iterations` for the same reason; xAI and OpenAI Responses report no per-pass figures, so such a reply is skipped. Pi drops counts from aborted or failed replies.
- **Reasoning counted**: Twenty reasoning items went back with every request of a Grok conversation and the estimate counted none: the history read 22% short, so compaction came late.

`/compact` is the branch's foreground operation (`op_kind: compact`, an `op_id` on `compaction_started`). The page's Stop and the terminal's Ctrl-C both send `operation.cancel` with that id; the summary request ends with nothing written and the row reads "stopped". An automatic compaction that fails says nothing; the next request tries again.

Why: Claude Code, Codex and Kimi Code all cancel a manual compaction with the key that stops a turn; follows Claude Code, whose terminal is also Ink.

**Automatic compaction that keeps failing**

Each failed try still pays for the whole conversation. After `FAILS_MOST` (3) failures in a row of one branch on one model, each within `HELD_FOR_S` (5 minutes) of the last, automatic compaction on that branch waits five minutes from the last failure, then tries once (`runtime/context/compaction/hold.py`, keyed by conversation, model and branch, consulted by `DefaultContextEngine.compact`).

Another branch keeps compacting. Follows magpie's compaction guard (yetone/magpie, MIT).

| Kind | Cases |
| --- | --- |
| Failures | Summarizer error (a 429, for example), a summary missing sections after the reminder, one that reaches its output cap, empty with an error, no reduction |
| Not failures | Cancellation, changed source |
| Clears the count | A summary that installs. `/compact` always goes |

## Overflow recovery

The agent loop (`runtime/agent/loop/loop.py`) compacts a turn's chain in two places; the turn's own steps stay verbatim.

| When | What happens |
| --- | --- |
| The provider rejects a request as too long | Drop the rejected reply, compact (`reactive`), re-render and send the same request again. One compaction per request, two per turn; a second overflow, or nothing freed, fails the turn with the provider's error. The turn never reruns from its start, so tools are not called again |
| A round of tool results passes the auto-compact threshold | Compact once per turn (`mid_turn`) and continue on the re-rendered request |
| A stop during either | The turn ends as stopped |
| A call that cannot compact durably | Failover to a smaller window, `Runtime.exec`, background and clean runs, an override history: the request checkpoint below |

**Why this design**

- **Retry the one request**: Follows Claude Code and Codex: both compact on a context-length error and resend the request that failed, with a bound on attempts. Compared: rerunning the whole turn's loop, which repeats every step already done, tool calls with side effects included.
- **Compact between steps**: Codex compacts mid-turn when usage passes its limit after a sampling step; Claude Code checks before each request. A long tool loop inside one message otherwise only grows until the provider refuses it.

## Summary prompt and role

One prompt (`compaction/prompts.py`) writes every summary, first or rolling, with these `##` sections: User intent, All user messages, Decisions and constraints, Completed work, Current work, Next step, Relevant files. It leaves out what every request sends anyway (system prompt, AGENTS.md, guides, memory), marks cancelled requests, and attributes claims.

- A reply without every section is asked once more with a reminder (`NUDGE`); still incomplete, the compaction fails, writes nothing and counts toward the hold.
- The output cap is 20,000 tokens, or a quarter of a smaller window. A summary that reaches it fails instead of being kept cut off.
- The summary is user input with a prefix that says what it is.

**Why this design**

- **Sections and a reminder**: Follows Claude Code's sectioned summary, with the user's own messages kept, and its check for a summary that left them out. Compared: two prompts (first and update) with five loose parts, which let a rolling summary drop the user's earlier instructions.
- **User role, with a prefix**: Follows Codex and Pi, which hand the summary back as user input that names itself. An assistant-role summary reads as something the model said and was believed as its own claim.
- **A capped summary fails**: Claude Code treats an incomplete summary as a failure; a cut-off summary loses the Next step and Relevant files, the parts a continuation needs most.

## What a compaction restores

After the summary text, in the same message, the node carries a `<restored-state>` block (`compaction/restore.py`), within 10,000 tokens and the same bytes on every request:

| Section | Source |
| --- | --- |
| Approved plan | The last `exit_plan_mode` the user approved on the chain, unless plan mode was entered again after it; over 6,000 tokens it is cut with a note |
| Todo list | The conversation's todo board, with each item's status |
| Background jobs still running | Jobs that have not ended |
| Files read, Files changed | Paths the covered calls read, wrote or edited, added to the previous summary's lists, the latest 30 of each. A stored call keeps its arguments as the JSON text the model sent, and the path (and the plan) are read from it |

**Why this design**

- **State written, not re-read**: Follows Claude Code, which re-attaches the plan, todos, running tasks and read files after compacting. Compared: re-reading file contents, the most bytes and stale once the file changes; paths let the model read again. Kept in the node, the block stays cached.

## Summary request

The summary sends the last request again with the summary prompt as one user message more (`compaction/fork.py`): same system prompt, tools and cache key, so the provider reads the prefix from its cache. A tool call in the reply is not run; the summary is asked once more.

That message opens by saying it comes from the system, not the user (`FORK_SUMMARY_PROMPT`): it is left out of every section, and the latest request quoted under Next step is the user message before it. The summary covers the whole conversation up to it, kept turns included; the kept turns still render raw after it.

It reads the covered text instead when the model differs, the request plus the summary would not fit, the request is not on the chain, or the compaction recovers from an overflow.

**Why this design**

- **Fork the cached prefix**: Follows Claude Code's forked summary and OpenCode's compaction on the same message list: the conversation is already cached, so the summary pays cache reads instead of a fresh input. Compared: rendering the covered turns as text in a new request, which pays every token at full price; it remains the fallback.
- **The prompt names itself**: Follows Codex, whose compaction prompt opens as a context checkpoint, and Claude Code, which asks for "the conversation so far". Sent bare, the prompt is the newest user message, and a model quoted it as the user's latest request. Compared: covering only the turns before the kept tail, which changes the prefix and loses the cache.

## Model downshift

A branch that follows its Agent onto a model with a smaller window is compacted before its next turn with the model the history was written with (`trigger: model_downshift`). If that model fails, the turn's own model summarises once. A model whose window is not larger takes no part.

**Why this design**

- **The larger model summarises**: Follows Codex's model downshift compaction. The smaller model may not hold the history it is asked to summarise; the one that read it still does.

## HEAD integrity

| Writer | Rule |
| --- | --- |
| `SessionStore.set_head` | The way HEAD changes, for explicit moves: send-turn advance, retry or edit fork, checkout, rewind, branch delete. Compaction, session load, worker restart, model switch and meta saves never call it |
| `append_message` | Moves HEAD only when the node's predecessor is the current HEAD. Summary splices, side-branch writes and relics leave it alone |
| Spawned turns | Same-session sub-agent turns run with `TurnRequest.advance_head=False`; every inner write is head-neutral, so the user's window is not switched mid-run. Cross-session sends do advance the target's head |
| Writes that are not moves | Attach cards, inbox and sub-agent paths that append through the store restore `head_before` afterwards |
| `TurnWriter` (`turn_runtime/turn_writer.py`) | Performs a turn's chain writes and alone applies `advance_head`. In that package only this file moves HEAD, plus the user-initiated function-run path in `forced_tool.py` and the restores in `slash_actions.py` |
| Mirrors | The webui `conv` mirror and one-shot `load_session` snapshot are read-only. The React session store is the only live transcript. `save_meta` strips `head_id`; no mirror row becomes stored |
| Stored HEAD on a call | Older sessions can hold one; a call has no predecessor, so the next request would have no history. `_conversation_head` in `store/session/memory_index.py` reads it as the reply that made the call |

## Graph contract

- For each branch tip, the summary its chain reads carries `covers_ids`: `metadata.covers_ids`, extended with covered turns' caller subtrees, minus ids no longer present.
- A summary no branch reads carries `superseded_summary: true` and no `covers_ids`.
- The builder does no seq arithmetic or head-dependent filtering.

**Fitting a request**

Every AgentLoop provider request, tool continuations and function-local `llm()` and `agent()` included, is sized by the rule above (`compaction/request.py`). Over the limit, it is made to fit for this send only: messages and the DAG stay intact. Each step runs only when the ones before it did not free enough.

| Step | Rule |
| --- | --- |
| Output cap | Unspecified: the smallest of model capability, 16,384 and a quarter of the window, used for budgeting and dispatch alike. Explicit caps are never reduced |
| 1. Earlier media | Images and other media before the turn's own message become a one-line note |
| 2. Checkpoint | An older complete prefix becomes one task summary, reused within the invocation for the same model and an unchanged source prefix. The newest user messages stay verbatim within 20,000 tokens; older ones are in the summary. Media reaches the summarizer as a note, and a finished turn's reasoning as its summary text. The turn's own signed reasoning and an unanswered call keep their prefix out. A summary that fails is skipped; a stop still stops |
| 3. Earlier tool results | Results before the turn's message keep 1,200 characters of head and 400 of tail |
| 4. Oldest steps | Left out from the front, a whole step at a time, behind a note that says how many |
| 5. The turn's own steps | Results before its latest step shortened, then its media, then those steps left out behind a note, then every result shortened |
| Fails | Only when the latest message, the system prompt and the tools alone do not fit the window, saying so |
| Summary calls | Bounded chunks, retried smaller on overflow; at most 32 requests; bypass AgentLoop. Each request runs while its stream keeps producing and fails after 60 seconds without an event; a stop closes it at once |
| What is measured | The rendered request: each reply with its tool calls and results. The stored rows hold a reply's text only; measured by them, a conversation of mostly tool work read a fifth of its size, never compacted, and had its request refused |

**Why this design**

- **Fit, then send**: No peer refuses a request on its own estimate: Claude Code and Codex compact and send, and fail only after the provider reports an overflow and recovery is spent. Compared: keeping every user message, picture and signed reasoning verbatim and failing when they did not fit, which ended a turn of a 109k conversation in a 256k window.
- **Cheap steps first**: Media before summaries follows Hermes, which keeps only the latest picture, and OpenCode, which strips media to recover. Shortening results before leaving steps out follows OpenClaw; leaving the oldest out follows Codex, whose compaction drops history from the front when it does not fit. User messages kept within 20,000 tokens follows Codex.
- **No per-result summaries while it fits**: Codex, OpenCode, Pi and Kimi Code have none, and Hermes turns its own off: replacing tool results one by one rewrites the middle of the request, so every later request misses the prompt cache. The steps above run only when the request does not fit.
- **No cache-edit clearing**: Anthropic's `clear_tool_uses` context edit cleared old results on the provider side with the same effect on the cache and only on one provider; it is not sent.

**Choosing the share from the user's own calls**

Compacting sooner reads less per call but pays for more summaries and rework. `context.auto_compact_percent` (Settings → Model services → Behavior → Summarize long conversations at, 50–95, read at each decision) is advised by `GET /api/usage/tuning?days=30` (`runtime/context/token_accounting/tuning.py`), replaying every share from 50% to 95% on the period's chat, exec and subagent calls, per model. Follows magpie's tune (yetone/magpie, MIT).

| Part | Rule |
| --- | --- |
| Replay | Calls replay in order, each prompt growing as it really grew, with recorded compactions (a drop to under 60% of a prompt of at least 20K) removed |
| Past the threshold | The threshold is the share of the window less the reply reserve. A compaction reads the whole prompt and writes a summary as long as those seen (or 10K over the start when none were). The next call writes it to cache; later ones read back what recorded compactions were followed by (at least 10K until five were seen) |
| Prices | Tokens are weighed against plain input with catalog prices or the vendor's usual ratios |
| Advice | Shares leaving less than half a summary, or twenty calls' growth, of room are not tried. Of those within 1% of the cheapest, the largest is advised, only if it saves at least 3% over the current one. Fewer than 50 calls: no advice |
| Cache lifetime | The same endpoint advises `models.prompt_cache_ttl` (`5m` or `1h`) for Anthropic API and Bedrock calls: hour-long writes cost twice input, and a call after expiry writes its whole prompt again. The setting lengthens only a plain cache (`with_lifetime_setting` in `providers/settings/cache_spec.py`) |

**Other compaction schemes**

One rolling summary per chain keeps the cache prefix stable. It is policy, not storage: schemes differ only in which summaries are active and how the renderer substitutes them, so switching migrates no data.

| Scheme | Change |
| --- | --- |
| Segmented (several live on one chain) | N nodes over disjoint segments; the rule returns a set per chain |
| Nested | `covers_ids` admits summary ids; substitution is recursive |
| External memory | Same node; the renderer stops inlining it |

Any scheme keeps two contracts: context is a deterministic view over append-only nodes, and the ids that entered a prompt are stamped on the call as `reads`.

## Invariants

| Invariant | Tested in |
| --- | --- |
| After compaction, the active branch renders `[ROOT, S, kept tail…]` | `tests/unit/context/compaction/test_compaction_covers.py`; scenario suite |
| Each chain reads its own summary; switching writes nothing; a rewind falls back; the builder agrees | `tests/unit/context/compaction/test_summary_per_chain.py` |
| An overflow retries the one request, at most twice per turn; a stop ends it as stopped | `tests/component/context/test_reactive_retry.py` |
| A new summary is user input with its prefix; an incomplete or capped one fails and counts toward the hold | `tests/unit/context/compaction/test_summary_prompt_and_role.py` |
| The restored state follows the summary, in budget, the same bytes on every request | `tests/unit/context/compaction/test_compaction_restore.py` |
| The summary request reuses the last request's prefix; an overflow recovery never forks | `tests/unit/context/compaction/test_compaction_fork.py` |
| A downshift is summarised by the larger model, then the turn's | `tests/unit/agent/test_downshift_compaction.py` |
| Under the window a turn's requests only grow at the end; over it, one checkpoint and no per-result summary | `tests/component/context/test_request_checkpoint_only.py` |
| A request is sized by the last single-pass count plus the change; a count of several passes, a failed reply's or an implausible one is not used | `tests/unit/context/token_accounting/test_request_measure.py` |
| A request over the limit is fitted, history untouched; only a latest message over the window fails | `tests/component/context/test_request_checkpoints.py` |
| S carries the tools its turns loaded, ordered and cut to the window; on openai-codex one pair before S keeps the tools array the same before and after compaction; any other provider reads S first | `tests/unit/context/compaction/test_compaction_keeps_loaded_tools.py` |
| Compaction never moves HEAD | Scenario suite |
| `covers_ids` never names a node off the summarized chain | `tests/unit/dag/test_graph_builder_covers.py` |
| HEAD survives restart, session load, model switch, meta save | `tests/integration/dag/test_dag_mutation_scenarios.py` |
| No mirror row or head writes back into the store | Web UI persistence tests |

The scenario suite runs chat, fork, checkout, compact, chat, compact, chat, restart-load on a real `SessionStore`, checking head and rendering after every step.

## Implementation status

| Part | Code |
| --- | --- |
| Node shape and pipeline | `runtime/context/compaction/persistence.py` (`insert_summary_node`, `covered_chain_ids`, `rendered_history`), `runtime/context/engine.py` |
| Which summary | `state/store/session/reading/summaries.py`; `runtime/context/session_dag/nodes.py` (`render_context`); `state/store/session/graph/builder.py` |
| Overflow recovery, mid-turn compaction | `runtime/agent/loop/loop.py`, `turn_runtime/turn_compaction.py` |
| Prompt, restore, fork | `compaction/prompts.py`, `summarize.py`, `bounded_summary.py`, `restore.py`, `fork.py` |
| Model downshift | `turn_runtime/loop_runner.py` (`_auto_compact_new_turn`) |
| `/compact` as an operation | `server_runtime/run_slots.py`, `ws_actions/chat/commands.py`; terminal Ctrl-C in `apps/cli/src/screens/REPL.tsx` |
| HEAD integrity | `state/store/session/session_store/messages.py`; `interfaces/server/persistence.py` strips `head_id` |
| Not built: cutting inside the current turn | Mid-turn and overflow compaction cover only the history before the turn's user message; a turn whose own steps outgrow the window still relies on the request checkpoint. Covering the turn's finished steps needs each step stored as it ends, and the transcript marker placed mid-turn |
| Not built: the in-process terminal through the server | The older Python REPL's `/compact` runs in its own process, outside the branch's foreground slot |
| Not built: unread job results | The restored state lists running jobs; finished jobs whose results were never read are not tracked yet |

[Compaction tiers](https://fzkuji.github.io/OpenProgram/docs/reference/design/context/compaction-diagram.html)
