Compaction for AI Agents: Strategies That Keep Long Sessions Sharp
Every coding agent hits the same wall. A session starts sharp: the model knows the task, the files, the constraints. Two hours and forty tool calls later, the context window is full of stale file reads, test logs and half-abandoned plans. The agent gets slower, more expensive and, worst of all, forgetful.
Compaction is how an agent decides what to keep. Done badly, it throws away the one constraint the user said at the start. Done well, the agent works for hours and never seems to notice.
This post walks through the main strategies, what each one costs, and how they combine.
Why context fills up
Before picking a strategy, look at what is actually in the window. In a coding agent, the conversation itself is rarely the problem. Tool output is.
- File reads. The same file read three times across a session, each copy still in context.
- Command output. Test runs, build logs,
git diff,ls -R. Hundreds of lines where three mattered. - Search results. Grep output across a large repo.
- Superseded work. Edits that were later reverted, plans that changed, errors that were fixed.
That shape matters, because the cheapest wins come from targeting tool output, not from summarising the conversation.
The costs every strategy trades off
Each approach below is a trade between four things:
- Fidelity. How much the agent can still recall after compaction.
- Cost. Extra model calls, tokens and latency.
- Prompt cache. Providers cache the prompt prefix. Any change to an earlier message invalidates the cache from that point on, so the next request pays full price for everything after it.
- Predictability. Whether you can say exactly what was removed, and why.
The prompt cache is the one people forget. A compaction that saves 40% of tokens but rewrites the start of the conversation can cost more than it saves.
1. Sliding window
Drop the oldest turns once the window passes a threshold.
the window fits 6 turns; each new one pushes one out
[ 1 ][ 2 ][ 3 ][ 4 ][ 5 ][ 6 ]
░░░ [ 2 ][ 3 ][ 4 ][ 5 ][ 6 ][ 7 ]
░░░ ░░░ [ 3 ][ 4 ][ 5 ][ 6 ][ 7 ][ 8 ]
▲
└─ turn 1 held the task: "never touch migrations/"
It is trivial to build and costs nothing to run. It is also the bluntest tool there is: the oldest turns are usually where the user explained the task. An agent with a sliding window forgets why it is working before it forgets what it is doing.
Use it for: chat-style agents with short, independent turns. Almost never for coding agents on its own.
2. Tool output trimming
Shrink tool results instead of dropping turns. Two flavours:
- At write time: trim output before it ever enters context. Keep the failing tests, not the 400 passing ones. Keep the error and its stack frame, not the whole build log.
- After the fact: once a tool result is old and has been acted on, replace it with a stub.
at write time
┌ $ npm test ──────────┐ ┌ in context ─────────┐
│ ✓ 400 passing │ trim │ ✗ 2 failing │
│ ✗ 2 failing + stack │ ─────► │ + stack frames │
└──────────────────────┘ └─────────────────────┘
after the fact
┌ read src/server.ts ──┐ ┌ in context ─────────┐
│ 412 lines │ old, │ [cleared: 412 lines │
│ (acted on 10 turns │ ─────► │ re-read if needed] │
│ ago) │ used │ │
└──────────────────────┘ └─────────────────────┘
The stub matters. It tells the model the information existed and how to get it back, so it re-reads instead of guessing.
Use it for: almost every coding agent. It is usually the biggest single win for the lowest risk.
3. Summarisation
When the window is nearly full, ask a model to summarise the conversation so far, then start a fresh context from that summary.
┌ context ── 150K tokens, near the limit ─────────┐
│ sys │ t1 │ t2 │ t3 │ t4 │ … │ t38 │ t39 │ t40 │
└────────────────────────┬────────────────────────┘
│ model call: "summarise this"
▼
┌ new context ── 4K tokens ────┐
│ sys │ summary │ t41 … │ prompt cache: cold
└──────────────────────────────┘
This is what most people mean by "compaction", and it is powerful: a 150K-token session can collapse into a few thousand tokens of state. But it has real costs:
- It is lossy in ways you cannot predict. The summariser decides what matters. The detail it drops is often the one that comes back to bite.
- It costs a model call, often a large one, at exactly the moment the session is most expensive.
- It resets the prompt cache. The new context is all new tokens.
- It drifts. Summaries of summaries lose precision with each round.
A good summary prompt asks for structure, not prose: the user's goal, constraints they stated, decisions made, files touched, what is done, what is next, and open questions.
Make it lossless. Before compacting, save the full transcript to disk, and end the summary with a pointer to it. The agent is told that the summary is a digest, not the whole story: when it needs something the summary dropped, like an exact error message, an earlier version of a file, or what the user said word for word, it reads the original back with a tool call instead of guessing.
┌ context ── 4K tokens ──┐ ┌ disk ──────────────────┐
│ sys │ saved │ session.md │
│ summary │ ─────► │ all 40 turns, verbatim │
│ "full log: session.md" │ │ │
│ t41 … │ ◄───── │ t17: exact error text │
└────────────────────────┘ read └────────────────────────┘
Nothing is forgotten, it just moves out of the window. That removes summarisation's biggest risk, unpredictable loss, for the price of an occasional extra tool call. It still costs a model call to write the summary and still resets the prompt cache.
Use it for: long sessions where the early detail genuinely no longer matters, as a last resort after cheaper strategies.
4. Rolling summarisation
Instead of summarising everything at once, summarise the oldest chunk and keep recent turns verbatim. The window becomes: system prompt, a running summary, then the last N turns in full.
┌─────┬────────────────┬───────────────────────────┐
│ sys │ summary 1–30 │ t31 t32 t33 t34 t35 t36 │
└─────┴────────────────┴───────────────────────────┘
lossy, compact verbatim, last N
▲ │
└──────────┘
next: t31–t32 fold into the summary
The model always has exact recent context, and only old material goes through the lossy step. The trade-off is more frequent summarisation calls, and the boundary between "summary" and "verbatim" still moves, which still invalidates part of the cache.
Use it for: agents that run for hours with a steady stream of work.
5. Rule-based compaction
Compact with deterministic rules instead of a model call:
- Collapse repeated reads of the same file into the latest one.
- Drop edits that were later reverted, and errors that were later fixed.
- Clear tool output older than N turns that has already been acted on.
- Keep every user message, every stated constraint, and the most recent turns untouched.
before after
══ sys + cached prefix ══ ══ sys + cached prefix ══
u1 task + constraints u1 task + constraints
read a.ts ░░░
read a.ts ◄ same file read a.ts
edit b.ts ◄ reverted ░░░
TypeError ◄ fixed ░░░
u9 recent turn u9 recent turn
no model call · prefix untouched · cache stays warm
No model call means no added latency, no added cost, and no surprises: you can log exactly what was removed. And because rules can be designed to only touch content after a stable point, you can keep the cached prefix intact while still freeing space.
The limit is that rules only remove what you can recognise. They will not condense a long design discussion into its conclusion.
Use it for: the default first pass. Reach for summarisation only when rules are not enough.
6. Offloading to memory
Do not keep everything in context: write it somewhere the agent can read back.
- A plan or todo file that the agent updates as it goes.
- Notes on decisions and constraints, re-read after compaction.
- Large outputs saved to disk, with only a path and a short summary in context.
context window disk
┌──────────────────────┐ ┌───────────────────┐
│ sys: "plan lives in │ write │ PLAN.md │
│ PLAN.md" │ ────► │ NOTES.md │
│ recent turns │ ◄──── │ build.log (2 MB) │
└──────────────────────┘ read └───────────────────┘
This turns compaction from "what do we forget" into "what do we keep close at hand". The cost is that the agent has to know to look, so the system prompt has to tell it what lives where.
Use it for: multi-hour tasks, and anything with constraints that must survive every compaction.
7. Sub-agents
The best compaction is context that never enters the window. Hand a self-contained task, like "find every caller of this function" or "work out why this test fails", to a sub-agent with its own fresh context, and get back only the answer.
main agent sub-agent, fresh context
┌──────────────────────┐ task ┌──────────────────────┐
│ goal, plan, recent │ ─────► │ grep, read, read, │
│ turns │ │ grep, read … │
│ │ │ 60K tokens of noise │
│ + answer, 300 tokens │ ◄───── │ │
└──────────────────────┘ answer └──────────────────────┘
The main agent stays focused on the task while the noisy exploration happens elsewhere. The cost is coordination: the sub-agent knows only what you tell it, and you only see its summary.
Use it for: search-heavy and exploratory work.
Putting it together
No single strategy is enough. A layered setup that works well for coding agents:
- Trim at write time. Tool output enters context already lean.
- Rule-based compaction first. Deterministic, free, cache-friendly.
- Offload what must survive. Goals, constraints and plans live in files the agent re-reads.
- Delegate exploration to sub-agents.
- Summarise last, with a structured prompt, only when the rest is not enough.
Whatever you build, always preserve the system prompt, the user's original request, every constraint they stated, and the most recent few turns. Those are the things an agent cannot recover by re-reading a file.
Measuring it
Compaction is easy to ship and hard to verify. Things worth tracking:
- Tokens per task and cache hit rate, before and after.
- Task success after compaction on a fixed set of long tasks.
- Constraint recall: state a rule early ("never touch the migrations folder"), compact, and check whether the agent still follows it.
Wrapping up
Context is the agent's working memory, and compaction is how it manages that memory. Start with the cheap, predictable strategies, protect the prompt cache, keep what the user told you, and treat summarisation as the last tool you reach for, not the first.