Skip to content
Source on GitHub (opens in a new tab)

The context-management contract for long-running sessions. Compaction changes the model’s working window, never deletes source events from the session log, and performs no workspace reads during replay.

Requests contain the recorded system prompt and tools in fixed order, then dynamic context, then history. Instructions loaded mid-run arrive after the relevant tool results. System and tool prefixes stay byte-identical through turns and deliberate history rewrites; TestCacheStablePrefix checks rendered Anthropic and Responses requests.

  • Anthropic: system/tool breakpoints and automatic rolling conversation caching (anthropic.WithCache(false) disables them).
  • Responses: automatic prefix caching, routed by a per-session cache key (openai.WithCacheKey fixes one instead). Native windows already contain the context they compacted: unchanged dynamic context is not prepended again. Changed context still reaches subsequent requests.

The estimate uses the last measured input plus new history at 3 bytes per token, or estimates the complete rendered request when no measurement applies. Measurements are tied to a prefix/model revision. Injecting context, changing mode or switching models invalidates older measurements, including usage returned by an already-running call. A switch to a smaller model also lowers effective threshold and retention bounds; it cannot inherit a larger model’s trigger.

  1. Bounded output at the source. Tools keep bounded output and save complete oversized output in paged blobs.

  2. Microcompaction. Results older than the 6 most recent and larger than 2 KiB are rewritten in one batch. Stubs retain result status, a bounded 512-byte head/tail preview, and any full-output blob reference with its Read path. They do not tell the model to repeat an action to recover its output. No model call is made; this deliberate prefix rewrite pays a cache miss once for the batch.

    Clearing. Microcompaction also runs on its own trigger, long before a full compaction is near: once the estimated input passes Compaction.Clear (default 100,000 tokens), and only when the batch removes at least Compaction.ClearAtLeast (default 20,000). The trigger is a size of context, not a share of the window, so it also works on routes that declare no window. The minimum keeps passes few and large, so each cache miss pays for itself. A cleared Read’s stub names the file and range and says to read it again, since the file may have changed; it keeps no preview of the old revision. Other stubs are as above. In replays of four recorded sessions, a 60K trigger cut main-loop input to 44% for about 10% more uncached input, in about three passes a session. Live, 60K sat barely above the files a run was working in: passes cleared them, the model read them again, and two passes came three turns apart. The default is 100K, the API’s own trigger for clearing tool results. Subagents record the same policy. WithCompaction sets both values.

  3. Portable summary. A model summarizes the prefix before a cut, with system and tool definitions unchanged. The request forbids tool calls (provider.ToolChoiceNone): the tools stay so the cached prefix still matches, but a summary must be text. A live model once answered a summary request with a tool call, which left nothing to compact with. Some routes ignore the choice: Laguna on OpenRouter wrote a whole summary and then called tools. A summary that stops at a tool call is accepted, since its text ended before the call; the calls are dropped and never run. The harness asks, after the host’s prompt (compact.Envelope), for the summary between <summary> and </summary> lines, as Claude Code’s compaction does, and keeps only what is between the first opening tag and the last closing one (compact.Unwrap), so tags quoted in the summary stay in it. A reply with no non-empty tagged block is rejected (see Failed summaries below). A 9B model answered a summary request with its own tool-call markup as text, ending its turn, and that replaced seventy turns with a todo list. The tags tell a summary from anything else whatever the host’s prompt asks the summary to contain, where matching particular markup formats would only catch the formats already seen. Recent history remains byte-for-byte intact. Cuts keep calls and results paired and do not split adjacent assistant reasoning from its calls. The summary prompt requests each request marked done (with what showed it), open or dropped; constraints; decisions; files; verified/unverified state; background work by handle; refusals; and actionable next steps. Marking requests done is what retires finished work where no run reports (the conversational hosts), as Goal.Met does where one does. The prompt tells the model what the harness re-attaches after the summary (goal, recent user messages, task list, instruction files, memory, the system prompt), so the summary records what those don’t say, and that tools come back after it: live summaries carried “no tools may be called”, from the prompt and from the provider’s note that tools are withheld, into their constraints. TestLiveCompactionKeepsRequestStatus (tag live) checks both. The prompt is recorded in each session’s configuration, so a change reaches only new sessions.

  4. Native compaction. A capable provider also produces its own canonical window of the ordinary request. It is recorded alongside the portable summary, and its usage is charged. Native items are never pruned or rewritten. zelk sends the protected deterministic handoff alongside the opaque native items, without duplicating the model-written summary. Only that provider family uses them; another family uses the portable handoff. An unavailable or failed native call leaves the portable summary with a warning. If a successful native window remains oversized, a smaller portable handoff can be used instead.

A summary has a separate output budget: at most 20,000 tokens, room for a reasoning model to think before it writes (with 4,096 one spent them all reasoning and wrote nothing), at most one quarter of the effective threshold when known, and never above the working turn’s output limit. This budget is part of the request and reservation. A cut-off, refused, paused or empty summary is not accepted as complete. A non-shrinking candidate that remains oversized is rejected before replacing its source history.

Failed summaries: when an automatic compaction gets no usable summary (the summary call itself overflows, or the reply is rejected as above), the history before the cut is dropped instead, and a compaction_failed warning is recorded. The handoff that replaces it is the same deterministic one a summary gets (goal, retained user messages, task list, plan, instructions, processes, verification), under a note that the older part was dropped. Ending the run instead would strand the session: its next message would ask for the same compaction, from a request at least as large, and fail the same way. A manual compaction that fails reports the error and keeps the history, since nothing forces it. A summary call that fails for another reason (a transient error the driver’s retries didn’t clear) ends the run as before, since the next attempt may succeed. Compaction cannot cycle indefinitely without ordinary model work between summaries; a window still too large after compaction ends with an explicit error.

Manual compaction: a compact command (zelk.Compact(focus), the hosts’ /compact [focus]) asks for a summary now. An idle session starts a run that only compacts and then ends, with no report: it did no work, so it neither meets nor fails the goal. Mid-run, the next model call compacts first. The cut is the usual one, or the whole history when the usual one would keep everything. PreCompact hooks see trigger manual, with the focus as custom_instructions, and may block it; a blocked or empty compaction ends a run that was only for it. The focus is appended to the summary prompt and recorded in the effect’s Compact, so a replay sends the same request. A session without compaction, or with no history while idle, refuses the command.

Reactive overflow: a request classified as context_overflow triggers microcompaction, a full summary and one new ordinary attempt. On a route that declares no context window, such as OpenAI’s API with a key, this is the only compaction; TestLiveOverflowIsClassified (cmd/zelk/internal/host, live tag) checks that the provider’s real refusal is classified as an overflow. Another overflow without intervening work ends the run. This is context repair, not a retry that hides an unchanged failure.

A session that compacts carries a short system-prompt section (prompt.Continuity) saying that a long conversation is summarized and goes on, so the model never wraps up early or hands off because a session feels long, as Claude Code tells its model. A session without compaction isn’t told it.

State preserved independently of the summary

Section titled “State preserved independently of the summary”

Even a model that omits these facts cannot erase them from the portable handoff (or the protected handoff alongside a native window):

  • The active goal and revision (explicit goals in full; default requests within the verbatim bound), or the fact that the user abandoned it. A goal a successful run reported met is carried as done, not as current work: a run a background wake starts keeps the session’s goal, and restating a met request as “the goal” handed the model finished work again (TestCompactionRetiresAMetRequest).
  • A persistent 8 KiB verbatim user-message reserve, retaining the original task when it fits and prioritizing the newest constraints over intermediate detail. Harness notes do not displace user messages. Later instructions supersede earlier ones. Older or oversized messages remain in the log and are represented semantically by the model summary; the handoff states when they fall outside the verbatim reserve. The reserve also keeps what the user said in answer to the agent, in its place among the messages: answers to questions, a rejected plan and its note, and the instruction given with a denied action. Those arrive as tool results, so the reserve preserves them when the summary replaces the results. The retained-messages heading is left out when the goal, stated above it, is the only message.
  • Current todos, including task keys, statuses and recorded failure counts for those tasks.
  • The plan the user approved last with ExitPlanMode, with what they added approving it, bounded to 16 KiB. A later approval replaces it, and once a run reports the request it served met (or, in a session without reports, once a run ends normally after the approval) it is left out, and re-entering plan mode no longer offers it for revision: handing on finished work set the model to do it again. Claude Code keeps its plan in a file and points back to it after compaction; the session log is zelk’s file.
  • The active skill’s recorded rendered instructions, including invocation arguments and trust framing. It need not be reloaded from mutable files.
  • Current project instructions with their path scopes. Superseded or removed root guidance is retired at the rewrite boundary; scoped guidance is carried separately from the user-text allowance.
  • Running process handles, commands and working directories.
  • The files read or changed most recently, newest first, at most 12, with an instruction to read one again before relying on or editing it. Claude Code points its model back to the files it had read; zelk names them rather than attaching their contents, since replay never reads the workspace and what was read before may have changed.
  • Latest verification IDs, result generations and freshness status. A running background process still makes freshness unknown; summarization does not upgrade evidence.

These are bounded recorded facts, not a claim that arbitrary model-written rationale is lossless. If required context cannot fit the actual model window, compaction must report that limit rather than silently discard applicable constraints. Semantic summary quality still needs long-session evaluation with real models.

Option Effect
default threshold max(window × 0.9 − max output, window ÷ 4), keep min(20,000, threshold ÷ 5); unknown windows initially permit reactive compaction only. The hosts learn an OpenAI-compatible model’s window from the server’s model list (context_length on OpenRouter, max_model_len on vLLM), a ChatGPT plan model’s from the account’s model list (context_window, as Codex reads it), a Claude model’s from Anthropic’s Models API (max_input_tokens) and a Gemini model’s from the Gemini API’s model resource (inputTokenLimit). OpenAI’s API and OpenCode list none: there, and for any model whose provider reports no window, a host declares one with WithContextWindow(tokens) (the hosts’ -context-window), which a reported window overrides
WithCompaction(event.Compaction{Threshold, Keep, Clear, ClearAtLeast}) set any bound; zero retains its default; effective bounds also respect a subsequently smaller model window
WithoutCompaction() disable compaction; an overflowing request ends with an error

Resolved configuration and the compaction instruction are recorded in SessionStarted.

TestLongRunningCompaction exercises 200 consecutive compactions with JSON state restoration, checks retained constraints and todos, closed call/result pairs, resumed model work and bounded request size. TestLongCompactionFileReopen also runs 200 cycles with ten real file-store close/reopen and replay checkpoints, comparing restored state to uninterrupted execution. Other regression tests cover prefix updates during a call, smaller-model switches, active skills and project guidance, operational state, output previews, reasoning boundaries, incomplete/non-shrinking summaries, native context duplication and portable fallback.

FuzzCompaction also varies output sizes, prefix changes and restoration across compaction sequences. These are deterministic offline protocol tests. They do not establish real-model recall quality.

A process stop withdraws unseen completion notices from later requests. Both requests in a native compaction attempt use the post-start state handed to that provider worker. A stop pins notices in unresolved requests from that handoff so their visibility survives compaction.