Context Engineering for Long-Running LLM Agents
A practitioner's guide to deciding what tokens enter the LLM's context window — grounded in production systems at Anthropic, OpenAI, Cursor, Cognition (Devin), and Manus.
What This Book Is
Context engineering is the discipline of deciding what tokens enter the LLM's context window at each step, in what structure, from which sources — to maximize outcome probability while respecting the finite attention budget.
This book covers only context engineering. It does not cover:
- Prompt engineering (how to phrase a single instruction)
- Harness engineering (sandboxes, permissions, tool execution, UI rendering)
- Agent orchestration plumbing (IPC, VM management, team protocols)
It covers what lives in the context window, how it gets there, how it's structured, how it shrinks when the window fills, and how it survives across context boundaries — the full lifecycle of context in a long-running agent.
How It's Organized
The book follows the lifecycle of context in an agent: from deciding what enters the window, through arranging and compressing it, to externalizing and preserving it across sessions.
Part I — Foundations defines context engineering, explains the attention budget as a resource to spend (not a container to fill), and dissects the anatomy of a real context window.
Part II — Selection covers what belongs in the window: static context (system prompts, project memory files), tool definitions (the hidden token tax and four production approaches to reduce it), and retrieval (pulling external knowledge in just in time).
Part III — Structure covers how to arrange context for two different goals: cache hit rate (stable prefix first, dynamic last — Manus's three rules) and attention (primacy, recency, and the todo.md recitation technique).
Part IV — Compression covers what to do when the window fills: clearing (surgical removal via clear_tool_uses, MicroCompact's two paths) and compaction (Claude Code's four-tier system, OpenAI's standalone endpoint, the 9-section summary format, post-compaction reconstruction).
Part V — Externalization covers context that lives outside the window: the file system as extended context (Manus's restorable compression, Claude Code's memory layers, Anthropic's memory tool) and cross-session memory (Devin's Knowledge + Playbooks, LangGraph's checkpointer-vs-store pattern, the Brain-Made-of-Markdown architecture).
Part VI — Isolation covers sub-agents through the context-engineering lens only: fresh vs. forked windows, return format design, the three-layer hierarchy for multi-agent coding.
Part VII — Practice covers measurement and iteration: the metrics that matter, diagnosing context problems, ranked production improvements, and the empirical loop that drives context engineering forward.
Who This Is For
Engineers designing agents that run for hours or days. Teams building coding agents, research agents, customer-support agents, or any system where the agent must maintain coherence across many inference calls.
Everything in this book is grounded in how real production systems actually work. No theoretical frameworks, no academic benchmarks — source code, engineering blogs, and production bug reports.
Reading Paths
- "I'm new to context engineering" → read cover to cover. Parts I–II give the mental model; Parts III–VII teach the techniques.
- "I'm hitting context limits in production" → start at Chapter 2 (diagnose the failure mode), then Chapter 9 or Chapter 10 as appropriate.
- "My agent forgets between sessions" → Chapter 11 and Chapter 12.
- "I want to reduce costs" → Chapter 7 (KV-cache optimization has the highest ROI in production) and Chapter 5 (tool token tax).
- "I'm building a multi-agent system" → Chapter 13 covers sub-agents as a context-compression technique.
- "How do I know if any of this is working?" → Chapter 14.
Primary Sources
This book is grounded in industrial implementation, not academic research:
- Anthropic Engineering: Effective Context Engineering for AI Agents, Harness Design for Long-Running Apps, Context Editing and Memory Tool
- OpenAI: Unrolling the Codex Agent Loop, Harness Engineering
- Manus: Context Engineering for AI Agents: Lessons from Building Manus
- Cursor: Dynamic Context Discovery, Securely Indexing Large Codebases
- Cognition: Rebuilding Devin for Claude Sonnet 4.5, How Cognition Uses Devin to Build Devin
- Claude Code v2.1.88 source leak (512K lines TypeScript, reverse-engineered analyses of
compact.ts,autoCompact.ts,microCompact.ts,QueryEngine.ts) - OpenAI Codex Rust source (
codex-rs/core/src/compact.rs) - Anthropic SDK source and official API documentation
By Atum — Source: github.com/A7um/ContextManagementBook
Chapter 1: What Context Engineering Is
"Context engineering is the art and science of filling the context window with just the right information for the next step." — Andrej Karpathy, June 2025
"I really like the term 'context engineering' over prompt engineering. It describes the core skill better: the art of providing all the context for the task to be plausibly solvable by the LLM." — Tobi Lütke, CEO of Shopify, June 2025
1.1 A Definition That Practitioners Converge On
In the summer of 2025, a small group of practitioners — Karpathy, Lütke, the Manus team, the Anthropic Applied AI team — independently arrived at the same vocabulary. The thing they were doing all day was not "writing prompts." It was not "fine-tuning models." It was deciding, for each LLM call, what information should be present in the context window and what should be left out.
They called this context engineering, and the definition that has stuck across blog posts, internal docs, and post-mortems is the one Anthropic published in September 2025:
Context engineering is the discipline of deciding what tokens enter the LLM's context window at each step, in what structure, from which sources — to maximize outcome probability while respecting the finite attention budget.
Every word in that sentence does work.
"Tokens" — not "instructions," not "messages," not "documents." The unit that matters is the token, because the model has a fixed number of them and every additional token has a cost in attention, latency, and price.
"Enter the LLM's context window" — context engineering is concerned with what the model sees, not with how it computes. It is upstream of the model.
"At each step" — agents make many LLM calls. The context for turn 47 is not the context for turn 1. Decisions are made continuously, not once.
"In what structure" — order matters. Section headers matter. The choice between dumping a 50K file into a user message or summarizing it and pointing at a path matters.
"From which sources" — the system prompt, project memory files, retrieval indexes, tool outputs, scratchpads, sub-agent summaries. Each is a faucet that can be turned on or off.
"Maximize outcome probability" — context engineering is empirical. The right context is the one that makes the model more likely to do the right thing. There is no Platonic "correct" context.
"Respecting the finite attention budget" — the window has a hard ceiling, and even before that ceiling, model performance degrades as the window fills. The budget is real.
This book is about that discipline. Not how to ask a model a single good question. Not how to wire up a sandbox or a permission system. The middle layer: what goes in the window, what comes out, what gets compressed, what gets retrieved, what gets thrown away.
1.2 The Three Disciplines, Nested
A useful mental model has emerged for separating the things people lump together as "AI engineering." Three concentric disciplines, each strictly contained in the next:
┌──────────────────────────────────────────────────────────────────┐
│ HARNESS ENGINEERING │
│ (the runtime: sandbox, tools, hooks, IPC, permissions, UI) │
│ │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ CONTEXT ENGINEERING │ │
│ │ (what tokens enter the window across all calls) │ │
│ │ │ │
│ │ ┌──────────────────────────────────────────────────────┐ │ │
│ │ │ PROMPT ENGINEERING │ │ │
│ │ │ (how a single instruction is phrased) │ │ │
│ │ └──────────────────────────────────────────────────────┘ │ │
│ │ │ │
│ └────────────────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────┘
Each layer has a different surface area, a different unit of work, and different failure modes.
Prompt engineering is the inner ring. Its unit of work is a single instruction. Its surface area is wording: which verbs to use, whether to give the model a persona, whether to ask it to think step by step, whether to show one example or three. Prompt engineering treats the model as an opaque function that converts a text input into a text output, and asks: how do I phrase the input to get the output I want?
A prompt engineer cares whether "Summarize this document" or "Write a one-paragraph summary of the key decisions in this document" produces better summaries. That is a real question, and the answer matters. But the unit is one call.
Context engineering is the middle ring. Its unit of work is everything the model sees across an entire interaction — often hundreds of LLM calls in a long-running agent session. Its surface area is the composition of the input: not "how do I phrase this instruction" but "given that I have a 200K-token budget, a system prompt I wrote six months ago, a conversation that has run for three hours, twenty tools registered, six files the agent has read, and a user task that just arrived, what subset and arrangement of all this material should I send to the model right now?"
Context engineering subsumes prompt engineering — every LLM call still contains prompts that someone wrote — but most of its work is not about wording. It is about selection, compression, and structure. A perfect prompt embedded in a polluted context will fail. A mediocre prompt embedded in a clean, well-structured context will succeed.
Harness engineering is the outer ring. OpenAI named the discipline in their February 2026 Harness Engineering post, and Anthropic followed with their Harness Design for Long-Running Application Development guide. The harness is the runtime: the agent loop that orchestrates inference calls and tool execution, the sandbox the tools run inside, the permission system that decides whether a destructive command needs confirmation, the hooks that fire on session start, the UI that streams tokens to a user, the IPC channel between the CLI and the app server, the YOLO classifiers that decide which commands are safe to auto-approve, the feature flags, the telemetry. Harness engineering subsumes context engineering — every harness must decide what goes in the window — but most of its work is not about the window. It is about the system around the window.
The boundaries are sharp, and this book is about the middle ring only. We will not cover sandboxing, permission models, IPC protocols, or VM lifecycle management. Tool definitions affect context (the model sees them) and are in scope. Tool execution (how a bash call is actually run, how stdout is captured, how a network call is sandboxed) is harness engineering and is out of scope. We will not cover safety classifiers or command validators. We will not cover multi-agent orchestration plumbing, except where the summary a sub-agent returns to a parent is a context-engineering decision.
A useful test: if changing your decision changes which tokens the model sees, it is context engineering. If it changes how those tokens are produced or what happens after the model emits its output, it is harness engineering.
flowchart TB
subgraph H["Harness Engineering"]
direction TB
subgraph C["Context Engineering"]
direction TB
subgraph P["Prompt Engineering"]
p1["How do I phrase<br/>this instruction?"]
end
c1["What tokens enter<br/>the context window?"]
end
h1["How does the runtime<br/>execute tools & maintain state?"]
end
style H fill:#fef3c7,stroke:#ca8a04
style C fill:#dbeafe,stroke:#2563eb
style P fill:#dcfce7,stroke:#16a34a
The three disciplines as nested concerns. This book covers only the middle layer.
1.3 Why the Middle Layer Is the Hard Problem
You can build a working chatbot without thinking about context engineering. The conversation is short, the tool calls are few, the window is never close to full. Single-turn or low-turn applications can be served well by careful prompt engineering and a decent base model.
The problem becomes hard the moment an agent runs long enough to fill its window. And modern agents do — routinely, deliberately. OpenAI describes Codex sessions that "work on a single task for upwards of six hours." Devin sessions are measured in hours, not minutes. Claude Code coding sessions regularly hit auto-compaction multiple times in a single task. Manus published a statistic from production that captures the regime: their agents process roughly 100 tokens of input for every token they generate. The economics and the engineering are dominated by what is in the window, not what comes out of the model.
Three structural facts about LLMs make context the binding constraint:
The model is stateless. Between two API calls there is no shared memory. Anything the model "knows" in turn 47 — a decision it made in turn 5, a file it read in turn 12, an error it encountered in turn 30 — must be re-presented in the prompt at turn 47. The model has no privileged access to its own history.
The window is finite. Even at a million tokens, the window has an end. And the cost of using it scales linearly with the number of tokens, both in dollars and in latency. Filling a million-token window for every turn of a 200-turn session is not just expensive; it is slow enough to be unusable.
Performance degrades within the window. This is the discovery that has reshaped the field. Models do not perform uniformly across their advertised context length. Anthropic measured a 15% SWE-bench drop when running Claude with the full 1M-token window compared to a managed-compaction setup that kept context focused at ~200K. Cognition coined "context anxiety" to describe Claude Sonnet 4.5's tendency to take shortcuts as its window filled — even when no specific cue suggested it should. OpenAI Codex issue #10346 documents the same phenomenon under a different name: long threads with multiple compactions cause the model to "be less accurate." More room in the window does not, by itself, give you more usable model.
These three facts together mean that the question "what should be in the context right now?" has to be answered hundreds of times per agent session, and getting it wrong has compounding consequences. Wrong choices in turn 5 produce a polluted context that biases turn 6, which produces an even more polluted context for turn 7, and by turn 50 the agent has lost the plot and is "running but not making progress." This is the failure mode every team that ships a long-running agent eventually has to fix, and the fix is always the same shape: better context engineering.
1.4 The Activities of Context Engineering
Strip the discipline down to its operational verbs and a small set of activities emerges. Every production agent does some version of all of these; mature systems do them well and explicitly.
Selection — what belongs in the window? Of all the information that could be relevant to the next LLM call (the entire codebase, every previous turn, every tool's full schema, every file the agent has read), what subset will actually be sent? Cursor's dynamic context discovery work is essentially the systematic study of selection: their A/B testing showed a 46.9% token reduction with no quality loss when they shifted from loading-everything to load-on-demand.
Structure — how is the selected content arranged? The system prompt comes first because the model attends to it heavily and because anything before the first changing token can be cached. Tool definitions follow. Conversation history comes after that. The current task is at the end where recency attention is highest. Within each section, headers, separators, and ordering all matter. Anthropic's writing on effective context engineering explicitly calls out structure as a first-class concern, not an afterthought.
Compression — what to shrink? An eight-thousand-token grep result can usually be replaced by a hundred-token summary plus a path on disk. A fifty-turn conversation can be condensed into a five-paragraph state-of-the-task description. The tool that produced the original output is still available; the agent can re-run it if the summary turns out to be insufficient.
Externalization — what to store outside the window? Files on disk, vector indexes, scratchpad notes, structured memory stores. Manus calls the file system "the ultimate context" — a place to put information that the agent might need later but doesn't need now. Externalization is what makes long-running agents possible at all; without it, the window would have to grow without limit.
Retrieval — what to bring back in? The mirror of externalization. When the agent needs information it previously saved (or never saw — code that lives in the repo, documentation that lives in a wiki), some mechanism brings it back into the window. This can be agentic (the model emits a tool call to read a file or run a search), it can be automatic (a sub-agent injects the contents of CLAUDE.md after every compaction), or it can be retrieval-augmented (a semantic index returns top-k chunks for a query).
Preservation — what must survive context boundaries? When the window is compacted or reset, some information must persist verbatim. The user's original task. Critical decisions. Open commitments. Claude Code's compaction explicitly preserves the most recent N turns in full, summarizes everything before, and re-injects project memory after the summary. The set of things that must survive is itself a context-engineering choice.
Measurement — is it working? Token utilization, cache hit rate, time-to-first-token, pass rates per task type. A context strategy that cannot be measured cannot be improved. Manus reports that KV-cache hit rate is the single most important metric for a production agent; teams that don't track it are flying blind.
These seven activities are not a sequence — they happen continuously and in parallel. They are also not independent: a decision to externalize a tool output (rather than keep it in conversation) makes future retrieval necessary; a choice of structure determines what can be cached; a measurement that hit rate has dropped triggers a re-examination of selection criteria.
flowchart LR
S[Selection] --> St[Structure]
St --> Cm[Compression]
Cm --> Ex[Externalization]
Ex --> R[Retrieval]
R --> S
Pr[Preservation] -.crosses.-> S
M[Measurement] -.observes.-> S
M -.observes.-> Cm
M -.observes.-> R
style M fill:#fee2e2
style Pr fill:#e0e7ff
The context engineering lifecycle. Selection, structure, compression, externalization, and retrieval form the main loop. Preservation spans sessions; measurement observes the whole system.
1.5 How the Rest of This Book Is Organized
The remaining chapters of Part I establish the constraints the agent operates under. Chapter 2 examines the attention budget — why a token in the window costs more than its share of memory — and what production teams have discovered about model behavior as that budget is consumed. Chapter 3 dissects an actual context window, with real allocations from real production systems, and provides a concrete budget framework with reserve accounting.
Subsequent parts work through the activities listed above. Compaction, microcompaction, and the various flavors of context editing — the compression and preservation mechanisms. Knowledge bases, file-system memory, and dynamic retrieval — the externalization and retrieval mechanisms. Multi-agent context isolation — the selection problem applied across agents. Caching — the structure decisions that make stable prefixes valuable. Production case studies — how Codex, Claude Code, Cursor, Devin, and Manus actually compose all of these into shipping systems.
A note on what is not here: there is no chapter on prompt phrasing, no chapter on sandbox design, no chapter on team protocols for multi-agent orchestration. Those are real topics with real engineering, but they belong to the inner and outer rings. Keeping the focus on the middle ring — what tokens enter the window, in what structure, from which sources — is what makes the discipline of context engineering legible as its own thing.
1.6 The One-Line Summary
If you read no further than this paragraph, the entire discipline collapses to a sentence Anthropic uses in their effective-context-engineering guide:
Context engineering is the practice of finding the smallest possible set of high-signal tokens that maximize the likelihood of the desired outcome.
Smallest, not largest. High-signal, not exhaustive. Maximize the likelihood, not guarantee it. That is the job.
The rest of this book is a long answer to the question of how, exactly, production teams have learned to do that job — and what the next agent you build can borrow from them.
Chapter 2: The Attention Budget
"Treat context as a precious, finite resource. We've found that even with longer context windows available, finding the smallest possible set of high-signal tokens consistently outperforms larger, less curated context." — Anthropic Engineering, Effective Context Engineering for AI Agents
"Context is a scarce resource. A giant instruction file crowds out the task, the code, and the relevant docs — so the model tends to ignore parts of it." — OpenAI, Harness Engineering
2.1 Context Rot Is a Production Phenomenon
For a long time the dominant story about context windows was the one the model providers told: longer is better. 8K tokens became 32K became 128K became 200K became 1M. Each jump was advertised as a strict upgrade. If 32K was good, 128K was better, and 1M was best.
Then teams started building agents that actually used those windows. And the story stopped matching the marketing.
The phenomenon now goes by various names — context rot, context anxiety, context degradation — but the substance is the same: as the context window fills up, model behavior gets worse, sometimes much worse, well before any hard limit is hit. This is not a finding from a research lab. It is a discovery that production teams keep making, independently, by shipping things and watching them break.
A short tour of the evidence the practitioners have published.
Cognition's "context anxiety." When the Devin team began deploying Claude Sonnet 4.5, they noticed something unusual. The model behaved differently late in long sessions than it did at the start. It would take shortcuts — leaving tasks incomplete, glossing over verification, rushing through work it had previously done carefully. The pattern was reproducible enough that the Cognition team named it: context anxiety. The model was, in a measurable behavioral sense, aware that it was running out of room and was modifying its actions in response.
The fix Cognition landed on is instructive precisely because it is counterintuitive. They enabled Claude's full 1M-token extended context window — not because the agent needed that much room, but because having headroom reduced the anxiety behavior. With slack in the budget, the model relaxed and worked methodically even when actual content was small. Context anxiety is a behavioral effect that no benchmark measures, but it dominates real-world quality.
Anthropic's 15% SWE-bench drop. Anthropic ran the inverse experiment. On SWE-bench, they compared Claude Opus running with the full 1M-token window against the same model running with managed compaction that kept the working context at roughly 200K tokens. The 1M configuration scored 15% lower. More room, worse results. The model did not benefit from the extra information; it suffered from it.
The crucial detail is that this was not a degradation of the model under stress; this was a degradation of the model when given more material to attend to. Anthropic's Effective Context Engineering post is unambiguous about the implication: "the smallest possible set of high-signal tokens" outperforms a larger, less curated set, and treating context as a "precious, finite resource" is the right mental stance even when the limit is technically very far away.
OpenAI Codex issue #10346. A bug report in the OpenAI Codex repo, filed by users running long sessions, captures the same phenomenon from a different angle. After the agent crossed multiple compaction cycles, "long threads and multiple compactions" caused the model to "be less accurate." Each compaction is lossy; multiple compactions stack their losses. The agent loses track of decisions it made earlier in the conversation, contradicts itself, or re-does work it already completed. OpenAI's harness now surfaces this directly to users as a warning when compaction is triggered.
Manus's 100:1 ratio. From Yichao Ji's Context Engineering for AI Agents: Lessons from Building Manus: the production agent processes, on average, 100 tokens of input for every token of output it generates. This is not because Manus is unusually verbose with input; it is because that is what an agentic workload looks like. Tools return file contents, logs, search results, web pages — material that must be in the window for the model to reason about it, but that the model itself did not produce. When the input-to-output ratio is 100:1, every wasted token in the window is paid for a hundred times over, in dollars and in attention.
Together, these reports establish context rot as a production fact. The window is not a neutral container. Filling it has consequences.
2.2 Lost in the Middle, Briefly
There is one more piece of background that practitioners need to know about, even though it has been studied to death and we will not dwell on it: models attend non-uniformly across their context.
Empirically, attention is highest at the very beginning of the context (where the system prompt sits) and at the very end (where the most recent user message and tool results sit). The middle — wherever the bulk of the conversation history accumulates — gets less attention. This is the "lost in the middle" effect.
xychart-beta
title "Attention recall across context position (U-shape)"
x-axis "Position in context" ["Start", "25%", "50%", "75%", "End"]
y-axis "Recall accuracy %" 40 --> 100
line [95, 72, 58, 74, 92]
Recall follows a U-shape. Information at the beginning and end gets more attention than the middle — a production constant practitioners plan around.
For the practitioner, three implications matter:
- Critical instructions belong at the beginning (system prompt) and, for very long sessions, are worth re-injecting near the end as periodic reminders. Claude Code does both.
- The freshest tool outputs and the user's current message belong at the end, where recency attention is highest. This happens naturally if the conversation is in chronological order.
- Compaction does double duty: it shrinks the middle (which improves token utilization) and it moves important historical information out of the low-attention zone into the high-attention end (where the compaction summary itself sits, just before recent turns).
That is everything most practitioners need to know about lost-in-the-middle. The deeper academic story is well covered elsewhere; what matters for context engineering is the structural decisions that follow from it.
2.3 The Attention Budget Framing
The most useful frame Anthropic introduced in their Effective Context Engineering writing is treating context as a budget rather than a container.
A container has one parameter: capacity. Either something fits or it doesn't. The mental model that goes with "context as container" is "fill it as full as you can without overflowing." If you have 200K tokens of room and you can find 199K tokens of plausibly relevant material, you put it all in.
A budget has two parameters: capacity and cost per unit. Every token competes with every other token for the model's attention. Adding a token is not free even when there is plenty of room — it costs latency, it costs dollars, and it dilutes the attention paid to every other token already in the window. The mental model that goes with "context as budget" is "what is the smallest set of tokens that has the highest probability of producing the right outcome?" If you can find 30K tokens of high-signal material, you do not pad it out to 199K just because there is room.
This is not a metaphor. The economics are real:
- Every token in the window is processed during prefill, which is compute-bound and proportional to input length. A 100K-token prefill takes around 11.5 seconds. A 200K prefill is roughly twice that.
- Every token in the window contributes to KV-cache memory pressure on the GPU, which directly shapes batching, throughput, and per-call cost.
- Every token in the window competes for attention with every other token. The model has a fixed attention budget per layer; spreading it thin across more material reduces the weight any individual piece can receive.
The production discipline is a re-orientation: the question stops being "what could I include?" and becomes "what is the minimum set of high-signal tokens I need?" Manus's published rules of thumb, OpenAI's guidance to keep AGENTS.md to roughly 100 lines, Anthropic's "smallest possible set" formulation — they are all expressions of the same shift.
2.4 The Three Failure Modes
Watching production agents misbehave, three distinct failure modes recur. They have different root causes and different fixes, and being able to distinguish them is most of the diagnostic skill.
flowchart TD
A[Long session] --> B[History grows]
B --> C1[Token budget pressure]
B --> C2[Attention dilution]
B --> C3[Context pollution]
C1 --> D1["Hits window limit<br/>or triggers compaction"]
C2 --> D2["Stale content competes<br/>with current task"]
C3 --> D3["Subtask A's residue<br/>interferes with subtask B"]
D1 --> E[Quality / cost degrades]
D2 --> E
D3 --> E
style C1 fill:#fecaca
style C2 fill:#fed7aa
style C3 fill:#fde68a
Three compounding failure modes. All trace back to the same root — unbounded context growth — but each needs a different remedy.
Failure mode 1: Token budget pressure
The simplest and most visible. The conversation has grown large enough that there is no longer room for the next tool result, or for the model's response, or for the next user message. The harness must compact, evict, or block.
Symptoms: API errors about exceeding context length; truncated responses that cut off mid-tool-call; the agent harness firing emergency compaction or refusing to continue.
Production thresholds where this becomes acute:
- Claude Code triggers auto-compaction at roughly 92.8% of the effective window (effective = total minus output reserve), with hard-stop measures around 98.3%.
- OpenAI Codex defaults compaction trigger to the configured threshold (typically ~73.5% of the nominal window, leaving substantial reserve for compaction itself to run).
- Manus and Devin both run with custom thresholds tuned per workload.
Token budget pressure is the failure mode that everyone notices first because it produces visible errors. It is also the one with the most mechanical fixes (compaction, eviction, file-system offload).
Failure mode 2: Attention dilution
The conversation is technically below the limit, but the model's attention is spread across so much material that it cannot focus on what matters now. The system prompt is fine, the recent turns are fine, but in between are forty thousand tokens of tool outputs from earlier subtasks that the agent is no longer working on.
Symptoms: the model loses the thread; it answers slowly or shallowly; it misses obvious cues in the most recent turn because it is allocating attention to old content; tool selection accuracy drops because there are too many similar definitions competing.
Attention dilution is the failure mode behind Anthropic's 15% SWE-bench drop with the full window — the model wasn't out of room, it was out of focus.
The fix for attention dilution is rarely "more compaction" in the gross sense. It is targeted compaction or eviction of the specific dilutive content: stale tool outputs (Claude Code's microcompaction targets exactly this), no-longer-relevant tool definitions (Anthropic's deferred-loading mechanism, Cursor's tools-as-files pattern), expired thinking blocks (Claude's clear_thinking context editing tool).
Failure mode 3: Context pollution
The model is reasoning about task B but its context still contains material from task A. Output from a subtask the agent abandoned still looks authoritative. A failed approach the agent moved on from is still being treated as "what we tried." A summary from a sub-agent contradicts the main agent's current state.
Symptoms: the agent applies the wrong file's conventions to the right file; it cites errors that were already resolved; it follows up on plans the user redirected away from; it treats a sub-agent's intermediate finding as a final result.
Context pollution is the most insidious failure mode because the agent does not know it is polluted. Token utilization may be moderate, attention is not obviously diluted, and from inside the model's perspective everything in the window looks like real history. The fix is structural: clean separation between subtasks (sub-agent isolation, context resets between phases), explicit markers when context shifts ("the previous approach is abandoned, ignore it"), and aggressive eviction of content that is no longer accurate.
These three failure modes correspond to three different kinds of context-engineering work: budget management (against pressure), curation (against dilution), and isolation (against pollution). A production agent has to do all three.
2.5 The 60-70% Rule
The teams that have built and shipped long-running agents converge on the same operational guideline: do not wait for the window to be full to start managing it. Begin proactive management at 60-70% utilization.
The reason is not safety margin in the conventional sense — there is plenty of room left at 70%. The reason is that all three failure modes get worse non-linearly as the window fills. By the time you are reactively responding to budget pressure at 95%, the model has already been operating in attention-diluted territory for a long time, and you may already have pollution from earlier turns that you can no longer cleanly separate.
The actual thresholds in shipped systems:
| System | Begin management | Force action | Hard stop |
|---|---|---|---|
| Claude Code | ~81.7% of effective window | ~92.8% of effective window | ~98.3% |
| OpenAI Codex | ~73.5% (default) | At threshold | N/A (compacts) |
| Manus | Custom per-task | ~70% (observation masking) | Model fallback |
| Relevance AI | 30% (observation phase) | 60% (reflection phase) | Larger model fallback |
Claude Code's numbers look high because they are measured against the effective window — the nominal window minus the reserved output budget. Translated back to a percentage of the nominal 200K, the trigger sits around 73.5%, right in the 60-70% zone everyone else lands in too.
Translated into a recipe: instrument utilization, set a warning threshold around 70% where you start clearing or compressing peripheral content (old tool outputs, deferred tools), and a forced-action threshold around 85% where you trigger full compaction or context restructuring. The hard limit is not where the work is.
2.6 Why Bigger Windows Don't Solve It
A predictable objection: Gemini 2.5 Pro offers 1M tokens as standard, with 2M available; Claude Opus 4.6 has gone to 1M; surely the right answer is to use a bigger window and stop budgeting?
Three reasons this does not work, each grounded in production data already cited.
Degradation is proportional, not absolute. The 15% SWE-bench drop Anthropic measured was on the 1M-token model. Larger windows do not change the shape of the degradation curve; they shift the x-axis. A 1M-token model running at 80% utilization shows the same rough degradation pattern as a 200K-token model running at 80%. More room is more budget, not a license to stop budgeting.
Cost and latency scale linearly. Sending 800K tokens to the model when 80K would have done costs roughly 10x more dollars and 5-10x more time-to-first-token. For an agent that makes hundreds of LLM calls per task, this is the difference between a $2 task and a $20 task, and between a 30-second response and a 5-minute one. Cursor's A/B testing measured 46.9% token reduction with no quality loss when moving from static to dynamic context loading. Almost half the tokens being sent in the static configuration were useless — present in the window but contributing nothing — and removing them paid out as both faster and cheaper inference.
Context anxiety appears at any size. Cognition's discovery that Sonnet 4.5 takes shortcuts as the window fills is not a property of any particular window size. The model is responding to the fraction of the window in use, not the absolute count. Even on a 1M-token window, an agent that fills 800K of it will exhibit the behavioral degradation Cognition described.
There is a real benefit to larger windows: they raise the ceiling, which means agents that need a lot of working room can fit more under the hood. The Cognition team's choice to enable Claude's 1M extended window is exactly this — not as a license to fill the window, but as headroom that reduces anxiety even when actual usage stays modest. That is the right way to think about it. A bigger window is a bigger budget. It is not a reason to stop budgeting.
There is a quality/cost/latency triangle implicit in all of this. You can pick any two:
QUALITY
▲
│
│
LOW COST ─── LOW LATENCY
(you can have all three only if
you actively manage context)
Without context engineering, more context means higher quality up to a point, then declining quality, while cost and latency rise monotonically. With context engineering, the curve flattens — high quality at moderate cost and latency, sustained even on long-running agents.
2.7 What This Means for Your Agent's Budget
Three operational consequences for anyone building an agent today.
Start tight, expand only when measurement shows it helps. Resist the temptation to "just include everything that might be useful." Pick a small set of high-signal tokens. Run the agent. Measure outcomes. If a particular kind of task consistently fails because the agent did not have access to some specific information, then expand the context to include it — but expand surgically, not blanketly. Cursor's dynamic loading approach is the operational version of this principle: load what the agent has explicitly demonstrated it needs, not what you imagine it might need.
Reserve real headroom. Every production system reserves output budget — not just max_tokens for the response itself, but additional buffer for compaction, for thinking blocks, for unexpected tool outputs. Claude Code reserves roughly 33K tokens out of 200K (20K for output, 13K for the autocompact buffer, 3K manual buffer). That is 16.5% of the nominal window held back permanently. Without the reserve, the agent runs out of room mid-thought, tool calls truncate, and the failure modes from §2.4 land all at once.
Treat utilization as a leading metric. Do not wait for budget-pressure errors to surface in user reports. Track utilization continuously, as a percentage of effective window (not nominal). Set alerts at 70%, 85%, and 95%. Track cache hit rate alongside it (we will return to caching in a later chapter — for now, accept Manus's claim that it is the single most important production metric). Track time-to-first-token. The right size for your context budget is whatever combination of these numbers produces the best outcomes for your workload, and you can only find that empirically.
The chapter that follows takes the budget framing and makes it concrete: the actual structure of a context window, what each component costs in real production systems, and how to compose those components into a working budget. The discipline of context engineering, from this point on, is mostly applied resource management — and like any good resource management, it starts with knowing exactly where the resource is going.
Chapter 3: Anatomy of a Context Window
"Every Claude Code session has a single budget: the context window. Two hundred thousand tokens, give or take, that have to hold the system prompt, the tool definitions, the conversation history, the user's input, the model's output, and (if extended thinking is on) the chain of thought. There is exactly one pile, and everything gets withdrawn from it."
The previous chapter argued that context is a budget rather than a container. This chapter takes that framing and asks the obvious follow-up: where, exactly, is the budget being spent? Until you can break a real production context window down into named line items with measured token counts, every conversation about "managing context" stays abstract.
The answer turns out to have remarkable structure. Across Claude Code, OpenAI Codex, Cursor, Devin, and Manus, the categories of content that compete for the window are nearly identical, even when the specific values differ. And each category has its own control model, its own growth pattern, and its own typical compression strategy. Once you can see the four categories clearly, the rest of context engineering is mostly resource accounting against them.
3.1 A Real Token Breakdown
Here is an actual breakdown from a Claude Code session at approximately turn 40, derived from inspecting the Messages API request payload (the values come from the leaked Claude Code v2.1.88 source analysis and are typical, not pathological):
pie showData
title "Claude Code 200K session breakdown"
"Conversation history" : 80000
"Tool outputs" : 50000
"Headroom / reserve" : 35000
"Tool definitions" : 25000
"Model output (turn)" : 5000
"System prompt" : 3000
"CLAUDE.md" : 2000
A real 200K context window fills with conversation history and tool outputs first. Static content (prompt, tools, CLAUDE.md) is a minority.
┌─────────────────────────────────────────────────────────────────┐
│ 200,000 TOKEN CONTEXT WINDOW │
│ │
│ ┌────────┐ System Prompt ~3,000 tokens (1.5%) │
│ ├────────┤ │
│ │░ │ CLAUDE.md (project memory) ~2,000 tokens (1.0%) │
│ ├────────┤ │
│ │██████ │ Tool Definitions ~25,000 tokens (12.5%) │
│ │██████ │ (built-in + MCP servers) │
│ ├────────┤ │
│ │ │ │
│ │██████████████ Conversation History ~80,000 tokens (40.0%) │
│ │██████████████ (user + assistant turns) │
│ │██████████████ │
│ ├────────┤ │
│ │██████████ Tool Outputs ~50,000 tokens (25.0%) │
│ │██████████ (file reads, grep, bash, web) │
│ ├────────┤ │
│ │░ │ Model Output (this turn) ~5,000 tokens (2.5%) │
│ ├────────┤ │
│ │ │ │
│ │ │ Headroom / Output Reserve ~35,000 tokens (17.5%) │
│ │ │ │
│ └────────┘ │
└─────────────────────────────────────────────────────────────────┘
The breakdown is striking in two ways.
First, the "interesting" parts of the prompt — the carefully-engineered system prompt, the CLAUDE.md the team curated to capture project conventions — together consume less than 3% of the window. The bulk is conversation history (40%), tool outputs (25%), and tool definitions (12.5%). These three together account for nearly 80% of the spend.
Second, 17.5% of the window is deliberately empty. The headroom is not free space waiting to be used; it is reserved capacity that the harness will not let conversation grow into. Without that reserve, the model would have nowhere to put a long response or a complex tool call. We will return to the math on this in §3.5; for now, note that nearly a fifth of the nominal window is structurally unavailable for input.
3.2 The Four Categories of Context
The seven specific line items in the breakdown above — system prompt, CLAUDE.md, tool definitions, conversation history, tool outputs, current model output, headroom — collapse into four categories with genuinely different properties. Treating them as the same kind of thing is the most common mistake in early context engineering.
quadrantChart
title Four categories of context
x-axis Low compressibility --> High compressibility
y-axis Engineer-controlled --> Emergent
quadrant-1 Compressible & emergent
quadrant-2 Resistant & emergent
quadrant-3 Resistant & controlled
quadrant-4 Compressible & controlled
"Static context": [0.2, 0.15]
"Model output": [0.4, 0.85]
"Conversation history": [0.7, 0.75]
"Tool outputs": [0.9, 0.6]
Context engineering leverage is highest in the upper-right (emergent, highly compressible) — but you can only shape it indirectly.
Static context
Members: system prompt, project memory files (CLAUDE.md, AGENTS.md, .cursor/rules/*.mdc), tool definitions, persistent skills.
Defining property: stable across calls within a session (and often across sessions).
Growth behavior: changes only on configuration edits, deploys, or session boundaries. Within a session, mostly unchanged.
Compressibility: very high via caching, very low via summarization. Because static content is identical from one call to the next, it can sit in a provider-side prompt cache and be served on subsequent calls at a 90% discount (Anthropic) or 50% (OpenAI). Summarizing it would defeat the cache without saving any window space, so the right strategy is "leave it long, but make sure the provider can cache it."
The single most important context engineering decision around static content is to put it at the very front of the prompt and never change a token of it within a session. Cursor's engineering writes about this explicitly; Manus's published rules all reduce to it. A single timestamp injected into the system prompt invalidates the cache on every call.
Conversation context
Members: user messages, assistant messages, tool calls (the structured request part — the result is a separate category).
Defining property: grows monotonically across turns.
Growth behavior: for a chat-only agent, perhaps 500-1,500 tokens per turn. For a tool-using coding agent, 5,000-15,000 tokens per turn including the tool calls themselves. Conversation context is the line item that turns context management from a configuration question into an engineering question.
Compressibility: moderate via summarization, the primary target for compaction. Old turns can be condensed into a state-of-the-task description; recent turns are kept verbatim. Claude Code's compact.ts and microCompact.ts are exactly this: lossy condensation of conversation history with the most recent turns preserved unchanged. OpenAI Codex implements both a server-side compaction (which returns an opaque encrypted blob preserving the model's latent understanding) and a local fallback that emits a structured summarization prompt.
Conversation context is the line item that moves; it is also the line item where the work of context engineering is most visible. Most of Part II of this book is about the mechanisms that act on conversation context.
Tool output context
Members: results of file reads, command executions, search/grep output, web fetches, MCP server responses.
Defining property: spiky, ephemeral, and re-fetchable.
Growth behavior: highly variable. A single grep with a common pattern can return 20K tokens in one call. A read_file on a large file can return 50K. Most calls return less than 2K. The volatility is the issue: one unfortunate tool call can move utilization from comfortable to critical in a single turn.
Compressibility: highest of all four categories, because tool outputs can always be re-fetched. The agent does not need the full grep output in the window; it needs (a) a summary of what was found and (b) the ability to re-run the grep if needed. Claude Code's microcompaction (microCompact.ts) saves old tool outputs to disk and replaces them in the conversation with file references — the "hot tail" of the most recent N tool results stays verbatim, and everything older becomes a path plus a one-line description. Cursor's approach is similar: large tool outputs are written to files at the harness layer, and the agent receives back a path plus a short preview, then uses the file-read tool to selectively examine sections.
Tool outputs are where the largest and easiest wins in context engineering tend to come from. A 50K-token grep output replaced by a 200-token reference is a 250x compression with no information loss (because the original is still on disk).
Model output context
Members: the model's response on the current turn — its reasoning, its assistant message, its tool call JSON, the parameters of those tool calls (which can themselves be large, e.g., a multi-line file edit).
Defining property: the output side of the current call, governed by max_tokens and any reserved output budget.
Growth behavior: bounded per turn by max_tokens. Across turns, every model output becomes part of next turn's conversation context.
Compressibility: not compressible at the moment of generation (you need every token of the response to be valid). After generation, model outputs become conversation context and follow that category's compression rules.
Model output is the only category the model itself controls (the other three are controlled by the agent designer or the harness). It is also the line item that determines the output reserve: the harness must hold back enough of the window for a complete response. Without that reserve, the model can run out of tokens mid-tool-call and emit truncated, invalid JSON.
A summary table
| Category | Controller | Growth behavior | Typical compression strategy |
|---|---|---|---|
| Static (system prompt, project memory, tool definitions) | Agent designer | Stable within session | Cache aggressively; never modify mid-session |
| Conversation history | Accumulates per turn | Monotonic, 500-15,000 tokens/turn | Summarize old turns, preserve recent verbatim |
| Tool outputs | Environment | Spiky, 100-50,000 tokens/call | Externalize to disk; replace with reference + preview |
| Model output (current turn) | The model | Bounded by max_tokens | Reserve headroom; not directly compressible |
The categories matter because they determine which mechanism applies. Cache control affects static context. Compaction affects conversation history. Microcompaction and file offload affect tool outputs. Output reserve constrains model output. Mixing the strategies — for instance, trying to "compact" a system prompt or trying to "cache" a tool output — accomplishes nothing or actively breaks things.
3.3 The Token Budget as Code
A useful way to make all of this concrete is to express the budget as an actual data structure that the harness can reason about. Here is a representative implementation, derived from the way Claude Code, Codex, and Manus all internally track utilization:
from dataclasses import dataclass
from typing import Literal
@dataclass
class TokenBudget:
"""Static configuration for a context window budget."""
context_window: int # Total model context (e.g. 200_000)
max_output_tokens: int # Output reserve (e.g. 20_000)
compaction_buffer: int # Buffer for autocompact to run (e.g. 13_000)
manual_compact_buffer: int # Emergency reserve (e.g. 3_000)
# Measured fixed costs (not estimated)
system_prompt_tokens: int
tool_definition_tokens: int
project_memory_tokens: int
@property
def output_reserve(self) -> int:
"""Total reserved output budget across all buffers."""
return self.max_output_tokens + self.compaction_buffer + self.manual_compact_buffer
@property
def effective_window(self) -> int:
"""The budget actually available for input."""
return self.context_window - self.output_reserve
@property
def fixed_overhead(self) -> int:
"""Tokens consumed before any conversation."""
return (self.system_prompt_tokens
+ self.tool_definition_tokens
+ self.project_memory_tokens)
@property
def available_for_conversation(self) -> int:
"""Remaining budget for history + tool outputs."""
return self.effective_window - self.fixed_overhead
@dataclass
class ContextSnapshot:
"""Live measurement of the current context window."""
budget: TokenBudget
history_tokens: int = 0
tool_output_tokens: int = 0
@property
def total_input_tokens(self) -> int:
return (self.budget.fixed_overhead
+ self.history_tokens
+ self.tool_output_tokens)
@property
def utilization(self) -> float:
"""As a fraction of effective window, not nominal."""
return self.total_input_tokens / self.budget.effective_window
def health(self) -> Literal["healthy", "warning", "compact", "critical"]:
u = self.utilization
if u >= 0.98:
return "critical"
elif u >= 0.92:
return "compact"
elif u >= 0.82:
return "warning"
return "healthy"
Two points about this code. First, every threshold is measured against effective_window, not context_window. This is the production discipline: when the budget is published as "92.8%," it means 92.8% of the budget after the output reserve is subtracted, not 92.8% of the nominal window. Most apparent discrepancies between systems' published thresholds are actually disagreements about whether the denominator includes the output reserve.
Second, fixed_overhead is measured, not estimated. It is tempting to assume "the system prompt is around 2K tokens" and never re-check. In practice, an MCP server registration can silently push tool definitions from 25K to 45K tokens, the kind of change that should immediately update the budget. Production harnesses count the actual tokens of each component on each call and use the measurements as the source of truth.
3.4 Claude Code's Actual Budget
The leaked source analysis of Claude Code v2.1.88 gives us the most fully documented budget of any production agent. The constants (taken from the source-analysis writeups) are:
MODEL_CONTEXT_WINDOW_DEFAULT = 200_000
COMPACT_MAX_OUTPUT_TOKENS = 20_000 # output reserve for compaction summary
AUTOCOMPACT_BUFFER_TOKENS = 13_000 # buffer to let autocompact actually run
MANUAL_COMPACT_BUFFER_TOKENS = 3_000 # emergency buffer for manual /compact
Working through the arithmetic:
Effective usable window
= MODEL_CONTEXT_WINDOW_DEFAULT
- COMPACT_MAX_OUTPUT_TOKENS
- AUTOCOMPACT_BUFFER_TOKENS
- MANUAL_COMPACT_BUFFER_TOKENS
= 200_000 - 20_000 - 13_000 - 3_000
= 164_000 tokens
The nominal window is 200K. The window the agent can actually use for input is roughly 164K. That is 18% of the nominal window held back as reserve.
Why so much? Because the reserve serves three different functions, and each needs its own slice:
-
COMPACT_MAX_OUTPUT_TOKENS(20K). When the model generates its response on a normal turn, this is the maximum length it can produce. More importantly, when compaction runs, the summary the model writes also has to fit in this budget. A 20K reserve is large because compaction summaries are themselves substantial — they have to capture forty turns of conversation in a way the model can use to continue working. -
AUTOCOMPACT_BUFFER_TOKENS(13K). Autocompaction is itself an LLM call. When it runs, the input to that call is the conversation being compacted, plus the summarization instructions, plus any extra context. The buffer is room for autocompact's input overhead. Without it, autocompact would trigger only when there is no longer enough room to run autocompact, which is too late. -
MANUAL_COMPACT_BUFFER_TOKENS(3K). A small emergency reserve for the user-invoked/compactcommand. If the agent has somehow consumed all of autocompact's reserve as well, manual compact still has room to fire.
The triple-buffer structure encodes a real lesson: a single reserve is not enough. The mechanism that protects against running out of room must itself have room to operate. Production harnesses end up with layered reserves like this because each layer protects a different failure mode.
The corresponding utilization thresholds in Claude Code's source measure against effective_window (164K), not context_window (200K). The auto-compact trigger fires at roughly 92.8% of effective window, which is 92.8% × 164K ≈ 152K tokens — roughly 76% of the nominal 200K. This is why there is sometimes apparent disagreement between different writeups about "when Claude Code triggers compaction": the answer depends on which denominator you use.
3.5 The Output Reserve Problem
The output reserve is the most commonly mishandled piece of any context budget, in part because it is invisible until it fails. A cautionary case:
# WRONG — no output reserve management
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=4096, # Model can generate up to 4K
messages=messages_at_198K # 198K of 200K window already used
)
# The model has 200K - 198K = 2K tokens left for output.
# But max_tokens=4096 promises 4K of room.
# Result: response truncates mid-thought.
# If the model was emitting a tool call, the JSON may be invalid.
# If it was writing code, the function may be incomplete.
# RIGHT — reserve-aware
MAX_WINDOW = 200_000
OUTPUT_RESERVE = 33_000
MAX_INPUT = MAX_WINDOW - OUTPUT_RESERVE # 167_000
if count_tokens(messages) > MAX_INPUT:
messages = compact(messages, target=MAX_INPUT)
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=20_000,
messages=messages
)
The failure mode in the "wrong" example is not a clear error. The API does not refuse the call; it accepts the input, runs the model, and returns whatever the model managed to emit before running out of room. The truncation is silent. If the truncated content was a tool call, the harness sees an invalid JSON and either errors or — worse — half-executes a malformed call. If the truncated content was a code edit, the file gets corrupted.
The fix is structural, not reactive: hold back the reserve at the budget level, not at the API-call level. The harness should refuse to grow conversation past MAX_INPUT regardless of max_tokens settings. This is the function autocompact and microcompaction serve in Claude Code: they fire automatically at predetermined thresholds, with no agent or user intervention, to keep input below the reserve line.
3.6 Token Counting Strategies
Every component of the budget framework above depends on counting tokens. Token counting is harder than it sounds, and different counting strategies have different cost/accuracy tradeoffs. The Claude Code source analysis documents four:
| Strategy | Accuracy | Cost | When to use |
|---|---|---|---|
| API token count endpoint | Exact | One round-trip per call | Final budget verification before sending the actual API call |
characters / 4 | ~85% on English prose | Free | Hot-path estimation, conversation tracking |
characters / 2 | ~85% on JSON-heavy content | Free | Tool outputs, structured data |
Fixed 2000 tokens | Order-of-magnitude only | Free | Images, documents, opaque blob attachments |
The characters / 4 heuristic comes from BPE tokenizers: for English text, the average token corresponds to roughly 4 characters. It is dramatically wrong on dense JSON (which has higher information density per character) and on languages with non-Latin scripts, but it is correct often enough to drive on for hot-path budgeting. When you absolutely need an accurate number — say, to decide whether a particular API call will fit — use the provider's tokenizer endpoint.
The characters / 2 heuristic is for JSON. Tool definitions, structured tool outputs, MCP server payloads — all of these tokenize denser than prose. Using the prose heuristic on JSON systematically underestimates by close to 50%, which means a budget that says "78% used" is actually at 89%.
The fixed 2000 for images and documents is the most blunt of the heuristics, and reflects reality: the relationship between image size and token count is non-trivial, and varies by provider. A flat 2K per image is roughly right for typical screenshots and is good enough for budget tracking. The exact count comes from the provider's response after the call.
Production harnesses use a layered strategy: cheap heuristics for live tracking, a single expensive count before each API call to confirm. The expensive count is one round-trip, paid once per agent turn — affordable. The cheap heuristics fire every time conversation grows, every time a tool returns — needs to be free.
3.7 Designing Your Own Budget
Putting it all together, the design procedure for a context budget on a new agent has four steps.
Step 1: Start from capacity. Pick the model and look up its nominal context window. Whatever number the provider advertises is your context_window.
Step 2: Subtract output reserve. Decide your max_output_tokens based on what your agent actually needs to emit per turn. For a chat-only agent, 4K is plenty. For a tool-using agent that produces multi-line file edits and structured tool calls, 8-20K is more realistic. Add a buffer for compaction (Claude Code uses 13K) and a small emergency buffer (3K). The total is your output reserve. Subtract it from context_window to get effective_window.
Step 3: Subtract fixed overhead. Measure (do not estimate) system_prompt_tokens, tool_definition_tokens, and project_memory_tokens. Together they are your fixed overhead. Subtract from effective_window to get available_for_conversation.
Step 4: Allocate the remainder across categories. Within available_for_conversation, plan what fraction will go to conversation history versus tool outputs. There is no universal split — it depends on workload. A code-editing agent with heavy read_file use will need more room for tool outputs than a chat-driven analyst agent. Set targets and then track them.
A worked example. Suppose you are building a coding agent on Claude Sonnet (200K window) with 30 registered tools (~25K tokens of definitions) and a 4K-token system prompt. You want 16K of output budget per turn (enough for a substantial code edit), with 13K compaction buffer and 3K emergency:
context_window = 200_000
output_reserve = 16_000 + 13_000 + 3_000 = 32_000
effective_window = 200_000 - 32_000 = 168_000
system_prompt_tokens = 4_000
tool_definition_tokens = 25_000
project_memory_tokens = 2_000
fixed_overhead = = 31_000
available_for_conversation = 168_000 - 31_000 = 137_000
Out of a nominal 200K window, you have 137K — or 68.5% of the nominal — actually available for conversation history and tool outputs. From the perspective of the §2.5 60-70% management threshold, you start managing when conversation + tool outputs together hit roughly 96K. From the perspective of forced action at 85%, the trigger is at roughly 116K.
If you discover during development that conversation alone is reliably consuming 100K by turn 30, you do not have a "context too small" problem. You have a budgeting problem: 30K of static overhead is a third of your usable budget, and the place to attack is tool definitions (deferred loading, per-task filtering) or system-prompt content (move detail into on-demand docs/ files). The category framework from §3.2 tells you which mechanism applies.
This is what context engineering looks like in practice once the abstractions are concrete. Not "the window is full, what now," but a continuously-tracked budget against measured component sizes, with category-specific compression mechanisms applying at well-defined thresholds. The chapters that follow are essentially a deeper look at each of those compression mechanisms — what compaction is doing under the hood, how microcompaction differs, what it means to externalize state to the file system, when retrieval is the right answer and when it isn't. All of them act on the categories defined in this chapter, against the budget defined in this chapter. Once the anatomy is in view, the rest is mechanism.
Chapter 4: Static Context — System Prompts and Project Memory
"The system prompt is the one piece of context that will be present on every single inference call for the rest of the session. Whatever you put there, you are paying to ship over the wire every turn, and — more importantly — you are paying for the model's attention on those tokens every turn. Treat it like a constitution, not a notebook."
4.1 What "Static" Actually Means
Static context is the set of tokens that don't change — or change rarely — across calls in an agent session. It is the layer that sits at the front of every request the harness sends to the model.
Concretely, static context is usually composed of:
- The system prompt — the role definition, tool usage guidance, output format rules, and behavioral constraints authored by the agent designer.
- Project memory files —
CLAUDE.md,AGENTS.md,.cursor/rules/*.mdc,.github/copilot-instructions.md, and their equivalents across tools. - Occasionally, a fixed catalog — a short list of tool names, skill names, or available docs that the agent can pull into context on demand.
Everything else — the user's current message, the scrollback of turns so far, tool outputs, retrieved snippets, the model's in-flight reasoning — is dynamic. It moves every call.
The distinction matters for two reasons.
First, static context is the only layer you fully control. You wrote it. You decide what it says and how long it is. Dynamic context is shaped by what the user asks for and what the tools return; you can influence it (by choosing tools, by truncating, by compacting) but you cannot deterministically specify it.
Second, static context is the only layer that reliably hits the KV-cache. Every provider with prompt caching — Anthropic, OpenAI, Google — keys the cache on an exact prefix match. If your system prompt and tool definitions are byte-identical from call to call, the provider serves the attention computation for those tokens from cache at a fraction of the input price. If a single character changes — a timestamp, a user ID, a reordered section — the cache is invalidated from that point forward. Static context written in a stable, prefix-friendly shape is the difference between paying full price per call and paying 10% of full price per call. (Chapter 7 covers the mechanics of KV-caching in detail; this chapter covers the content that feeds it.)
The rest of this chapter is about what belongs in that stable layer, how to size it, and how to structure it so the model actually uses it.
4.2 Anthropic's Goldilocks Altitude
Anthropic's engineering guidance for system prompts is the clearest framing anyone has published on the sizing problem. They call it "the right altitude."
The two failure modes are symmetric:
Too vague (too high altitude). The prompt reads like a mission statement: "You are a helpful coding assistant. Be accurate, be thorough, write clean code." The model is left to infer everything specific — which tools to prefer, how to format output, what the conventions of this codebase are, when to ask vs. when to act. Different calls produce different behaviors because the prompt gave the model no steering.
Too prescriptive (too low altitude). The prompt is a decision tree: "If the user asks about X, do Y. If they mention Z, do W. If the file has .ts extension, use tsc. If it has .py, use pyright. If the error is a TypeError, first check imports. If imports are fine, check type annotations…" The prompt tries to hardcode every case. It overfits. New situations — which arrive every session — aren't in the tree, and the model either ignores the prompt or, worse, tries to force the new situation into one of the hardcoded branches.
The goldilocks altitude is "specific enough to steer, flexible enough not to overfit." Three canonical examples of each end of the spectrum:
Anti-pattern (too vague):
You are a helpful coding assistant. Write clean, correct code.
Use best practices. Be thorough.
This gives the model nothing. It will write Python like Java, Java like Python, and ship four-space indented files into a two-space codebase. It won't know what "thorough" means — write tests? document functions? justify every line?
Anti-pattern (too prescriptive):
When the user reports a bug:
1. First ask for the exact error message
2. Then ask for the file name
3. Then ask for the line number
4. Then ask for the runtime environment
5. Then ask for recent changes
6. Then ask for related logs
7. Then, and only then, propose a hypothesis
8. Before proposing a fix, list at least three alternatives
9. After proposing a fix, write a test case
10. ...
The model will follow this rigidly even when the user says "the test at line 42 of auth.py fails with TypeError because we pass a string to an int parameter, here's the fix." It will still ask for the error message, the file, the line number, the environment — because the prompt told it to.
Goldilocks:
<role>
You are a senior engineer pair-programming with the user on their codebase.
You make changes directly when the path is clear; you propose and ask
when the path is ambiguous or destructive.
</role>
<working_style>
- Prefer reading code over asking about it. Use Read, Grep, Glob first.
- When investigating a bug, reproduce it before proposing a fix.
- When the user's intent is unambiguous, act. When it's ambiguous, ask
one focused question — not a checklist.
- Match the codebase's existing style (indentation, naming, imports).
If the codebase contradicts general best practice, match the codebase.
</working_style>
This steers without scripting. It gives the model heuristics ("read code first," "reproduce before fixing," "match the codebase") and lets it apply them per situation.
The practical test: read your system prompt and ask whether a competent human teammate would find it useful guidance or a bureaucratic irritation. If the latter, you're at the wrong altitude.
4.3 Section Structure: Why XML and Markdown Help
A system prompt is parsed by a model that has been trained on a mixture of prose, code, markdown, and structured data. The model does not care deeply about syntax, but it does benefit from clear section boundaries. Structure makes three things easier:
- For the author: the prompt stays maintainable. You can tell at a glance where tool guidance ends and output format begins.
- For the model: attention is drawn to section headers. When the user says "format the output as JSON," the model can look at
<output_format>instead of scanning the whole prompt. - For debugging: when behavior goes wrong, you can identify which section is being ignored or misapplied.
The two dominant conventions in production are XML tags (Anthropic's recommendation, used internally in Claude's training data) and markdown headings (used by Cursor, Codex, and most open-source harnesses). They work roughly equivalently; the important thing is to pick one and stay consistent.
A workable skeleton for a coding-agent system prompt:
<role>
Who the agent is, what it's doing, who it's doing it for.
2-4 sentences. No mission-statement fluff.
</role>
<tools>
Which tools are available (by name) and when to prefer each one.
Not the full JSON schemas — those live in the tools field of the API call.
</tools>
<tool_guidance>
Non-obvious rules for tool use. Things like:
- "Always Read a file before Edit."
- "Prefer Grep over Bash(grep) because it respects .gitignore."
- "Batch independent file reads into parallel calls."
</tool_guidance>
<output_format>
What the final message should look like. Markdown conventions,
code block expectations, when to cite files, when to include artifacts.
</output_format>
<constraints>
Hard invariants. Things the agent must never do, or must always do.
Short list. Each item is a rule, not a preference.
</constraints>
A few notes on each section:
Role should answer: who, what, for whom. "You are a coding agent that helps users with software engineering tasks" is a real role statement. "You are a friendly, knowledgeable AI" is not — it describes personality, not function.
Tools should reference names, not duplicate schemas. The API's tools field already carries the full definitions; the system prompt just needs the narrative layer — "use A for X, B for Y, prefer A when both apply." Duplicating schemas wastes tokens and creates drift (when the schema changes, the prompt is wrong).
Tool guidance is where the agent actually gets good. Rules like "Read before Edit," "Grep is faster than Bash(grep)," and "batch independent calls in parallel" are what separate a cautious agent from a sloppy one. These rules are hard-won from watching the agent fail, and they belong here because they apply on every turn.
Output format is where you prevent the most annoying failure modes: the agent that writes a wall of prose when you wanted a diff, the agent that emits JSON when you wanted markdown, the agent that forgets to cite file paths. Specify it once here.
Constraints is the smallest section and the most important. "Never force-push." "Never commit secrets." "Never run rm -rf." These are invariants. If a constraint section grows past ~10 bullets, it's probably eating into the tool guidance section's territory.
Keep each section short. A coding-agent system prompt that exceeds 3,000 tokens is usually bloated. Claude Code's leaked system prompt sits around 3,000 tokens including its tool-specific guidance, which is a useful upper bound reference point for a sophisticated general-purpose coding agent.
4.4 Project Memory as Context: The Codex Lesson
Everything in the system prompt applies to every project the agent ever works on. But most agent work is project-specific: this codebase uses pnpm, not npm. This team squashes commits on merge. This module is being deprecated — don't add features to it.
Project memory files are where that information lives. They sit in the repository, they are read once at session start (and sometimes re-read after compaction), and they ride along with the code.
The naive version of project memory is "dump everything important into one big file." The OpenAI Codex team tried this, and their postmortem has become the canonical cautionary tale:
"We tried the 'one big AGENTS.md' approach. It failed in predictable ways: context is a scarce resource. A giant instruction file crowds out the task, the code, and the relevant docs — so the model tends to ignore parts of it."
The lesson is simple and sharp: context is a scarce resource. Every line you add to a project memory file is a line the model has to attend to on every turn, competing with the user's question, the tool outputs, the code under edit. A 2,000-line AGENTS.md full of "nice to know" information doesn't make the agent better; it makes the agent worse, because important instructions get buried under unimportant ones.
Codex's fix became the template: AGENTS.md as a map, not an encyclopedia.
AGENTS.md (~100 lines — the map)
├── Repo overview (2-3 sentences)
├── Architecture summary (3-5 sentences)
├── Key commands (test, lint, build)
├── Pointer: see docs/architecture.md for system design
├── Pointer: see docs/testing.md for test patterns
├── Pointer: see docs/api.md for endpoint conventions
└── Pointer: see docs/style.md for code style details
docs/
├── index.md (table of contents, verification status)
├── architecture.md (loaded when agent works on structure)
├── testing.md (loaded when agent writes tests)
├── api.md (loaded when agent works on endpoints)
├── database.md (loaded when agent works on schema)
└── deployment.md (loaded when agent works on CI/CD)
The AGENTS.md stays in context at all times. It's ~100 lines, ~300 tokens. It contains:
- A two-sentence description of what the project is.
- A short architecture summary (which languages, which frameworks, which directories matter).
- The commands the agent needs most often (
pnpm test,cargo clippy,just migrate). - A list of pointers: "for testing, read
docs/testing.md," "for deployment, readdocs/deployment.md."
The detailed docs don't enter context unless the agent decides it needs them for the current task. This is progressive disclosure applied to project knowledge: announce what's available, load it when it's actually needed.
The docs/index.md that Codex teams tend to maintain also includes a verification status — whether each doc has been checked for currency, by whom, when. Docs drift; a doc marked "last verified 2024-03" that describes a migration system that was replaced six months ago is actively harmful. Verification status makes the agent (and the human) treat stale docs with appropriate skepticism.
4.5 Project Memory Across Tools: A Practitioner's Tour
Different agent systems implement project memory differently. Understanding the variations is useful both when you're working in one of these systems and when you're designing your own.
Claude Code: The Four-Level CLAUDE.md Hierarchy
Claude Code loads CLAUDE.md files from four locations, in order, with later levels overriding earlier ones:
1. /etc/claude-code/CLAUDE.md # Enterprise-wide rules (admin-controlled)
2. ~/.claude/CLAUDE.md # User preferences across all projects
3. ./CLAUDE.md # Project root conventions
4. ./src/CLAUDE.md # Directory-scoped (any subdirectory)
The enterprise level is typically thin — organization-wide rules like "never use this deprecated internal library," "always use our internal http client, not fetch." The user level is where individuals put personal preferences: "I use zsh, not bash," "I like comments above code, not after." The project level is the one most developers write: project-specific conventions, commands, patterns. The directory level is where subsystem-specific rules live — ./src/api/CLAUDE.md might contain API versioning rules that only apply when editing inside src/api/.
Each level overrides the previous. If ~/.claude/CLAUDE.md says "prefer tabs" and ./CLAUDE.md says "this project uses spaces," the project wins. If ./CLAUDE.md says "use Jest" and ./src/legacy/CLAUDE.md says "use Mocha (legacy only)," Mocha wins inside src/legacy/. This scoping is what makes four levels tractable: the narrower level always wins, so you can set a sensible default globally and override locally without refactoring.
Cursor: .cursor/rules/*.mdc with Four Activation Modes
Cursor's rules live in .cursor/rules/, one rule per .mdc file (Markdown with YAML frontmatter). Each rule declares how it gets activated:
---
name: python-style
description: Python code style rules for this project
alwaysApply: false
globs: ["**/*.py"]
---
- Use 4-space indentation.
- Type-annotate all public functions (return type + params).
- Prefer `pathlib.Path` over `os.path` for filesystem operations.
- Use f-strings for formatting; avoid `.format()` and `%`.
- Raise specific exceptions, not bare `Exception`.
The frontmatter controls activation. Cursor's docs describe four modes:
- Always apply (
alwaysApply: true): the rule is injected on every turn. Use sparingly — this is the mode that turns a rule into "static context" in our sense. - Intelligent routing (description-based): the rule has a
descriptionbut no glob or always-apply flag. Cursor's agent reads descriptions and pulls in rules that match the current task. - Glob-scoped (
globs: [...]): the rule is activated when the agent is working on files matching the glob.globs: ["**/*.py"]pulls inpython-style.mdcwhenever a Python file is being edited. - Manual (
@rule-name): the rule is loaded only when the user explicitly invokes it in chat with@python-style.
The combination is powerful. You can have a small set of always-apply rules (core conventions), a larger set of glob-scoped rules (per-language, per-subsystem), and a long tail of manual rules (onboarding checklists, incident playbooks) that sit in the repo but don't consume context until someone asks for them.
Codex: AGENTS.md + structured docs/
We covered this above; the distinctive piece is the docs/index.md with verification status. Codex-style project memory leans harder on the "map vs. encyclopedia" split than any other system: the encouraged AGENTS.md length is around 100 lines, enforced by convention rather than tooling.
Cross-Tool: AGENTS.md as an Emerging Standard
As of 2026, AGENTS.md at the repo root is recognized by Claude Code, GitHub Copilot, Cursor, Gemini Code Assist, and OpenAI Codex. Each tool has its own native format (CLAUDE.md, .cursor/rules/, copilot-instructions.md), but most of them will also read AGENTS.md if present, and several projects use AGENTS.md as the canonical source and symlink the others to it. If you're writing for a team that uses more than one agent tool, write AGENTS.md; it's the lowest common denominator that actually reaches the model.
4.6 Skills as Progressive Context: The Three-Level Loading Pattern
Skills — typically packaged as SKILL.md files — represent a layer of the static context hierarchy that emerged in 2026. Unlike CLAUDE.md (always loaded at session start) or docs/ files (loaded on demand by the agent's own judgment), skills use a three-level progressive disclosure pattern specifically designed for context efficiency.
The pattern works because skills are instructions, not reference material. An agent with 100 installed skills cannot afford to load all of them — at an average of 1,500 tokens per skill body, that would consume 150K tokens, more than the entire effective window. Instead, the harness loads skills in three stages, each triggered by need:
Level 1 — Metadata only (~50 tokens per skill)
At session start, the harness loads only each skill's name and one-line description from YAML frontmatter. With 100 installed skills, this costs ~5K tokens — less than 3% of a 200K window. The model can scan this manifest and know what capabilities are available without paying the cost of reading every skill's full body.
Level 2 — Full SKILL.md body (~500–2,000 tokens)
When the agent identifies a task that matches a skill's description, it loads the full SKILL.md instructions. The body contains the process, decision trees, constraints, and rules — everything the agent needs to execute that skill. But critically, it does NOT contain heavy reference material.
Level 3 — Reference files (variable, loaded on demand)
Heavy documentation, worked examples, API specs, and prompt templates live in a references/ subdirectory alongside the SKILL.md. These are loaded only when the agent actually needs them during execution — for instance, a prompt template referenced by the skill instructions, or an API specification needed to generate correct output.
Production examples
Superpowers (obra/superpowers): A complete development methodology packaged as skills. Skills like subagent-driven-development, brainstorming, test-driven-development each contain a SKILL.md with structured process and prompt templates in supporting files. The agent loads only the relevant skill for the current phase of work. The project demonstrates what a mature skill ecosystem looks like at scale — dozens of skills, each self-contained, with clear activation conditions.
Claude Code Plugins: Anthropic's official plugin system bundles skills into namespaced packages. Discovery is cheap (Level 1); full instructions load only on activation. The documented recommendation: keep SKILL.md under 150 lines, move heavy docs to references/. This constraint exists because skill bodies sit in the context window alongside the active task — a 500-line skill body competes directly with the code the agent is trying to understand.
Semantic routers for large registries: For skill registries exceeding ~50 skills, metadata-only routing becomes noisy — the model struggles to pick the right skill from a wall of one-line descriptions. Production systems use embedding-based semantic routers: embed the user's task description, compare against skill description embeddings, load the top-1 or top-3 matches. Measured result: 456x token reduction versus loading all skill bodies, with comparable routing accuracy.
The context engineering insight
Skills formalize what Chapter 5's tool-search pattern does for tools — they apply progressive disclosure to instructions, not just capabilities. The pattern is identical in structure: announce cheaply at Level 1, load fully at Level 2, expand references at Level 3. The taxonomy of what gets progressively disclosed is expanding: first it was tool schemas (§5.3), then project docs (§4.4), now skill instructions.
Connection to Cursor's
.cursor/rules/*.mdc(section 4.5): Cursor's glob-scoped rules are essentially Level-2 skills triggered by file pattern rather than semantic match. The skill ecosystem generalizes this with explicit YAML frontmatter controlling activation —description,when,globs,alwaysApply— giving the harness multiple routing signals instead of a single glob.
One deliberate design constraint worth noting: a CLAUDE.md at a plugin root is NOT loaded as project context. Plugins contribute context through skills, not through CLAUDE.md. This prevents always-on context bloat from plugin installation — without this rule, installing 20 plugins would inject 20 plugin-level CLAUDE.md files into the always-loaded layer, exactly the kind of unchecked growth that §4.4's Codex lesson warns against.
4.7 Sizing Rules: Under 500 Lines, Usually Under 300
The Claude Code community, Cursor forums, and Codex internal guidance all converge on the same empirical range: project memory should stay under 300–500 lines.
The reason isn't a hard limit. It's that every line in project memory competes with the task for the model's attention. A 1,500-line CLAUDE.md doesn't get read 5x more carefully than a 300-line one — it gets read less carefully, because the model's attention per line is lower. The useful rules get lost in the noise.
Practical rules of thumb collected from production teams:
AGENTS.md/CLAUDE.md(always-loaded): aim for ~100 lines, hard ceiling at 300. If it exceeds 300, split into pointed docs..cursor/rules/*.mdc(each file, glob-scoped): aim for under 100 lines per rule. A rule that needs more is usually doing too many things.docs/*.md(loaded on demand): can be longer. These are reference material; the agent reads one at a time when the task warrants. Individual docs in the 200–800 line range are fine.
A signal you're bloated: your project memory contains sentences like "for more details, see…" and then inlines the more details anyway. Pick one. Either the detail belongs in the always-loaded file (and it's worth paying for on every turn) or it belongs in a pointed doc (and the memory file should be a pointer, period).
Another signal: the memory file contains information the model already knows. "Python uses indentation for blocks." "React components are functions or classes." "Git commits should have descriptive messages." Delete these. The model knows. You are paying tokens to remind it of things it will not forget.
4.8 The Cache Preservation Angle
Static context is the layer that benefits most from KV-cache. The provider's cache keys on an exact prefix match starting from the first token, so the tokens at the very front of the request — system prompt, then tool definitions, then project memory — are the ones that get cached. Every turn where those tokens are byte-identical to the previous turn, the provider serves their attention from cache.
Chapter 7 covers the mechanics in detail. For this chapter, the implication is structural: design the static layer for stability.
That means:
- Don't inject timestamps into the system prompt. "The current date is 2026-04-19" at the top of the prompt invalidates the cache every day (or every turn, if the prompt includes time, not just date).
- Don't embed session-specific or user-specific data in static context. Names, session IDs, request IDs — these belong in the user turn or a dedicated "user context" dynamic block, not stitched into the role statement.
- Order sections stably. If
<tools>comes before<constraints>on Monday, it should come before<constraints>on Tuesday. Reordering (for any reason — refactoring, A/B testing, a different author's style) invalidates the cache from the first reordered token. - Keep project memory files byte-stable across a session. Re-reading a file is fine; rewriting it mid-session isn't. If you need to update project memory, do it between sessions, not mid-turn.
This discipline pays off. In a 50-turn session with a 5K-token static layer, cache preservation turns ~250K tokens of repeated input into ~250K tokens of cached input, billed at ~10% of the normal input rate. That's the difference between a session that's dominated by input costs and one that's dominated by (much smaller) output costs.
4.9 Designing Your Own Static Context Layer
A practical checklist when designing or auditing the static layer for a new agent.
What always goes in the static layer
- Role and working style. Who the agent is, how it should behave on ambiguity, when to act vs. ask.
- Tool preferences and guidance. Not schemas — narrative rules like "prefer A over B when both apply," "batch independent calls," "Read before Edit."
- Output format contract. Markdown vs. JSON, when to include file paths, how to cite evidence, where to put artifacts.
- Hard constraints. Never force-push. Never commit secrets. Never delete without confirmation. Short list, bright lines.
- Project conventions (in project memory). Language, framework, test/build/lint commands, branch style, naming rules.
- A catalog of on-demand sources. "For testing patterns, see
docs/testing.md." Pointers, not content.
What never goes in the static layer
- Timestamps, current date, or any time-derived string. These belong in a dynamic system block added per call, outside the cached prefix — or, better, not in the prompt at all (put them in a tool that the model calls when it needs to).
- Per-session or per-user state. Session IDs, user IDs, API keys, auth tokens, the current working directory, the git branch. These change per session (or per turn) and destroy cache hit rate.
- The current task. Tasks belong in the user message, not the system prompt.
- Large inlined documents. If the content is more than ~500 lines and isn't actively needed every turn, move it out of the static layer into on-demand docs.
- Dynamic tool outputs. Never. The static layer is authored; tool outputs are captured.
- Generated content that might drift. Auto-generated docstrings, schema dumps, OpenAPI specs that change with every deploy. These belong in loaded-on-demand files, not always-on memory.
How to test for bloat
Two quantitative checks, run on a typical call:
- Token count of the static layer. Count system prompt + tools + always-loaded project memory. Compare to your context window. If it exceeds ~20% of the window for a general-purpose agent, you're probably bloated. Claude Code's static layer sits around 5–7% of a 200K window in practice. If you're three times that, audit.
- Cache hit rate. Every major provider reports cache hit rate per call (Anthropic:
cache_read_input_tokens; OpenAI:prompt_tokens_details.cached_tokens). On a warmed-up session, your cache hit rate on static-layer tokens should be above 95%. Below that, something is changing between calls that shouldn't be — often a timestamp, a session ID, or a section that got reordered.
Two qualitative checks:
- "Could a human teammate use this?" Read the static layer top to bottom. If you, as a new engineer on the team, would find it useful onboarding material, the model will too. If it reads like a bureaucratic checklist, the model will either ignore it or over-follow it.
- "Is every line earning its place?" For each line, ask: does this change the agent's behavior in at least one common scenario? If not, delete. This is the hardest discipline in static-context design because every line feels important when you're writing it. The ones that actually are remain useful months later; the rest are noise you're paying to ship every turn.
4.10 Summary
Static context is the cache-preserving layer: the tokens that don't change across calls. It is the foundation on which everything dynamic sits.
The design problem has three parts: what goes in (role, tool guidance, output format, constraints, project conventions, pointers to on-demand docs), how much goes in (aim for under 20% of the window, under 300 lines of always-loaded project memory), and how it's shaped (stable structure with clear section boundaries, no per-session data, no timestamps, no drift). Get all three right and you have a cheap, focused, high-signal layer that steers the agent on every turn. Get any one wrong and you either overfit, crowd out the task, or leak cache and pay full price.
Chapter 5 takes the same lens and points it at tool definitions — the other half of the static layer, and the one most likely to be silently eating half your context window.
Chapter 5: Tool Definitions — The Hidden Token Tax
"A tool definition you never call still costs tokens. A tool definition you never call still competes for the model's attention. The cheapest tool is the one that isn't in your context window."
5.1 The Tax You Pay Just by Being Connected
Tool definitions are a context engineering problem that hides in plain sight. Most practitioners think about them as a tool execution problem — how do I call this tool, how do I parse the result, how do I handle errors — but the context cost shows up long before any tool is invoked. Every tool you register gets serialized as JSON Schema and injected into the prompt on every turn. The model processes these definitions whether it uses zero tools or ten.
This chapter is not about how tools execute. It is about how their definitions consume context, and what production systems do to stop that.
The per-tool math
Measurements across production systems converge on a simple range:
| Tool complexity | Token cost per definition |
|---|---|
Simple (read_file(path)) | 550–700 tokens |
| Medium (3–5 typed parameters) | 700–1,000 tokens |
| Complex (nested schemas, enums, examples) | 1,000–1,400 tokens |
Where the tokens go in a typical "medium" tool:
- Function name + description: 50–100 tokens.
- Parameter schema (JSON Schema, with types and constraints): 200–800 tokens.
- Parameter descriptions: 100–300 tokens.
- Enums, defaults, examples: 100–200 tokens.
- Formatting overhead (braces, quotes, field labels): 50–100 tokens.
This is before anyone calls the tool. It is the cost of describing the tool to the model.
The MCP multiplier
Model Context Protocol servers bundle related tools together, which makes it easy to register dozens of tools at once — and easy to forget how much context they consume. Measurements from production MCP deployments:
| MCP server | Tools | Token cost |
|---|---|---|
| Filesystem MCP | 11 | ~6,000 |
| Database MCP | 15 | ~10,000 |
| Jira MCP | 23 | ~17,000 |
| GitHub MCP | 30+ | ~20,000 |
A developer who connects Jira + GitHub + Filesystem MCPs has already spent ~43,000 tokens on tool definitions alone. On a 128K-window model, that is 33.6% of the context window consumed before the user sends their first message. Common enterprise combinations can push this to 45% of a 128K window — nearly half the budget, gone to schemas.
The 40-tool session
For a coding agent with 40 registered tools (three or four MCP servers plus the built-in tools), per-call math looks like this:
Minimum: 40 × 550 = 22,000 tokens per inference call
Typical: 40 × 850 = 34,000 tokens per inference call
Maximum: 40 × 1,400 = 56,000 tokens per inference call
Over a 50-call session at 34K tokens per call, the agent sends 1.7 million tokens of tool definitions — most of them byte-identical to what it sent last turn. Even with aggressive prompt caching knocking input costs down 90% on cache hits, tool definitions can still dominate the session's input bill, and they still consume the attention budget the model is supposed to spend on the user's task.
5.2 Tool Selection Accuracy: More Tools, Worse Decisions
The cost story is only half the problem. The quality story is worse.
Tool selection accuracy — how often the model picks the right tool for a given task — degrades sharply as the tool count grows. The curve, measured across several public benchmarks and echoed in production telemetry:
| Tool count | Selection accuracy | Failure mode |
|---|---|---|
| 5 | ~92% | Occasional parameter formatting errors |
| 15 | ~74% | Wrong tool picked from a similar-purpose cluster |
| 50+ | ~49% | Coin-flip accuracy; hallucinated tool names appear |
At 50+ tools, the model is essentially guessing. This is not just a context-length problem. A 200K context easily accommodates 50 tool schemas with room to spare for the user's task. The bottleneck is attention dilution: the model has to attend to 50 different tool descriptions, compare them against the current task, and pick one. Each description is a candidate that steals some attention weight from the others. Past a certain point, the "correct" tool's signal is indistinguishable from noise.
The two failures compound. More tools means more tokens (expensive) and worse selection (low-quality). The rest of this chapter is about what practitioners actually do to get out of this regime.
5.3 Four Production Approaches
Four approaches, each from a production system, each targeting a different shape of the problem. None of them is universally best; which one you want depends on how your tool set is structured, how often it changes, and what you're optimizing for (tokens, cache stability, or latency).
Approach 1: Anthropic's Tool Search (defer_loading)
Anthropic's tool search — tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119, generally available since February 2026 — is the most direct answer to "I have too many tools." The mechanism:
- Mark tools with
defer_loading: true. Their full schemas are excluded from the system prompt. Only the name and description remain visible. - Include a search tool (
tool_search_tool_regexortool_search_tool_bm25) that Claude can use to discover deferred tools. - When Claude calls the search tool, it receives back
tool_referenceblocks containing the full schemas of the matched tools, loaded into that turn only. - Claude then calls the discovered tool normally.
The effect: the model sees all the names and one-line descriptions up front (a few hundred tokens for 40 tools), and only the handful of tools actually needed this turn pay their full schema cost.
Real Python, using the Anthropic SDK:
from anthropic import Anthropic
client = Anthropic()
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2048,
tools=[
# The search tool itself — always loaded
{
"type": "tool_search_tool_regex_20251119",
"name": "tool_search_tool_regex",
},
# Deferred tools: name + description visible, schema loaded on demand
{
"name": "search_knowledge_base",
"description": "Search the company knowledge base by topic or keyword.",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string"},
"category": {
"type": "string",
"enum": ["engineering", "product", "hr", "finance"],
},
"max_results": {"type": "integer", "default": 10},
},
"required": ["query"],
},
"defer_loading": True,
},
{
"name": "create_support_ticket",
"description": "Create a new support ticket with priority and assignment.",
"input_schema": {
"type": "object",
"properties": {
"title": {"type": "string"},
"description": {"type": "string"},
"priority": {"type": "string",
"enum": ["low", "medium", "high", "critical"]},
"assignee": {"type": "string"},
},
"required": ["title", "description", "priority"],
},
"defer_loading": True,
},
# ... 40 more tools, all defer_loading: True
],
messages=[
{"role": "user", "content": "Find our OAuth2 documentation."},
],
)
Production results published by Anthropic and echoed by early adopters:
- ~85% token reduction on tool-definition overhead for toolsets of 40+ tools.
- Tool selection accuracy improved from 49% to 74% at the 50+ tool scale. Fewer schemas in context means less attention dilution even for the tools that are selected.
- Scales smoothly to 100+ tools without a new failure mode — the search step does the filtering the attention mechanism was doing badly.
The one cost is latency. The search tool is an extra turn in the loop; when Claude doesn't know which tool it needs, it has to call tool_search_tool_regex first, then the discovered tool. In practice this adds ~200ms per tool lookup, which is usually a good trade against the quality and cost improvement — but it's real, and for latency-sensitive use cases you may want to pre-bias which tools load normally versus deferred.
Approach 2: Cursor's File-Based Tool Descriptions
Cursor went further: they stripped tool definitions from the context entirely and replaced them with file references. The system prompt contains only tool names. When the agent needs a tool, it reads the full definition from a file on disk.
The shape of the system prompt:
## Available tools (58 total)
GitHub: create_pr, list_issues, create_issue, get_file, search_code,
create_branch, merge_pr, list_prs, get_pr_diff, add_comment
Database: query, list_tables, describe_table, run_migration,
backup, restore, explain_query, get_slow_queries
Slack: send_message, list_channels, search_messages, add_reaction,
create_channel
Jira: create_ticket, update_ticket, list_tickets, add_comment,
transition_ticket, get_sprint, list_sprints, create_sprint,
add_to_sprint, remove_from_sprint
AWS: list_instances, get_logs, deploy_lambda, update_env_var, ...
Full tool definitions: /tools/{tool_name}.json
Tool status: /tools/status.json
Token cost of this catalog: ~400 tokens for 58 tool names. Full schemas would cost 32K–81K tokens.
When the agent decides to use a tool, it reads the relevant JSON file. The definition enters context only for the turns that actually use it.
The status file is the detail that makes this production-grade. MCP servers disconnect, rate limits trigger, tools go into maintenance mode. In a static tool-definition world, these events require editing the system prompt (cache invalidation, deployment). With a status file, the agent just reads fresh status before each call:
// /tools/status.json
{
"github_create_pr": {"status": "available", "latency_ms": 340},
"github_list_issues": {"status": "available", "latency_ms": 280},
"slack_send_message": {
"status": "unavailable",
"reason": "MCP server disconnected",
"since": "2026-04-14T10:23:00Z"
},
"jira_create_ticket": {
"status": "rate_limited",
"retry_after": "2026-04-14T10:25:00Z"
}
}
Cursor's A/B test measured 46.9% total token reduction versus the static-loading baseline while maintaining or improving task completion quality. The key insight — useful well beyond tool definitions — is that files are a natural progressive-disclosure interface. The catalog is small and always visible; the detail is behind a read.
There are two second-order benefits worth calling out:
- Cache-friendly. The static prompt, with only names, rarely changes. Adding or removing a tool means editing the catalog (still cache-invalidating, but cheap because the catalog is small). Updating a tool's schema — changing one parameter, improving a description — does not invalidate anything, because the schema lives in a file the catalog points to.
- Status as first-class context. The model can decide not to call a tool because it's currently unavailable. This is harder to express in a pure schema-in-prompt world, where the prompt is static and the tool's availability is implicit.
Approach 3: Manus's Logit Masking
Manus made a different choice. Rather than remove tool definitions from context, they keep every tool defined at all times and mask the logits during decoding to restrict which tools the model is allowed to select on a given turn.
The reasoning is explicit in Manus's engineering writeups: removing a tool from context invalidates the KV-cache from that point forward. If you have a workflow with 20 states, and each state enables a different subset of tools, dynamically removing schemas would cause a cache miss at every state transition. On a long-running agent, that's catastrophic.
Masking sidesteps the problem. The tool definitions stay exactly where they are in the prompt — the cache stays intact — but during the decode step, the logits for tool tokens that are currently invalid are pushed to negative infinity. The model can only sample from the allowed subset.
For this to be practical, tool names need to share prefixes that make group masking efficient. Manus's naming convention is illustrative:
browser_open_url
browser_click
browser_type
browser_scroll
browser_close
shell_exec
shell_read_output
shell_kill
file_read
file_write
file_delete
With this structure, "mask out all browser tools" becomes "mask tokens that begin with browser_." The tokenizer usually represents these prefixes as a small number of tokens, so the masking operation stays fast.
The pattern works especially well when the tool set is stable but the availability is workflow-dependent. For example:
- In a planning state, only
plan_*tools are valid. - In an execution state,
browser_*,shell_*,file_*are valid butplan_*is not. - In a review state, only
report_*andask_userare valid.
Each transition changes what the model is allowed to call, but not what's defined. The cache survives the entire session.
The cost of logit masking is infrastructure — you need a harness that sits between the model and the user, and an inference provider that supports either direct logit biasing or a finite-state grammar. (Anthropic and OpenAI both support logit bias / structured outputs; open-weights local serving supports it via libraries like Outlines or llama-cpp's grammars.) For teams using managed APIs without this control, Approach 1 or 2 is easier. For teams running their own inference, masking is often the right answer.
Approach 4: Anthropic's Programmatic Tool Calling (Code Mode)
The fourth approach attacks a different problem: tool chains where intermediate results balloon the context without adding value for the final answer.
Consider the classic "summarize recent commits" workflow:
Turn 1: User: "What changed in the last 3 commits?"
Turn 2: Assistant calls git_log(n=3) → result injected (~2K tokens)
Turn 3: Assistant calls git_diff(abc123) → result injected (~5K tokens)
Turn 4: Assistant calls git_diff(def456) → result injected (~8K tokens)
Turn 5: Assistant calls git_diff(ghi789) → result injected (~6K tokens)
Turn 6: Assistant synthesizes answer
Five turns, ~21K tokens of raw diff output clogging the context, even though the final answer is a 300-token summary. Worse, each intermediate step requires a full inference call — five model turns where one or two would do.
Programmatic tool calling (sometimes called "code mode") collapses this into a single code block that executes in a sandbox:
Turn 1: User: "What changed in the last 3 commits?"
Turn 2: Assistant generates:
```python
commits = git_log(n=3)
changes = {}
for c in commits:
diff = git_diff(c.sha)
changes[c.sha] = {
"message": c.message,
"files": [f.path for f in diff.files],
"insertions": diff.total_insertions,
"deletions": diff.total_deletions,
}
return changes
```
Code runs in sandbox. Intermediate git_diff outputs never enter the conversation.
Only the final compressed `changes` dict is returned.
Turn 3: Assistant synthesizes answer (~1K tokens of summarized data in context).
The intermediate results — the raw diffs — execute in the sandbox and never enter the conversation. Only the compressed result returns. In published numbers, this pattern yields a ~37% latency reduction on multi-step tool chains plus substantial token savings, because the large intermediate tool outputs don't re-cycle through the context on every subsequent turn.
Programmatic tool calling is not a universal replacement for individual tool calls. It works when:
- The intermediate results are only used to compute the final answer.
- The tool calls have no side effects that require per-step human approval.
- Error handling can be generic (the sandbox catches exceptions; the model doesn't need to reason about each one).
It fails when the model needs to reason about intermediate results before deciding the next step — say, a debugging workflow where "what does this stack trace tell us?" guides the next tool call. In those cases, the individual-call-per-turn pattern is worth its cost.
5.4 Which Approach When
No single approach dominates. The right choice depends on how your tool set is structured. The following table — informed by Anthropic's own recommendations and by production telemetry from Cursor, Manus, and several open-source harnesses — is the closest thing we have to a decision rubric:
| Situation | Best approach | Why |
|---|---|---|
| Static toolset, < 20 tools | None — just cache | Cache handles the per-call cost; selection accuracy is fine at this count. |
| Static toolset, 20–100 tools | Tool search (defer_loading) | 85% token reduction, accuracy gains, minimal infra. |
| Dynamic toolset (workflow states change what's valid) | Logit masking | Preserves cache across state transitions; masking is reversible per turn. |
| Chains of tool calls with bulky intermediate results | Programmatic tool calling | Intermediate data stays in the sandbox, never in context. |
| Very large toolset (> 100), heterogeneous | Combine: tool search for base, then programmatic for chains | The approaches are additive; apply both where their domains overlap. |
| Custom harness, heavy MCP use | File-based (Cursor pattern) | Status files and per-tool schemas as files scale cleanly; full control over caching. |
A practical heuristic: start with prompt caching alone, measure, and only move to a more sophisticated approach when either (a) tool definitions exceed 15% of the context window on every call, or (b) selection accuracy is below 80% on a representative task set. Both are observable; both correspond to a specific fix in the table.
A note on combining approaches: tool search and programmatic tool calling are orthogonal and compose naturally. Tool search reduces how many schemas sit in the prompt; programmatic tool calling reduces how many intermediate results sit in the history. A mature agent often uses both, for the same reason a mature web service uses both indexing and caching — they solve different aspects of the same "too much data in the hot path" problem.
5.5 Tool Definition Quality: Description-Accuracy Link
None of the approaches above rescues you from bad tool descriptions. A deferred tool with a vague description is just as hard to find as a non-deferred one. A tool in a file with a misleading name will be skipped by the agent when it actually needed it.
Anthropic's engineering guidance states the principle directly: "If a human engineer can't tell when to use the tool from reading its description, the model can't either."
Rules that production teams have converged on:
1. Name tools by what they do, not by what they wrap.
- Bad:
api_v2_post_users_id_tickets_create - Good:
create_support_ticket
The name is for the model (and the developer reading the prompt), not the underlying REST path. The REST path belongs inside the tool's implementation.
2. Make descriptions answer "when should I use this?"
- Bad:
"Gets information about a user." - Good:
"Look up a user's profile, preferences, and active subscriptions by user ID. Use when you need to check user permissions or fetch account details before taking action on their behalf."
The second version tells the model when to reach for the tool. The first leaves the decision to guesswork.
3. Use consistent prefixes for groups.
If you have five tools that work with files, all of them should start with file_. If you have six browser tools, all should start with browser_. Consistent prefixes help the model cluster tools mentally, help users reading the prompt, and — if you ever want to use logit masking — make group-level control trivial.
4. Document non-obvious preconditions in the description, not in a separate doc.
If a tool requires the agent to first call another tool (run_migration requires a prior backup), say so in the description. The model reads descriptions; it does not reliably cross-reference external docs at tool-selection time.
5. Keep descriptions short but specific.
Target 1–3 sentences. A 20-line description pushes a simple tool into the 1,200-token bracket. A 5-word description ("Gets user data.") leaves the model to guess. Specificity beats length: one specific sentence is worth three vague ones.
6. When in doubt, ship it to the model and read back what it does.
The ultimate test for a description is empirical: give the agent a task that should use the tool, and see if it picks it. If not, the description is wrong. If it picks the tool but mis-fills parameters, the parameter descriptions are wrong. Fix and re-test. Tool descriptions, like any other prompt engineering artifact, get better with iteration.
A subtle byproduct of this discipline: clear descriptions are shorter. A description that clearly says "use when X, returns Y" is usually 50 tokens. A description that tries to hedge, restate, or enumerate edge cases is usually 200 tokens and harder for the model to act on. Good tool-description writing is a token optimization that looks like a quality optimization.
5.6 Skills Face the Same Tax — and the Same Solutions
The tool-definition tax from §5.1 has an exact parallel in skills. An agent with 100 installed skills and each SKILL.md averaging 1,500 tokens would spend 150K tokens loading them all — more than the entire effective window. The economics are identical: static overhead that the model pays on every inference call, whether it uses the skill or not.
The same four production approaches from §5.3 apply, adapted to the skill domain:
1. Progressive disclosure (the default). Only Level 1 metadata loads at session start — the skill's name and one-line description from YAML frontmatter, ~50 tokens per skill. This is the skill equivalent of Anthropic's defer_loading. Claude Code's plugin system enforces this by design: plugin skills never enter context until activated. At 100 skills, the Level 1 manifest costs ~5K tokens versus ~150K for full bodies — a 30x reduction in baseline overhead.
2. Semantic routing. For registries exceeding ~50 skills, metadata-only routing becomes noisy. The model scans a wall of one-line descriptions and struggles to pick the right match. Production systems use embedding-based semantic routers: embed the user's task description, compare against skill description embeddings, load the top-1 or top-3 matches. Measured result: 456x token reduction versus naive full-load, with comparable routing accuracy. The implementation is straightforward — a vector store over skill descriptions, queried once at the start of each turn before the LLM sees anything.
3. Hierarchical namespacing. Superpowers-style plugins group skills by workflow phase: brainstorming → planning → implementation → review. The agent only considers skills within the current phase — a form of logit masking applied to skill selection. This mirrors Manus's approach from §5.3: the full catalog stays available (preserving cache), but the active subset is constrained by the current workflow state.
4. Frontmatter as routing signal. SKILL.md files declare activation conditions in YAML frontmatter — description, when, globs, alwaysApply. The harness uses these as cheap routing signals before committing to a full load. A skill with globs: ["**/*.py"] only activates when the agent is working on Python files. A skill with when: "user asks about deployment" activates on semantic match against the task. These structured signals cost nearly zero tokens at routing time and prevent unnecessary Level 2 loads.
The rule of thumb mirrors tools: if your skill registry exceeds 15% of the context window at Level 1 (names + descriptions alone), you need routing. Below that threshold, the overhead is acceptable and the simplicity of loading the full manifest outweighs the complexity of a routing layer.
The structural parallel to tools is no accident. Skills and tools are both capabilities the agent can invoke; they differ only in what they deliver (instructions vs. execution). The same information-theoretic constraint applies: the model's attention is finite, and anything in the context window that isn't relevant to the current task is noise that degrades performance. Progressive disclosure, semantic routing, and state-based filtering are general solutions to "too many capabilities in the hot path" — whether those capabilities are tool schemas or skill instructions.
5.7 MCP and the Tool Explosion
One implication of the math above is worth naming: MCP makes this problem worse before it makes it better.
The Model Context Protocol solves a real problem — giving agents a standard way to discover and call tools from third-party systems — but the natural consequence is more tools. A team that used to have 8 built-in tools now has 8 built-in tools plus a GitHub MCP (30 tools) plus a Jira MCP (23 tools) plus a database MCP (15 tools) plus a Slack MCP (10 tools). That's 86 tools, trivially reachable, each consuming ~850 tokens, for a base tool-definition cost of ~73K tokens — before anyone has typed a word.
This isn't a reason to avoid MCP; it's a reason to pair MCP with one of the four approaches in this chapter. The ecosystem is now large enough that "connect every relevant MCP server" is a choice that has to be made deliberately, with the token and accuracy implications in mind, and accompanied by a strategy for keeping definitions out of the hot path.
A later chapter in this book goes deeper into MCP specifically — its design goals, its trade-offs, and how to reason about it when you're the one designing an MCP server. For this chapter, the takeaway is that MCP amplifies the tool-definition tax, and the techniques here are how production systems keep that tax from dominating the budget.
5.8 Summary
Tool definitions are static overhead that the model pays on every inference call, whether it uses the tools or not. At typical scales — 40 tools, three MCP servers, ~34K tokens per call — they can consume a third to a half of the context window and drag tool-selection accuracy below 50%.
Four production approaches address this:
- Tool search with
defer_loadingkeeps tool schemas out of the prompt until the model discovers them via a search tool. ~85% reduction in tool-definition tokens. - File-based tool descriptions move schemas onto disk and leave only names in the prompt. Cursor measured ~47% total token reduction. Enables live status tracking.
- Logit masking keeps tools defined (preserving cache) and restricts what the model can call on a given turn. The right answer for dynamic, state-dependent tool availability.
- Programmatic tool calling collapses multi-step chains into sandboxed code blocks so intermediate results never enter the context. ~37% latency reduction on repetitive chains.
The right choice depends on how your tool set is structured. Small and static: cache and move on. Large and static: tool search. Dynamic by workflow state: masking. Chains with bulky intermediates: code mode. Many production systems combine two or more.
Underneath all four is the same insight from Chapter 4's cache discussion: the static layer is most valuable when it stays small, stays stable, and earns every token it occupies. Tool definitions, being the largest part of that static layer in most agents, are where the biggest wins live.
Chapter 6: Retrieval — Pulling Context In Just in Time
"If the retrieval returns more than you can show the model in focus, you have a retrieval quality problem, not a context size problem." — Anthropic Engineering
6.1 The Framing: Retrieval as Context Selection
Retrieval is often filed away as an architectural pattern — "use a vector database" — and discussed in isolation from the rest of the agent's design. In a context-engineering book, it belongs in a different drawer. Retrieval is the decision about which external knowledge to put in the window, and when.
Said more sharply: retrieval is selection plus just-in-time loading. The question isn't "how do I build a RAG pipeline?" It's "at this moment in this agent's loop, with this task, what's the smallest set of tokens from outside the context that would most help the next step?"
Framed that way, almost everything in this book is a retrieval decision in some form. The system prompt is a pre-retrieval; it's the context you decided belonged in every call. Project memory is a coarse retrieval scoped to the session. Tool outputs are a micro-retrieval triggered by the model. What's typically called "retrieval" — pulling snippets from a knowledge base or codebase index — is the general case: the agent asks, the system selects, the tokens enter the window.
The principle that unifies all of them: don't front-load what you can fetch later. Pre-loading is the default instinct, and the wrong one. Every token in the window costs attention, and attention is scarce in ways context length is not.
6.2 Why Long Context Doesn't Replace Retrieval
Every time a provider announces a bigger context window, someone declares RAG obsolete. The production data says otherwise.
Anthropic measured a 15% drop on SWE-bench when Claude used its full 1M-token window instead of managed compaction and retrieval. The benchmark is specifically designed to require reading a lot of source code, the kind of task that ought to favor longer context, and the drop is real.
The math is equally brutal on cost. Filling a 200K-token window at $3/MTok input costs $0.60 per request. Over a 50-request session, that's $30 in input alone. Focused retrieval with a 5K-token payload costs $0.015 per request — $0.75 for the same session. A 40× cost reduction, with better accuracy.
The cause is attention dilution. Longer context doesn't improve the model's ability to focus on the relevant tokens; it just provides more tokens for the model's attention to spread across. A 5K-token focused RAG result outperforms a 200K-token context dump, even though the dump contains the 5K tokens the model needed plus 195K of potentially-relevant surrounding material. The model does not reliably zero in on the right passage in the dump. It attends, diluted, to all of it.
Retrieval is not a workaround for small context windows. It is a quality optimization at every context size, and a cost optimization at every scale.
6.3 Production Retrieval for Coding Agents
Generic RAG tutorials show up in every model-serving library: embed documents, store in a vector DB, query on user input, inject top-k. The production systems for coding agents look nothing like this.
Cursor's semantic codebase index
Cursor's codebase retrieval is the most mature production RAG system for coding agents. The engineering decisions are worth studying individually.
Merkle tree-based change detection. Rather than re-embed the entire codebase on every change, Cursor uses a Merkle tree to track which files have changed since the last index. Only changed files get re-embedded. In a 50,000-file monorepo where a typical commit touches five files, the system re-embeds five files instead of 50,000.
Simhash-based index reuse across branches and teammates. Most of a codebase is identical across branches and between developers on the same project. Cursor uses simhash (a locality-sensitive hash) to detect that a new branch's index is ~98% identical to an existing index, and it reuses the matching portions. The measured effect on end-user latency:
| Metric | Without reuse | With reuse |
|---|---|---|
| Time-to-first-query (median) | 7.87 seconds | 525 milliseconds |
| Time-to-first-query (p99) | 4.03 hours | 21 seconds |
A p99 of 4 hours means that, for the worst-case user on a very large repo, a fresh index used to take half a workday to complete. With index reuse, it takes 21 seconds. This is the difference between a product that some users actively avoid and a product that's always ready to query.
Content proofs for security. Cursor's cross-teammate index reuse raises a real concern: could file contents leak between users of the same repo? Cursor addresses this with cryptographic content hashes. The server holds embeddings keyed by content hash, not by path or user identity. A request returns embeddings only for hashes the client can prove it has the source content for. The mechanism means the server never reveals content a client doesn't already have locally.
Hybrid signals beyond semantic similarity. Pure embedding search on code returns too many false positives — code about "authentication" and "authorization" cluster close enough that the signal is noisy. Cursor's retrieval combines:
- Semantic search (embedding similarity against the index).
- Recency (recently opened/edited files get a boost).
- Import-graph proximity (files that import or are imported by the file under edit rank higher).
- Path matching (queries mentioning "auth" boost files with "auth" in their path).
- Live linter/type errors related to the edit (relevant files get pulled automatically).
The combination is what makes the results high-precision. Any single signal, alone, has too many false positives at code-search scale.
The interaction layer. Cursor exposes retrieval to the agent through two complementary primitives:
@codebase— "figure out what's relevant from the index and inject it." The agent decides when to ask, the index decides what to return.@file path/to/x.ts— "I know exactly what I need; pin this specific file." A precise override for when the agent (or user) knows more than the index.
The distinction is useful. The index is a statistical guess; sometimes the user has ground truth. Both should be available.
Devin's DeepWiki
Cognition takes a different tack with DeepWiki: pre-generate comprehensive documentation for a repository and serve it as a retrieval source. When Devin starts working on a codebase, it can pull in DeepWiki documentation that explains architecture, key modules, conventions, and patterns — without reading every file.
This inverts the classic RAG flow. Instead of query → embed → search → retrieve chunks, it's pre-process → generate docs → load relevant sections. The advantage: generated documentation is already coherent, summarized, and organized by topic. Raw code chunks from embedding search often lack surrounding context; a DeepWiki article about the auth module includes the framing the model needs to understand it.
DeepWiki is also available as an MCP server, which means other agents (Claude Code, Cursor, Codex) can consume the same generated knowledge base through a standard interface. A pre-generated documentation layer becomes a shared retrieval source across tools.
OpenClaw's QMD — BM25 over the workspace
OpenClaw (an open-source Claude Code alternative) ships QMD: a BM25 keyword search over the workspace that runs in sub-second time with zero ML infrastructure. No embeddings, no vector DB, no GPU. Standard BM25 indexing over all markdown files, re-indexed on change.
Why BM25 works well here: technical documentation uses consistent terminology. When the agent is debugging an "authentication timeout," searching for "authentication timeout" in BM25 finds the exact doc on auth timeout configuration. Semantic search, on the same query, often also returns docs about "session expiry" and "token refresh" — semantically related, less relevant. For structured documentation where language is stable, keyword search outperforms embeddings and comes with a fraction of the infrastructure burden.
QMD is the existence proof that small projects don't need embeddings to get useful retrieval. For teams starting out, it's usually the right first system to stand up.
6.4 The Production Principle: Retrieve What You Need, When You Need It
The thread running through all three systems — Cursor, Devin, OpenClaw — is the same. None of them retrieves on every query. The retrieval runs when the agent asks, or when the task is of a kind that benefits from it, and not otherwise.
Contrast this with naive static RAG: embed the user query, run a top-k search, inject the results, every time. The naive version gets you two kinds of bad outcomes:
- For simple queries where no retrieval is needed ("rename this variable"), you've wasted tokens on irrelevant snippets that may actively confuse the agent.
- For complex queries, one retrieval is rarely enough; real tasks unfold across multiple searches as the agent's understanding develops.
Production retrieval is agentic: the agent calls retrieval when it needs to, shapes the query to the current sub-problem, and re-retrieves as its understanding of the task evolves. The retrieval system is a tool the agent uses, not an automatic preprocessor that runs on every turn.
6.5 Retrieval Decisions the Context Engineer Owns
Every retrieval system embeds a set of decisions. Making these explicit is most of the design work.
flowchart TD
Q[User query or agent step] --> D1{Query complexity?}
D1 -->|Simple / factual| Z1[Direct LLM, no retrieval]
D1 -->|Needs external data| D2{Knowledge source type?}
D2 -->|Codebase| R1[Semantic + keyword<br/>over repo index]
D2 -->|Documents| R2[Vector search<br/>+ metadata filter]
D2 -->|Multiple sources| R3[Route to appropriate source]
R1 --> RR[Retrieve top 20]
R2 --> RR
R3 --> RR
RR --> RK[Rerank → keep top 3-5]
RK --> C{Grade relevance?}
C -->|Relevant| INJ[Inject into context]
C -->|Irrelevant| RQ[Rewrite query or fall through]
RQ --> RR
style Z1 fill:#dcfce7
style INJ fill:#dcfce7
A retrieval decision flow. Most production systems skip retrieval entirely for simple queries, rerank after an initial wide net, and include a relevance grading step.
When to retrieve
Three patterns, from heaviest to lightest:
- On every query (naive RAG). Embed user input, retrieve, inject. Simple, and usually wrong for agents. The right answer for single-turn Q&A bots; the wrong answer for multi-turn agents that build up context themselves.
- On agent-decision (agentic retrieval). The agent is given retrieval as a tool and calls it when it needs to. This is what Cursor, Devin, and Claude Code do in practice. It requires the agent to know when retrieval would help — which is where good tool descriptions and examples in the system prompt earn their keep.
- Routed (conditional retrieval). A lightweight classifier or heuristic decides whether retrieval runs at all. "Rename variable" → skip. "Where is X implemented?" → retrieve. This is a cost optimization for systems handling high query volume; it's usually overkill for interactive coding agents.
What to retrieve over
- Vector-only. Embed everything, search by cosine similarity. Good for prose and unstructured documents, noisy for code and structured docs.
- Keyword-only (BM25). Fast, cheap, great for terminology-heavy content. Misses paraphrased queries.
- Hybrid (vector + keyword, with reciprocal rank fusion). The production default. Catches both semantic similarity and exact-term matches.
For coding agents specifically, hybrid with code-aware signals (imports, recency, path) is the consensus winning combination. Pure vector search is rarely enough on its own for code.
How much to retrieve
top_k is a three-way trade-off: precision (small k), recall (large k), and tokens (small k). Production defaults:
- Over-retrieve to 20 candidates.
- Rerank with a cross-encoder.
- Keep the top 5 after rerank.
The reranker step adds ~80ms of CPU latency and buys 15–20% accuracy. On almost every measured task, it's worth it. The cross-encoder sees pairs (query, candidate) and scores them jointly, which catches relevance signals that the independent-embedding stage misses.
Rerank choices
Cross-encoder reranking is dominant in production. Candidates include bge-reranker-v2, Cohere Rerank 3, and several open-source options. The specific model matters less than the pattern: don't ship top-k-out-of-embeddings directly to the model; run a cheaper reranker first.
6.6 Chunking (Condensed)
Chunking is a well-covered topic; here's the production baseline without detour.
For prose documents: 200–400 tokens per chunk with 50-token overlap. Recursive splitting on natural boundaries (paragraph → sentence → word) beats fixed-size splitting. The LangChain RecursiveCharacterTextSplitter is a reasonable default:
from langchain.text_splitter import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=400,
chunk_overlap=50,
separators=["\n\n", "\n", ". ", ", ", " ", ""],
)
For code: split on structural boundaries (function, class, block) using a parser like tree-sitter. A code chunk that ends halfway through a function body is almost always worse than one that ends at a function boundary even if the latter is 600 tokens instead of 400. The structural cut preserves meaning.
Metadata per chunk: file path, language, line range. The agent uses this both to cite evidence and to decide whether a chunk is from an area it cares about.
The 200–400 / 50 sweet spot is empirical, not derived. Below 200 you lose local context ("what is this function for?"); above 400 you dilute relevance ("this chunk contains two unrelated functions, one is relevant"). It drifts a bit with embedding model choice, but the band holds across most production setups.
6.7 Dynamic Retrieval in Agent Loops
The "don't front-load" principle applied to agent design: the system prompt contains a catalog of retrievable sources, not the sources themselves. The agent decides per-step what to pull.
A minimal catalog at the top of a system prompt:
## Knowledge sources
- Codebase index (call `search_codebase("query")` or `@codebase`)
- DeepWiki (call `deepwiki("module_name")` for auto-generated docs)
- Internal docs (BM25 over `docs/*.md`; call `search_docs("query")`)
- Issue history (call `search_issues("query")` for past bugs and fixes)
Retrieve when you're about to make a decision that requires knowledge
you don't already have in the conversation. Prefer one focused query
over several broad ones. If the results aren't what you expected,
refine the query rather than retrieving more.
Tokens: ~100. The catalog announces capability without consuming the capability's content.
At retrieval time, two patterns for where the results go:
-
Direct inject into context with clear boundaries. The retrieved snippet becomes part of the assistant turn's input with an explicit header:
<retrieved_from=docs/auth.md lines=45-80>...</retrieved_from>. The boundaries help the model treat the content as reference material, not as its own prior turn. -
Write to working memory (a scratchpad file), then reference. For large results (multi-file search, a long article), write the raw output to a file and put a pointer plus a brief summary in context. The agent can re-read the file when it needs more detail. This is the Manus/Claude Code pattern of using the filesystem as an overflow zone.
Which pattern to use is a size question. Under ~2K tokens: direct inject. Above ~5K: scratchpad. Between those: your call, lean toward direct inject unless you expect to re-reference multiple times in the same session.
6.8 The Failure Mode: Retrieve Everything Relevant
The most common production bug in RAG systems isn't low recall. It's too-high recall: retrieving 20 chunks that are all kind of relevant, injecting the whole batch, and letting the model sort them out. This does not work.
Anthropic's guidance frames it bluntly: "If the retrieval returns more than you can show the model in focus, you have a retrieval quality problem, not a context size problem."
Symptoms of this failure mode:
- Retrieval hit rates look fine (the relevant chunk is in the top-k) but end-to-end task accuracy is low.
- The model's response references irrelevant chunks or mixes information across chunks incorrectly.
- Increasing top-k makes things worse, not better.
The fix is rarely more context window. It's better ranking (cross-encoder rerank), better queries (let the agent refine), better signals (hybrid search, structural features for code), or a tighter top-k. "Retrieve less, retrieve better" is the path; "retrieve more and hope" is the trap.
6.9 Agentic RAG Patterns (Condensed)
Three named patterns keep appearing in production systems built on agent frameworks (LangGraph, LlamaIndex, custom harnesses). They're worth knowing by name; the details are well-covered elsewhere.
Corrective RAG (CRAG). After retrieval, grade the results. If confidence is low, rewrite the query and retry. If it's still low, fall back to a broader source (web search) or admit uncertainty. The grading step is usually a lightweight LLM call or a scoring model.
query → retrieve → grade
│
┌──────────┴──────────┐
│ │
ok │ │ low
▼ ▼
generate rewrite query → retry
Self-RAG. The agent retrieves, generates, and self-evaluates ("is this answer well-supported by the retrieved context?"). If not, retrieve again with a refined query. This is a more LLM-heavy pattern — each self-evaluation is another call — but it's well-suited to tasks where hallucination is the primary risk.
Adaptive RAG. A router classifies the query into "simple" (direct answer, no retrieval), "standard" (one retrieval pass), or "complex" (multi-step retrieval with refinement). Matches retrieval cost to query difficulty.
LangGraph's documentation contains a minimal pattern for CRAG that's representative:
def should_retry(state):
if state["retrieval_grade"] == "low":
return "rewrite_and_retry"
return "generate"
graph.add_conditional_edges(
"grade_retrieval",
should_retry,
{
"rewrite_and_retry": "rewrite_query",
"generate": "generate_answer",
},
)
graph.add_edge("rewrite_query", "retrieve")
These patterns share a common shape: retrieval is a node in a loop, not a step in a pipeline. The agent can go around more than once, refining its query as it learns what the first pass missed. That's the whole point of making retrieval agentic in the first place.
6.10 When Not to Use Retrieval
Retrieval is not always the answer. Three cases where direct injection or just caching beats retrieval:
1. The context fits comfortably and rarely changes. If you have a 3K-token style guide that's relevant on most turns, don't build a retrieval system for it. Put it in the static layer and let the KV-cache handle it. The cost of setting up retrieval (infrastructure, tuning, failure modes) is worse than the cost of always loading a small, stable document.
2. The task-specific context is already loaded. If the agent is in the middle of editing auth.ts and has already pulled the file into context, don't re-retrieve chunks of auth.ts from a vector index. Re-retrieving what you already have is a quiet but common waste of tokens.
3. One-shot queries where the answer is obvious. "What's the capital of France?" doesn't need retrieval. Routing simple queries around retrieval saves cost and latency without losing accuracy.
The symmetric failure — not using retrieval when you should — tends to announce itself as the agent guessing or hallucinating. The failure of using retrieval when you shouldn't is quieter: it slows the agent down, adds a turn, and pollutes the context with irrelevant snippets. That's the one worth guarding against explicitly.
6.11 Summary
Retrieval is a context engineering technique, not an architectural pattern you bolt on. The core decision is: which tokens from outside the window would most help the next step, and when? Every answer to that question is a retrieval — from the system prompt (pre-retrieval at design time) to @codebase (retrieval at decision time) to reading a file from the filesystem (retrieval at tool-call time).
Production systems — Cursor's Merkle-tree index, Devin's DeepWiki, OpenClaw's BM25 QMD — share three properties:
- They don't retrieve on every query. The agent decides.
- They combine signals. Semantic embeddings alone underperform; recency, import graphs, and keyword matches fill the gap.
- They optimize for small, focused results. A 5K-token retrieval that's right beats a 200K-token dump that contains the right thing somewhere.
The decisions the context engineer owns: when to retrieve (agent-driven beats on-every-query), what to retrieve over (hybrid beats vector-only), how much (top-5 after reranking top-20), and what rank (cross-encoders buy 15–20% accuracy). Chunk size 200–400 tokens with 50-token overlap is the production sweet spot; code should be split on structural boundaries, not token counts.
The failure mode to avoid: retrieving everything plausibly relevant and trusting the model to sort it out. If the retrieval returns more than the model can focus on, you have a retrieval quality problem, not a context size problem. The answer is not a bigger window.
Chapter 7 picks up the thread from a different angle — how the tokens you've carefully decided to include actually get priced, cached, and reused across turns. Retrieval puts tokens in the window; caching decides how much they cost.
Chapter 7: Structuring Context for the Cache
"If I had to choose just one metric, I'd argue that the KV-cache hit rate is the single most important metric for a production-stage AI agent." — Yichao 'Peak' Ji, Manus
Context engineering decides which tokens enter the window. But a second question follows immediately: in what order? The order is not a stylistic choice. It determines whether the provider's KV-cache can reuse prior computation or has to recompute it from scratch. At production scale, that choice dominates your cost and latency curves.
This chapter is about arranging tokens so the cache survives. We will not cover tool execution, orchestration plumbing, or sandboxing. The scope is narrower: given some corpus of tokens you have decided to send, how should you lay them out so the provider's prefix cache pays you back?
7.1 Why Cache Hit Rate Is the #1 Production Metric
Every LLM inference has two phases. Prefill processes the input tokens to build the internal key-value tensors. Decode generates output tokens one at a time, attending to the KV tensors from prefill. Prefill is compute-bound and scales with input length. Decode is memory-bandwidth-bound and scales with output length. For any reasonable context, prefill dominates both cost and latency.
Prompt caching stores prefill KV tensors and reuses them whenever the exact same token prefix appears in a later request. A single token difference at position N invalidates the cache from position N forward. Everything before N is a cache hit; everything after N must be recomputed.
In agent workloads, the economics are brutal:
- Manus: 100:1 input-to-output ratio in production. For every output token, 100 input tokens are processed.
- Anthropic pricing: cached-read tokens cost 10% of standard input price (a 90% savings). Cache-write tokens cost 125% (a 25% premium).
- OpenAI pricing: automatic prefix caching above 1024 tokens, 50% discount on the cached portion. No markup for writes.
- Latency: an arXiv 2026 evaluation across three providers measured 13–31% TTFT improvement with cache-aware layout. Anthropic's own marketing materials cite up to 85% TTFT reduction on long prefixes.
At 100:1 input-to-output ratio, optimizing output tokens buys you almost nothing. Optimizing input tokens — specifically, getting as many of them served from cache as possible — is the single highest-leverage intervention in production agent design.
7.2 The Fundamental Rule: Stable Prefix First, Dynamic Content Last
The rule is mechanical. Caching works on prefixes. A prefix is a contiguous run of tokens starting from position zero. If the first 30,000 tokens of your request are byte-identical to the first 30,000 tokens of a prior request within the cache TTL, those 30,000 tokens are a cache read. If token 29,999 differs, the cache read stops at 29,998 and everything afterward is a cache write.
This forces an unambiguous layout:
flowchart LR
subgraph Layout["Cache-optimal context layout"]
direction LR
A["System prompt<br/>🔒 stable<br/>1h cache"] --> B["Tool definitions<br/>🔒 stable<br/>1h cache"]
B --> C["Session summary<br/>🔄 slow-changing<br/>5min cache"]
C --> D["Conversation history<br/>📈 growing<br/>no cache"]
D --> E["Current input<br/>⚡ dynamic<br/>never cached"]
end
style A fill:#dbeafe
style B fill:#dbeafe
style C fill:#fef3c7
style D fill:#fed7aa
style E fill:#fecaca
Stability decreases left-to-right. Anything before a changed token invalidates the cache from that point onward — so order by stability.
┌───────────────────────────────────────────────────────────────┐
│ CACHE-OPTIMIZED PROMPT LAYOUT │
│ │
│ Position 0 Position N Position M │
│ ▼ ▼ ▼ │
│ ┌────────────────┐ ┌──────────────────┐ ┌──────────────┐ │
│ │ Layer A: │ │ Layer B: │ │ Layer C: │ │
│ │ System prompt │ │ Session context │ │ Conversation │ │
│ │ + tool defs │ │ + CLAUDE.md │ │ + current │ │
│ │ (IMMUTABLE) │ │ (SLOW-CHANGING) │ │ message │ │
│ │ │ │ │ │ (DYNAMIC) │ │
│ │ TTL: 1 hour │ │ TTL: 5 minutes │ │ Not cached │ │
│ │ Hit rate: 99%+ │ │ Hit rate: 70–85% │ │ Hit rate: 0% │ │
│ └────────────────┘ └──────────────────┘ └──────────────┘ │
│ │
│ ◀──── ALWAYS CACHED ────▶◀── OFTEN CACHED ──▶◀── NEVER ──▶ │
└───────────────────────────────────────────────────────────────┘
Everything that almost never changes goes at the front. Everything that changes every turn goes at the back. Everything in between is layered by change rate. The reason is not aesthetic — it is that the cache only works on prefixes.
Violations are common and expensive. A timestamp in the system prompt nukes the cache on every request. A tool definition inserted between the system prompt and conversation invalidates the cache for all downstream turns. Reordering two middleware instructions in your project memory invalidates the cache from that point forward. At Manus's 100:1 ratio, one careless template change can double your monthly inference bill without changing a single behavior.
7.3 The Hierarchical Context Architecture for 24/7 Agents
For agents that run continuously — customer support, coding copilots, research assistants — a three-tier architecture is the durable pattern:
flowchart TB
subgraph A["Layer A — Immutable (1h cache)"]
a1[System prompt]
a2[Tool definitions]
end
subgraph B["Layer B — Slow-changing (5min cache)"]
b1[User profile]
b2[Session summary]
end
subgraph C["Layer C — Growing (uncached)"]
c1[Recent turns]
c2[Current input]
end
A --> B
B --> C
style A fill:#dbeafe,stroke:#2563eb
style B fill:#fef3c7,stroke:#ca8a04
style C fill:#fecaca,stroke:#dc2626
Three cache-lifetime layers. Layer A amortizes across the entire session; Layer B across turns; Layer C is per-request. Target 70–80% hit rate on A+B combined.
Layer A: Immutable (1h cache) system prompt, tool definitions
Layer B: Slow-changing (5min) session context, project summary, CLAUDE.md
Layer C: Growing (no cache) conversation, tool results, current input
Layer A — Immutable. The agent's identity, its behavioral rules, its full tool schema. This content changes on deployment, not on request. Target cache hit rate: 99%+. For Anthropic, mark this explicitly with the 1-hour extended TTL so it survives idle windows.
Layer B — Slow-changing. Per-session context: the user's profile, the project's CLAUDE.md, a compressed summary of the last 50 turns. This changes over the life of a session but not within a turn. Target cache hit rate: 70–85%. Use the default 5-minute TTL, which auto-refreshes on each hit.
Layer C — Growing. The current conversation, the current tool result, the user's current message. This changes every turn by definition. Do not attempt to cache it — the cache-write premium will cost you more than it saves.
The architecture has a practical side effect: it forces discipline about where any given piece of context lives. If you're tempted to put "today's date" in the system prompt, this architecture tells you the right answer is to move it into Layer C (where dynamic content lives) instead.
7.4 Manus's Three KV-Cache Rules
Manus designed their agent loop around cache preservation and distilled the discipline into three concrete rules. Each one corresponds to a common anti-pattern that production codebases drift into.
Rule 1: Stable Prefix — No Timestamps, No Session IDs, No Nonces
The system prompt must be byte-identical across requests. This sounds obvious until you audit a real codebase and find a dozen subtle violations.
# BAD — cache invalidated every single request
system_prompt = f"""You are an assistant. Current time: {datetime.now()}.
Session ID: {uuid4()}. User: {user_name}.
Conversation started at: {session_start.isoformat()}."""
# GOOD — identical prefix every request
system_prompt = """You are an assistant specializing in backend engineering.
You follow these conventions:
- Result<T, E> pattern for error handling
- Repository pattern for database access
- Zod schemas for input validation"""
# Dynamic data goes in the conversation, not the system prompt
messages = [
{"role": "system", "content": system_prompt}, # CACHED
{"role": "user", "content": (
f"[Context: user={user_name}, "
f"session started {datetime.now().isoformat()}]\n\n"
"Fix the race condition."
)}, # NOT cached — that's fine, this was always going to change
]
The datetime.now() call in the original prompt was probably a well-meaning debugging aid. It also produced a 0% cache hit rate. The fix is not to remove the timestamp — it's to move it into Layer C where it belongs.
Rule 2: Append-Only — Never Insert in the Middle
New context goes at the end. Never in the middle.
# BAD — inserting a new system message at position 2 invalidates
# the cache for every message after position 2
messages = [
system_prompt, # position 0 — cached
user_message_1, # position 1 — cached
NEW_CONTEXT_INJECTION, # position 2 — BREAKS CACHE from here forward
assistant_response_1, # position 3 — cache invalidated
user_message_2, # position 4 — cache invalidated
]
# GOOD — append new context at the end
messages = [
system_prompt, # position 0 — cached
user_message_1, # position 1 — cached
assistant_response_1, # position 2 — cached
user_message_2, # position 3 — cached
{"role": "user", "content": (
f"[Additional context: {new_info}]\n\n{current_query}"
)},
]
This rule has one counterintuitive implication: it's better to accept some redundancy at the tail than to reorganize the middle. A cleaner-looking message array that reorders two earlier messages will invalidate far more cache than duplicating a note at the end.
Rule 3: Deterministic Serialization — Same JSON Key Order Every Time
Many tool schemas and message payloads serialize as JSON. Python dictionaries preserve insertion order, but different code paths may construct the same logical object with different key orders. The two byte strings look different to the cache:
import json
# BAD — same logical tool, different byte serialization
tool_v1 = {"name": "search", "description": "Search code", "parameters": {...}}
tool_v2 = {"description": "Search code", "name": "search", "parameters": {...}}
json.dumps(tool_v1) != json.dumps(tool_v2) # cache invalidated!
# GOOD — sort keys deterministically
def serialize_tools(tools: list[dict]) -> str:
return json.dumps(tools, sort_keys=True, separators=(",", ":"))
# Better — define tools with a schema that always serializes in the same order
from pydantic import BaseModel
class ToolDefinition(BaseModel):
model_config = {"json_schema_serialization_defaults_required": True}
name: str
description: str
parameters: dict
The same hazard appears for parameter defaults, whitespace, trailing commas, and Unicode normalization. Any non-determinism in serialization translates directly into cache misses. Pick one serialization function, use it everywhere, and add a test that compares its output across runs.
7.5 Provider-Specific Caching APIs
The three major providers expose prompt caching differently. The same cache-first layout applies to all of them — only the explicit markup and pricing differ.
Anthropic: Explicit Cache Control
Anthropic gives you explicit control over cache breakpoints. You can place up to 4 breakpoints per request. Each breakpoint tells the provider "cache everything from the start of the request up to this point." Default TTL is 5 minutes (auto-refreshed on hit); extended TTL is 1 hour.
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
system=[
{
"type": "text",
"text": SYSTEM_PROMPT, # Layer A
"cache_control": {"type": "ephemeral", "ttl": "1h"},
},
],
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": SESSION_CONTEXT, # Layer B
"cache_control": {"type": "ephemeral"}, # default 5min
},
],
},
{"role": "assistant", "content": "Session context loaded."},
# Layer C: no cache_control, changes every turn
{"role": "user", "content": current_query},
],
)
usage = response.usage
print(f"Input tokens: {usage.input_tokens}")
print(f"Cache read tokens: {usage.cache_read_input_tokens}")
print(f"Cache creation tokens: {usage.cache_creation_input_tokens}")
Anthropic cache economics:
| Feature | Detail |
|---|---|
| Cache breakpoints | Up to 4 per request |
| Default TTL | 5 minutes, auto-refreshed on hit |
| Extended TTL | 1 hour via "ttl": "1h" |
| Cached-read price | 10% of standard input price |
| Cache-write premium | 25% above standard input price |
| Minimum cacheable | 1024 tokens (system), 2048 tokens (other blocks) |
Break-even math. A cache write costs 1.25× and a cache read costs 0.1×. Break-even is at just 2 reads per write: 1.25 + 2(0.1) = 1.45 vs. 3(1.0) = 3.0. Any cached block read more than twice saves money.
OpenAI: Automatic Prefix Caching
OpenAI caches automatically. There is no markup, no explicit breakpoint, and no write premium. If the same prefix of ≥1024 tokens appears in a later request, the cached portion is billed at 50% of the standard input rate.
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": SYSTEM_PROMPT}, # >1024 tokens
{"role": "user", "content": current_query},
],
)
print(f"Cached tokens: {response.usage.prompt_tokens_details.cached_tokens}")
Caching is per-organization, granular to 128-token blocks, and typically survives a few minutes between reuses. You still need to structure your prompt to create long stable prefixes — the automatic caching only pays out if the prefix actually repeats. The rules from §7.4 apply unchanged.
Gemini: Explicit Context Caching API
Google's context caching is a different model. Instead of caching on the fly, you explicitly upload content and receive a cache ID. Subsequent requests reference the cache by ID. You pay a small storage cost per hour; the cached tokens themselves are effectively free at query time.
import google.generativeai as genai
import datetime
cache = genai.caching.CachedContent.create(
model="models/gemini-1.5-pro-002",
display_name="project_docs",
system_instruction="You are a senior engineer analyzing this codebase.",
contents=[
genai.types.ContentDict(
role="user",
parts=[genai.types.PartDict(text=large_document_text)],
),
],
ttl=datetime.timedelta(hours=1),
)
model = genai.GenerativeModel.from_cached_content(cached_content=cache)
response = model.generate_content("What auth patterns does this codebase use?")
This model is best for "chat with your docs" workloads: a single large document queried many times. Minimum cacheable content is 32K tokens. For most agent loops, Anthropic's or OpenAI's implicit/explicit per-request model is a better fit — you rarely have one giant static blob of context that doesn't need to change.
7.6 Compaction-Aware Cache Design
Compaction is covered in detail in Chapter 10. This section is narrow: how does compaction interact with the cache, and what layout choices preserve the cache when compaction fires?
The Claude Code source leak (v2.1.88) exposed the answer. When Claude Code performs a full summarization pass, the summarization call reuses the exact same system prompt, tools, and model as the main conversation. The compaction instruction is appended as a new user message at the tail of the message list — it does not replace or modify the prefix.
The experimental justification is in the leaked notes: using a different system prompt for summarization produced a 98% cache miss rate. With a 30–40K-token system prompt, that miss is a significant expense paid on every compaction. The fix is mechanical — the compaction call piggybacks on the main conversation's cached prefix, so the summarization model reads the full history as a cache hit and generates only the summary as new tokens.
sequenceDiagram
participant Agent
participant API as Anthropic API
participant Cache as KV Cache
Note over Cache: Main conversation builds up cache hit
Agent->>API: Request with stable prefix + history
API-->>Cache: Check prefix match
Cache-->>API: ✅ Cache hit on 150K tokens
API-->>Agent: Response
Note over Agent: Compaction triggered
Agent->>API: Compaction request (SAME system prompt, SAME tools)
API-->>Cache: Check prefix match
Cache-->>API: ✅ Cache hit preserved
API-->>Agent: Summarized context
Note over Agent: Different prompt would cause:
Agent--xAPI: ❌ Compaction with different system prompt
API--xCache: Cache miss — 98% of tokens re-processed
Claude Code's cache-aware compaction. Reusing the exact same system prompt, tools, and model preserves the cache. A different system prompt causes a 98% miss rate.
The same discipline applies when you implement your own compaction:
# BAD — custom summarization prompt breaks the cache
summary_response = client.messages.create(
model=MAIN_MODEL,
system="You are a summarization engine. Produce a 9-section summary...",
messages=conversation, # different system prompt → cache miss
)
# GOOD — append the compaction instruction as a user message
summary_response = client.messages.create(
model=MAIN_MODEL,
system=[{
"type": "text",
"text": MAIN_SYSTEM_PROMPT, # identical to main conversation
"cache_control": {"type": "ephemeral", "ttl": "1h"},
}],
messages=[
*conversation,
{"role": "user", "content": COMPACTION_INSTRUCTION},
],
)
The compaction instruction now lives at the end of the message array, where it is a cache miss (new tokens) but everything before it is a cache hit (all cached). The overall cost of compaction drops dramatically.
A second implication: do not rewrite messages that are inside the cached prefix. If compaction wants to mutate a tool result that sits inside the cached range, use a provider mechanism that deletes by reference without touching the bytes (for Anthropic, this is the cache_edits mechanism described in Chapter 9). Rewriting an old tool result invalidates the cache from that position forward and defeats the whole design.
7.7 "Don't Break the Cache" — the arXiv 2601.06007 Finding
A January 2026 paper by Lumer et al. (arXiv 2601.06007) provided the first systematic evaluation of caching strategies for agentic tasks across OpenAI, Anthropic, and Gemini. They compared three strategies:
- Cache everything. Place breakpoints across the entire context, including tool results.
- Cache system prompt only. Breakpoints exclusively on system + tool definitions.
- Cache stable prefix + conversation, exclude dynamic tool results. The middle path.
| Metric | Strategy 1 | Strategy 2 | Strategy 3 |
|---|---|---|---|
| Cost reduction | 41–60% | 50–70% | 60–80% |
| TTFT improvement | 8–15% | 13–25% | 18–31% |
| Consistency | Low | High | Highest |
Strategy 3 wins on every metric. The headline result: 41–80% cost reduction and 13–31% TTFT improvement across providers, with the exact numbers depending on which strategy you pick.
The paradox is Strategy 1. Intuitively, caching more things should save more money. In practice, caching tool results increases latency because each turn's tool result is different — you pay the 25% write premium every turn, and the cache reads never hit. You're buying cache entries that are never reused.
The winning layout:
[ SYSTEM PROMPT ] cache breakpoint, 1h TTL ← Layer A
[ TOOL DEFINITIONS ] cache breakpoint, 1h TTL ← Layer A
[ CONVERSATION (old) ] cache breakpoint, 5min TTL ← Layer B
[ TOOL RESULTS ] no cache breakpoint ← Layer C
[ CURRENT TURN ] no cache breakpoint ← Layer C
Cache the stable prefix aggressively with long TTLs. Cache the slower-changing conversation portion with short TTLs. Never cache dynamic tool results — they're the part that changes every turn and will never be reused.
7.8 Monitoring Cache Performance
You cannot optimize what you don't measure. Every provider exposes cache counters in the response. A minimal monitoring wrapper is a few dozen lines:
from dataclasses import dataclass
@dataclass
class CacheMetrics:
total_input_tokens: int = 0
cached_tokens: int = 0
cache_write_tokens: int = 0
total_requests: int = 0
@property
def hit_rate(self) -> float:
if self.total_input_tokens == 0:
return 0.0
return self.cached_tokens / self.total_input_tokens
@property
def write_to_read_ratio(self) -> float:
if self.cached_tokens == 0:
return float("inf")
return self.cache_write_tokens / self.cached_tokens
def record(self, usage: dict) -> None:
self.total_input_tokens += usage.get("input_tokens", 0)
self.cached_tokens += usage.get("cache_read_input_tokens", 0)
self.cache_write_tokens += usage.get("cache_creation_input_tokens", 0)
self.total_requests += 1
Targets to alert on:
| Metric | Target | Red flag |
|---|---|---|
| Cache hit rate | >70–80% | <50% |
| Write-to-read ratio | <0.2 | >1.0 |
| Cache read tokens per request | stable | trending down |
A hit rate below 50% means the prefix is churning. Common causes: a timestamp crept into the system prompt; a tool definition was regenerated with different key order; the session context is being re-injected at a different position. Before tuning anything, dump a diff of the serialized prefix across two consecutive requests — the problem is almost always visible on inspection.
A write-to-read ratio above 1.0 means you're creating cache entries faster than you're using them. Either your TTL is too short for your traffic pattern, or you've placed a breakpoint on content that doesn't actually repeat.
7.9 When Caching Is Counterproductive
Caching is not a free lunch. Four scenarios where aggressive caching loses money:
Highly personalized prefix per user. If every user gets a unique system prompt (e.g., their full preference document injected verbatim), no two requests share a cacheable prefix. Each request pays the write premium and never gets a read. Fix: move per-user content into Layer B or C, keep Layer A truly global.
Very low traffic. If your requests come less frequently than the cache TTL, every request is a cold start. You pay the 25% write premium and the cache expires before the next request. For Anthropic with the default 5-minute TTL, you need at least one request every few minutes per user to benefit. Fix: use the 1-hour extended TTL, or accept the miss.
Frequent prefix changes. If you ship a new system prompt every day, every deployment invalidates the global cache. If your prompt is large and your traffic is spiky, the cache-rebuild cost on each deployment may exceed the savings in between. Fix: version the prompt, stagger deployments, or accept the one-time flush.
Tiny prompts. Below the provider's minimum cacheable size (1024 tokens for Anthropic/OpenAI, 32K for Gemini), the caching system doesn't engage at all. Fix: either leave caching off, or combine several small prompts into a single larger one if they genuinely share content.
7.10 Key Takeaways
-
Cache hit rate is the #1 production metric. Manus's 100:1 input-to-output ratio means cached input dominates cost. Design the layout first; tune everything else second.
-
Stable prefix first, dynamic content last. The cache works on prefixes. One changed token at position N invalidates everything after N. This is the single rule from which most production practice follows.
-
Three layers: immutable, slow-changing, growing. System prompt and tool definitions at the front (1h TTL). Session context and project memory in the middle (5min TTL). Conversation and current input at the tail (no cache).
-
Three rules from Manus. No timestamps, session IDs, or nonces in the prefix. Append-only — never insert in the middle. Deterministic serialization —
sort_keys=Trueeverywhere. -
Compaction-aware layout. Summarization must reuse the main system prompt and tools; append the compaction instruction as a new user message. A different system prompt yields a 98% miss rate at the scale of a 30–40K-token prefix.
-
Strategy 3 wins. Cache the stable prefix and conversation history. Do not cache dynamic tool results — caching them paradoxically increases latency because the write premium is paid every turn and the cache is never read.
-
Monitor continuously. Target >70% hit rate. Treat <50% as a red flag. The monitoring code is tiny — there is no excuse for flying blind on a metric that drives your inference bill.
-
Know when caching loses. Per-user prefixes, very low traffic, frequent prefix changes, tiny prompts. In these four cases, the write premium may exceed the read savings. Measure before you assume caching helps.
Chapter 8: Structuring Context for Attention
Chapter 7 arranged tokens so the KV-cache could survive. This chapter arranges the same tokens so the model can actually read them. The two concerns interact — the cache-preserving layout has a strong overlap with the attention-preserving layout — but they are not identical. You can keep your cache hit rate at 90% and still produce a context window the model ignores.
The distinction matters because attention is not uniform. Models do not weight every token equally. Production observations, supported by the "lost in the middle" line of research, converge on a U-shaped attention curve: tokens near the start and end of the window receive more attention than tokens in the middle. The practical consequence is that where a token sits in the window is a property of that token, just as much as its content is.
8.1 The U-Shaped Attention Curve
Researchers have been reporting variants of this pattern since at least 2023. In practice, it looks like this:
Attention weight
▲
High │█ █
│██ ██
│███ ███
│████ ████
Med │ ████ ████
│ ████ ████
│ ████ ████
│ █████ █████
Low │ █████ █████
│ █████████████████████
│ middle
└────────────────────────────────────────►
0% 100%
beginning end
"primacy" "recency"
The shape is not a sharp cliff. Tokens in the middle still receive some attention, and the curve's depth varies by model, task, and context length. But the qualitative finding is robust across every frontier model we've seen tested: information at the beginning and end of the window gets more attention than information in the middle.
For context engineering, this shape dictates three practical rules:
- Put stable directives where primacy helps. System prompts, critical invariants, project conventions — these belong at the start of the window, which also happens to be where the cache-friendly layout puts them.
- Put the current task and its recent signals where recency helps. The user's current message and the last few tool results go at the tail of the window, where the model will actually attend to them.
- Treat the middle as a graveyard. Tokens in the middle of a long window are nominally present but practically invisible. Do not rely on a middle-of-window tool result to drive the next decision.
8.2 Primacy and Recency in Practice
Position in the context window is a first-class design parameter. A concrete layout split by attention zone:
Primacy zone (beginning):
- System prompt — role, behavioral rules, output format
- Tool definitions — so the model knows its capabilities
- Project conventions — the always-apply
CLAUDE.mdcontent or equivalent - Critical invariants — "never modify these files," "always run tests before committing"
Middle zone (middle of window):
- Reference material the model may consult but does not need every turn
- Older conversation history, compacted or partially cleared
- Background skill definitions that are relevant but not active
Recency zone (end):
- The current user message
- The last 2–5 tool results (the "hot tail," §8.7)
- The active task state — current file being edited, current subtask
- A recitation anchor (the
todo.mdpattern, §8.3)
The layout aligns with cache optimization: stable content at the front, dynamic content at the end. The two disciplines reinforce each other. But they answer different questions. Cache layout asks "what doesn't change?" Attention layout asks "what does the model need to see?"
8.3 Manus's todo.md Recitation Technique
Manus's public writeup reports an average of ~50 tool calls per task in production. That's 50 model turns, each with new tool results feeding into the context, each pushing the original task description further up into the primacy zone and — past a certain point — into the middle-of-window graveyard.
Their fix is mechanical: the agent maintains a todo.md file and re-reads it near the end of each turn's context. The file lives on disk. The recitation — inserting its current contents into the tail of the context window — is what does the work.
A production todo.md after 15 turns of a migration task:
# todo.md
## Original Objective
Migrate billing endpoints from Express to Fastify.
## Completed
- [x] /api/billing/invoices (commit abc123)
- [x] /api/billing/payments (commit def456)
- [x] Shared Zod schemas extracted to src/schemas/billing.ts
## In Progress
- [ ] /api/billing/subscriptions ← CURRENTLY WORKING ON THIS
- Route handler: 80% converted
- Zod schema: needs update for the new plan_tier field
- Integration test: still failing on line 42
## Blocked
- [ ] /api/billing/webhooks (waiting on Stripe SDK update)
## Rules for this task
- Never delete test files; convert them
- Keep the old route file until tests pass
- Coverage must stay at or above 85%
The agent updates the file at the start of each turn (new progress marker) and re-reads it at the end of the context before deciding the next action. The todo.md sits in the recency zone regardless of how much tool output has accumulated — the same bytes always occupy the tail position.
This is context engineering as attention manipulation. The bytes could be anywhere; putting them at the tail is the design decision. It costs one file read per turn. In exchange, the model's next action is grounded in the original objective rather than drifting toward whatever was most recent in the middle of the window.
The pattern generalizes. Any long-running agent benefits from a recitation anchor: a small, stable-format document that summarizes the objective, progress, and rules, and is read at the tail of each turn. Call it todo.md, PROGRESS.md, or PLAN.md — the format matters less than the discipline of re-reading it.
8.4 Structured Sections Beat Unstructured Prose
Anthropic's documentation is explicit on this point: use <xml_tags> or ## markdown headers to delineate sections of the prompt. The reason is attention, not aesthetics. Models are trained on enormous corpora of structured text — documentation, code with docstrings, HTML, Markdown. They learn to attend to structural markers. An <instructions> tag or a ## Rules header is a strong signal that the content inside matters.
An unstructured system prompt:
You are a backend engineer. Use Result types for error handling. Always
validate inputs with Zod. Follow the repository pattern for database
access. Never throw exceptions. Always write tests before code. Use pino
for structured logging. All API responses must include request IDs. Prefer
async/await over callbacks. If you encounter a type error never silence
it. The code must pass the linter. Migrations must be idempotent.
The model sees a wall of declarative statements and is forced to weight each one against the others. In long contexts, some of them effectively disappear.
The same content, structured:
## Role
You are a backend engineer on a Node.js + PostgreSQL codebase.
## Critical Invariants (do not violate)
- Never throw exceptions — use `Result<T, E>` instead
- Never silence type errors
- All migrations must be idempotent
## Required Patterns
- Input validation: Zod schemas
- Database access: repository pattern
- Logging: structured JSON via pino
- API responses: include request ID
## Conventions
- Async/await over callbacks
- Tests before code
- Pass lint before submitting
Same tokens, different structure, measurably different behavior. The ## Critical Invariants heading is an attention hook. The model is statistically more likely to notice that the rule "never throw exceptions" is in the invariants section, not the conventions section, and to treat it as a hard constraint rather than a preference.
This applies to tool results and conversation context as well. A tool result that starts with ## Error Output or <test_failures> carries a stronger attention signal than one that is dumped in as raw text. The Claude Code source leak shows tool results wrapped in structured markers by default — not for readability, but because the markers change how the model weights what it reads.
8.5 The Anti-Pattern: Context Noise
"Context noise" is the accumulation of unrelated, verbose, or stale content in the middle of the window that competes with the task-relevant content for attention. In long-running agents, noise comes from a small set of recurring sources:
- Verbose tool responses left inline. A
grepreturning 400 matches when the agent only needed one. Acatof a 2000-line file when only lines 100–120 were relevant. - Stale system reminders. Reminders that were relevant at turn 5 but are noise at turn 50.
- Duplicate context injections. The same
CLAUDE.mdre-injected twice because two code paths both thought they were responsible for it. - Intermediate reasoning left to accumulate.
thinkingblocks from prior turns that served their purpose but were never cleared. - Obsolete file content. A file that was read at turn 10 and modified at turn 20, with the stale version still sitting in the middle of the window.
The problem is not that these are impossible to ignore — the model can route around some of them. The problem is that each unit of noise is a unit of attention diluted away from the current task. Chroma Research's context rot work measured the cost: at long context lengths, the same model scores measurably worse on the same task when irrelevant content is added, even when the relevant content is still fully present.
Detection is mostly mechanical. A small audit script can check for obvious noise patterns:
def audit_context_noise(messages: list[dict]) -> list[str]:
warnings = []
seen_content = set()
for i, m in enumerate(messages):
content = str(m.get("content", ""))
if len(content) > 5000 and m.get("role") == "tool":
warnings.append(f"msg {i}: {len(content)} chars of tool output inline")
if content in seen_content:
warnings.append(f"msg {i}: duplicate content")
seen_content.add(content)
if "remind" in content.lower() and i < len(messages) - 5:
warnings.append(f"msg {i}: reminder still in context, {len(messages)-i} turns old")
return warnings
Remediation is covered in detail in Chapter 9 (clearing) and Chapter 10 (compaction). The point here is that noise is a context-engineering problem, not a model problem. You cannot prompt your way out of attention dilution caused by 40K tokens of irrelevant tool output. You have to remove the tokens.
8.6 Conversation History as Attention Management
A long conversation is itself a candidate for attention-aware layout. Not all turns are created equal. A useful three-tier split of conversation history:
Recent turns (last 2–3): Keep verbatim. These are what follow-up prompts refer to ("edit the second paragraph," "that function you just wrote"). They live in the recency zone and must be fully visible. The "never compact the previous turn" rule from Chapter 9 is the enforcement mechanism.
Middle turns (roughly turns 4–20 back): Candidates for summarization or clearing. The information they contain has either been superseded or captured in a later turn. A middle turn's tool result from 15 turns ago is almost certainly stale and is definitely in the attention graveyard. Clear it; re-fetch if needed.
Critical older turns: Preserve verbatim even if they're old. Specifically:
- User corrections ("no, actually, we use Postgres not MySQL")
- Explicit user preferences expressed early
- Architectural decisions with rationale
- Error root causes that prevent re-hitting the same dead end
Priority-based retention (covered in Chapter 9, §9.7) is the implementation pattern. For this chapter, the key point is that the decision of what to preserve is driven by attention, not by age alone. A turn is worth keeping if losing it would make the agent less effective, and worth discarding if keeping it dilutes attention without adding signal.
8.7 Tool Output Layout: The "Hot Tail" Pattern
Tool outputs are the largest and most ephemeral category of context content. In a typical agent session:
read_filereturns 500–50,000 tokensgrepreturns 500–20,000 tokensbashreturns 200–30,000 tokensweb_fetchreturns 2,000–50,000 tokens
A 50-turn session with a handful of large reads per turn is a few hundred thousand tokens of tool output alone. Most of it is obsolete by the next turn, and almost all of it is noise by turn 30.
Claude Code's source (v2.1.88 leak) documents the hot tail pattern: keep the last 5 tool results inline in the context; replace everything older with a reference. A cleared old tool result becomes something like:
[Old tool result cleared — read_file("src/billing.ts") at turn 8.
Re-run the tool if this information is needed.]
The hot tail sits in the recency zone, where the model needs it. The reference sits in the middle zone, where it costs almost nothing. The full content is still retrievable on demand — the tool can be called again — but it no longer occupies tokens the model is ignoring anyway.
A second, complementary pattern: summarize + link. When a tool returns a large output, write the full output to disk and put only a summary plus a pointer into the context:
[read_file("src/billing/stripe.ts")]
Lines: 842 total. Key symbols: StripeClient, handleWebhook, validateSignature,
retryPayment. Full file at /tmp/results_001.txt.
This pattern pushes the large content out of the window entirely. It is covered more fully in Chapter 6 (external memory) of the old book structure and does not need to be repeated here. The attention point is narrow: large outputs buried in the middle of the window are attention waste. Either keep them in the recency zone (hot tail) or push them out of the window (summarize + link). Leaving them in the middle is the worst choice.
8.8 A Context Layout Checklist
When you lay out a context window, walk through this list:
-
Is the task statement where it should be? If it's a stable directive (behavioral rule, project convention), it goes at the beginning — primacy zone, cache-friendly. If it's the current task, it goes at the end — recency zone, where the model will actually act on it.
-
Are critical constraints where the model will look? "Never modify production secrets" at turn 5 of a 40-turn conversation is effectively invisible. Critical constraints go in the system prompt (primacy zone) and, for long sessions, get restated in the recitation anchor (recency zone).
-
Is anything stale or irrelevant competing for attention? Old tool outputs, completed subtasks, duplicate injections, prior-turn
thinkingblocks. Each is an attention tax. Clear, compact, or move out of the window. -
Can any middle content be moved to the beginning or end — or removed? If a middle-of-window item is important, it belongs in primacy or recency. If it's not important, it belongs out of the window. The middle is the one place no important content should live.
-
Is the structure signaled? Section headers, XML tags, consistent formatting. If the model has to parse a wall of undifferentiated prose, it will attend unevenly and unpredictably.
-
Is there a recitation anchor? For long-running tasks (20+ turns), a
todo.mdor equivalent at the tail of the context is cheap insurance against attention drift. For short tasks, it may be overkill. -
Are tool outputs managed? The last 5 inline, everything older cleared or referenced. Large outputs should either be in the hot tail or pushed to disk.
The checklist is not a one-time design exercise. It runs every turn. An agent that starts with a clean layout at turn 1 and ignores attention hygiene by turn 30 is an agent whose behavior will degrade regardless of how capable the underlying model is.
8.9 Key Takeaways
-
Attention is U-shaped, not uniform. Tokens at the beginning and end of the window get more attention than tokens in the middle. Position is a property of a token, not an afterthought.
-
Primacy and recency drive layout. Stable directives go at the front (primacy). Current task and active state go at the tail (recency). The middle is the attention graveyard.
-
Recite an anchor. Manus's
todo.mdpattern — maintaining a small objective/progress file and reading it near the tail of each turn — keeps the model focused across long tool-call sequences. With 50 tool calls per task, this is not optional. -
Use structure, not prose. Section headers, XML tags, and consistent formatting are attention hooks. Walls of declarative text spread attention unpredictably; structured sections concentrate it.
-
Remove context noise. Verbose tool responses, stale reminders, duplicate injections, and obsolete file contents in the middle of the window all dilute attention. Noise is a context-engineering problem — solve it by removing the tokens, not by prompting harder.
-
Tier conversation history. Last 2–3 turns verbatim (primacy fallback). Middle turns summarized or cleared. Critical older turns (corrections, decisions, user preferences) preserved verbatim regardless of age.
-
Hot tail for tool outputs. Keep the last 5 tool results inline. Clear or reference everything older. Large outputs either occupy the recency zone or get pushed out of the window — never buried in the middle.
-
Run the checklist every turn, not just at design time. Attention hygiene is not a one-shot layout decision. It is an ongoing obligation of the agent loop.
Chapter 9: Clearing — Surgical Context Removal
"Context editing gives you fine-grained runtime control over curation. It's about actively curating what Claude sees: context is a finite resource with diminishing returns, and irrelevant content degrades model focus." — Anthropic Documentation
Compaction (Chapter 10) is a sledgehammer. It replaces a swath of conversation with a summary. Clearing is a scalpel. It removes specific content types — old tool results, prior thinking blocks — without summarizing anything. The messages and their structure stay in place; only selected content inside them is replaced or dropped.
The distinction matters because the two mechanisms have different failure modes. Compaction is lossy by construction: the summarizer chooses what survives and what doesn't, and it sometimes chooses wrong. Clearing is mechanically predictable: if you tell it to drop tool results older than the 3 most recent, that's exactly what it drops. If the content turns out to be needed later, the agent can re-fetch it from the filesystem or re-run the tool. Nothing is summarized, nothing is paraphrased, nothing is reconstructed by an LLM.
This chapter is about the scalpel. Chapter 10 covers the sledgehammer. In production, they compose.
9.1 Clearing vs. Compacting vs. Truncating
Three mechanisms sit on a spectrum of aggressiveness:
| Mechanism | What it does | Cost | Reversibility | Information loss |
|---|---|---|---|---|
| Truncation | Drops old messages at the head | Zero | None (lossy) | High — whole messages gone |
| Clearing | Replaces specific content within messages | Zero (mechanical) | Re-fetchable | Low — structure preserved |
| Compaction | Summarizes old messages into a single block | LLM call | Irreversible (lossy summary) | Medium — depends on summary quality |
Clearing is the preferred first response to context pressure. It is free (no LLM call), precise (only the content you target is removed), and recoverable (if the agent needs a cleared tool result, it can re-run the tool or re-read the file). You only escalate to compaction when clearing isn't freeing enough space.
A second reason to prefer clearing: it preserves the cache-friendly layout from Chapter 7. When clearing happens via provider-level mechanisms (Anthropic's cache_edits, Claude Code's Path B below), it deletes content by reference without touching the bytes of the cached prefix. The next request still hits the cache. A naive client-side truncation that modifies the bytes of messages in the cached prefix would invalidate the cache from that point forward — a double cost.
flowchart LR
C["Full context<br/>200K tokens"]
C --> T["Truncation<br/>Drop oldest N"]
C --> CL["Clearing<br/>Remove specific items"]
C --> CMP["Compaction<br/>Summarize + continue"]
T --> T1["⚠️ Lossy<br/>⚡ Fast<br/>❌ Breaks coreference"]
CL --> CL1["✅ Precise<br/>⚡ Fast<br/>✅ Reversible<br/>❌ Limited to known targets"]
CMP --> CMP1["✅ Preserves gist<br/>🐢 Expensive (LLM call)<br/>❌ Irreversible<br/>✅ Handles any content"]
style T fill:#fecaca
style CL fill:#dcfce7
style CMP fill:#fef3c7
Three options for making room. Clearing is the highest-ROI when targets are known (tool results, thinking blocks). Compaction is the fallback when everything matters. Truncation is a last resort.
9.2 Anthropic's Server-Side Context Editing
Anthropic exposes clearing through its context-management-2025-06-27 beta header. Two clearing strategies are available:
clear_tool_uses_20250919— clears oldtool_use/tool_resultpairsclear_thinking_20251015— clears oldthinkingblocks (extended-thinking output)
Both are server-side. The client maintains the full unedited conversation history. When the client sends a request, the server applies the edits before the prompt reaches the model. The model sees the post-edit view; the client never loses its record of the pre-edit content.
This split is important. Client-side truncation permanently drops content from the client's record. Server-side clearing is non-destructive from the client's perspective — the full history is still in memory, still persisted to disk, still available for replay or analysis. Only the inference-time view is reduced.
9.3 clear_tool_uses_20250919 — the Highest-ROI Clearing
Tool results are the largest and most ephemeral category of context content. A single read_file can return 8,000 tokens that are useful for exactly one turn and noise thereafter. An agent with 40 tool calls has, by default, all 40 tool results sitting in the window. Most of them are stale. Some are actively contradicted by later tool results (the file that was modified in turn 20 has a stale version sitting in turn 10).
Anthropic's internal evaluation on agentic search tasks (100-turn web research workflows) reported:
- +29% task completion rate with context editing alone (clearing)
- +39% task completion rate with context editing plus the memory tool
The +29% is not a marginal improvement. It is the difference between an agent that completes the task and an agent that runs out of context partway through. Clearing old tool results is the single highest-ROI clearing strategy; in many production agent loops, it is the only clearing strategy you need.
Full Parameter Set
from anthropic import Anthropic
client = Anthropic()
response = client.beta.messages.create(
model="claude-opus-4-5",
max_tokens=4096,
betas=["context-management-2025-06-27"],
context_management={
"edits": [
{
"type": "clear_tool_uses_20250919",
"trigger": {
"type": "input_tokens",
"value": 100000,
},
"keep": 3,
"clear_at_least": 0,
"exclude_tools": ["memory"],
"clear_tool_inputs": False,
}
]
},
tools=[...],
messages=[...], # Full conversation history
)
Parameter Reference
| Parameter | Type | Default | Notes |
|---|---|---|---|
type | string | — | Must be "clear_tool_uses_20250919" |
trigger.type | string | "input_tokens" | Only input_tokens supported currently |
trigger.value | integer | 100,000 | Token threshold that activates clearing |
keep | integer | 3 | Number of most recent tool use/result pairs preserved |
clear_at_least | integer | 0 | Minimum pairs to clear once triggered |
exclude_tools | string[] | [] | Tool names whose results are never cleared |
clear_tool_inputs | boolean | false | If true, also clears the tool call arguments (not just the result) |
What Happens on the Server
- The server counts input tokens.
- If the count is below
trigger.value, no clearing is performed. - If the count is at or above
trigger.value, the server identifies alltool_use/tool_resultpairs in the conversation. - It retains the most recent
keeppairs. Tool calls to any tool named inexclude_toolsare retained regardless of age. - Remaining pairs have their result content replaced with a short marker. If
clear_tool_inputs=true, the original call arguments are cleared too. - If
clear_at_least > keepwould clear more than any pair is retained, the server clears accordingly. - The edited view is passed to the model.
The result looks like this:
Before (120K tokens): After (75K tokens):
msg 1: user msg 1: user
msg 2: tool_use(read_file) 800 tok msg 2: tool_use(read_file)
msg 3: tool_result 8,000 tok msg 3: [CLEARED]
msg 4: assistant 500 tok msg 4: assistant
... ...
msg 45: tool_use(memory) 200 tok msg 45: tool_use(memory)
msg 46: tool_result 500 tok msg 46: tool_result (preserved — excluded)
msg 47: tool_use(grep) 100 tok msg 47: tool_use(grep)
msg 48: tool_result 3,000 tok msg 48: tool_result (preserved — recent)
msg 49: tool_use(read_file) 100 tok msg 49: tool_use(read_file)
msg 50: tool_result 5,000 tok msg 50: tool_result (preserved — recent)
msg 51: tool_use(bash) 50 tok msg 51: tool_use(bash)
msg 52: tool_result 2,000 tok msg 52: tool_result (preserved — recent)
Why exclude_tools: ["memory"] Matters
The memory tool writes to persistent storage and reads back previously written memories. If its tool results are cleared along with everything else, the agent loses its record of what it has already written. Common failure modes:
- Re-researching information it already researched
- Storing duplicate memories under slightly different keys
- Operating without awareness of its own memory store
Adding "exclude_tools": ["memory"] — or the name of whatever persistent-storage tool you use — prevents this. Any persistent-storage-style tool should almost always be in the exclude list. If clearing removes the agent's record of what it has stored, you have effectively given the agent amnesia about its own long-term memory.
Choosing keep
The default is 3. For many agents, this is too low. A single debugging session may involve a grep to find the file, a read_file to inspect it, a bash run to reproduce the error, an edit_file to fix it, and another bash to verify — that's already 5 tool calls that likely all need to be inline. Production defaults of 5–8 are common. The trade-off is obvious: higher keep retains more context for follow-up actions but frees less space when clearing fires.
9.4 clear_thinking_20251015 — Clearing Extended Reasoning Blocks
When extended thinking is enabled, Claude emits thinking blocks containing chain-of-thought reasoning. These blocks improve output quality but consume significant tokens: a complex reasoning step can generate 2,000–10,000 tokens of thinking.
Once the reasoning has been emitted and the model has produced its tool call or response, the thinking block has served its purpose. The model's conclusion — expressed in the visible output — carries forward. The reasoning process is disposable.
response = client.beta.messages.create(
model="claude-opus-4-5",
max_tokens=4096,
betas=["context-management-2025-06-27"],
context_management={
"edits": [
{
"type": "clear_thinking_20251015",
"trigger": {
"type": "input_tokens",
"value": 80000,
},
}
]
},
messages=[...],
)
Parameter Reference
| Parameter | Type | Default | Notes |
|---|---|---|---|
type | string | — | Must be "clear_thinking_20251015" |
trigger.type | string | "input_tokens" | Only input_tokens supported |
trigger.value | integer | 80,000 | Token threshold |
keep | integer | (all old cleared) | Number of recent thinking blocks to preserve |
Thinking blocks are cleared from all prior turns; the most recent assistant turn's thinking is typically preserved (the model may still be mid-reasoning). The savings are model-dependent but can be substantial — a long extended-thinking session can have 50K+ tokens in thinking blocks alone.
9.5 Composing Clearing and Compaction
Clearing and compaction are not alternatives; they are layers. The layered pattern:
response = client.beta.messages.create(
model="claude-opus-4-5",
max_tokens=4096,
betas=["context-management-2025-06-27", "compact-2026-01-12"],
context_management={
"edits": [
# Layer 1: Clear thinking blocks (free)
{
"type": "clear_thinking_20251015",
"trigger": {"type": "input_tokens", "value": 80000},
},
# Layer 2: Clear old tool results (free)
{
"type": "clear_tool_uses_20250919",
"trigger": {"type": "input_tokens", "value": 80000},
"keep": 5,
"exclude_tools": ["memory"],
},
# Layer 3: Full compaction (expensive — LLM call)
{
"type": "compact_20260112",
"trigger": {"type": "input_tokens", "value": 150000},
},
]
},
tools=[...],
messages=[...],
)
Execution Order Matters
The edits fire in the order specified in the edits array. Clearing first, compaction last is the right order, for two reasons:
-
Clearing is free; compaction is expensive. An LLM call to generate a summary costs tokens and latency. Running clearing first often frees enough space that compaction never fires at all. Most requests will never trigger the compaction layer if the clearing layer is doing its job.
-
Compaction operates on an already-cleared view. When compaction does fire, it summarizes the post-clearing conversation. That summary is more focused — the old tool results are already gone, so the summarizer doesn't waste output tokens describing them.
A useful threshold pattern:
- Clearing triggers: 80K tokens (fires early, often)
- Compaction trigger: 150K tokens (fires rarely, only when clearing isn't enough)
On a 200K-token window, this pattern produces about 5× as many clearing events as compaction events in typical workloads. Most context pressure is absorbed by the cheap mechanism before the expensive mechanism ever runs.
9.6 Claude Code's MicroCompact — the Client-Side Equivalent
Teams that don't use Anthropic's server-side editing need a client-side equivalent. The Claude Code v2.1.88 source leak documents one, called MicroCompact.
Despite the name, MicroCompact is a clearing mechanism, not a compaction mechanism. It does not call an LLM. It does not produce a summary. It replaces old tool-result content with a short placeholder, which is exactly what clear_tool_uses_20250919 does server-side.
The interesting detail is that MicroCompact has two execution paths depending on cache state:
flowchart TD
Start[Tool result needs clearing] --> Q{Prompt cache<br/>warm?}
Q -->|Yes| P2["Path B: cache_edits API<br/>Delete by tool_use_id<br/>Cached prefix preserved"]
Q -->|No| P1["Path A: direct mutation<br/>Replace with placeholder:<br/>[Old tool result cleared]"]
P1 --> Done[Context reclaimed]
P2 --> Done
style P1 fill:#fef3c7
style P2 fill:#dcfce7
style Done fill:#dbeafe
Claude Code's MicroCompact chooses its strategy based on cache state. Cache-aware deletion is the critical optimization — it reclaims context without invalidating the KV cache.
Path A — cache cold (or non-Anthropic provider). Directly mutates the message content in the conversation array. Older tool results are overwritten with [Old tool result content cleared] or a similar placeholder. This is the simple path: scan messages, replace content, done. It also invalidates any cached prefix that included the now-modified messages.
Path B — cache warm (Anthropic with active prompt cache). Uses Anthropic's cache_edits API to surgically delete specific tool results by tool_use_id without modifying the bytes of the cached prefix. The server keeps the cached prefix intact and applies a directive to skip specific content blocks during the next inference call.
Path B is critical for production performance. Path A would force a prefix rebuild on every clearing event — a 30–40K-token system prompt plus thousands of tokens of conversation history, all written to cache again. At Manus's 100:1 input-to-output ratio, this is a substantial avoidable cost. Path B delivers the same reduction in inference-time context without invalidating the cache.
Compactable tools from the source: FileRead, Bash, PowerShell, Grep, Glob, WebSearch, WebFetch, FileEdit, FileWrite. Tool results from these tools are eligible for clearing; anything else is preserved.
What stays: The most recent N tool results (the "hot tail" from §8.7), all user messages, all assistant messages (including tool calls), and all system content.
This is a cleaner mental model than "clearing vs. compaction": the client maintains a single cache-aware clearing pass that chooses Path A or Path B based on the cache state. You can implement it for any provider — even providers without cache_edits-equivalent semantics, where Path A is the only option and the cache cost is simply accepted.
9.7 Client-Side Pruning for Teams Not Using Anthropic
If your provider doesn't offer server-side clearing, the principles still apply — you just do them in client code. Two patterns cover most needs.
Priority-Based Retention
Categorize every message by importance at the moment it enters the context. Clear low-priority items first when pressure rises.
| Priority | Content | Retention |
|---|---|---|
| Critical | User corrections, key decisions, error root causes | Keep until superseded |
| High | Recent file reads, test failures, diagnostic output | Keep 10 turns, then clear |
| Medium | Search results, web fetches, directory listings | Keep 5 turns, then clear |
| Low | Routine tool outputs, old file reads, verbose logs | Keep 3 turns, then clear |
| Disposable | Thinking blocks, intermediate reasoning, superseded versions | Clear when newer version exists |
A minimal implementation:
from dataclasses import dataclass
from enum import IntEnum
class Priority(IntEnum):
DISPOSABLE = 0
LOW = 1
MEDIUM = 2
HIGH = 3
CRITICAL = 4
@dataclass
class TaggedMessage:
message: dict
priority: Priority
turn_number: int
RETENTION_TURNS = {
Priority.DISPOSABLE: 0,
Priority.LOW: 3,
Priority.MEDIUM: 5,
Priority.HIGH: 10,
Priority.CRITICAL: 10_000, # effectively forever
}
def prune(
tagged: list[TaggedMessage],
current_turn: int,
target_reduction: int,
estimate_tokens,
) -> list[TaggedMessage]:
# Sort candidates by priority (lowest first), then by age (oldest first)
candidates = sorted(tagged, key=lambda m: (m.priority, m.turn_number))
freed = 0
pruned_ids: set[int] = set()
for m in candidates:
if freed >= target_reduction:
break
age = current_turn - m.turn_number
if age > RETENTION_TURNS[m.priority]:
pruned_ids.add(id(m))
freed += estimate_tokens(m.message)
return [m for m in tagged if id(m) not in pruned_ids]
Sliding Window with Exceptions
A simpler variant: keep the last N messages plus a small always-preserve set.
def sliding_window(
messages: list[dict],
keep_last: int = 20,
always_preserve: set[int] | None = None,
) -> list[dict]:
always_preserve = always_preserve or set()
keep_indices = set(range(max(0, len(messages) - keep_last), len(messages)))
keep_indices |= always_preserve
return [m for i, m in enumerate(messages) if i in keep_indices]
The always_preserve set is populated as the conversation runs: when the user corrects the agent, mark that message; when the agent commits to an architectural decision, mark the assistant message that contains it. The always-preserve set is small — typically a handful of indices — and grows slowly.
These client-side patterns give you most of the benefit of server-side clearing. They do not get you Path B's cache-preservation — if you modify the bytes of cached messages, you pay the cache cost. A middle ground for teams willing to accept more complexity is to maintain two views: a full "journal" on disk and a pruned "window" for inference, where the pruned window is always constructed fresh rather than mutated in place. The pruned window has a stable layout, so cache keys on the stable prefix stay valid turn to turn.
9.8 The "Never Compact the Previous Turn" Rule
This rule was codified by Relevance AI's production team after repeated user-facing failures. It applies to clearing as well as compaction.
Follow-up prompts depend on the previous turn being visible verbatim:
- "Edit the second paragraph." — needs the paragraphs visible.
- "Change the variable name from
ntocount." — needs the code visible. - "That's wrong — the API uses POST, not GET." — needs the generated code visible.
- "Add error handling to the function you just wrote." — needs the function visible.
If the previous assistant turn was compacted into a summary or had its content cleared, the coreference fails. The model reads the summary "Wrote a recursive Fibonacci function" and doesn't know which specific implementation the user is asking to modify. The failure is confusing: the agent confidently produces a plausible-looking answer that does not match what was actually written.
The rule: never clear or compact the immediately previous assistant turn (and typically the immediately previous user turn as well, since it may contain references the next message resolves against).
The exception: panic mode. If the context is at >95% and every other compressible thing has already been compressed, the previous turn may be the last candidate. In that case, you are choosing between a bad behavior (loss of coreference) and a worse one (total failure because the API rejects the request). Panic mode picks the bad behavior.
A practical implementation:
def select_clearable(
messages: list[dict],
panic_mode: bool = False,
) -> tuple[list[dict], list[dict]]:
if panic_mode:
return messages[:-1], messages[-1:]
# Keep the last user+assistant pair verbatim
keep_from = max(0, len(messages) - 2)
return messages[:keep_from], messages[keep_from:]
Two messages of protection cover the common follow-up pattern. More aggressive implementations preserve the last three or four, trading additional inline tokens for robustness against multi-turn follow-ups.
9.9 Common Clearing Failure Modes
A short debugging table for when clearing is configured but something still goes wrong:
| Symptom | Likely cause | Fix |
|---|---|---|
| Agent re-searches information it already found | Tool results cleared before agent wrote findings to memory | Raise clearing trigger; prompt agent to write to memory before pressure hits |
| Follow-up prompts fail | keep too low; previous turn cleared | Increase keep to 5–8; enforce "never clear previous turn" |
| Memory tool results vanish | memory missing from exclude_tools | Add "exclude_tools": ["memory"] |
| Cache hit rate collapses after clearing | Path A executed when Path B should have | Verify cache_edits is engaged; audit message mutations |
| Model reasoning quality drops | Thinking cleared too aggressively | Raise thinking trigger; consider keeping last thinking block |
| Clearing fires too early, then re-fires | Trigger set too close to normal operation tokens | Measure p90 normal-operation tokens; set trigger well above it |
Most of these are configuration issues, not bugs. The clearing primitives are mechanical: they do exactly what they're told. Configuring them correctly requires measuring the agent's actual token usage patterns and tuning the triggers and keep values to match.
9.10 Key Takeaways
-
Clearing is the first response to context pressure. It is free, precise, and recoverable. Escalate to compaction only when clearing doesn't free enough space.
-
clear_tool_uses_20250919is the highest-ROI strategy. +29% task completion on Anthropic's 100-turn agentic search evaluation; +39% with the memory tool. In production agent loops, this is often the only clearing strategy you need. -
clear_thinking_20251015is safe and cheap. The model's conclusions are in its visible output; the reasoning process itself is rarely needed after the action it informed is complete. -
Always
exclude_tools: ["memory"]. Any persistent-storage tool should be excluded from clearing, or the agent loses awareness of its own memory store. -
Compose clearing with compaction; clear first. Clearing is free; compaction is an LLM call. Order matters: clearing before compaction means compaction rarely fires and, when it does, summarizes an already-clean conversation.
-
MicroCompact's two paths. Path A mutates message content (simple, breaks cache). Path B uses
cache_editsto delete by reference without touching the cached prefix (cache-preserving, Anthropic-only). Production agents should use Path B when available. -
Client-side clearing works without Anthropic. Priority-based retention or sliding-window-with-exceptions gives you most of the benefit. The cache cost is higher than Path B but still lower than full compaction.
-
Never clear the previous turn. Follow-up prompts depend on verbatim visibility of the previous turn. The only exception is panic mode at >95% window utilization.
Chapter 10: Compaction — Summarizing Without Forgetting
"Compaction is not 'summarize and hope.' It is summarization plus context restoration."
Clearing (Chapter 9) removes specific content types without replacing them — old tool results are dropped, old thinking blocks go away, and the agent can re-fetch or re-run what it needs. Compaction is the next level up. It replaces a large span of conversation with a smaller summary. This is lossy by construction: the summarizer chooses what to keep, the summary cannot be reversed, and the agent proceeds on an interpretation of its history rather than the history itself.
The quality of that summary determines whether the agent continues its task coherently or effectively starts over with partial amnesia. A good summary captures the essentials — what was accomplished, what decisions were made, what errors occurred, what the current state is, what should happen next. A bad summary is worse than truncation, because the agent proceeds with false confidence in incomplete information.
This chapter is about doing compaction well. It covers the provider APIs, the production implementations (especially Claude Code's 4-tier system from the v2.1.88 source leak), the summary format, the post-compaction reconstruction step, the cache preservation discipline, and the failure modes that production teams have learned to design against.
10.1 Compaction vs. Clearing vs. Truncation
The full trade-off matrix, expanded from Chapter 9:
| Dimension | Truncation | Clearing | Compaction |
|---|---|---|---|
| Cost | Zero | Zero | LLM call |
| Reversibility | None (lossy) | Re-fetchable | Irreversible |
| Information loss | High | Low | Medium |
| Structure preserved | No (messages removed) | Yes | No (replaced with summary) |
| Cache impact | Typically breaks prefix | Cache-preserving with Path B / server-side | Preserved with cache-aware discipline |
| When to use | Never (prefer clearing) | First response to pressure | When clearing isn't enough |
Compaction is the sledgehammer. It is strictly more aggressive than clearing: if clearing can free enough tokens, do that instead. If it cannot, compaction becomes necessary — but it should fire rarely and at carefully chosen boundaries.
10.2 Anthropic's Compaction API
Anthropic exposes compaction through the compact-2026-01-12 beta header. The API is compact_20260112 and it composes with the clearing strategies from Chapter 9:
from anthropic import Anthropic
client = Anthropic()
response = client.beta.messages.create(
model="claude-opus-4-5",
max_tokens=4096,
betas=["compact-2026-01-12"],
context_management={
"edits": [
{
"type": "compact_20260112",
"trigger": {
"type": "input_tokens",
"value": 150000,
},
"pause_after_compaction": False,
}
]
},
tools=[...],
messages=[...],
)
Parameter Reference
| Parameter | Type | Default | Notes |
|---|---|---|---|
type | string | — | Must be "compact_20260112" |
trigger.type | string | "input_tokens" | Only input_tokens supported currently |
trigger.value | integer | 150,000 | Token threshold; minimum 50,000 |
pause_after_compaction | boolean | false | If true, returns the compaction block to the client before resuming |
The minimum trigger is 50,000 tokens. Setting it lower produces a worse compaction event: the summarizer has less context to compress and the resulting summary lacks detail.
How the Compaction Block Feeds Back
When compaction fires, the response contains a compaction content block. This block is opaque — it carries latent state in a format the model decodes internally. The client's job is to carry it forward: replace the compacted portion of the conversation with this block, append any new messages that arrived after compaction, and send the result on the next turn.
for block in response.content:
if block.type == "compaction":
# Replace conversation history with the compaction block
# plus any new messages after the compaction point
conversation = [block] + new_messages_after_compaction
The opaque format is intentional. Anthropic's internal representation preserves more information than a plain-text summary — it's closer to a mid-layer activation than a transcript. The client cannot inspect it, but the model on the next turn can use it as if the full history were still present.
pause_after_compaction for Inspection
Setting this to true pauses the API call immediately after compaction so the client can inspect the result and decide whether to continue. In production, this is useful for:
- Debugging: verifying that compaction fired at the expected point and produced a reasonable block
- Human-in-the-loop: letting a user review what was summarized before the agent resumes
- Cadence control: deciding whether to proceed immediately or to take a snapshot of the conversation for analysis
For most production loops, the default false is correct — pausing on every compaction event introduces latency and operator overhead.
10.3 OpenAI's Compaction
OpenAI exposes compaction in two modes: server-side automatic via the Responses API's context_management, and a standalone /responses/compact endpoint for on-demand compaction outside a running conversation.
Server-Side Automatic
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.3-codex",
input=conversation,
store=False,
context_management=[
{
"type": "compaction",
"compact_threshold": 200_000,
}
],
)
for item in response.output:
if item.type == "compaction":
# This is the opaque compaction item with encrypted_content
conversation = [item] + new_messages_after_compaction
When compaction fires, the output contains a compaction item with an encrypted_content field. Like Anthropic's compaction block, it is opaque — the client carries it forward but cannot inspect its contents. The preservation of latent state (rather than a plain-text summary) is cited in OpenAI's harness engineering documentation as a meaningful quality improvement over text-only summarization.
Standalone /responses/compact
For on-demand compaction outside a streaming conversation:
compacted = client.responses.compact(
model="gpt-5.4",
input=long_input_items_array,
)
Returns a compacted version of the input that can be used as the starting point for a new responses.create() call. This is useful for batch scenarios — compacting a long conversation offline before starting a new session — or for forking a session into a lighter-weight branch.
Codex's build_compacted_history Logic
The Codex CLI (Rust, open source) implements a client-side variant for non-OpenAI providers where server-side compaction isn't available. The logic, simplified from codex-rs/core:
#![allow(unused)] fn main() { const COMPACT_USER_MESSAGE_MAX_TOKENS: usize = 20_000; fn build_compacted_history( messages: &[Message], compaction_result: &CompactionResult, ) -> Vec<Message> { let mut compacted = Vec::new(); // 1. The compaction summary/item sits at the head compacted.push(compaction_result.to_message()); // 2. Preserve user messages from after the compaction point — // messages the user sent that weren't included in the summary for msg in messages.iter().skip(compaction_result.compacted_through) { compacted.push(msg.clone()); } // 3. Truncate any user message that exceeds the per-message max for msg in &mut compacted { if msg.role == Role::User { msg.content = truncate_to_tokens( &msg.content, COMPACT_USER_MESSAGE_MAX_TOKENS, ); } } compacted } }
Two design decisions are worth highlighting. First, user messages after the compaction point are preserved verbatim. Compaction never summarizes content the summarizer hasn't seen yet. Second, a hard 20,000-token cap per user message prevents a single pathological user input (a pasted log file, a huge document) from re-inflating the context immediately after compaction.
Known Bug: Mid-Turn Compaction (Issue #10346)
A documented issue in Codex: when compaction triggers mid-turn — while the model is executing a multi-step plan — the model can lose track of where it is. The reported symptom:
"Long threads and multiple compactions can cause the model to be less accurate."
The mechanism:
- The model is partway through a plan (e.g., "first edit file A, then update test B, then rerun C").
- Compaction fires and summarizes the conversation, including the partial plan.
- The model resumes with the summary but has lost the detailed state of which step it was on.
- It may repeat steps, skip steps, or pivot to a different approach.
The mitigation that Codex ships: after compaction fires mid-turn, append an explicit marker to the context warning the model that compaction occurred and asking it to re-verify its current state before proceeding. The cleaner fix is to avoid mid-turn compaction in the first place — compact at task boundaries (§10.10) rather than waiting for the auto-trigger.
10.4 Claude Code's 4-Tier Compaction System
The Claude Code v2.1.88 source leak (March 2026) exposed the most detailed production compaction implementation in public view. The system has four progressive tiers — plus a fifth emergency recovery tier — each with its own threshold and strategy. Studying the constants and the tier structure is the clearest way to understand how a mature production system actually manages context pressure.
Source Constants
const MODEL_CONTEXT_WINDOW_DEFAULT = 200_000;
const COMPACT_MAX_OUTPUT_TOKENS = 20_000;
const AUTOCOMPACT_BUFFER_TOKENS = 13_000;
const WARNING_THRESHOLD_BUFFER_TOKENS = 20_000;
const MANUAL_COMPACT_BUFFER_TOKENS = 3_000;
const MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES = 3;
const AUTOCOMPACT_TRIGGER_FRACTION = 0.90; // Rust port equivalent
Every threshold in the system is derivable from these constants:
Effective window = MODEL_CONTEXT_WINDOW_DEFAULT - COMPACT_MAX_OUTPUT_TOKENS
= 200_000 - 20_000
= 180_000 tokens
Auto-compact threshold = Effective window - AUTOCOMPACT_BUFFER_TOKENS
= 180_000 - 13_000
= 167_000 tokens (92.8% of effective window)
Warning threshold = Auto-compact threshold - WARNING_THRESHOLD_BUFFER_TOKENS
= 167_000 - 20_000
= 147_000 tokens (81.7% of effective window)
Manual compact threshold = Effective window - MANUAL_COMPACT_BUFFER_TOKENS
= 180_000 - 3_000
= 177_000 tokens (98.3% of effective window)
These are not nice round numbers. They are the output of specific reasoning: leave enough room for 20K output tokens, maintain a 13K safety margin so auto-compaction never gets stuck halfway, warn the user 20K tokens before auto-compaction fires so they can intervene manually, and block execution at 98.3% to prevent the API from rejecting the next call.
The Threshold Map
Token usage
0% 81.7% 92.8% 98.3% 100%
│ │ │ │ │
│ Normal │ Warning │ Auto-compact │ Manual/ │
│ operation │ (light, tier │ (full, tier │ Hard stop │
│ (tier 1 │ 2 engages) │ 3 engages) │ (tier 4) │
│ only) │ │ │ │
└─────────────┴──────────────┴──────────────┴───────────┘
stateDiagram-v2
[*] --> Normal: Session starts
Normal --> MicroCompact: Tool output exceeds size
MicroCompact --> Normal: Context reclaimed
Normal --> Warning: tokens ≥ 147K (81.7%)
Warning --> AutoCompact: tokens ≥ 167K (92.8%)
AutoCompact --> Normal: Summary injected<br/>files re-read
Normal --> SessionMemory: Repeated compaction pressure
SessionMemory --> Normal: Facts persisted<br/>to disk
Normal --> HardStop: tokens ≥ 177K (98.3%)
HardStop --> [*]: User must act
AutoCompact --> Reactive: API rejects<br/>prompt_too_long
Reactive --> Normal: Aggressive truncation
Reactive --> HardStop: Still too large
note right of AutoCompact
Max 3 consecutive failures
→ circuit breaker trips
end note
Claude Code's compaction as a state machine. MicroCompact runs continuously; AutoCompact triggers at 92.8%; SessionMemory extracts durable facts; Reactive handles API rejections; HardStop is the final brake.
Tier 1: MicroCompact (covered in Chapter 9)
The lowest-threshold tier is MicroCompact, which is a clearing mechanism rather than a compaction mechanism. It replaces old tool-result content with placeholders and has two execution paths (cache-warm via cache_edits, cache-cold via direct mutation). The full details are in §9.6. MicroCompact absorbs most context pressure in normal operation — many production sessions never exceed Tier 1 at all.
Tier 2: AutoCompact — Full Summarization
When MicroCompact cannot free enough space and the context crosses the auto-compact threshold (~167K, 92.8% of effective window), AutoCompact fires. This is the expensive tier: a full summarization pass using an LLM call.
The summarization prompt is not an open-ended "summarize this conversation." It is a structured contract requiring 9 specific sections (§10.5). The summarization call reuses the exact same system prompt, tools, and model as the main conversation — this is the cache-preservation discipline from Chapter 7. The compaction instruction is appended as a new user message at the tail, preserving the cached prefix.
A simplified view of the logic:
function calculateTokenWarningState(
currentTokens: number,
contextWindow: number = MODEL_CONTEXT_WINDOW_DEFAULT,
): "ok" | "warning" | "autocompact" | "blocking" {
const effectiveWindow = contextWindow - COMPACT_MAX_OUTPUT_TOKENS;
const autoCompactThreshold = effectiveWindow - AUTOCOMPACT_BUFFER_TOKENS;
const warningThreshold = autoCompactThreshold - WARNING_THRESHOLD_BUFFER_TOKENS;
const blockingThreshold = effectiveWindow - MANUAL_COMPACT_BUFFER_TOKENS;
if (currentTokens >= blockingThreshold) return "blocking";
if (currentTokens >= autoCompactThreshold) return "autocompact";
if (currentTokens >= warningThreshold) return "warning";
return "ok";
}
The circuit breaker prevents infinite compaction loops. If the summarization call fails three times in a row — typically because the conversation is too degraded for a coherent summary — the system stops attempting auto-compaction and falls through to Tier 4.
const MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES = 3;
let consecutiveFailures = 0;
async function attemptCompaction(): Promise<boolean> {
try {
await runCompaction();
consecutiveFailures = 0;
return true;
} catch (error) {
consecutiveFailures++;
if (consecutiveFailures >= MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES) {
log.warn("Auto-compact circuit breaker: 3 consecutive failures");
return false;
}
return false;
}
}
Tier 3: SessionMemory — Extract to Persistent Storage
When compaction alone cannot reduce pressure enough, Tier 3 extracts key information to persistent session memory files that survive beyond the context window. This is durable state: written to disk, readable on future session resumes, outside the conversation altogether.
The extracted state includes:
- Key decisions and their rationale
- File modification history
- Error patterns observed and resolved
- User preferences expressed during the session
The memory files live outside the conversation. The compacted summary references them ("User preferences are documented in ~/.claude/projects/<project>/memory/user_preferences.md") but the files themselves are not loaded into context unless the model reads them.
Tier 4: HardStop — Block Execution
When the window exceeds 98.3%, Claude Code blocks further execution outright:
if (warningState === "blocking") {
throw new ContextOverflowError(
"Context window is critically full. " +
"Run /compact or start a new conversation.",
);
}
This is a safety valve, not a failure. Continuing to push tokens into a nearly-full window means the model has almost no room to respond, tool-call JSON might be truncated (causing parse errors), and any output would be working with the worst possible context quality. Stopping explicitly is better than producing low-quality output from an exhausted context.
Tier 5: Reactive Compact — Emergency Recovery
A fifth tier handles the case where the API itself rejects a request with prompt_too_long. This can happen if token counting was inaccurate, if the user pasted a huge message right at the edge, or if all previous tiers failed to fire in time.
The recovery sequence:
- Truncate oldest message groups — not individual messages, but logical groups (a user message + the assistant response + the tool results it generated, as one unit).
- Retry the API call with the reduced context.
- If still too long, truncate more groups and retry.
This tier is more aggressive than AutoCompact (which summarizes) — Reactive Compact simply drops old content without summarization. The information is lost, not compressed. But it keeps the agent running when the alternative is a complete halt. HardStop blocks proactively before the API call; Reactive Compact fires reactively after the API rejects one. Together they cover both "we predict overflow" and "overflow happened anyway."
10.5 The 9-Section Summary Format
The Claude Code compaction prompt requires the summary to contain nine specific sections. This rigid format is not a stylistic choice — each section exists because unstructured summaries were missing specific categories of information that the post-compaction agent needed.
The required sections, in order:
- Primary Request and Intent — what the user originally asked (verbatim if short)
- Key Technical Concepts — important technical details discussed
- Files and Code Sections — files touched, what was read/written/modified
- Errors and Fixes — what went wrong and how it was resolved
- Problem Solving — approaches tried, what worked and what didn't
- All User Messages — preserved verbatim, every single one
- Pending Tasks — what's left to do
- Current Work — what was being worked on when compaction fired
- Optional Next Step — recommended next action
Two sections are worth particular attention.
Section 6 — All User Messages, verbatim. Most summarization approaches paraphrase user input. Claude Code does not. The rationale is that user intent expressed in their exact words is too important to risk paraphrasing — a subtle rephrasing could shift the meaning of a nuanced instruction ("refactor this module" is meaningfully different from "rewrite this module"). Preserving user messages verbatim also preserves coreferences ("the function you just wrote") that a paraphrase would destroy.
Section 5 — Problem Solving, including failed approaches. Summaries that record only what worked are worse than useless — they let the agent re-try known dead ends. Recording what was tried and didn't work is what prevents the agent from falling into the same hole twice. This section is often what separates a competent compaction from an incompetent one.
The No-Tools Preamble
The summarization call inherits the parent conversation's full tool set (because it reuses the same system prompt for cache efficiency). If the model decides to call a tool during summarization, the result is catastrophic — the compaction flow doesn't expect tool calls and may loop or corrupt state.
The fix is a preamble appended to the compaction instruction:
You are generating a summary. Do not call any tools. Produce only text output, in the required 9-section format.
This is a necessary safeguard whenever you reuse a tool-rich system prompt for a task that should be pure text generation. Any custom compaction implementation that follows the cache-preservation discipline needs its own equivalent.
A Compaction Prompt Template
For teams implementing their own compaction, the template below captures the same structure in a portable form:
COMPACTION_PROMPT = """You are summarizing a conversation to preserve the context
needed for continued work. The summary will REPLACE the conversation history,
so it must contain everything needed to continue.
Do not call any tools. Produce only text output in the 9-section format below.
REQUIRED SECTIONS:
1. PRIMARY REQUEST AND INTENT: What the user originally asked (verbatim if short).
2. KEY TECHNICAL CONCEPTS: Important technical details discussed.
3. FILES AND CODE SECTIONS: Files touched (with paths), what was read/written.
4. ERRORS AND FIXES: What went wrong and how it was resolved.
5. PROBLEM SOLVING: Approaches tried, what worked, what didn't.
6. ALL USER MESSAGES: Every user message, verbatim.
7. PENDING TASKS: What's left to do.
8. CURRENT WORK: What was being worked on when compaction fired.
9. OPTIONAL NEXT STEP: Recommended next action.
Rules:
- File paths, function names, and error messages VERBATIM.
- Failed approaches are as important as successes — the agent must not repeat them.
- If you were debugging, include the current hypothesis and evidence.
- Be specific: "Fixed auth middleware in src/auth.ts line 42" not "Fixed auth."
"""
10.6 Post-Compaction Reconstruction
The under-documented half of compaction is what happens after the summary is generated. A summary alone is not a usable working context. The agent's next turn needs tools, memory, file state, skills, and project instructions — all of which were in the prior turn's context but not in the summary.
Claude Code's source shows the full reconstruction sequence in a specific order:
sequenceDiagram
autonumber
participant Old as Pre-compaction context
participant Sum as Summarizer
participant New as New context window
Old->>Sum: Send messages to summarize
Sum->>Sum: Generate 9-section summary<br/>(intent, concepts, files,<br/>errors, problem-solving, messages,<br/>pending, current work, next step)
Sum->>New: 1. Boundary marker with metadata
Sum->>New: 2. Formatted 9-section summary
Note over New: Restoration begins
Sum->>New: 3. Re-read 5 most recent files<br/>(capped at 50K tokens)
Sum->>New: 4. Re-inject skills (sorted by recency)
Sum->>New: 5. Re-announce tool definitions
Sum->>New: 6. Re-run session hooks
Sum->>New: 7. Restore CLAUDE.md at system level
Sum->>New: 8. Continuation message
Note over New: "Continue without asking further questions"
New-->>New: Agent resumes mid-task
The 8-step reconstruction sequence from Claude Code source. Summary alone isn't enough — the file re-reads, skill re-injection, and continuation message are what let the agent pick up work mid-task.
- Boundary marker with pre-compaction metadata — token counts, turn counts, timestamp. This gives the model a clear signal that compaction occurred and when.
- The formatted 9-section summary from the summarization call.
- 5 most recently read files, capped at 50K tokens total — re-read from disk, not from the summary. This is the critical detail: if the agent was working on a file at turn 40 and the file has been modified since, the summary only records "worked on
src/auth.ts." The agent needs the current contents, which means re-reading from disk. - Re-injected skills sorted by recency — skills the agent used recently are restored first, so the most relevant capabilities are immediately available.
- Tool definitions re-announced — full tool schemas, so the model knows what capabilities it has.
- Session hooks re-run — any
PreToolUse/PostToolUsehooks that had modified state are re-executed. CLAUDE.mdrestored at system level — project instructions re-injected.- Continuation message — a specific, carefully worded instruction to continue without asking the user for clarification:
"This session is being continued from a previous conversation that ran out of context. Please continue without asking the user any further questions. Continue with the last task."
The continuation message is worded to prevent the common failure mode where the model, disoriented after compaction, asks the user to re-explain what they want. "Without asking the user any further questions" is the explicit anti-pattern block. "Continue with the last task" says what the model should do instead.
The 50K token budget for file restoration is deliberate. It is large enough to restore meaningful file context (the five files the agent was most recently working with), small enough to leave room for the model to actually work. Production teams tuning their own reconstruction logic should plan for a similar budget split — roughly a third of the effective window going to the summary, a third to rehydrated files, and a third to ongoing work.
10.7 Cache-Aware Compaction
Cache preservation during compaction was covered in Chapter 7 and is restated here because it is one of the most cost-sensitive decisions in the whole compaction pipeline.
The rule: the summarization call must use the exact same system prompt, tools, and model as the main conversation. Any deviation breaks the cached prefix and you pay full-price prefill on every compaction event.
The Claude Code source documents the experimental justification: using a different system prompt for the summarization call produced a 98% cache miss rate. With a 30–40K-token system prompt and compaction firing every few dozen turns, the cost difference between cache-aware compaction and naive compaction is substantial — on the order of thousands of dollars per month for a well-used agent.
Two patterns implement this correctly:
Pattern 1 — append instruction as user message. The compaction instruction becomes a new user message appended to the conversation. Everything before it is cached. Only the new user message and the generated summary are new tokens.
summary_response = client.messages.create(
model=MAIN_MODEL,
system=[{
"type": "text",
"text": MAIN_SYSTEM_PROMPT, # byte-identical to main conversation
"cache_control": {"type": "ephemeral", "ttl": "1h"},
}],
tools=MAIN_TOOLS, # byte-identical to main conversation
messages=[
*conversation,
{"role": "user", "content": COMPACTION_INSTRUCTION},
],
)
Pattern 2 — cache_edits for surgical deletes. When compaction needs to remove specific tool results from the middle of the cached prefix (rare, but sometimes necessary), use Anthropic's cache_edits mechanism. This deletes content by tool_use_id without modifying the bytes of the cached prefix, so the cache remains valid. The pattern is covered under MicroCompact Path B in §9.6.
Do not rewrite the bytes of the cached prefix. Do not use a custom summarization system prompt. Do not strip tool definitions to "save space" during summarization. Every one of these produces a 98% miss rate and wastes the compute that cache hits would have saved.
10.8 Compaction-Aware Agent Design
Compaction is a force multiplier for agents that are designed for it, and a liability for agents that aren't. The Codex team's hard-won learning, stated plainly in their harness engineering documentation: assume compaction will drop details, and preserve essentials externally before it fires.
Three design patterns make this concrete.
Write critical state to files before compaction. Files exist outside the message array and are never affected by the summarizer's choices. A progress file that the agent updates at the end of each turn survives compaction completely:
def update_progress(agent_state) -> None:
progress = f"""# Task Progress
Updated: {datetime.now().isoformat()}
## Original Request
{agent_state.original_request}
## Completed
{format_list(agent_state.completed)}
## In Progress
{format_list(agent_state.in_progress)}
## Decisions (with rationale)
{format_list(agent_state.decisions)}
## Errors Encountered (with resolutions)
{format_list(agent_state.errors)}
## Key Files
{format_list(agent_state.active_files)}
"""
with open("PROGRESS.md", "w") as f:
f.write(progress)
After compaction, the agent re-reads PROGRESS.md and regains full awareness of project state — nothing lost, nothing paraphrased. This is especially important for things that summaries typically lose: exact error messages, file:line references, the reasoning behind decisions.
Explicit "where were we" markers. At the end of a sequence of related tool calls, the agent emits a small marker summarizing what it just finished and what comes next:
[Marker] Just finished: converting /api/billing/invoices route to Fastify.
Next: update Zod schemas in src/schemas/billing.ts.
These markers are cheap (a few tokens) but give the summarizer an anchor to work with. A summary that incorporates "Just finished /api/billing/invoices conversion" is much more useful than one that has to reconstruct what was finished from the tool-call trace.
Compact at task boundaries, not mid-task. Covered in §10.10.
10.9 Compaction Failure Modes
From production teams' post-mortems, the common failure modes after compaction and the mitigations that address them:
| Symptom | Likely cause | Mitigation |
|---|---|---|
| Agent repeats work it already did | Summary didn't capture completed work with enough specificity | Enforce Section 7 (Pending Tasks) and Section 3 (Files and Code Sections) with file paths |
| Agent uses outdated file contents | Rehydration didn't re-read modified files | Re-read the N most recent files after compaction (the 50K budget) |
| Agent changes approach unexpectedly | Summary lost the rationale for the chosen approach | Enforce Section 4 (Errors and Fixes) and Section 5 (Problem Solving) with decision rationales |
| Agent re-encounters a known dead end | Summary didn't capture failed approaches | Section 5 must record failed approaches explicitly; this is critical |
| Agent asks user to re-explain the task | Summary didn't capture original intent, continuation message missing | Include verbatim original request; include explicit continuation message |
| Agent loses coreference ("it", "the function") | Previous turn compacted along with older turns | Enforce "never compact previous turn" (Chapter 9 §9.8) |
| User preferences mentioned early are ignored | Early user messages paraphrased or lost | Section 6 requires verbatim preservation of all user messages |
| Agent stops mid-task after compaction | Context anxiety after compaction event (Sonnet 4.5 specifically) | Consider context resets instead of compaction for anxiety-prone models |
Memory-tool writes before compaction are the most general mitigation. Any time the agent learns something important — an architectural decision, a root cause, a user preference — write it to memory immediately. The write-then-clear / write-then-compact pattern ensures the information survives even if both the clearing layer and the summarizer fail to preserve it in the context.
10.10 Compaction Cadence Patterns
When compaction fires is a policy choice. Four patterns appear in production:
Automatic at threshold. The default. The server or client triggers compaction when token count crosses a threshold. Simple, mechanical, and the worst choice for summary quality — the trigger has no awareness of where in the conversation structure the compaction falls. Mid-debug-session compactions produce messier summaries than end-of-subtask compactions.
Manual at task boundaries (recommended). The agent (or an orchestrator) triggers compaction when it finishes a logical unit of work. The conversation has a natural boundary at that point — "we just finished feature X, next we do feature Y" — and the summarizer can follow the structure. This is the highest-quality pattern.
async def agent_loop(task: str):
while not is_complete():
result = await execute_next_step()
if result.completed_subtask:
update_progress(state)
if context_utilization() > 0.60:
await compact() # clean summary at a clean boundary
Compacting at 60% utilization at a task boundary produces a better summary than waiting until 90% utilization mid-task. The trade-off is that you compact more often; the gain is that each compaction is cleaner.
Never (fit within window, rely on cache). For short-duration tasks or narrow-scope agents, compaction may never fire. The agent runs, finishes, the conversation stays under the window, and compaction is irrelevant. This is the ideal state for short agents and should be the target whenever task structure permits.
Preview (pause_after_compaction=true). Pause on each compaction event to inspect the generated summary before continuing. Useful during development, tuning, and debugging. Also useful in human-in-the-loop deployments where an operator reviews summaries before the agent resumes. Not typical for autonomous production loops.
A Decision Tree
Task duration < single window?
└── Yes: No compaction needed. Focus on cache preservation instead.
└── No: Compaction will fire.
│
├── Are there natural task boundaries?
│ └── Yes: Prefer manual compaction at boundaries.
│ └── No: Automatic at threshold (with circuit breaker).
│
└── Is the model anxiety-prone (Sonnet 4.5-era)?
└── Yes: Consider context resets with handoff artifacts.
└── No: Compaction alone is sufficient (Opus 4.6+).
The context-reset alternative is covered in the old book's Chapter 3 §3.6 and does not need to be repeated here. The short version: for models that exhibit "context anxiety" (behavioral degradation as the window fills, even below the limit), a fresh agent started from a handoff artifact may outperform a compacted continuation. For models without anxiety, compaction alone works fine.
10.11 Key Takeaways
-
Compaction is summarization plus rehydration. The summary alone is insufficient. Re-reading current files (the 50K budget), restoring skills and tool definitions, and issuing an explicit continuation message are what make compaction work in practice.
-
Know your exact thresholds. Claude Code: auto-compact at 167K (92.8%), warning at 147K (81.7%), hard stop at 177K (98.3%). Derive them from the source constants and monitor against them. Codex: configurable threshold, 50K minimum for Anthropic, 20K per-message cap on user messages.
-
The 4-tier progression outperforms single-pass. MicroCompact absorbs most pressure (free). AutoCompact handles the rest (expensive, LLM call). SessionMemory extracts durable state. HardStop blocks safely. Reactive Compact handles emergencies. Five layers of defense.
-
The 9-section format is not optional. Each section addresses a specific failure mode: lost intent (Section 1), lost file state (Section 3), lost error resolutions (Section 4), repeated dead ends (Section 5), paraphrased user intent (Section 6), lost coreference (Section 8).
-
Cache-aware compaction is a hard requirement. Same system prompt, tools, and model as the main conversation. Append the compaction instruction as a new user message. A different system prompt yields 98% cache miss. At 30–40K-token system prompts and frequent compaction, this dominates the inference bill.
-
Write critical state to files before compaction fires.
PROGRESS.mdand memory-tool entries survive compaction because they live outside the message array. Design the agent to assume compaction will drop details and to preserve essentials externally. -
Compact at task boundaries, not at thresholds. Automatic-at-threshold is the default but not the best. Compacting at a clean boundary — "just finished X, next Y" — produces a cleaner summary than compacting in the middle of a debugging session.
-
Preserve the previous turn. Never compact (or clear) the immediately previous turn. Follow-up prompts depend on verbatim visibility. Panic mode at >95% is the only exception.
-
Plan for failure modes. Loss of coreference, loss of exploration history, loss of user preferences, context anxiety. Each has a named mitigation: verbatim previous turn, Section 5 failed approaches, Section 6 verbatim user messages, context resets for anxiety-prone models.
-
Match cadence to task structure. Fit-within-window when possible. Manual at boundaries when not. Automatic at threshold as a safety net. Preview with
pause_after_compactionduring development and debugging. Different tasks call for different cadences — compaction is not a single knob but a family of policies.
Chapter 11: External Memory — The File System as Extended Context
"We treat the file system as the ultimate context: unlimited in size, persistent by nature, and directly operable by the agent itself." — Yichao 'Peak' Ji, Manus
11.1 The Paradigm Shift
Every previous chapter has treated the context window as a fixed-size container the agent works inside. This chapter inverts the framing. The context window is the small, expensive working set; the file system is the rest of the context. Tokens that aren't currently in the window can be brought back in on demand, as long as the agent knows they exist and where to find them.
That's the lens this chapter takes. Files are not infrastructure. They are extended context. Deciding what lives in a file versus what lives in the window is a context engineering decision, identical in shape to deciding what goes in the system prompt versus the user message. The only difference is latency: a file read is one tool call away.
Manus articulated the principle directly: the file system is unlimited, persistent, and directly operable by the agent itself. Once you accept that framing, the engineering problem changes from "how do I fit everything in the window?" to "what's the smallest set of tokens I need in the window right now, given that everything else is one cat away?"
11.2 Why Context Windows Aren't Enough — Even at 1M Tokens
The natural objection: model vendors keep growing context windows. Gemini ships 1M-token windows. Claude Opus 4.6 handles 200K with strong long-context performance. Why bother with external memory?
Three reasons, all of which compound past a few hundred thousand tokens.
Observations can be enormous. A single web page fetch can return 50K tokens of HTML. A PDF extraction can produce 200K tokens. A find . -name "*.py" | head -100 can return 30K tokens of paths and previews. Loading any of these in full is rarely the goal — the agent typically needs a small fraction. Storing the full thing in the window means 95% of the tokens are dead weight competing for attention with the 5% the agent actually uses.
Context accumulation is toxic. Even when individual observations were relevant at the time, their accumulated mass degrades model performance. After 50 tool calls — a normal count for production agents — the window becomes a sediment of stale terminal output, half-read files, fetched documentation for completed subtasks, and old reasoning traces. Chroma Research's 2025 Context Rot study formalized what production teams already knew: as input length grows, model accuracy degrades non-linearly, even on tasks well within the nominal window size.
Compression destroys recoverability. The obvious fix is aggressive in-context summarization. A 12K-token web page becomes a 200-token summary. The problem: if the agent later needs a specific CSS selector or error message that wasn't in the summary, it's gone. Standard compaction is irreversibly lossy. Once the original tokens leave the window, they exist nowhere.
The file system fixes all three. Big observations land on disk, with only a reference in the window. Old context can be evicted because the originals still exist. Compression becomes restorable.
11.3 Manus's Restorable Compression Principle
Manus's central contribution to context engineering vocabulary is the term restorable compression. The principle: every piece of context dropped from the window should leave behind a pointer that can re-materialize it.
flowchart LR
subgraph Before["Before: stuffing into context"]
W1[Web page content<br/>40K tokens]
F1[File content<br/>15K tokens]
T1[Tool output<br/>8K tokens]
CW[Context window<br/>overflowing]
W1 --> CW
F1 --> CW
T1 --> CW
end
subgraph After["After: restorable pointers"]
W2["URL: https://...<br/>~30 tokens"]
F2["Path: /src/x.ts<br/>~20 tokens"]
T2["File: /tmp/output.txt<br/>~25 tokens"]
CW2[Context window<br/>focused]
FS[(Files on disk<br/>full content)]
W2 --> CW2
F2 --> CW2
T2 --> CW2
W2 -.re-fetchable.-> FS
F2 -.re-readable.-> FS
T2 -.re-readable.-> FS
end
style Before fill:#fecaca
style After fill:#dcfce7
Restorable compression. Large content leaves the context window but stays re-materializable via pointers. Nothing is permanently lost — only moved out of active attention.
This contrasts with standard compaction (Chapter 3), which replaces a region of the conversation with a summary. After standard compaction, the original tokens are unreachable — they were transformed in place. Restorable compression keeps the original tokens addressable on disk and replaces the in-window region with a reference.
The pattern in production:
| Resource | In Context | On Disk | Recovery |
|---|---|---|---|
| Web page | URL + 3-line summary | Full HTML/markdown | Re-fetch URL or cat cached file |
| Path + section headings | Full extracted text | cat or grep specific sections | |
| Large code file | Path + key signatures | Full source | cat or grep |
| Terminal output | Exit code + last 20 lines | Full output log | cat /tmp/.../cmd_output.log |
| API response | Status + summary | Full JSON | Re-read file |
A reference implementation:
from pathlib import Path
WORKSPACE = Path("/tmp/workspace")
def restorable_compress(
content: str,
filename: str,
summary: str,
source_url: str | None = None,
) -> str:
"""Write full content to disk, return a compressed context reference."""
filepath = WORKSPACE / filename
filepath.write_text(content)
ref = f"**File:** `{filepath}`\n"
if source_url:
ref += f"**Source:** {source_url}\n"
ref += f"**Summary:** {summary}\n"
ref += f"**Size:** {len(content):,} chars\n"
ref += f"**Recovery:** `cat {filepath}` or grep specific sections"
return ref
The two key properties: the URL or path survives in the window even after the body is dropped, and the recovery action is a single tool call away. The model doesn't need to remember that the page existed — the reference is right there in the window.
The contrast with standard compaction is the entire point. Standard compaction throws away tokens. Restorable compression evicts tokens from one location (the window) and parks them in another (the disk).
11.4 The todo.md Recitation Technique
Manus discovered, in production, that agents averaging 50 tool calls per task lose track of their objective somewhere around action 25–30. The window is full of tool outputs. The original task description is buried. Attention drifts.
Their fix exploits a property of transformer attention: tokens at the end of the context get more attention than tokens in the middle. By writing and re-reading a todo.md file, the agent forces task state into the recency window where attention is strongest.
# todo.md — Task: Migrate auth to JWT
## Objective
Migrate authentication from session-based to JWT-based.
## Progress
- [x] Audit current session-based implementation
- [x] Design JWT structure (access + refresh)
- [x] Implement JWT generation in auth service
- [ ] Update middleware to validate JWT
- [ ] Add refresh token rotation endpoint
- [ ] Update integration tests
## Current Focus
Updating middleware. Replacing SessionMiddleware in
src/middleware/auth.ts with JWTMiddleware.
## Key Decisions
- Access token TTL: 15 minutes
- Refresh token TTL: 7 days
- Algorithm: RS256 with 2048-bit keys
## Blockers
None.
The recitation cycle: at every meaningful checkpoint, the agent reads todo.md, updates it, and writes it back. The updated content appears at the END of context (most recent tool output), pulling attention back to the objective. Each recitation costs ~200 tokens of tool output but provides massive anchoring.
This is a context engineering pattern, not just an organizational one. The same todo.md could be kept as a hidden orchestrator state and re-injected into the system prompt, but that would invalidate prefix caches. Writing it as a tool output keeps caches stable while still delivering the attention benefit. (Chapter 8 covers prefix caching in depth.)
11.5 Claude Code's Multi-Layer External Memory
Analysis of the Claude Code v2.1.88 source bundle revealed a four-layer external memory architecture. Each layer has a different scope and persistence profile, and each is explicitly engineered to keep the active window small.
flowchart TB
subgraph Persistent["Persistent (disk)"]
L1["Layer 1: CLAUDE.md hierarchy<br/>/etc/, ~/.claude/, ./, ./src/"]
L2["Layer 2: Session memory<br/>~/.claude/projects/<proj>/memory/"]
L3["Layer 3: Tool output cache<br/>microcompacted to disk"]
L4["Layer 4: Working scratchpads<br/>PROGRESS.md, TODO.md"]
end
subgraph Context["Active context window"]
CW[Current conversation]
end
L1 -->|loaded every session| CW
L2 -->|read on demand| CW
L3 -->|re-read on demand| CW
L4 -->|read + write during session| CW
style Persistent fill:#e0e7ff
style Context fill:#fef3c7
Four memory layers with different lifetimes and access patterns. Only Layer 1 auto-loads; Layers 2–4 are accessed on demand.
Layer 1: CLAUDE.md Hierarchy (Project Memory)
Covered in Chapter 4. Files at four nesting levels (system, user, project, directory) are loaded at session start and survive compaction because they're read from disk, not stored in conversation. They're the persistent prologue to every session.
Layer 2: Session Memory at ~/.claude/projects/<project>/memory/
A per-project memory directory with a strict file layout:
~/.claude/projects/my-app/memory/
├── MEMORY.md # Index — max 200 lines, pointers only
├── user_role.md # type: user
├── feedback_testing.md # type: feedback
├── project_auth.md # type: project
└── reference_docs.md # type: reference
Every memory file uses YAML frontmatter to declare its type and surface metadata for index loading:
---
name: User Role
description: User's role and project context
type: user
---
# User Role
- Senior backend engineer at FinTech startup
- Project: payment processing service
- Tech: Python 3.12, FastAPI, Postgres, Redis
- Communication: prefers concise explanations, code over prose
MEMORY.md is the index — capped at 200 lines (~1K tokens) to fit comfortably in every session's prologue without meaningful context cost. It carries one-line pointers to the larger memory files so the agent knows what's available without loading any of it.
# MEMORY.md — Index
## User
- user_role.md — role, tech stack, comms preferences
## Project
- project_auth.md — JWT migration in progress, key decisions
## Feedback
- feedback_testing.md — reviewer prefers vitest, no jest
## Reference
- reference_docs.md — API spec, deployment runbook
The 200-line cap is not arbitrary. It's tuned so every session can load the full index for ~1K tokens, then load specific memory files only when needed. This is progressive disclosure for memory: the index is always present, the bodies are demand-loaded.
Layer 3: Tool Output Cache (Microcompacted to Disk)
When tool outputs exceed a size threshold (typically 10–20K characters), Claude Code's microCompact.ts writes them to temp files and replaces the in-context entry with a reference:
Tool output (35K chars) → /tmp/.claude-output/tool-result-a1b2c3.txt
→ In context: "[Output written to /tmp/.claude-output/
tool-result-a1b2c3.txt — 847 lines. Key findings:
3 test failures in auth module.]"
This is restorable compression applied automatically to every tool result that crosses the threshold. The agent doesn't need to think about it; the harness handles it. From the model's perspective, all it sees is a short reference and a recovery action. The 30K of raw output never enters working memory.
Layer 4: Working Scratchpads (Project Directory)
The most ephemeral layer: PROGRESS.md and TODO.md files that Claude Code creates and maintains in the working directory.
# PROGRESS.md
## Session: 2026-04-12
### Completed
- [x] Fixed auth middleware JWT validation (src/middleware/auth.ts)
- [x] Added refresh token rotation (src/routes/auth/refresh.ts)
- [x] Updated 12 unit tests in src/__tests__/auth/
### In Progress
- [ ] E2E test for full auth flow
### Files Modified
- src/middleware/auth.ts (lines 45–120)
- src/routes/auth/refresh.ts (new file)
- src/__tests__/auth/jwt.test.ts (lines 10–85)
These are the in-flight equivalents of Layer 1's CLAUDE.md — short, structured, frequently updated. They serve the recitation function (attention anchoring) and the resumability function (a fresh agent can read PROGRESS.md and pick up where the previous one stopped).
The four layers, viewed as a context-engineering stack:
| Layer | Lifetime | Loaded When | What It Holds |
|---|---|---|---|
| 1. CLAUDE.md | Permanent | Session start | Conventions, invariants, project setup |
| 2. Session memory | Cross-session | Session start (index) + on demand (bodies) | User facts, project state, learnings |
| 3. Tool output cache | Session | Reference always; body on demand | Large tool results |
| 4. Working scratchpads | Within-task | Read frequently for anchoring | Current task state |
11.6 The Scratchpad Pattern
A scratchpad is a file the agent uses for intermediate reasoning that should not pollute the conversation context. The pattern: write thoughts, exploration, alternatives, and rejected ideas to a file; keep the conversation focused on the actions actually taken.
This is the file-system equivalent of the model's hidden thinking blocks (Chapter 4). The difference is durability and recoverability — the scratchpad persists across compaction events and is re-readable on demand.
A typical scratchpad pattern:
# .scratch/auth-migration-investigation.md
## Hypothesis 1 — JWT issued but rejected by middleware
- Checked: middleware reads `Authorization` header (line 47)
- Checked: token verified with `jwt.verify(token, publicKey)` (line 53)
- Issue found: publicKey loaded from `process.env.JWT_PUB_KEY` at startup,
but key was rotated 2 days ago and service not restarted
- ❌ NOT THE BUG — verified key matches running service
## Hypothesis 2 — Clock skew between services
- Checked: NTP sync on auth-service: synced 30s ago
- Checked: NTP sync on api-gateway: 4 minutes ago
- Issue: tokens issued by auth-service expire ~4min before gateway thinks
- ✅ LIKELY ROOT CAUSE
## Decision
Fix gateway NTP sync first; if unresolved, add 5-minute clock skew tolerance.
The scratchpad is one tool call away if the agent needs to revisit a hypothesis, but its contents do not consume window space the way an inline thought tree would. After the investigation, the conversation history shows only the actions taken; the exploration lives in the file.
The implementation pattern is straightforward — a write tool plus a discipline (codified in CLAUDE.md or AGENTS.md) of using .scratch/ for exploratory reasoning. Some teams enforce it through a hook that warns when the model emits long reasoning chains in regular tool outputs.
11.7 Anthropic's Memory Tool
Anthropic ships a first-party memory tool (memory_20250818) that codifies several of the patterns above into a single API:
from anthropic.tools import BetaLocalFilesystemMemoryTool
memory = BetaLocalFilesystemMemoryTool(base_path="./memory")
# Stores at ./memory/memories/
# Operations: view, create, str_replace, delete, insert, rename
The tool exposes six commands — view, create, str_replace, delete, insert, rename — all operating on markdown files under ./memory/memories/. The model invokes them via tool calls; the tool handles file I/O.
The system prompt that Anthropic ships with the tool contains one critical instruction:
"DO NOT just store the conversation history. Store facts about the user and preferences."
That single sentence prevents the most common failure mode of memory systems: agents defaulting to dumping transcripts into memory, which is voluminous, unstructured, and destroys the value of the memory tool. With this instruction, the agent extracts and stores facts instead of raw exchanges.
For custom backends — Postgres, S3, Redis — Anthropic provides BetaAbstractMemoryTool, an abstract base class with the same six commands. Implementations override the storage layer:
from anthropic.tools import BetaAbstractMemoryTool
class PostgresMemoryTool(BetaAbstractMemoryTool):
def __init__(self, conn):
self.conn = conn
def view(self, path: str) -> str:
...
def create(self, path: str, content: str) -> None:
...
# ...etc
The abstract interface keeps the model-facing contract identical regardless of backend, which is the right design — the model should not care whether memory lives on a local disk or a database.
11.8 Subagent Output to Filesystem — Minimizing the Game of Telephone
Multi-agent architectures introduce a subtle context engineering problem: when a subagent passes large research results back through a lead coordinator agent's context, information gets lost or distorted at each hop. The coordinator asked for a comprehensive analysis; the subagent produced one; but by the time the result passes through the coordinator's context window to inform the next step, it's been compressed, paraphrased, or simply truncated. The dynamics are identical to a game of telephone — each relay degrades signal.
Anthropic's multi-agent research system (published June 2025) addresses this directly: subagents write their output to the filesystem (or an external artifact store), then pass only a lightweight reference back to the coordinator.
This is restorable compression (§11.3) applied to multi-agent communication:
| What the subagent produces | What enters the coordinator's context |
|---|---|
| 8K-token research report | File path + 3-line summary (~80 tokens) |
| Generated code module | File path + function signatures (~100 tokens) |
| Structured data extraction | File path + row count + schema summary (~60 tokens) |
The coordinator operates on references. When it needs the full content — to make a decision, to synthesize across subagents, or to pass specific details to the next subagent — it reads the file. The rest of the time, the reference is enough for routing and orchestration.
The pattern works particularly well for structured outputs — code, reports, data tables — where the subagent's specialized prompt produces better results than filtering the same content through a general coordinator's context. A research subagent prompted specifically for academic rigor will produce a higher-quality synthesis than a coordinator asked to relay findings from a tool call. Writing that synthesis to a file preserves its full fidelity.
Implementation is straightforward: subagents call tools to store their work in external systems (files, databases, artifact stores), then return a lightweight reference object to the coordinator:
# Subagent's final action
def complete_research(findings: str, summary: str) -> dict:
filepath = f"/workspace/.research/{task_id}-findings.md"
Path(filepath).write_text(findings)
return {
"status": "complete",
"artifact": filepath,
"summary": summary, # 2-3 sentences only
"token_count": len(findings.split()),
}
The coordinator sees the summary and the path. It can route, prioritize, and orchestrate without loading 8K tokens of research into its own window. When synthesis requires the full content, one cat call brings it back.
A related pattern from the same system: the lead researcher saves its research plan to memory BEFORE spawning subagents. The reason is defensive — if the coordinator's context exceeds 200K tokens, it will be truncated, and the research plan (which defines the entire session's direction) could be lost. Writing critical orchestration state to a file before the context grows is "write critical state to files before compaction" (§10.8) applied at the multi-agent level. The plan survives any truncation event because it lives on disk, not in the window.
Together, these two patterns — subagent output to filesystem, coordinator state to filesystem — mean that multi-agent communication routes through durable storage rather than through volatile context windows. The filesystem becomes the shared memory bus; context windows become the per-agent working sets.
11.9 Design Principles for the File System as Context
A handful of principles fall out of the patterns above. They apply whether you're using Anthropic's memory tool, building Manus-style restorable compression, or rolling your own scratchpad system.
Prefer structured formats. Markdown is the right default. LLMs were trained on enormous quantities of it (GitHub READMEs, docs, wikis), so they parse and generate it fluently. JSON and YAML are appropriate for data interchange, not for memory bodies. Plain text loses the headings and lists that make selective reading possible.
Use clear pointers that survive in context. A URL, a file path, an ID — the pointer is what stays in the window after the body is evicted. Make pointers human-readable and stable: /tmp/workspace/auth_docs.md is far better than obj_8a2f1c. The model needs to see the pointer and know what it can do with it.
Index aggressively. A MEMORY.md index is the table of contents the model sees every session. Without it, the model doesn't know what's on disk and cannot ask for it. The index is the bridge between disk and window — keep it small enough to load every session, structured enough to navigate.
Size limits per file. Indexes capped around 200 lines (~1K tokens). Memory bodies under 500 lines or split into multiple files. Larger files become their own context-management problem: the model has to fit them in the window when reading. Files that exceed the limit get split or summarized into smaller files with cross-references.
Atomic updates. Memory file writes should be atomic — write to a temp file, then rename, never partial-write a file in place. A corrupted memory file silently breaks every future session that loads it.
Date-stamp meaningful entries. ISO 8601 (2026-04-12T14:30:00Z) lets the model and human reviewers reason about staleness. The model should never have to guess whether a fact is from yesterday or last quarter.
11.10 Lossless Context Management — Three Patterns
Three patterns recur across production systems. Together they form what some teams call Lossless Context Management (LCM): the discipline of designing so that no information that mattered is ever permanently lost, even when the window must be cleared.
Pattern 1: Checkpoint Every Multi-Step Task
Every multi-step task gets a structured state file. Checkpoints land at meaningful milestones — not every turn, but at natural breakpoints (subtask completion, before risky operations, before long tool calls).
# .state/issue-142-auth-migration.md
## Meta
- Task: Migrate session auth to JWT (#142)
- Last checkpoint: 2026-04-12T14:30:00Z
- Status: in_progress
## Completed
- JWT generation service (src/services/jwt.ts) — tested
- Refresh endpoint POST /auth/refresh — tested
- 12 unit tests passing
## Current State
- AuthMiddleware partially migrated (line 67)
- File open: src/middleware/auth.ts
## Next Steps
1. Complete error handling in AuthMiddleware
2. Add rate limiting to refresh endpoint
3. Write integration tests
## Key Context
- RS256 keys are in /etc/secrets/jwt-{public,private}.pem
- Old session table NOT to be dropped — keep for rollback
- User.roles is a JSON array, not CSV (gotcha discovered earlier)
The state file is the agent's escape hatch from window loss. If the session crashes, compacts badly, or hands off to a fresh agent, the state file lets work resume without re-discovering the context.
Pattern 2: Searchable Compaction
Standard compaction collapses old conversation into a summary. Searchable compaction does the same, but writes the full pre-compaction content to disk first as a searchable archive:
def archive_pre_compaction(session_id: str, messages: list[dict], summary: str) -> str:
archive_dir = Path(".context-archive")
archive_dir.mkdir(exist_ok=True)
now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
filepath = archive_dir / f"{session_id}-{now}.md"
content = f"# Context Archive: {session_id}\n## Summary\n{summary}\n\n## Full Content\n"
for msg in messages:
content += f"\n### [{msg.get('role','unknown')}]\n{msg.get('content','')[:2000]}\n"
filepath.write_text(content)
return str(filepath)
If the agent later needs detail that the summary dropped, it greps the archive. The summary remains the primary in-context representation; the archive is the recovery path.
Pattern 3: Rhythmic Operation
Long-running agents pulse. They wake, work, write state, sleep. They wake again, read state, work, write state, sleep. The file system is the memory across pulses; the context window is the working set within a pulse.
Session 1: Wake → Read .state/ → Work 20 actions → Write .state/ → Sleep
│
Session 2: Wake → Read .state/ ─────────────────────────────┘
→ Work 20 actions → Write .state/ → Sleep
The startup protocol is short and explicit:
## Agent Startup Protocol
1. Read .state/current-task.md — what am I working on?
2. Read .state/<task-id>.md — where did I leave off?
3. Read memory/CORRECTIONS.md — what mistakes should I avoid?
4. Read the files listed in "Files Modified" — refresh working context
5. Resume from "Next Steps"
The shutdown protocol is the inverse:
## Agent Shutdown Protocol
1. Write checkpoint to .state/<task-id>.md
2. Update todo.md with current progress
3. If learned something, append to memory/LEARNINGS.md
4. If task complete, move state file to .state/completed/
Together, these three patterns give the agent something the context window alone cannot: a continuous identity across pulses. The window is volatile; the file system is durable; the protocols stitch them together.
11.11 When File-Based Memory Is Not the Right Choice
External memory has overhead. It's not free.
Short-lived sessions. A 5-turn QA exchange doesn't need a memory directory. Setting up the directory, loading the index, and writing back state costs more than it saves. The break-even is somewhere around 20–30 turns or one cross-session resumption.
Highly structured state. If your state is a mutable graph of typed objects with referential integrity requirements — say, an active financial transaction with locked rows — markdown files are the wrong storage layer. Use a database. Reserve file-based memory for prose, lists, and lightly structured records.
Sensitive data. PII, credentials, customer secrets — anything that shouldn't live on agent-accessible disk. The fact that the file system is "directly operable by the agent" is a liability when the agent is hallucination-prone or running with broad tool access. For sensitive data, route through a properly access-controlled store with the model receiving only opaque references.
Per-session disposable scratch work. If the work doesn't matter after the session ends and won't be referenced within the session, putting it on disk just clutters the workspace. Keep it in the window if it fits; let it disappear on session end.
The right framing: file-based memory is for tokens that need to survive a context boundary — either the window's size limit, a compaction event, or a session boundary. Tokens that don't need to survive any of these belong in the window.
11.12 Key Takeaways
-
The file system is extended context. Treat files as tokens that exist outside the window but can be brought in on demand. Deciding what lives where is a context engineering decision.
-
Restorable compression is the principle. Every piece of context evicted from the window should leave behind a pointer that can re-materialize it. Standard compaction destroys; restorable compression relocates.
-
todo.mdrecitation exploits attention mechanics. Periodically rewriting the task file forces it into the recency window, anchoring attention on the objective even after 50+ tool calls. -
Claude Code's four-layer architecture is the reference. CLAUDE.md hierarchy, session memory with frontmatter and a 200-line index, tool output cache, working scratchpads. Each layer has a specific lifetime and load pattern.
-
The scratchpad pattern keeps reasoning out of conversation. Write exploration, hypotheses, and rejected ideas to a file. Keep the conversation focused on actions actually taken.
-
Anthropic's memory tool ships restorable compression as an API.
BetaLocalFilesystemMemoryToolfor local disk,BetaAbstractMemoryToolfor custom backends. The system-prompt instruction "store facts, not transcripts" is doing critical work. -
Index, structure, size-limit, atomic-update. Markdown for bodies, YAML frontmatter for metadata, a 200-line index, files under 500 lines, atomic writes, ISO 8601 timestamps.
-
Lossless Context Management = checkpoint + searchable archive + rhythmic operation. Together they let the agent treat any context loss event as recoverable.
-
External memory isn't free. Skip it for short sessions, use a real database for highly structured state, keep sensitive data out of agent-readable files.
Chapter 12: Cross-Session Memory — Context That Outlives the Conversation
"An agent that cannot acknowledge mistakes is dangerous, and one that does not learn from them is useless." — Ben Banwart, on persistent agent memory
12.1 The Statefulness Problem
LLMs are stateless. Every inference call starts fresh. Without external mechanisms, an agent that brilliantly debugged a complex issue on Monday will approach the identical issue on Tuesday with zero memory of what worked. It will re-read the same files, re-form the same hypotheses, and re-discover the same solution — burning tokens, time, and user patience in an exact replay of yesterday's session.
Chapter 11 covered external memory within a session: files that hold tokens which can be brought back into the window. This chapter covers the cross-session case: tokens that persist between sessions, so the next session starts knowing things the previous session learned.
This is still a context engineering problem. The question is the same: what tokens enter the LLM's context window in the next session, and where do they come from? The answer for cross-session memory is: tokens that were committed to durable storage by previous sessions, and re-loaded at the start of the new one.
flowchart LR
subgraph S1["Session 1"]
S1c[Context window]
S1e["• Learn user prefers pnpm<br/>• Fix auth bug<br/>• Decide on JWT approach"]
end
subgraph S2["Session 2 (without memory)"]
S2c[Empty context]
S2e["• Tries npm first<br/>• Re-discovers auth bug<br/>• Re-debates JWT vs sessions"]
end
subgraph S3["Session 2 (with memory)"]
S3c[Context + loaded memory]
S3e["• Uses pnpm immediately<br/>• Knows about auth history<br/>• Continues from JWT decision"]
end
S1 -.context lost.-> S2
S1 -->|persist learnings| M[(Memory store)]
M -->|load at startup| S3
style S2 fill:#fecaca
style S3 fill:#dcfce7
style M fill:#e0e7ff
Without cross-session memory, every session starts from zero. The remedy is explicit persistence of learnings, decisions, and preferences — loaded at the start of the next session.
12.2 What Should and Shouldn't Cross Session Boundaries
Not everything from the previous session should ride into the next one. Three categories of information cross well; three categories don't.
Cross well — load every session:
- User preferences and style. The user wants concise explanations, prefers tabs to spaces, dislikes when you commit without running tests. These don't change between sessions and dramatically affect every interaction.
- Project architectural decisions. The team chose JWT over OAuth, picked Postgres over MongoDB, agreed on the Result type pattern. These rarely change and are expensive to re-derive.
- Lessons learned and corrections. "Last time you used
npm install, but this project uses pnpm." "The rate limiter requires Lua scripts, not MULTI/EXEC, in cluster mode." Each correction prevents a recurring class of mistake. - Ongoing task state for resumable work. The migration is 60% done. These three files still need updating. The next session must be able to pick up where this one stopped.
Cross badly — do not persist:
- Stale file contents. A file you read in session 1 may have been edited in session 1.5 by a human or another agent. Persisting its contents leads the next session to operate on outdated tokens. Persist the path, not the content.
- Per-session exploration dead-ends. You tried hypothesis A, ruled it out, moved to hypothesis B which worked. The dead-end was useful at the time but useless next session. Worse, dead-ends in cross-session memory mislead future reasoning.
- Time-sensitive observations. "The CI is currently broken." "User Alice is online right now." "The deploy queue has 3 items." These are facts about a moment, not about the world.
The discipline: ask of each piece of information, "would this be useful to a fresh agent two weeks from now, on a different task?" If yes, persist. If no, let it die with the session.
12.3 Devin's Knowledge System — The Most Mature Production Implementation
Cognition's Devin has the most developed cross-session memory in production. It operates at three levels, each addressing a different time horizon.
Persistent Knowledge
Devin maintains a Knowledge store of tips, documentation, and instructions that are recalled across all future sessions. The system has several distinctive features:
- Auto-suggested additions. "Devin will automatically suggest new additions to Knowledge" based on what it learns during conversations. When Devin discovers your project uses port 6380 for Redis instead of 6379, it suggests adding this as a knowledge entry.
- Manual curation. Users add, review, edit, and organize knowledge entries in the settings UI. The auto-suggestions are not auto-accepted — a human approves each one. This keeps the store curated rather than an undifferentiated pile.
- Knowledge search and folder organization. Entries are searchable and filed into folders. Deduplication prevents the same tip from being stored multiple times across sessions.
The flywheel: the first session with Devin on a project is slow because it knows nothing. By the 50th session, it has accumulated dozens of project-specific tips that make it substantially faster. The Knowledge store is the explicit, queryable form of "what the agent has learned about this codebase."
Session Insights
After completing a session, Devin analyzes the full trajectory and generates Session Insights: actionable recommendations about what went well, what could be improved, and what patterns should be captured. These are higher-level than individual knowledge entries — they're meta-observations about the agent's own performance, distilled into a form a human can review.
Session Insights become the bridge between raw experience and curated knowledge. The session generates insights; the human (or Devin itself, with approval) lifts the best of them into Knowledge entries that survive forward.
Playbooks: Sessions as Templates
The most powerful accumulation mechanism: Playbooks turn successful sessions into reusable templates. A playbook structure:
- Outcome — what the session accomplished
- Steps — the sequence of actions that worked
- Specifications — requirements and acceptance criteria
- Advice — tips for executing similar tasks
- Forbidden actions — things that were tried and didn't work
- Required context — files, docs, or knowledge entries needed upfront
When a similar task arrives, Devin can execute the playbook instead of figuring out the approach from scratch. The playbook captures not just what to do, but what not to do — forbidden actions encode debugging dead-ends that would otherwise be re-explored. This is the most context-efficient form of cross-session memory because it encodes a procedure, not facts: a single playbook represents what would otherwise require dozens of knowledge lookups.
The scale: Cognition reports 659 PRs merged in one week using playbook-driven sessions. Their internal phrasing — "Cognition uses Devin to build Devin" — captures how playbook-driven memory compresses institutional knowledge into agent-executable templates.
The thing to notice from a context engineering view: the playbook becomes the system prompt content for the new session. It's not "context the agent retrieves," it's "context the agent starts with." The retrieval happens at the playbook-selection layer; once a playbook is chosen, its content is the prologue.
12.4 Claude Code's Cross-Session Memory
Claude Code stitches together three mechanisms for cross-session persistence.
CLAUDE.md Hierarchy
The primary mechanism, covered in Chapter 4. The four-level hierarchy (system → user → project → directory) is loaded at every session start and after compaction. These files survive any context loss event because they're loaded from disk, not from conversation history.
When you discover a project convention during one session — "always use pnpm, never npm" — adding it to the project CLAUDE.md means every future session knows it. The act of writing to CLAUDE.md is itself the cross-session persistence operation.
Session Memory at ~/.claude/projects/<project>/memory/
Covered in Chapter 11. The per-project memory directory persists across sessions for the same project. Where CLAUDE.md is for invariants ("always use pnpm"), session memory is for evolving facts ("the auth migration is on iteration 3, see project_auth.md").
The split matters: things that go in CLAUDE.md should be true essentially permanently. Things that go in session memory may evolve as the project does. Mixing them — putting fast-changing state in CLAUDE.md — turns the project file into a noisy, frequently-edited surface that becomes harder to trust over time.
The Memory Tool for Explicit In-Session Persistence
Anthropic's memory tool (memory_20250818, covered in Chapter 11) is the within-session API for writing to persistent memory. The agent calls memory.create("project_auth.md", "...") to commit a fact mid-session. The next session loads the file at startup. The pivotal instruction in the system prompt — "Store facts about the user and preferences. Do not just store the conversation history" — is what turns the tool from a transcript-dump into a structured memory.
Background AutoDream Consolidation
Claude Code includes a background process — internally referred to as AutoDream — that runs after the session goes idle. It consolidates recent session activity into the persistent memory files. From a context engineering perspective, what matters is the output: updated memory files that the next session loads. The mechanism is interesting but tangential.
The four-phase process:
- Orient — read the existing memory index to understand what's already known.
- Gather — collect new signal from the just-completed session (decisions, learnings, corrections).
- Consolidate — merge new signal into existing memory files, deduplicating against what's already there.
- Prune — remove stale or contradicted entries.
The result is that memory files grow with experience but don't grow without bound. The consolidation pass is what converts raw session signal into the structured, deduplicated form that future sessions actually benefit from. Without consolidation, memory stores silt up with redundant entries; the model's session is then forced to navigate noise.
12.5 Codex's Repository-as-Memory Approach
OpenAI Codex takes the most pragmatic approach to cross-session memory: treat the repository itself as the memory store.
repo-root/
├── AGENTS.md # ~100 lines, table of contents
├── docs/
│ ├── architecture.md
│ ├── api-contracts.md
│ ├── testing-strategy.md
│ └── troubleshooting/
│ ├── auth.md
│ └── build.md
└── .codex/
└── skills/
├── security-review.md
└── deployment.md
Every Codex session starts by reading AGENTS.md. AGENTS.md routes to relevant docs/ and skills/. The docs/ directory is human-written, version-controlled, and maintained as part of the codebase. When an agent learns something new — a debugging technique, a non-obvious gotcha — the appropriate response is to update the relevant doc file.
The lesson OpenAI internalized while building this: skills are cross-session knowledge units. A skill is a bundled set of instructions for performing a specific task — security review, deployment, schema migration. They live in .codex/skills/*.md and are accessible to every session.
# .codex/skills/security-review.md
## Approach
1. Check for SQL injection in all database queries
2. Verify authentication on all API endpoints
3. Check for hardcoded secrets or credentials
4. Review input validation on user-facing endpoints
5. Check dependency versions against known CVEs
## Common Findings
- Use parameterized queries, never string concatenation
- Verify JWT validation includes expiry check
- Check that CORS configuration is restrictive
The philosophical contrast with Devin's Knowledge store is sharp: Codex stores knowledge in the repository itself, not in a separate system. Knowledge becomes version-controlled, reviewable through PRs, and shared across all developers and agents who work on the project. When an engineer updates a troubleshooting guide, every agent that reads the repo benefits immediately. There's no synchronization, no migration, no separate knowledge store to maintain.
The downside: there's no auto-suggestion. The agent doesn't learn from experience unless a human (or a deliberately prompted agent) updates the docs. This makes the pattern best suited for teams that already maintain documentation — for them, agent memory becomes "the docs you should be writing anyway."
The reason this works: git version-controls the memory. Memory updates flow through code review. Bad memory entries can be reverted. Memory at one commit is always paired with code at the same commit. None of those properties are easy to replicate in a separate knowledge store.
12.6 The "Brain Made of Markdown" Pattern
A community-developed pattern for fully persistent agents structures the file system into six cognitive systems that mirror how human memory works.
brain/
├── Identity/ # Who the agent is (role, style)
│ └── core.md
├── Memory/
│ ├── conversation_log.md # Notable interactions only
│ ├── learnings.md # What worked
│ └── corrections.md # What didn't — MOST VALUABLE FILE
├── Skills/ # Capabilities learned
│ ├── debugging.md
│ └── deployment.md
├── Projects/ # Active work state
│ └── active/
│ └── payment_migration.md
├── People/ # Context about collaborators
│ └── alice.md
└── Journal/ # Daily reflections
└── 2026-04-12.md
Six systems: Identity, Memory, Skills, Projects, People, Journal. The entire brain typically loads in 2K–7K tokens — comfortably within any modern context window's session-start budget.
Why corrections.md Is the Most Valuable File
The single highest-value file in the entire architecture:
# corrections.md
### Incorrectly used npm instead of pnpm
- Date: 2026-03-20
- Context: Tried to install dependencies with `npm install`
- Correction: This project uses pnpm exclusively. Use `pnpm install`.
- Root cause: Assumed default package manager without checking lockfile
- Prevention: Always check for lockfile type first (pnpm-lock.yaml → pnpm)
### Forgot timezone in cron schedule
- Date: 2026-04-02
- Context: Set cron to "0 9 * * *" assuming UTC
- Correction: Server runs in America/Chicago. "0 14 * * *" for 9am local.
- Root cause: Assumed UTC without checking server timezone
- Prevention: Always run `timedatectl` before setting cron schedules
Three properties make corrections uniquely valuable as cross-session memory:
- High specificity. Each correction is tied to a concrete scenario, not an abstract principle. The agent can pattern-match incoming situations against past corrections without inferring applicability.
- Direct applicability. When a similar situation arises, the correction is immediately actionable — there's no "okay but how do I apply this principle here?" gap.
- Compounding value. Each correction prevents a class of errors. Over 50 corrections, the agent's error rate drops measurably. There's no growth curve in fact-style memory that compares.
The CLAUDE.md Startup Hook
The brain works because the project's CLAUDE.md instructs the agent to load it at session start:
# CLAUDE.md — Startup Hook
## On Session Start
1. Read identity/core.md for your core identity
2. Read memory/corrections.md for past mistakes to avoid
3. Read memory/learnings.md for accumulated insights
4. Read the relevant projects/<name>/CONTEXT.md
5. Read projects/<name>/TODO.md for current task state
6. Read people/<user>.md for user preferences
## During Conversations
- Add to corrections.md IMMEDIATELY when you make a mistake
- Update learnings.md when you discover something non-obvious
- Write a journal entry at the end of each session
## Memory Rules
- NEVER trust your training data over file-based memory
- ALWAYS check corrections.md before giving advice in a domain
where you've been corrected before
- ALWAYS search memory before claiming you don't know something
The hook is the bridge: without an explicit instruction to load the brain, the agent will start sessions ignorant of files that contain the answers. With it, every session begins by ingesting the accumulated cross-session context.
12.7 OpenClaw's Four-Layer Memory System
OpenClaw, an open-source Claude Code alternative, implements perhaps the most explicit cross-session memory architecture in production.
Layer 1: Bootstrap files. Five files loaded at every session start.
SOUL.md ← Agent personality, values, communication style
AGENTS.md ← Technical capabilities, conventions, "retrieve-before-act"
USER.md ← User preferences, skill level, project context
MEMORY.md ← Cross-session persistent memory (searchable index)
TOOLS.md ← Available tools and usage patterns
Layer 2: Daily memory files.
~/.openclaw/daily/
├── 2026-04-10.md
├── 2026-04-11.md
└── 2026-04-12.md
Each daily file captures significant events, learnings, and decisions. Daily files give temporal context the bootstrap files don't — "yesterday we decided approach X, here's why."
Layer 3: memoryFlush. Before context compaction, the agent writes important facts to memory files. Configurable thresholds determine when:
## Memory Management (from AGENTS.md)
- At 60% context utilization: review for unflushed learnings
- At 80% utilization: mandatory memoryFlush before compaction
- After significant discovery: immediate write to MEMORY.md
This solves a chronic failure mode: facts learned within a session being lost at the next compaction or session boundary because nothing wrote them down.
Layer 4: QMD search. BM25 keyword search over the workspace, paired with a "retrieve-before-act" protocol in AGENTS.md:
## Hard Rule: Retrieve Before Act
Before starting any task:
1. Search MEMORY.md for relevant past experience
2. Search daily/ files for recent related work
3. Search AGENTS.md for applicable conventions
Only then begin the task.
The protocol is what closes the loop. Without it, accumulated memory exists but isn't actually consulted; the agent rederives instead of recalling. With it, memory becomes the first thing the agent checks, and every session benefits from every previous one.
12.8 Skills as Cross-Session Knowledge Units
Skills (SKILL.md files, .codex/skills/, or dedicated skill directories) are the newest form of cross-session memory. Where other memory forms store facts, preferences, or corrections, skills encode reusable procedures — workflows the agent follows when a matching situation arises.
The distinction from other memory forms is structural:
| Memory Form | What It Stores | Example |
|---|---|---|
| CLAUDE.md | Invariants | "Always use pnpm" |
| Session memory | Evolving facts | "Auth migration at iteration 3" |
| Knowledge / Playbooks (Devin) | Successful patterns | "How we deploy to staging" |
| Corrections | Past mistakes | "Don't use npm here" |
| Skills | Executable workflows | "4-phase systematic debugging process" |
The obra/superpowers project is the clearest example. It packages skills as standalone markdown files, each encoding a complete methodology:
systematic-debugging— a 4-phase root cause process: reproduce → isolate → hypothesize → verify. The skill specifies exact steps for each phase, including when to use binary search on commits vs. when to add instrumentation.test-driven-development— encodes RED-GREEN-REFACTOR with explicit rules: write the failing test first, make it pass with minimal code, then refactor. The skill includes decision criteria for when to write unit vs. integration tests.subagent-driven-development— encodes the full dispatch-review loop: decompose task → spawn specialized subagent → review output → integrate or retry.
Each skill is typically 1000–1500 tokens — compact enough to load alongside the task context, rich enough to replace what would otherwise require the agent to figure out from scratch every session.
Skills compound across sessions. Once a team writes a debugging skill, every future session benefits from the encoded methodology without per-session learning. The 50th debugging session uses the same refined process as the 5th — no regression, no drift. This is the cross-session property that matters: skills don't just persist knowledge, they persist competence.
Skills vs. Devin Playbooks. The two are similar in spirit — both encode "how to do X" as a persistent, reusable unit. The difference is authorship and lifecycle:
- Playbooks are auto-generated from successful sessions. The system observes what worked and crystallizes it.
- Skills are manually authored (or agent-authored with human review). A senior engineer encodes their methodology directly.
- Both persist across all future sessions and both are invoked by task-matching.
The trade-off: playbooks capture implicit expertise that humans might not articulate; skills encode explicit methodology that observation might not surface. The best systems will use both.
Cross-organizational sharing. The plugin packaging layer in tools like Claude Code and Cursor enables skills to cross not just session boundaries but organizational boundaries. A systematic-debugging skill authored at one company can be published, installed, and used at another. Knowledge units that cross project and team boundaries are a new category — prior cross-session memory (CLAUDE.md, Devin Knowledge) was always scoped to a single project or user.
From a context engineering perspective, skills are the most compact form of cross-session knowledge because they encode a procedure rather than facts. A single 1500-token skill replaces what would otherwise require dozens of knowledge lookups, multiple correction checks, and significant in-session reasoning to reconstruct the same workflow. The procedure is pre-compiled; the agent just executes it.
12.9 The ACE Pattern — Self-Updating Context
The Agentic Context Engineering (ACE) pattern treats context not as static configuration but as a living playbook that self-updates based on agent performance. Where traditional context engineering asks "what should we put in the context?", ACE asks "how should context evolve based on what's working?"
The core idea: after each session, evaluate what context helped and what didn't, then update the context sources accordingly. The context itself becomes a target of optimization, not just the agent's actions.
The feedback loop:
Session N:
Agent performs task
→ Measure outcome (success/failure, token efficiency, user corrections)
→ Identify which context helped or hurt
→ Update context configuration
Session N+1:
Updated context loaded
→ Better performance
→ Further refinements
→ ...
This extends the "explicit learning" principle from §12.11: instead of just writing corrections to memory, the ACE pattern updates the retrieval rules, skill triggers, and even the system prompt itself. The memory isn't just recording what happened — it's reshaping what the agent sees next time.
What gets updated:
- Skill triggers. If a debugging skill was loaded but unused (the task didn't require it), lower its match priority for similar future tasks. If it was loaded and heavily used, reinforce the trigger.
- Retrieval configuration. If the agent repeatedly reads a memory file and then ignores it, the file's retrieval priority drops. If the agent reads a file and immediately applies its contents, the priority rises.
- System prompt content. Instructions that consistently correlate with good outcomes get reinforced; instructions that correlate with failures or user corrections get revised or removed.
- Skill content. When an agent discovers a better approach than what a skill prescribes, the skill itself can be updated — not just the memory that references it.
The connection to Superpowers' writing-skills skill is direct: agents can create new skills based on workflows they discover during operation. If an agent solves a novel class of problem through a series of steps that works well, the ACE pattern formalizes that implicit discovery into a persistent, executable skill. The next session doesn't just remember that the approach worked — it has a ready-made procedure to follow.
The key insight: traditional cross-session memory asks "what did we learn?" ACE asks "how should we learn differently next time?" It's meta-learning applied to context engineering — the context configuration itself is the thing being optimized across sessions.
12.10 LangGraph's Production Pattern: Checkpointer ≠ Store
LangGraph is the most widely deployed Python framework for stateful LLM agents. The single most common architecture mistake people make in it: confusing the checkpointer with the store.
flowchart TB
subgraph Thread1["Thread: conversation-abc"]
T1msg[Messages<br/>checkpointer]
end
subgraph Thread2["Thread: conversation-xyz"]
T2msg[Messages<br/>checkpointer]
end
subgraph Thread3["Thread: conversation-pqr"]
T3msg[Messages<br/>checkpointer]
end
subgraph Store["Store (cross-thread)"]
Su["namespace: user:alice<br/>preferences, facts, profile"]
Sp["namespace: project:my-app<br/>architecture, conventions"]
end
T1msg -.reads.-> Su
T2msg -.reads.-> Su
T3msg -.reads.-> Sp
style Thread1 fill:#fef3c7
style Thread2 fill:#fef3c7
style Thread3 fill:#fef3c7
style Store fill:#dcfce7
LangGraph's two-layer split. Checkpointer holds per-thread conversation state; Store holds cross-thread facts. Confusing them is the #1 architecture mistake in production.
from langgraph.checkpoint.postgres import PostgresSaver
from langgraph.store.postgres import PostgresStore
DB_URI = "postgresql://user:pass@localhost:5432/agent_memory"
# SHORT-TERM: Thread-scoped checkpoints (state of ONE conversation)
checkpointer = PostgresSaver.from_conn_string(DB_URI)
# LONG-TERM: Cross-session store (facts that persist across all threads)
store = PostgresStore.from_conn_string(DB_URI)
graph = builder.compile(
checkpointer=checkpointer,
store=store,
)
The two have similar shapes but completely different purposes:
| Checkpointer | Store | |
|---|---|---|
| Scope | Single thread/session | Cross-session, cross-thread |
| Data | Full conversation state | Structured facts/knowledge |
| Lifetime | Session duration | Indefinite |
| Query | By thread_id | By namespace + search |
| Use case | "Where was I in this conversation?" | "What do I know about this user?" |
The mistake: using the checkpointer for cross-session memory. Concrete shape: storing facts as conversation messages that get replayed on session start. The symptoms:
- Conversation replay on every session start (slow, expensive — you pay full prefill for an old conversation).
- Facts buried inside conversation context (hard to query, hard to update).
- Checkpoint size growing linearly with use of the system.
- No deduplication — the same fact gets stored repeatedly across threads.
A concrete example. Wrong:
# WRONG: storing user preference as a message in the checkpointer
async def save_preference(state, config):
state["messages"].append(
{"role": "system", "content": "User prefers tabs to spaces"}
)
return state
Now every future thread that loads this checkpoint replays that message. But there's no way to query "what does this user prefer?" — you have to scan the entire message history. And if a different thread learns the same fact, you get a duplicate.
Right:
# RIGHT: storing user preference in the store
async def save_preference(state, config, *, store):
user_id = config["configurable"]["user_id"]
await store.aput(
namespace=("users", user_id, "preferences"),
key="indentation",
value={"choice": "tabs", "learned_at": "2026-04-12"},
)
The store entry is queryable, deduplicatable, updatable, and not paid for in every future prefill of every future thread. From a context engineering perspective, the store is the cross-session memory; the checkpointer is the within-session continuation token.
The rule: if a fact would be useful in a future session with a different thread_id, it belongs in the store. If it's only useful for resuming this exact conversation, it belongs in the checkpointer.
12.11 Design Principles for Cross-Session Memory
Five principles fall out of the patterns above.
Selective persistence. Only persist what would be useful next session. Apply a 10:1 (or harsher) compression ratio: for every 10 messages, persist at most 1 memory entry. Anthropic's memory-tool instruction — "store facts, not transcripts" — is selective persistence in action. Without selectivity, memory stores silt up with low-value entries that drown out the high-value ones.
Decay and forget. Memories should expire unless reinforced. A codebase evolves; preferences change; APIs deprecate; bugs get fixed. An agent acting on stale memory is worse than one with no memory because it acts with false confidence.
def should_retain(memory: dict, current_date: str) -> bool:
age_days = (parse(current_date) - parse(memory["created_at"])).days
confidence = memory.get("confidence", "medium")
max_age = {"high": 180, "medium": 90, "low": 30}[confidence]
if memory.get("validation_count", 0) > 3:
return True
return age_days <= max_age
Time-based expiry is a crude tool, but it beats no expiry. Better: track validation count — every time an entry is read and not contradicted, extend its life. Entries that prove durable get to stay; transient observations age out.
Versioning. Memory can be wrong. The agent that "learned" something incorrect needs a way to be corrected. Treat memory entries as versioned: each has a created_at, optional invalidated_at, and an explicit override path. The corrections.md file is the simplest version of this — a correction supersedes whatever wrong memory created the original mistake.
Retrieval before write. Before storing a new memory, check if a similar one already exists. Without this, the same fact accumulates many entries with slightly different phrasings, all loaded into context, all competing for attention. Devin's Knowledge dedup, OpenClaw's QMD search, the retrieve-before-act protocol — all are versions of this principle.
Make learning explicit. If the agent discovers something and doesn't write it down before the session ends, the learning is lost. OpenClaw enforces this with mandatory memoryFlush at 80% utilization. Claude Code's AutoDream consolidation runs after idle. The Brain-of-Markdown's startup hook says "add to corrections.md IMMEDIATELY when you make a mistake." All instances of the same idea: implicit learning is no learning.
12.12 The Pattern Across Systems
| System | Storage | Auto-Capture | Manual Curation | Retrieval |
|---|---|---|---|---|
| Devin Knowledge | Persistent store | Auto-suggested | Settings UI | Search + folder |
| Devin Playbooks | Templates | From successful sessions | Editable | Task matching |
| Claude Code CLAUDE.md | Markdown files | No | Developer-maintained | Hierarchy load |
| Claude Code memory tool | Markdown files | Agent-driven | Agent-managed | File read |
| Codex AGENTS.md + docs/ | Repo files | No | Developer-maintained | File read |
| OpenClaw | Markdown files | memoryFlush | Developer-maintained | BM25 (QMD) |
| LangGraph store | PostgresStore | Agent-driven | API-managed | Namespace + search |
| Brain-of-Markdown | Markdown files | Agent-driven | Developer-reviewed | Hierarchy load |
Despite varying architectures, every system converges on the same principles: structured facts over raw transcripts, explicit capture over implicit learning, aggressive pruning over unbounded growth, retrieval before write. A cross-session memory system that violates any of these will degrade with use.
12.13 Key Takeaways
-
Cross-session memory is context engineering. The question is which tokens from past sessions enter the next session's window — and where they came from.
-
Devin's Knowledge + Playbooks is the most mature production pattern. Auto-suggested facts, manual curation, and playbooks-with-forbidden-actions create a flywheel where every session makes the next one faster.
-
CLAUDE.md is for invariants; session memory is for evolving facts. Mixing fast-changing state into CLAUDE.md turns it into a noisy, untrustworthy surface. Keep them separate.
-
Codex treats the repository as memory. AGENTS.md + docs/ + skills/ are version-controlled, reviewable, and shared across humans and agents alike. Git becomes the memory store.
-
The corrections file is the single highest-value cross-session memory. Each correction prevents a class of errors with high specificity and direct applicability. Track root cause and prevention, not just the fix.
-
Checkpointer ≠ Store. LangGraph users: facts go in the store, conversation continuation goes in the checkpointer. Mixing them is the most common architecture mistake.
-
Selective persistence, decay, versioning, retrieval-before-write, explicit capture. These five principles separate a memory system that improves with use from one that silts up and degrades.
Chapter 13: Context Isolation — Sub-Agents with Separate Windows
"When one agent tries to handle too many things in a single session, context accumulates, focus degrades, and the quality of each subtask suffers." — Cognition (Devin)
13.1 Sub-Agents Through the Lens of Context Engineering
Sub-agents are typically discussed as an orchestration pattern. This chapter takes a different cut: sub-agents are a context engineering technique. Specifically, they are a way to keep the parent agent's context window small by pushing subtask context into separate, isolated windows that the parent never sees.
Everything else about sub-agents — sandboxing, IPC, permissions, parallel execution, team protocols — is harness territory. From a context perspective, the only things that matter are: how much context does the parent give the sub-agent, what context does the sub-agent build up, and what comes back into the parent's window when it's done.
The motivation is simple. A single agent working a complex task accumulates context from every subtask: the file it read at step 3, the test output from step 12, the documentation fetched for a now-completed subtask at step 20. After 50 tool calls the window is heterogeneous sludge competing with the current task for attention. This is context pollution. The fix used by every production team that ships long-running agents: split work across multiple agents, each with its own clean window.
13.2 The Essential Properties
From a pure context engineering view, sub-agents have three defining properties.
Fresh context window per sub-agent. Each sub-agent's window is independent of the parent's. The 50K tokens the parent has accumulated do not enter the sub-agent's window. The sub-agent starts with whatever the parent passes in — typically a few hundred tokens of task description plus shared filesystem access — and builds its own context from there.
Summary return, not raw transcript. When the sub-agent finishes, it returns a summary into the parent's context, not its full conversation history. The 80K tokens the sub-agent might have consumed internally collapse into a few hundred tokens of result.
Parent context grows by ONE turn per sub-agent call. Regardless of how many tool calls, file reads, or model invocations the sub-agent performed, the parent sees a single tool result. From the parent's window perspective, delegating a sub-agent looks like calling a single tool — the work is invisible.
These three properties together make sub-agents a context compression technique. The sub-agent does the messy work in a private window; the parent sees only the cleaned-up output. From the parent's perspective, a sub-agent is a function that takes a small input and produces a small output, hiding arbitrarily large intermediate state.
13.3 The Token Economics
Concrete numbers make the savings tangible. Consider a parent agent doing a refactoring task that requires inspecting 5 modules:
Inline approach. The parent reads each module, runs tests, traces dependencies, and aggregates findings — all within its own window. After 50 tool calls, the parent has accumulated:
- 5 modules × ~5K tokens = 25K tokens of file content
- 50 tool calls × ~500 tokens each (test outputs, grep results) = 25K tokens
- Reasoning, chain-of-thought, self-corrections: ~30K tokens
- Total parent context: ~80K tokens
Delegated approach. The parent spawns 5 sub-agents, one per module. Each sub-agent does ~10 tool calls of work and returns a 200-token summary. Parent context:
- 5 delegation prompts × ~500 tokens = 2.5K tokens
- 5 sub-agent summaries × ~200 tokens = 1K tokens
- Parent's own coordination reasoning: ~10K tokens
- Total parent context: ~13.5K tokens
The parent's context dropped by ~83%. The sub-agents' contexts collectively used roughly the same total tokens as the inline approach (sometimes 15× more in production cases due to less efficient tool patterns), but the parent's window stays small. Since attention degradation is a function of window size for the agent currently making decisions, the savings translate to better quality, not just lower cost.
flowchart TB
subgraph Solo["Single-agent: everything inline"]
P1[Parent context]
P1 -->|50 tool calls| P1h["History: 80K tokens<br/>files, greps, errors, all inline"]
end
subgraph Multi["Multi-agent: delegated"]
P2[Parent context]
P2 -->|delegates| SA1[Sub-agent A<br/>fresh context<br/>10 calls]
P2 -->|delegates| SA2[Sub-agent B<br/>fresh context<br/>10 calls]
P2 -->|delegates| SA3[Sub-agent C<br/>fresh context<br/>10 calls]
SA1 -->|summary: ~500 tokens| P2h
SA2 -->|summary: ~500 tokens| P2h
SA3 -->|summary: ~500 tokens| P2h
P2h["Parent history:<br/>~15K tokens<br/>(5 summaries only)"]
end
style Solo fill:#fecaca
style Multi fill:#dcfce7
Sub-agents as context-compression. Parent context grows by one summary per delegation, regardless of how much work the sub-agent did.
The trade is real: total token consumption usually goes up with delegation, sometimes substantially. What you buy is per-agent window cleanliness, which translates to better attention, fewer hallucinations, and the ability to scale to longer total tasks.
13.4 Sub-Agent Context Patterns
Production systems implement sub-agent context isolation in two distinct patterns.
Fresh Context Sub-Agent
The sub-agent starts with effectively nothing: the system prompt, the delegation message, and shared filesystem access. None of the parent's accumulated history transfers.
Parent context (50 turns of accumulated work):
- System prompt (cached)
- 50 turns of file reads, tool calls, reasoning
- Current goal: spawn investigation sub-agent
Fresh sub-agent context:
- System prompt (sub-agent's own, may differ)
- Delegation message: "Investigate why test X fails. Return root cause."
- Shared filesystem access (the sub-agent can cat the same files)
The sub-agent's window is a clean slate. Its only knowledge of the task is what the delegation prompt says. This forces the parent to write a clear, self-contained prompt — there's no hand-waving "and you know about all the context above."
The advantage is maximum isolation: the sub-agent's reasoning cannot be polluted by the parent's accumulated noise. The cost is that any genuinely useful parent context must be re-derived from disk or written into the delegation prompt.
Forked Sub-Agent
The sub-agent starts with a copy of the parent's full context, plus a new directive at the end:
Forked sub-agent context:
- System prompt (same as parent — same cache key!)
- Parent's 50 turns of history (same cache key as parent)
- Delegation message: "Now do X based on the work above"
The advantage is cache efficiency. The Claude Code v2.1.88 source leak revealed an important optimization: when a fork uses the same prefix, only the final directive differs, so the fork hits the parent's prompt cache. Re-using the parent's tokens means re-using the parent's KV-cache. The first generation of the sub-agent costs only the delta tokens in prefill.
The cost is that the fork inherits the parent's context pollution. If the parent's window was already messy, the sub-agent's reasoning will be just as polluted as the parent's would have been.
Choosing Between Them
| Use fresh context when... | Use fork when... |
|---|---|
| The subtask is genuinely independent | The subtask needs parent's accumulated context |
| Parent's window is polluted | Parent's window is still clean |
| Cache savings aren't critical | Cache savings matter (long parent prefix) |
| You want maximum attention quality | You want minimum delegation latency |
Most production systems default to fresh context for any sub-agent that runs more than ~5 turns, since the isolation benefit dominates the cache benefit at that scale.
13.5 Return Format Design
The sub-agent's return format is what the parent's context absorbs. Choose deliberately — this is where you decide how much of the sub-agent's work pollutes the parent.
Text summary only. The smallest parent context impact, the most lossy.
Sub-agent returned: "Test X failed because the rate limiter does not handle
distributed timestamps. Fix is in src/middleware/rate-limit.ts line 47."
~30 tokens. The parent learns the answer but not the journey. If the parent needs the journey, it'll have to re-investigate or read scratchpad files the sub-agent left behind.
Structured result (JSON). Parseable, still compact, supports programmatic post-processing.
{
"status": "success",
"root_cause": "rate limiter does not handle distributed timestamps",
"files_to_modify": ["src/middleware/rate-limit.ts"],
"evidence": "Reproduced with curl burst at 1000 RPS, see test_log.txt",
"confidence": "high"
}
~80 tokens, but every field is queryable by the parent. Devin uses this pattern with structured output schemas — the parent declares what fields it needs back, and the sub-agent must return exactly those fields. This makes the return format a contract rather than a guideline.
Artifact reference. "See /tmp/research_results.md" — zero parent context cost.
Sub-agent returned: "Investigation complete. Full report at
/tmp/.scratch/test_x_investigation.md (847 lines)."
~20 tokens in the parent. The full investigation lives on disk. The parent reads it only if needed. This is the same restorable compression principle from Chapter 11, applied to sub-agent outputs.
The return format is a context engineering decision masquerading as an orchestration one. A sub-agent that returns 10K tokens of raw findings defeats the purpose of delegation — the parent's window bloats anyway. The discipline: enforce a return-format contract, and treat verbose returns as a bug.
13.6 Production Implementations — A Context Perspective
Each major production system implements sub-agent isolation slightly differently. Here we look only at the context engineering aspects.
Devin Managed Devins. Each managed Devin runs in its own VM. The coordinator Devin reads only structured outputs (status, files modified, summary) from each managed Devin. The work itself — terminal commands, browser actions, file reads — never touches the coordinator's window. From the coordinator's context, each managed Devin is a single tool call that returns a PR or a summary. The Cognition team explicitly designed this so the coordinator can supervise dozens of managed Devins without its own context exploding.
Codex custom agents (.codex/agents/*.toml). Each custom agent has its own configurable model, tool subset, and skill instructions. The parent context sees only the summary the sub-agent returns. The configuration matters from a context view because skills (Chapter 12) get loaded into the sub-agent's window — different sub-agents can specialize in different skill files without polluting each other's windows. A security-reviewer.toml agent loads only the security-review skill; a style-checker.toml agent loads only the style guide.
Claude Code subagents. Two isolation modes: fresh context (what the Task tool defaults to) and forked context (when the parent's accumulated work is needed). The return is a delta summary "1–2 sentences at most" — a deliberately tight return contract. A sub-agent that executes 40 tool calls, reads 15 files, and runs a test suite 3 times reports back in two sentences. The parent's window grows by tens of tokens, not thousands.
Cursor sub-agent types. Specialized sub-agents — explore, debug, computerUse, videoReview, generalPurpose — each with scoped tool access. The explore sub-agent is read-only by design: it can read files and search code but cannot edit. From a context perspective, the read-only constraint matters because it removes a class of failure mode where an investigation sub-agent silently mutates files, leaving the parent operating on a different codebase than the one in its context.
The convergence across systems: structured returns, fresh contexts by default, an explicit short return format. Different mechanisms, same context engineering goals.
13.7 Anthropic's Multi-Agent Research System — Isolation at Scale
In June 2025, Anthropic published "How we built our multi-agent research system" describing the architecture behind their Research feature. The system is a textbook case of context isolation delivering measurable gains — and a cautionary tale about when multi-agent economics are justified.
Architecture. A Lead Researcher agent (Claude Opus 4) coordinates multiple Subagents (Claude Sonnet 4) that run in parallel with independent context windows. The Lead Researcher decomposes a research question into subtasks, spawns 3–5 subagents simultaneously, and synthesizes their findings into a final report.
Result: 90.2% improvement over single-agent Claude Opus 4 on Anthropic's internal research eval. That number is striking — it's not a marginal gain from better prompting, it's a near-doubling in quality from an architectural decision about context.
The key finding. Anthropic's analysis revealed that "token usage by itself explains 80% of the performance variance." Multi-agent systems work primarily because they let you spend enough tokens on the problem by distributing work across isolated windows. A single agent hitting its context ceiling can't do more work; multiple agents with fresh windows can.
The economics are brutal. The multi-agent research system uses ~15× more tokens than a chat response and ~4× more than a single-agent approach. This is only justified for high-value tasks where quality matters more than cost — deep research queries, not quick lookups.
Critical Architectural Decisions (Context Perspective)
Every major design choice maps to a context engineering principle:
Self-contained delegation units. Each subagent gets a complete task description + output format + fresh context window. The subagent knows nothing about the broader research question beyond what's in its delegation prompt. No shared history, no inherited context, no ambient knowledge.
No inter-subagent awareness. Subagents don't know other subagents exist. They can't coordinate mid-task or read each other's outputs. This isn't a limitation — it's isolation by design. Cross-subagent coordination would require shared context, which would defeat the purpose.
Plan-to-memory before spawning. The Lead Researcher saves its research plan to a persistent memory tool before spawning subagents. Why? Because the Lead's own context may be truncated by the time subagents return (long-running sessions hit window limits). The plan lives outside any single context window — restorable compression applied to the coordinator itself.
Filesystem as return channel. Subagents write their output to filesystem rather than passing large results through the coordinator. Anthropic's framing: "minimize the game of telephone." This is the artifact-reference return pattern from section 13.5 — the coordinator's context absorbs a file path, not 10K tokens of findings.
CitationAgent as a separate verification pass. A dedicated agent with its own fresh context reads the assembled report and verifies citations. This works because citation verification is genuinely independent work — it doesn't need the research context, only the claims and their sources.
Parallelization Economics
The Lead Researcher spawns 3–5 subagents simultaneously; each subagent itself uses 3+ tools in parallel. This two-level parallelism cuts research time by up to 90% for complex queries compared to sequential execution.
From a context engineering perspective, parallelism and isolation are complementary: you can only parallelize safely when each worker has an independent context window. Shared-context parallel agents would create race conditions in attention — one agent's file read polluting another agent's reasoning.
When This Pattern Applies
| Works well | Doesn't work |
|---|---|
| Breadth-first tasks (research many sources) | Tasks needing shared context across workers |
| Heavy parallelization potential | Tight sequential dependencies (most coding) |
| Information volume exceeds a single window | Real-time coordination between workers |
| Many independent tool calls | Tasks where synthesis is harder than gathering |
The critical observation: Anthropic found this architecture works for research but explicitly notes it struggles with tasks requiring tight coordination — which includes most coding tasks. Context isolation shines when subtasks are genuinely independent at the information level.
13.8 Subagent-Driven Development — The Superpowers Pattern
The Superpowers project (github.com/obra/superpowers, 200K+ stars) formalized subagent isolation not as an occasional optimization but as a complete development methodology. Where Anthropic's research system isolates for breadth, Superpowers isolates for quality — using fresh-context subagents as the primary unit of all implementation work.
The Core Loop
Coordinator: plan tasks → for each task:
1. Spawn fresh subagent with precisely crafted instructions
2. Subagent implements (fresh context, no inherited history)
3. First review pass: spec compliance (did it do what was asked?)
4. Second review pass: code quality (is the implementation good?)
5. If passes both → mark DONE → next task
6. If fails → re-delegate with feedback
The coordinator never sees raw implementation details. It maintains a clean context of task descriptions + completion statuses + review summaries. The messy work — reading files, running tests, debugging — happens in disposable subagent windows.
Why It Works (Context Engineering Perspective)
The methodology's core insight, stated directly in its documentation:
"Fresh subagent per task + two-stage review = high quality, fast iteration"
"Subagents should never inherit your session's context or history — you construct exactly what they need"
This is the fresh-context pattern from section 13.4, elevated to a development principle. The coordinator doesn't delegate because it's running out of context — it delegates because fresh-context execution produces better results than continued-context execution, regardless of window pressure.
The coordinator's context stays strategic. It holds the project plan, task dependencies, completion status, and review summaries. It never accumulates file contents, test outputs, or debugging traces. A coordinator that has delegated 20 implementation tasks still has a clean window — 20 task descriptions + 20 status summaries ≈ 4K tokens of coordination overhead.
The Four-Status Return Contract
Subagents return one of four statuses:
| Status | Meaning | Coordinator action |
|---|---|---|
DONE | Task completed successfully | Move to review |
DONE_WITH_CONCERNS | Completed but flagged issues | Review with extra scrutiny |
NEEDS_CONTEXT | Missing information to proceed | Coordinator provides context, re-delegates |
BLOCKED | Cannot proceed (dependency, ambiguity) | Coordinator resolves blocker |
This is a return-format contract (section 13.5) at its most disciplined. The coordinator doesn't parse free-text descriptions of what happened — it reads a status enum and acts accordingly. The status drives the control flow; the optional details are secondary.
Model Selection as Context Optimization
Superpowers treats model choice as part of context engineering. Not all subagents need the most capable (and expensive) model:
- Mechanical tasks (rename variable, add import, run formatter): fastest/cheapest model. The context is simple, the task is well-specified, and reasoning depth doesn't matter.
- Standard implementation (implement a function to spec): mid-tier model. Needs enough reasoning to handle edge cases but doesn't need architectural judgment.
- Architecture and review: most capable model. Needs to reason about trade-offs, spot subtle issues, and make judgment calls.
This isn't just cost optimization — it's context efficiency. Cheaper models respond faster, which means the coordinator gets results back sooner and can proceed with its planning. The coordinator's context doesn't grow while waiting.
Two-Stage Review: Order Matters
The review sequence is deliberate:
- Spec compliance first. Does the implementation match what was asked? This catches scope creep, missing requirements, and misunderstandings before anyone evaluates code quality.
- Code quality second. Is the implementation well-written? This catches style issues, performance problems, and maintainability concerns.
The ordering is a context engineering decision. If code quality review came first, a reviewer might approve beautiful code that doesn't meet the spec — wasting the parent's context on a false positive. Spec compliance is cheaper to check and eliminates a larger class of failures.
Connection to Anthropic's Pattern
Both systems converge on the same core principles despite different domains:
| Principle | Anthropic Research | Superpowers |
|---|---|---|
| Delegation unit | Self-contained task description | Precisely crafted implementation spec |
| Subagent context | Fresh window, no inherited history | Fresh window, no inherited history |
| Return channel | Filesystem (artifact reference) | Status enum + artifacts on disk |
| Coordinator context | Research plan + synthesis | Task plan + review summaries |
| Parallelism | 3–5 subagents simultaneously | Sequential (dependencies between tasks) |
| Primary benefit | Breadth (cover more ground) | Quality (fresh attention per task) |
The shared insight: the coordinator's job is context curation, not execution. It decides what goes into each subagent's window, and it absorbs only summaries back. The execution happens elsewhere.
Single-Agent vs. Subagent-Driven: Context Growth
| Metric | Single agent (30 tasks) | Subagent-driven (30 tasks) |
|---|---|---|
| Coordinator context at task 30 | ~150K tokens (all accumulated) | ~12K tokens (plan + 30 summaries) |
| Attention quality at task 30 | Degraded (window pollution) | Fresh (clean coordinator window) |
| Per-task execution context | Inherited from all previous tasks | Fresh per task (~5-15K) |
| Total tokens consumed | Lower (no delegation overhead) | Higher (~2-4× more total) |
| Quality at task 30 vs. task 1 | Noticeably worse | Comparable |
The trade-off is consistent with section 13.3: you spend more total tokens to keep per-agent windows clean. The Superpowers methodology bets that for multi-task development sessions, the quality-at-task-30 improvement justifies the token overhead.
13.9 The Three-Layer Context Hierarchy for Multi-Agent Coding
When multiple agents work on a shared codebase, naive isolation isn't enough. Each agent still needs to know enough shared invariants ("this project uses tabs, never spaces") to do its work coherently. The pattern that works in production: a three-layer context hierarchy where each layer is loaded selectively.
flowchart TB
subgraph Shared["Layer 1: Root context (20-50 lines)"]
R[Shared invariants]
end
subgraph Backend["Backend Engineer Agent"]
R1[Root] --> B[Backend role context]
B --> BP["Package: api/<br/>+ db/"]
end
subgraph Frontend["Frontend Engineer Agent"]
R2[Root] --> F[Frontend role context]
F --> FP["Package: ui/<br/>+ components/"]
end
subgraph Tests["Test Engineer Agent"]
R3[Root] --> T[Test role context]
T --> TP["Package: tests/"]
end
Shared -.loaded by all.-> R1
Shared -.loaded by all.-> R2
Shared -.loaded by all.-> R3
style Shared fill:#dbeafe
style Backend fill:#fef3c7
style Frontend fill:#dcfce7
style Tests fill:#fae8ff
Three-layer context hierarchy. Each agent gets only its role and relevant package contexts — not the whole codebase's rules.
Layer 1: Root Context (20–50 lines)
Shared across every agent. Project-level invariants that everyone needs to know.
# Root CLAUDE.md
## Architecture
- Monorepo: packages/api, packages/ui, packages/database
- TypeScript 5.4 strict mode everywhere
- Node 20 LTS, pnpm workspaces
## Universal Conventions
- Error handling: Result<T, E> pattern — never throw
- Logging: structured JSON via pino
- No `any` types. Use `unknown` + type guards.
Tiny. Every agent loads it. The point is shared invariants, not detail.
Layer 2: Agent Role Context (100–200 lines)
Role-specific instructions. The backend agent sees database conventions; the frontend agent sees component patterns. Neither sees the other's domain knowledge.
# .claude/agents/backend-engineer.md
## Scope
- OWNS: packages/api/**, packages/database/**
- DOES NOT TOUCH: packages/ui/**, *.css, *.scss
## Database Rules
- All queries through repository classes
- No raw SQL in route handlers
- Always use transactions for multi-table writes
The backend agent gets backend rules. The frontend agent gets a different file with frontend rules. Cross-domain knowledge is not loaded into either agent's window.
Layer 3: Package Context (50–150 lines)
Domain-specific patterns for the exact code the agent is touching: route handler templates, service layer conventions, test patterns specific to the package.
What each agent actually sees:
Backend Agent: Root (30 lines) + Backend role (150 lines) + API patterns (80 lines) ≈ 260 lines
Frontend Agent: Root (30 lines) + Frontend role (120 lines) + UI patterns (100 lines) ≈ 250 lines
Each agent's instruction context is tailored. Zero cross-domain pollution. The backend agent never sees frontend component patterns; the frontend agent never sees database query conventions. Both share the same Layer 1 invariants, so cross-cutting decisions stay coherent.
This pattern composes naturally with sub-agent delegation. A parent backend agent that delegates a sub-agent to investigate a specific service loads the appropriate Layer 3 context for that service in the sub-agent's prompt — keeping the sub-agent specialized and its window small.
13.10 Anti-Patterns
Four context engineering anti-patterns recur across teams that try sub-agents and find them not delivering the expected gains.
Over-delegation. Spawning sub-agents for trivial tasks. Each delegation has overhead — the delegation prompt, the sub-agent's startup costs, the result summary, the parent's interpretation of the result. For a 3-tool-call task, that overhead exceeds the inline cost. Symptom: parent context fills with delegation/result pairs and meta-orchestration reasoning ("now I should delegate to..."). The window spent on coordination outweighs the savings from isolation. Rule of thumb: don't delegate tasks expected to take fewer than 5–10 tool calls.
Under-isolation. Sub-agents share mutable state without coordination, defeating isolation. If two sub-agents both modify package.json, the parent's view of package.json becomes invalidated, and the merge of their work is undefined. Sub-agents that need to share state should communicate through explicit, append-only files (Chapter 11) or limit themselves to non-overlapping subdirectories.
Verbose returns. A sub-agent that returns 10K tokens of raw findings to the parent. The parent's window bloats anyway, defeating the entire point of delegation. Symptom: parent context after a "delegated" task looks no different from parent context after an inline one. Fix: enforce a return-format contract. Devin enforces this with structured output schemas; Claude Code with a "1–2 sentences at most" instruction; you can enforce it with a wrapper that truncates over-long returns.
Eager delegation. Spawning a sub-agent before knowing whether the work is needed. The classic case: the parent thinks "I should investigate X" and spawns a sub-agent without first checking whether X is even relevant. The sub-agent does the work, returns a result, and the parent realizes the investigation was beside the point. Lazy alternative: do the cheap precheck inline first; only delegate when the work is confirmed necessary and substantial.
13.11 When NOT to Use Sub-Agents
Multi-agent isolation is a tool, not a default. Four situations where it's the wrong choice.
Simple linear task. Read file → edit file → run test. The work is sequential, the context stays small, and there's no parallelism to exploit. The overhead of delegation exceeds the benefit. A single agent in a single window does this faster, cheaper, and more reliably.
Strongly sequential dependencies. Even if the task has many subtasks, if each one depends on the previous one's specific output, you can't parallelize. Sequential sub-agents with cross-context handoffs cost more than a single agent doing the same work, because each handoff requires serializing context into a delegation prompt and deserializing a result.
Shared mutable state. If subtasks all read and write the same file, isolation creates merge conflicts and synchronization headaches. A single agent that modifies the file in a known order is simpler and safer than three sub-agents racing for it. Use isolation when subtasks are genuinely independent at the data level.
Short context. If the parent's window is at 20% utilization and likely to stay there, there's no pollution problem to solve. Isolation buys you nothing because nothing is suffering. Reach for sub-agents when context pressure is real — long-running tasks, large file inspections, multi-domain work — not as a default architecture.
The condition that justifies isolation is window pressure. If the parent's window would otherwise grow past the point where attention degrades, isolation pays off. If it wouldn't, isolation is overhead.
13.12 Key Takeaways
-
Sub-agents are context compression. The parent's window grows by one turn per delegation, regardless of how many turns the sub-agent ran internally. That compression ratio is the entire reason to delegate.
-
The three properties: fresh window per sub-agent, summary return, parent context grows by ONE turn. Anything that violates these properties — verbose returns, leaked sub-agent state, eager delegation — eats the savings.
-
Token economics: parent context ~80% smaller, total tokens often higher. You spend more total tokens to keep the parent's window clean. Whether that trade pays off depends on whether the parent's attention quality is the bottleneck.
-
Fresh context vs. fork. Fresh maximizes isolation; fork maximizes cache hit. Default to fresh once subtasks exceed ~5 turns; use fork for short subtasks that need parent context.
-
Return format is a contract. Text summary, structured JSON, or artifact reference. Pick one, enforce it. Verbose returns silently undo delegation.
-
Token usage explains 80% of multi-agent performance variance. Anthropic's research system demonstrates that isolation works primarily by letting you spend more tokens on the problem across parallel fresh windows — not through better prompting or coordination.
-
Subagent-driven development: fresh context per task + two-stage review. The Superpowers pattern shows that systematic isolation (every implementation task in a fresh window) keeps coordinator context at ~12K tokens even after 30 delegated tasks, while single-agent context would reach ~150K.
-
The three-layer context hierarchy. Root invariants (20–50 lines, shared) + role context (100–200 lines, per agent) + package context (50–150 lines, per domain). Each agent's window is tailored to its job.
-
Anti-patterns: over-delegation, under-isolation, verbose returns, eager delegation. Sub-agents that cost more context than they save are common; usually one of these four is why.
-
Reach for sub-agents when window pressure is real. Long tasks, large inspections, multi-domain work. For simple linear tasks, sequential dependencies, shared mutable state, or short contexts, a single agent is simpler, faster, and cheaper.
Chapter 14: Measurement and Iteration
"Start with simple prompts, optimize them with comprehensive evaluation, and add multi-step agentic systems only when simpler solutions fall short." — Anthropic Engineering
14.1 Context Engineering Without Measurement Is Guessing
Every previous chapter argues for one or another context engineering technique. Compaction. Restorable compression. Sub-agent isolation. The CLAUDE.md hierarchy. Each technique has a cost and a benefit, and which dominates depends on your workload, your model, your traffic mix, and a dozen smaller variables.
You will not know which techniques are actually helping you without measurement.
The dangerous failure mode in this discipline is plausible reasoning. "Surely tool result clearing is helping us; we've reduced average tokens per call." But did task quality drop? Did latency improve or get worse? Did cache hit rate change? Without instrumented baselines, every change is a guess that ships into production wearing the costume of an optimization.
This chapter is about the metrics that matter, how to diagnose context problems from them, how to A/B test changes safely, and how to iterate without burning down what already works. The framing throughout: context engineering is empirical. The teams that ship the best agents are the ones that measure first, change one thing, measure again, and keep what works.
14.2 The Metrics That Matter
There are dozens of metrics you could collect. A small handful actually drive decisions. In rough priority order:
Task completion rate. The ultimate outcome. Did the agent finish the task it was asked to do? Everything else is a leading indicator. If your context engineering optimizations improve cache hit rate but task completion drops, you've made things worse — even if every other metric looks better.
Cost per completed task. The economic reality. Total tokens (input + output) at provider prices, divided by task completions. This is what your CFO will ask about. It's also the metric that's most directly affected by everything else on this list — improvements to cache hit rate, compaction frequency, and tokens per task all flow into it.
KV-cache hit rate. The single most important leading indicator (Chapter 8). Target >70–80%. Below 50% is a red alert. Cache hit rate captures whether your prefix is stable: a low rate means you're paying full prefill cost on every call, which dominates both latency and cost. Manus's founder put it bluntly: "If I had to choose just one metric, I'd argue that the KV-cache hit rate is the single most important metric for a production-stage AI agent."
Tokens per task. Efficiency trend. Should decrease with iteration as you improve compaction, dynamic loading, and external memory. If this number is flat or rising over months of "optimization," your changes aren't actually helping.
Compaction frequency. Pressure indicator. How often is the conversation forced to compact mid-task? High frequency means your context is being over-stuffed at every turn — too many tools loaded, too much retrieval, too much history retention. Compaction is recovery, not a feature; if you're recovering frequently, design is the issue.
Average context utilization (%). Target 40–70%. Below 40% means you have room to load more context and possibly improve quality. Above 70% means you're operating under constant pressure — every additional turn risks compaction. Outside this band on either side, look for changes.
p95 time-to-first-token. Latency for user experience. Cache hit rate dominates this number, but tools loaded, retrieval calls, and prompt size all contribute. p95 (not average) because the worst experiences are what users remember.
Tool selection accuracy. For agents with many tools (>20), measure precision and recall of tool selection. Did the model pick the right tool? Did it pick the wrong one when a right one was available? Bad tool selection often points to context confusion — too many tools loaded, ambiguous descriptions, or competing instructions.
Token-to-performance correlation. Anthropic's multi-agent research evaluation revealed a striking finding: token usage alone explains 80% of the performance variance, with tool call count and model choice as secondary factors. This validates the core argument of this book — tokens are the fundamental resource. Multi-agent systems work primarily because they spend more tokens by distributing work across isolated windows. The implication: when measuring agent performance, track total tokens spent (including subagent tokens) as a primary predictor of quality, not just a cost metric.
14.3 A ContextMetrics Implementation
A reference Python implementation that captures all of the above. The point is to make instrumentation cheap so it actually gets added.
from dataclasses import dataclass, field
from datetime import datetime, timezone
from statistics import quantiles, mean
@dataclass
class TurnRecord:
timestamp: str
task_id: str
task_type: str
prompt_tokens: int
completion_tokens: int
cached_tokens: int # tokens served from prompt cache
context_window: int # model's max input
tools_in_prompt: int # tools advertised this turn
tools_called: int # tools the model actually invoked
compacted: bool # did this turn trigger compaction?
ttft_ms: int # time to first token
completed_task: bool # did this turn complete the task?
@dataclass
class ContextMetrics:
turns: list[TurnRecord] = field(default_factory=list)
def record(self, **kwargs):
kwargs.setdefault("timestamp", datetime.now(timezone.utc).isoformat())
self.turns.append(TurnRecord(**kwargs))
def cache_hit_rate(self):
total = sum(t.prompt_tokens for t in self.turns)
cached = sum(t.cached_tokens for t in self.turns)
return cached / total if total else 0.0
def tokens_per_task(self):
per_task = {}
for t in self.turns:
per_task.setdefault(t.task_id, 0)
per_task[t.task_id] += t.prompt_tokens + t.completion_tokens
return mean(per_task.values()) if per_task else 0
def compaction_frequency(self):
return sum(1 for t in self.turns if t.compacted) / len(self.turns)
def context_utilization(self):
utilizations = [
t.prompt_tokens / t.context_window for t in self.turns
]
return mean(utilizations)
def p95_ttft(self):
values = sorted(t.ttft_ms for t in self.turns)
if len(values) < 20:
return max(values, default=0)
return quantiles(values, n=20)[18] # 95th percentile
def tool_selection_accuracy(self):
# tools_called / tools_in_prompt is a precision-like proxy
ratios = [
t.tools_called / max(t.tools_in_prompt, 1) for t in self.turns
]
return mean(ratios)
def task_completion_rate(self, task_type: str | None = None):
relevant = [t for t in self.turns if not task_type or t.task_type == task_type]
if not relevant:
return 0.0
completed_tasks = {t.task_id for t in relevant if t.completed_task}
total_tasks = {t.task_id for t in relevant}
return len(completed_tasks) / len(total_tasks)
def report(self) -> str:
return f"""# Context Metrics
| Metric | Value | Target | Status |
|--------|-------|--------|--------|
| Task completion | {self.task_completion_rate():.1%} | >90% | {"✅" if self.task_completion_rate() > 0.9 else "❌"} |
| Cache hit rate | {self.cache_hit_rate():.1%} | >70% | {"✅" if self.cache_hit_rate() > 0.7 else "❌"} |
| Tokens / task | {self.tokens_per_task():,.0f} | trend ↓ | — |
| Compaction freq | {self.compaction_frequency():.1%} | <20% | {"✅" if self.compaction_frequency() < 0.2 else "⚠️"} |
| Context util | {self.context_utilization():.1%} | 40-70% | {"✅" if 0.4 <= self.context_utilization() <= 0.7 else "⚠️"} |
| p95 TTFT | {self.p95_ttft():,} ms | <3000 ms | {"✅" if self.p95_ttft() < 3000 else "⚠️"} |
| Tool selection | {self.tool_selection_accuracy():.1%} | >30% | {"✅" if self.tool_selection_accuracy() > 0.3 else "❌"} |
"""
The key design decisions:
- One record per turn, not one per session — turn-level data lets you slice by task type, time window, model version.
- Both
prompt_tokensandcached_tokensrecorded — cache hit rate depends on the difference. task_completion_rateaccepts atask_typefilter — aggregating across types hides per-type problems.
14.4 Diagnosing Context Problems — A Decision Tree
When the metrics show a problem, the first response shouldn't be "let me try X" — it should be "what does the metric pattern tell me about the cause?" A short decision tree for the common failures.
flowchart TD
P[Symptom] --> Q1{High cost?}
Q1 -->|Yes| Q2{Cache hit rate<br/>below 50%?}
Q2 -->|Yes| F1["🔧 Unstable prefix<br/>Check for timestamps,<br/>session IDs, non-deterministic<br/>JSON serialization"]
Q2 -->|No| F2["🔧 Context bloat<br/>Audit tool count,<br/>tool output accumulation"]
P --> Q3{Frequent compaction?}
Q3 -->|Yes| F3["🔧 Context pressure<br/>Move tool outputs to files,<br/>clear old results,<br/>add external memory"]
P --> Q4{Good cache,<br/>poor quality?}
Q4 -->|Yes| F4["🔧 Attention problem<br/>Move critical content<br/>to beginning or end,<br/>remove middle clutter"]
P --> Q5{Quality degrades<br/>late in session?}
Q5 -->|Yes| F5["🔧 Context rot<br/>Add state files,<br/>measure at 60/70/80%,<br/>consider sub-agents"]
style F1 fill:#dcfce7
style F2 fill:#dcfce7
style F3 fill:#dcfce7
style F4 fill:#dcfce7
style F5 fill:#dcfce7
A diagnostic decision tree. Each path leads to a distinct fix — context engineering problems look similar from the outside but need very different remedies.
High cost, low cache hit rate → unstable prefix. Inspect the system prompt and tool definitions for non-determinism. Common culprits: timestamps in the system prompt, session IDs in the prefix, JSON serialization that doesn't sort keys, dynamic tool ordering, model-version strings rendered into the prompt. Each of these flips a token at some position N, invalidating the cache from N onward. Fix by moving dynamic content to the end of the prompt and ensuring the static prefix is byte-stable across calls.
Frequent compaction → tools or context bloat. The model is being asked to handle more than it can comfortably hold. Audit: how many tools are loaded per turn? How long is the conversation history? Is the system prompt within bounds? Either reduce the per-turn context (Chapter 4 on context editing, Chapter 11 on external memory) or use sub-agents (Chapter 13) to isolate work.
Good cache, poor quality → attention problem. Cache hit rate is healthy, the model is fast, but task completion is dropping. Suspect context pollution: the model has so much in the window that it can't focus on what matters. Inspect for old, irrelevant content that should have been cleared. Check whether critical instructions are being placed mid-window where attention is weakest. Move important content to the end (recency bias) or to the system prompt (primacy bias).
Sub-agent runs returning too much → return format bloat. If you delegate to sub-agents and the parent's window grows by thousands of tokens per delegation, the sub-agents aren't isolating. Enforce a return-format contract (Chapter 13). Truncate over-long returns automatically. The point of delegation is parent-window cleanliness; verbose returns silently undo it.
Long tasks degrading → context rot. Tasks that complete fine when short but degrade as they grow are showing context rot (Chapter 1). Add explicit state files (Chapter 11) so the model can re-orient. Measure accuracy at 60%, 70%, 80% of window utilization to see where the cliff is. Below the cliff: keep context small. Above the cliff: compact, externalize, or delegate.
Tool selection accuracy dropping → too many tools. When the model has 50 tools loaded and uses 2 of them per turn, it's spending attention budget on tool descriptions instead of task reasoning. Implement tool search (Anthropic's defer_loading) or tool routing so only relevant tools enter the window.
Multi-agent system underperforming → insufficient token budget. If you've moved to a multi-agent architecture and quality hasn't improved as expected, check total token spend. Multi-agent systems use ~15x more tokens than single-agent chat. If budget constraints are artificially limiting subagent depth (fewer tool calls, shorter explorations), the isolation benefit is negated by insufficient investigation. The fix: either increase token budget or restrict multi-agent to high-value tasks where the 15x cost is justified.
14.5 A/B Testing Context Changes
Cursor's engineering blog on dynamic context discovery describes their methodology: every context change is A/B tested against the previous baseline. Their dynamic context discovery rollout showed a 46.9% token reduction with maintained quality — and they only knew this because they measured both arms against real workloads.
The discipline is harder than it sounds. The temptation is to verify the change works on a curated set of examples and ship it. Curated sets always look good — they're the cases the change was designed to handle. Real workloads have a long tail that curated sets don't capture.
A practical A/B framework:
- Define the success metric in advance. "Task completion rate equal or higher" or "Cost per completed task at least 20% lower with no quality regression." Specify the threshold before seeing data.
- Run on real traffic, not curated examples. Sample 10–20% of production requests into the experimental arm. The curated example set is for sanity-checking, not for the final decision.
- Slice by task type. A change that improves average performance can crater performance on a specific task type. Compute the success metric per task type and reject if any type regresses materially.
- Run long enough to see p95 effects. Averages converge fast; p95 latency and tail failures need more samples. A week of real traffic is a typical minimum.
- Hold one variable at a time. Don't ship "compaction tweak + tool router refactor + new system prompt" together. You won't know which one helped or hurt.
The placebo trap: it's surprisingly easy to convince yourself a change is helping when noise is the whole story. If the difference between arms is within day-to-day variance, you have no signal. Statistical significance matters even with informal experiments — eyeballing two numbers and seeing one is bigger is not a result.
Evaluating multi-agent architectures. Anthropic's experience with their Research system offers a model: focus on end-state evaluation rather than turn-by-turn analysis. Multi-agent systems take different paths between runs — you can't prescribe a "correct" sequence of steps. Instead, evaluate whether the system achieved the correct final state. For research tasks: factual accuracy, completeness, source quality. For coding tasks: test pass rate, code quality metrics, spec compliance. The Superpowers methodology adds explicit review gates — spec compliance review (does it match the plan?) followed by code quality review (is it well-built?) — that serve as measurable intermediate checkpoints.
14.6 The Iteration Loop
A simple six-step loop, easy to remember and easy to violate.
flowchart LR
I[Instrument] --> B[Baseline]
B --> H[Hypothesize]
H --> C[Change ONE thing]
C --> M[Measure delta]
M --> D{Improved?}
D -->|Yes| K[Keep + iterate]
D -->|No| R[Revert]
K --> H
R --> H
style I fill:#dbeafe
style K fill:#dcfce7
style R fill:#fecaca
The iteration loop. Change one thing at a time, measure, keep or revert. Context engineering is empirical — "Stochastic Graduate Descent" as Manus's team calls it.
- Instrument. Add metrics for everything you care about. If you can't see it, you can't change it.
- Baseline. Measure current state on real workload. Don't trust your intuition about where things stand.
- Hypothesize. Pick one bottleneck. Form a specific hypothesis about what's causing it. "Cache hit rate is 45% because we render the current timestamp into the system prompt."
- Change ONE thing. Implement the smallest possible change that tests the hypothesis. Resist the urge to fix multiple things at once.
- Measure delta. Run the change against the same workload as the baseline. Compare on the metric the hypothesis predicted would change, and on the side effects (does completion rate drop?).
- Keep or revert. If the change moved the right metric without regressing others, keep it. If not, revert. Either way, log what you tried and what you saw — even null results are data.
The most common failure of this loop in practice is skipping step 1 or 2. Teams change context architecture based on intuition without first measuring whether they had a problem, or measure inconsistently and then can't tell whether the change helped. Both failures stem from treating measurement as overhead instead of as the work.
14.7 Common Production Improvements, Ranked by Typical Impact
After working with multiple production agent teams, a rough ranking of improvements that consistently move metrics. Use this as a starting list when you're not sure where to look.
- Move timestamps and dynamic strings out of the system prompt. Single highest impact on cache hit rate. A timestamp at the top of a 30K-token system prompt invalidates the cache for the entire prompt on every call. Removing it can take cache hit rate from 30% to 90%.
- Implement tool search / defer_loading for large tool sets. When you have 50+ tools, the model's attention is spent on descriptions. Loading only the tools relevant to the current task can cut tool tokens by 80% and improve tool selection accuracy.
- Add compaction with tool result clearing. For agents that go past 100 turns, compaction (Chapter 3) plus selective tool result clearing (Chapter 4) keeps context utilization in the healthy 40–70% band instead of trending toward 95%.
- Move large tool outputs to files. Restorable compression (Chapter 11) for any tool output over ~10K characters. The model gets a path and a summary; the body lives on disk. This single change can halve average tokens per turn for tool-heavy agents.
- Structure conversation history with summaries instead of full transcripts. Older conversation segments collapsed into structured summaries (decisions, completed steps, current state) reduce context cost while preserving the information the model actually needs to continue.
- Isolate with subagents for tasks over ~50 tool calls. When a single agent session consistently exceeds 50 tool calls, context pollution is almost certain. Moving to a subagent-driven pattern — where each subtask runs in a fresh window and returns only a summary — has shown 83% reduction in parent context size (Chapter 13) and up to 90.2% quality improvement on breadth-first tasks (Anthropic's multi-agent research). The trade-off: total token consumption goes up ~15x. The gain: parent-agent attention quality stays high regardless of total task complexity.
These are not the only improvements, but they are the ones that pay off most consistently. If your metrics suggest you're stuck and you don't know where to start, work this list from the top.
14.8 The Manus Philosophy: Stochastic Graduate Descent
Manus's founder coined the phrase "Stochastic Graduate Descent" to describe their approach to context engineering: empirical, iterative, often non-obvious, sometimes regressive before improving. They rebuilt their agent framework four times before landing on the patterns now in production.
The lesson generalizes. Context engineering is not derivable from first principles. Different models behave differently. Different workloads stress different parts of the design. What works for a code-editing agent may fail for a research agent. Your system will need to be iterated, and you should design it to make iteration cheap.
What "designed for iteration" looks like in practice:
- Modular layers. Compaction, retrieval, tool routing, sub-agent delegation as separable components. You should be able to swap any one without rewriting the others.
- Configuration over code. Context window sizes, compaction thresholds, tool counts as config values, not hardcoded constants. This lets you A/B test thresholds without code changes.
- Logged context layouts. Sample 1% of requests and log the full context structure (sizes per layer, tools loaded, compaction state). When something breaks in production, you'll thank yourself.
- Reversible changes. Every shipped change should have a feature flag or kill switch. The change you were sure would help is the change most likely to surprise you.
You will iterate. The teams that succeed are the ones that planned for iteration from day one.
14.9 Pitfalls in Measurement
A short list of measurement traps that destroy more agent projects than they should.
Measuring only the happy path. Your metrics dashboard shows everything green, but production users report failures. You instrumented the cases the agent handles well; the failures aren't being captured. Instrument the edges: failed task completions, abnormally long sessions, sessions that hit the model's hard limits. The interesting signal lives in the tail.
Aggregating across task types. Task completion rate of 85% sounds great until you realize it's 95% for short tasks and 30% for long ones. Aggregate metrics hide per-type failures. Always slice metrics by task type before drawing conclusions.
Ignoring p95 and p99. Average latency is 800ms. Sounds fine. p95 is 9 seconds, p99 is 22 seconds — and those are the experiences users remember. Averages tell you about the median user; tail percentiles tell you about your churn risk.
Not logging enough context to debug failures. A failed task is logged as {"task_id": "abc", "outcome": "failed"}. You will never debug why. Log the prompt structure, the tools loaded, the cache state, the last few turns of conversation, the model output, the compaction state. Disk is cheap; missing diagnostic data is expensive.
Treating averages as truth in low-volume systems. Below ~1000 tasks per day, day-over-day averages are dominated by noise. Smooth over a longer window or use trimmed means before drawing trend conclusions.
14.10 A Pre-Production Checklist
A short checklist for any context-managed agent before it goes to production:
- Cache hit rate monitored with alerts firing if it drops below 50%.
- Token-per-task tracked over time — visible as a chart, not buried in logs.
- Compaction frequency dashboard — both rate (compactions per turn) and latency added.
- Per-tool usage telemetry — for agents with >10 tools, know which ones get used and which are dead weight.
- Context utilization histogram — distribution, not just average. Watch the right tail.
- Regression tests for context regression bugs — when you fix a context bug, write a test that fails if it comes back.
- Structured logs for context layout per request (sampled). 1% of requests log the full context structure. Indispensable when production behavior diverges from intent.
- Per-task-type slicing on the completion metric — not just one global completion rate.
- A defined rollback path for the most recent context change. If the on-call has to figure out the rollback in the middle of an incident, it's already too late.
If you can check all of these, your context engineering is no longer guesswork. You can change one thing, see what happens, and improve over time. That's the entire game.
14.11 Key Takeaways
-
Context engineering without measurement is guessing. Instrument before optimizing. The teams that ship the best agents are the ones that measure first.
-
Eight metrics drive almost all decisions. Task completion, cost per task, cache hit rate, tokens per task, compaction frequency, context utilization, p95 TTFT, tool selection accuracy. Track them all.
-
Cache hit rate is the #1 leading indicator. Target >70%. Below 50% is a red alert almost always traceable to an unstable prefix.
-
Diagnose with patterns, not single metrics. "High cost + low cache hit" is unstable prefix. "Frequent compaction" is context bloat. "Good cache + poor quality" is attention pollution. The pattern points at the cause.
-
A/B test on real workloads, not curated examples. Cursor's 46.9% token reduction was measurable only because they tested against production traffic.
-
Change one thing at a time. Multi-variable experiments produce ambiguous results that everyone interprets to support what they already believed.
-
Five improvements pay off most consistently: stable prefix, tool search, compaction, file-based tool outputs, structured history summaries. Work this list from the top.
-
Design for iteration. Modular layers, configurable thresholds, sampled logs of context layout, reversible changes. You will iterate; make it cheap.
-
Measurement pitfalls: happy-path-only, blind aggregation, average-only, under-logging. Each one masks the failures you most need to fix.
-
Token usage predicts quality. Anthropic's finding — token usage explains 80% of performance variance — reframes measurement. Track total tokens (including subagent tokens) as a leading indicator of quality, not just cost. When quality is low and budget allows, spending more tokens through multi-agent isolation is often the highest-ROI intervention.