An agent works a task for two hours. It reads a schema, runs a migration against a staging database, hits a foreign-key violation, works around it, writes the handler, runs the tests, and then the context window fills. The runtime summarises the transcript, the run continues, and twenty minutes later the agent drops and recreates the column it was told never to touch. The task description said, in the third line, not to touch that column. The summary said the migration was complete.
Nothing in that sequence is a model failure in the sense people usually mean. The model reasoned correctly over the context it was given. The context was wrong because the system had edited it, and the edit removed a prohibition while keeping an accomplishment — which is exactly what a summary does when it is asked to be brief about a transcript in which nothing happened to the forbidden column.
This is the least glamorous and most consequential part of running agents for hours. Compaction is not a memory feature bolted onto a chat product. It is a write to the only state the model trusts, performed under a budget, by the same model that is being supervised, with no undo. Treat it as an engineering operation with a schema, an invariant and a verification step, and most of the failure modes below stop being mysterious.
Context is a working set, not storage
The window is not a database that fills up once. It is re-read on every turn, and the model has no privileged access to anything that was removed from it. Whatever the prompt asserts is true as far as the run is concerned: if the prompt says a constraint was already honoured, it was; if the prompt no longer contains the constraint, it does not exist.
That gives compaction two motives that pull in the same direction but are not the same problem. The first is the hard limit: a run that exceeds the window stops, and a stopped run that has already performed side effects is a workflow problem rather than a token problem. The second is quality. Long contexts degrade before they overflow — recall of a specific detail in the middle of a large window is worse than recall of the same detail in a small one, and the degradation is not announced by a warning. Both motives say: keep the window small. Neither says which tokens are safe to delete, and that is the decision compaction forces early.
The useful mental model is a working set with an eviction policy, where the evicted pages cannot be re-read from disk. Everything else follows from choosing an eviction policy whose mistakes are recoverable.
Three operations people call summarising
Teams say "we compact" about three mechanisms with different costs and different ways of losing information. Distinguishing them is the first useful design act, because they need different safety rules.
| Operation | What it does | What it loses | When it is safe |
|---|---|---|---|
| Eviction | Replaces old tool results with a placeholder, keeps the call record | The payload — file contents, query output, search hits | When the result is re-fetchable by an idempotent call |
| Substitution | Replaces the transcript with a generated summary | Structure, exact strings, negatives, hedging | Rarely, and only with a record kept elsewhere |
| Externalisation | Moves state to a file or row the agent can read on demand | Nothing, if the agent knows to read it | Whenever the medium survives the run |
Eviction is the cheapest and the safest, because a re-callable tool is a cache. Clearing a file read costs one round trip to restore. Clearing a POST that created a record costs nothing to restore only if you kept the record's id, and costs a duplicate if you did not — the same asymmetry that makes retries dangerous in durable workflows. The rule that falls out: evict reads freely, evict writes never, and when in doubt keep the identifier and drop the body.
Substitution is the operation everyone reaches for and the one that breaks runs, because it is the only one that rewrites meaning rather than removing bulk. Externalisation is the one to build first, and the one most teams build last.
What a summary cannot carry
A summary preserves narrative and discards the properties that make technical state usable. Five categories go missing reliably enough that they should be treated as known losses rather than risks.
- Exact strings. An error message, a header name, a column type, a commit sha, a version pin, a path. A paraphrase cannot be grepped, cannot be passed to another tool, and cannot be compared against the next failure. "The endpoint was rate limited" loses
429andRetry-After: 30, and the retry policy that read that header no longer has an input. - Prohibitions. Constraints describe a space in which nothing happens, and nothing is precisely what a summary is trained by brevity to omit. A list of six things the agent must not do survives into a summary as a sentence about the task being complete.
- Negative results. The approach that failed, and why. Summaries keep the plan and drop the dead ends, so the next phase re-derives the same failure from scratch — the same wasted spend, sometimes with a duplicate side effect.
- Unresolved state. Which migration step ran, which write is half-applied, which question is waiting on the user. This is the category where information loss becomes a correctness bug rather than an efficiency loss.
- Confidence. "Verified in staging", "inferred from the docs" and "assumed" arrive in a summary as three identical declarative sentences. Downstream reasoning cannot distinguish them, so an inference becomes a fact after compaction.
The pattern behind all five: a transcript is evidence, and a summary is testimony. Testimony is shorter, more coherent, and less reliable, and the reader has no way to check it against the evidence because the evidence was the thing you deleted.
The summariser has the same failure modes as the agent
The summariser is usually the same model, given the same long input and a prompt that says be brief. Brevity pressure is a strong prior, and it acts on exactly the parts you needed: hedges get deleted because they are qualifications, units get dropped because they are detail, and connective tissue gets invented because a summary that reads well is rewarded. A summary is a generation, not a compression. It can contain assertions that were never in the input, and it can contain them in the same flat tone as the observations.
Two consequences follow, and both are cheap to design around once they are accepted. First, the summary should never be the only copy of anything you would be unwilling to lose. Second, the summary should be generated from a structured record where possible, not from the raw transcript, because a record is small enough that brevity has nothing to destroy.
Compaction generations drift
The failure compounds because a long run compacts more than once. The second summary is generated from the first summary plus recent turns, not from the original transcript. Each generation loses a little detail, paraphrases a little further from the source, and smooths over one more contradiction. After three cycles the surviving text is a legend about the run: a coherent account of what the agent believes it did, with the specific facts that would allow anyone to check it gone.
Nothing in the loop re-anchors the record, because the anchor was the original transcript. This is why the fix is architectural rather than prompt-level. If the authoritative state lives in an append-only log — the same log your traces write to — then compaction becomes a rendering of that state into a prompt. Re-rendering is idempotent. Summarising a summary is not. The difference between those two designs is the difference between a run that can be resumed after a crash and a run that can only be continued by whoever happens to still be holding the thread.
Cut at task boundaries, never inside a tool pair
There is a mechanical constraint that a naive compactor violates immediately. Modern tool-use APIs require pairing: an assistant message containing a call must be followed by a matching result, usually keyed by id. A compactor that truncates messages by token count will eventually cut between a call and its result. The prompt is then malformed, and the two ways that plays out are both bad — the provider rejects the request, or the model sees its own call with no answer and calls it again, re-running a side effect it already performed.
Compaction therefore belongs at phase boundaries: after exploration and before planning, after planning and before execution, after a subtask is verified and before the next one starts. At those points the working set is cold, the last tool pair is complete, and the state you need to preserve is exactly the state your checkpoint already holds. A threshold-only trigger has the opposite property: it fires at ninety-five percent of the window, which is mid-execution, with the hottest working set of the whole run and the least headroom to recover if the summary is bad.
Triggers are cheap, so use more than one. Token thresholds bound the hard limit; phase transitions improve quality. A run that compacts at a clean boundary with sixty percent headroom left can afford to keep the verbatim tail that a run compacting at ninety-five percent must drop to survive.
The checkpoint is a record; the summary is a hint
A durable agent needs a state object that could be handed to a different process — or a different model — and resumed. Prose is the wrong container for it, because prose is what a summariser is allowed to rewrite. A typed record, rendered into the prompt with a fixed template, is stable across compactions and verifiable in code.
interface RunState {
goal: string; // one sentence, the user's words where possible
constraints: readonly string[]; // verbatim, never summarised, never reordered
steps: ReadonlyArray<{
id: string;
intent: string;
status: 'open' | 'done' | 'failed';
evidence?: string; // commit sha, record id, test name
}>;
failures: ReadonlyArray<{ attempt: string; error: string }>; // exact text
artifacts: ReadonlyArray<{ kind: 'file' | 'commit' | 'record'; ref: string }>;
next: string; // the single action the run will take next
}
The division of labour matters. Code fills the mechanical fields: statuses from tool results, artifact ids from return values, error text copied byte for byte. The model writes only the fields that need judgement — the intent of a step, the reason an approach failed, what remains. Asking a model to be a database is how you get a summary that says the migration succeeded when one of four statements committed; asking it to explain why something failed is what it is good at.
Prompt assembly then becomes deterministic: system instructions and pinned constraints first, the rendered state next, a verbatim tail last, then the new turn. Stable content at the front is also what makes caching work, since a prefix cache survives only while the prefix is byte-identical. Rendering the same state twice produces the same prompt twice, which is the property that makes both caching and reproducibility possible.
Keep a small verbatim tail regardless of the summary: the last one or two tool results, the current file diff, and the most recent user message unresummarised. Those are the tokens the next action depends on, and they are small. The error is not keeping too few tokens in the window; it is keeping the wrong ones — a wordy summary of turn twelve and none of the diff from turn ninety.
Measure the prompt, not the usage envelope
Compaction fires on a number, and the number is often wrong. Vendor usage objects are built for billing: they include cached reads, cache writes, output tokens and, with server-side tools, tokens consumed by internal calls the model made on your behalf. Summing those fields produces a figure that can be several times your actual context length. Compaction triggered on that figure throws away history you did not need to lose, and the symptom is an agent that suddenly forgets a constraint at forty thousand tokens because the runtime believed it was at three hundred thousand.
The number to trust is the size of the prompt you are about to send, measured by your own tokeniser or approximated well enough to set a threshold with margin. Track it per turn, and record both sides of every compaction with the run trace: tokens before, tokens after, what was removed by category, and what the run did next. Without those pairs you cannot tell an efficient compactor from one that is quietly deleting the run's memory, and the difference only shows up as a task that fails for no visible reason.
Cache economics make small compactions expensive
Prompt caching rewards a stable prefix and punishes edits in the middle, because a cache hit requires the prefix to match exactly. Compaction is an edit in the middle by definition: everything after the point of removal must be rewritten, and the next request pays cache-write price for the whole new prefix before reads get cheap again.
So a compaction that frees two thousand tokens can cost more than two thousand tokens of cache reads across the remaining turns of the run — you traded a stream of cheap reads for one expensive write and a shorter stream of cheap reads. Two rules follow. Compact rarely and deeply: when the operation fires, free enough tokens that the write amortises, and skip it entirely if the reclaimable amount is below a threshold you set deliberately. And put the volatile material last, so the stable prefix you paid to cache survives as long as possible.
The counterintuitive case is the agent that compacts every turn: it invalidates its own cache on every request and pays the write price repeatedly, while producing summaries so incremental that each one loses detail without buying meaningful headroom.
Verify the compacted context before you spend on it
A compaction should be treated like a migration: it either preserves an invariant or it does not run. The invariant is checkable in code, before the next model call.
function assertCompacted(prompt: string, state: RunState, lastUser: string): void {
for (const constraint of state.constraints) {
if (!prompt.includes(constraint)) {
throw new CompactionLostConstraint(constraint);
}
}
if (!prompt.includes(lastUser)) throw new CompactionLostInstruction();
if (!prompt.includes(state.next)) throw new CompactionLostPosition();
// tool_use / tool_result pairing must survive: no assistant call without a result
assertPairing(promptMessages);
}
Three assertions carry most of the value: every pinned constraint appears verbatim, the most recent user message appears unmodified, and the state says what the run is doing next. A fourth belongs in the message layer — pairing — because it is the failure that produces a provider error at the worst possible moment.
There is also a behavioural check worth its cost. After compaction, ask the model to restate the constraints and the current step in one short call, and compare against the record. If it cannot, the prompt is wrong, not the model. This costs a fraction of a turn and catches the exact class of bug that produced the migration in the opening paragraph, where the summary was fluent, plausible and missing a prohibition.
The third instrument is an evaluation set: tasks long enough to force two or more compactions, with assertions on the final state of the work rather than the final prose. Run the same tasks with compaction enabled and disabled, and the difference in pass rate is the price of your summary. This is the same discipline as eval gates in CI, applied to the runtime rather than the model: the question is not whether the summary reads well, it is whether the run still finishes correctly after three generations of it.
What stays in the window permanently
The set of tokens that must never be evicted is small and stable across domains: the constraints, the output contract, the current step and its evidence, the last error verbatim, and the diff or payload about to be submitted. Everything else is either re-fetchable or reconstructable from the record, which is the test to apply when deciding.
There is a structural alternative worth naming, because it avoids compaction instead of surviving it. Run exploration in a subagent whose transcript is discarded on return, and pass back a typed result. The parent never holds the forty thousand tokens of file reads, so it never has to decide what to forget. This is compaction done correctly by construction: the information that crosses the boundary is chosen deliberately, and the bulk never enters the window at all. The same reasoning applies to pulling large tool output through a programmatic filter rather than into the conversation.
None of this is exotic. It is the ordinary discipline of any system that must forget something and continue: an append-only record, an eviction policy with a stated invariant, a verification step, and a measurement that distinguishes a cheap memory from a lost one. The teams that run agents for hours without incidents are rarely the ones with the largest context window. They are the ones whose agent can answer, at any turn, what it is doing, what it was told not to do, and where the evidence for both lives.
If you are running long-horizon agents and cannot say which tokens survive a compaction, tell us what your runs look like — this is routine work in our AI engineering practice, and it reads best next to step budgets, run traces and durable workflow compensation. It is also the constraint behind our own agent platform: an agent that cannot resume from a record cannot be trusted with a second hour of work.