Context Compaction Techniques for Coding Agents
Long-running coding agents routinely generate tens or hundreds of thousands of tokens of history: file reads, tool outputs, error logs, failed approaches, and intermediate decisions. At some point the context window fills, quality collapses, and the agent begins re-exploring solved problems, forgetting file paths, or contradicting earlier choices. The difference between a reliable multi-hour session and an expensive failure is rarely the underlying model. It is how the system manages context.
add pagination to /users
Done.
the tests fail
Fixed the off-by-one.
it's slow now
Added an index.
revert the index
Reverted.
why is it slow again?
Let me read the files.
- instruction files
- conversation
- reasoning
- error logs
- tool results
Context management, increasingly called context engineering, is the practice of deciding what enters the model's working memory, what is summarized or deleted, what is written outside the window for later retrieval, and what is isolated into separate agent sessions.
This article examines the problem, the strategies currently in use, their measurable effects on agent output, and the practical patterns that produce better results.
What context actually is
In a coding agent the context window contains far more than the latest user message. Typical contents include:
- System prompt and always-loaded instruction files (
AGENTS.md,CLAUDE.md, rules files) - Conversation history and prior reasoning traces
- Tool definitions and the full results of tool calls (file contents, search hits, test logs, diffs)
- Retrieved code snippets or repository maps
- Runtime feedback from builds, tests, or the environment
The window is a finite attention budget, not unlimited storage. Models degrade well before the advertised limit, and information in the middle of a long context is especially poorly recalled. Every low-signal token dilutes the high-signal ones.
Why context management determines agent quality
add auth route
Added.
add the tests
Done, 12 pass.
handle expiry
Done.
use zod here
npm install zod
- rule
- tool output
- drift
Coding tasks are long-horizon by nature. A non-trivial feature or bug fix can require dozens of tool calls, multiple failed hypotheses, and careful tracking of which files have been modified. Unmanaged history produces several failure modes:
- Context rot: accumulated noise causes the model to lose track of the original goal or earlier decisions.
- Re-exploration loops: critical details such as exact error messages, file paths and prior decisions are lost, so the agent re-reads the same files or re-tries the same approaches.
- Architectural drift: style rules, naming conventions, or design decisions established early in the session are forgotten.
- Cost and latency explosion: every subsequent turn pays for the full history.
Factory's evaluation of real production sessions (debugging, code review, feature implementation) spanning more than 36,000 messages showed that the quality of compression directly affects whether an agent can continue productively.1 The optimization target is tokens per task, not tokens per request.
Core strategies
Most effective techniques fall into four complementary levers.
Curate: what enters the window
The cheapest improvement is never loading irrelevant material in the first place.
- Keep instruction files short and high-signal. Long
AGENTS.mdorCLAUDE.mdfiles that are injected on every turn dilute attention. - Prefer just-in-time retrieval over bulk loading. Tools such as semantic search that return only relevant snippets, instead of entire files, dramatically reduce waste.
- Use progressive disclosure (Skills): load detailed domain instructions only when the current sub-task requires them.
- Maintain a condensed repository map, an Aider-style structural overview of classes, functions and relationships, rather than the full codebase.
Prevention is more powerful than later cleanup. Approaches that combine targeted search with compact diffs can extend the useful life of a context window by 3-4x before any compaction is required.
Distill: shrinking what is already there
When history still grows, systems apply one of several compression families.
Summarization (rewriting)
An LLM produces a condensed narrative of prior turns. Factory's structured, iteratively updated summaries, with anchored sections for intent, file modifications, decisions and next steps, retained more useful information than either OpenAI's high-ratio opaque compression or Anthropic's full-regeneration approach.1 On probe questions testing factual recall, artifact tracking and continuity, the structured method scored highest overall.
Verbatim, deletion-based compaction
Instead of rewriting, low-signal lines are simply removed. Morph's Compact, and the faster FlashCompact variant, operates at 33,000 tokens per second, achieves 50-70% reduction, and guarantees that every surviving line is byte-for-byte identical to the original.2 This preserves exact file paths, error messages and code fragments, the details that paraphrasing frequently loses. Because no new text is generated, hallucination risk from the compression step itself is zero.
Self-summarization as a trained skill
Cursor trains its Composer model with compaction-in-the-loop.3 The model learns to produce its own concise summaries when a token threshold is reached; those summaries become part of the training trajectory and are rewarded or penalized according to downstream task success. The resulting self-summaries are shorter, roughly 1,000 tokens against more than 5,000 for a prompted baseline, and reduce compaction error by approximately 50%.
Multi-layer pipelines
Claude Code employs a practical three-tier system: a cheap micro-compaction that runs on every turn to trim tool-result bloat, a session-memory reconstruction that rebuilds state from disk without an extra model call, and a full legacy summarization only when necessary.4 A preserved tail of recent messages is re-linked after the summary so the active working set remains intact.
Observation masking and adaptive rules
Older tool outputs can be replaced by placeholders while the tool-call skeleton is retained.5 Self-evolving systems such as TACO discover and reuse compression rules from the agent's own trajectories, filtering low-value terminal observations while protecting task-critical signals.
Proactive folding
Research systems (AgentFold, Context-Folding) treat context as a dynamic workspace.6 The agent can branch into a sub-trajectory for a subtask and later fold it, collapsing intermediate steps into a concise outcome summary. This can keep the active context an order of magnitude smaller than a pure ReAct baseline while matching or exceeding performance on long-horizon benchmarks.
Externalize: keeping state outside the window
Information that must survive across turns or sessions is written to durable artifacts:
STATE.mdorMEMORY.mdfiles that record objective, constraints, decisions and current status- Plan files and progress ledgers
- Disk-backed session memory that can be re-hydrated without replaying the entire transcript
The agent, or the harness, can later re-inject only the relevant slice. This is the coding-agent analogue of human note-taking.
Delegate: fresh windows for subtasks
Sub-agents receive a clean context containing only the information needed for their narrow responsibility. The parent retains only the final result. This prevents exploratory noise or large search results from permanently contaminating the main thread. Phase separation, research to plan to implement to review, in separate sessions achieves a similar isolation.
Effects on agent output
Good context management produces measurable improvements:
- Higher accuracy on factual probes: file paths, error messages, prior decisions.
- Better continuity: the agent can state what should happen next without re-deriving the entire history.
- Reduced re-exploration, and therefore lower total tokens per completed task.
- Longer coherent horizons: sessions that previously collapsed after 20-30 turns remain productive far longer.
- Lower cost and latency, because each subsequent call carries less baggage.
Poor management produces the opposite. Paraphrased summaries that lose critical details force the agent to re-fetch information, lengthening trajectories; JetBrains observed 13-15% longer runs under pure summarization. Opaque high-ratio compression can be even more damaging, because the lost information is no longer inspectable. Overly aggressive always-loaded instruction files dilute the very constraints they were meant to enforce.
Artifact tracking, meaning which files have been read or modified, remains a weak point across current methods and often requires dedicated indexing beyond pure summarization or deletion.
Practical recommendations
- Treat the context window as a scarce attention budget. Aim to keep utilization in a healthy range; many practitioners target 40-60% rather than waiting for the hard limit.
- Invest in prevention: targeted retrieval and compact edits reduce the frequency of compaction events.
- Prefer structured or verbatim techniques over opaque rewriting when exact details matter.
- Externalize durable state early and often. Do not rely solely on the conversation history.
- Use sub-agents or fresh sessions for distinct phases or exploratory work.
- Make compaction decisions at clean task boundaries when possible, rather than at arbitrary token thresholds.
- Evaluate compression by functional probes, meaning whether the agent can continue correctly, rather than by compression ratio alone.
Emerging directions
Research is moving from reactive cleanup toward proactive, agent-controlled management. Models are being trained to decide when and how to fold or compress their own history. Self-evolving rule sets adapt compression to the specific workflow. Specialized fast compaction models make it practical to run deletion-based cleanup inline before every LLM call. Knowledge-graph and code-intelligence layers promise richer external memory that can be queried precisely instead of being stuffed into the prompt.
The central insight remains simple: for coding agents, context is not a passive log. It is an actively governed workspace. The systems that treat it that way produce more coherent, cheaper and more reliable results over the long horizons that real software engineering demands.
References
- 1.Factory: Evaluating compression
- 2.Morph: Context compaction
- 3.Cursor: Self-summarization
- 4.X: Claude Code's three-tier compaction (@himanshustwts)
- 5.arXiv: A Self-Evolving Framework for Efficient Terminal Agents via Observational Context Compression
- 6.arXiv: AgentFold: Long-Horizon Web Agents with Proactive Context Management