AI Context Management Guide
Modern LLM context windows reach 200K to 1M tokens, yet multi-turn agents still fail in production most often because of poor context management. In Anthropic’s framing of Context Engineering, single-turn prompt engineering asks how to phrase one instruction, whereas context management asks how to curate the smallest, highest-signal set of instructions, tool schemas, memory, and live observations inside a finite attention budget at every step.
The Context Window Is an Attention Budget, Not a Dumping Ground
Published window sizes (such as the 200K / 1M limits in Anthropic Context Windows) are hard capacity caps, not quality guarantees. Two empirical effects govern production behavior:
- Context Rot: As conversation turns, verbose tool outputs, and tangential files accumulate, recall and instruction-following degrade—and models become more susceptible to stray directives embedded inside mid-context tool outputs.
- Positional Bias (Lost in the Middle): Lost in the Middle shows that models attend far more reliably to the beginning and end of the context than to the middle. Burying critical rules between twenty log dumps is effectively the same as omitting them.
Budget every component of a turn together and measure with the target vendor’s Token Counting API rather than estimating with another provider’s tokenizer:
Turn Budget = System Prompt
+ Tool Schema Definitions (including attached MCP tools)
+ Conversation History (prior tool_use / tool_result blocks)
+ Current User Input & Injected Material
+ Thinking / Reasoning Headroom + max_tokens Output ReserveHard failure modes are deterministic: input alone exceeding the window fails with 400 prompt is too long, while input plus output hitting the ceiling truncates generation mid-flight (stop_reason: "model_context_window_exceeded"). In production, trigger active pruning or compaction around 60%–75% of the window instead of waiting for overflow.
Four-Layer Layout and Prompt Caching Discipline
Order context blocks from most static to most dynamic. This sharpens model focus and is the prerequisite for hitting Anthropic Prompt Caching and OpenAI Prompt Caching:
[Layer 1: Static System] Role boundaries, repo invariants, output contract ← rarely changes (cached prefix)
[Layer 2: Tool Definitions] Minimal active tool schemas ← stable within session
[Layer 3: Durable Knowledge] Repo map, confirmed decisions, stable references ← stable across turns
[Layer 4: Dynamic Execution] Recent turns, task state, latest tool outputs ← changes every turn (at end)Three common anti-patterns that silently break caching and attention:
- Putting dynamic fields in the system prefix: Injecting per-second timestamps, random trace IDs, or turn counters at the top of the system prompt invalidates the entire cached prefix on every call. Move dynamic state to the tail of the latest user message.
- Attaching unbounded tool schemas: Connecting dozens of MCP servers pins tens of thousands of tokens of JSON schemas into every turn, inflating cost and hurting tool-selection accuracy. Scope active servers per task or load full schemas on demand.
- Burying constraints in the middle: Keep global invariants in Layer 1 and restate the current turn’s acceptance criteria at the end of the latest user message.
Acquisition Strategy: Stuffing, Just-in-Time, or External Retrieval
Choose how external information enters the context based on corpus size, churn rate, and cross-document reasoning needs:
| Strategy | Best Fit | Typical Mechanism | Skip When |
|---|---|---|---|
| Stuffing + Cache | Verified well under window via count_tokens, stable corpus, needs cross-file reasoning |
Core specs, key source files, full contracts | Corpus mutates every turn (cache never hits) or nears window cap |
| Just-in-Time (JIT) | Large repo or doc tree where each task touches only a narrow slice | Give the agent grep, read_file, and a lightweight directory map |
Tool calling is unavailable and answers must finish in a single turn |
| External Retrieval (RAG) | Corpus far exceeds the window, documents change frequently, localized fact lookup | Hybrid vector/BM25 retrieval + reranking (see RAG Evaluation Guide) | Multi-file data-flow analysis where chunking severs code/doc links |
For coding and engineering agents, lightweight maps plus Just-in-Time tool reads consistently beat upfront pre-stuffing: the agent inspects the tree first, reads only the exact files it needs, keeps working memory lean, and always sees the latest bytes on disk.
Four Core Controls for Long-Running Sessions
As multi-turn agents run, context inevitably grows. Reliable runtimes layer four controls in ascending order of cost:
Prune Old Tool Results First (Tool Result Clearing)
In coding, debugging, and data-analysis loops, over 70% of consumed tokens typically come from stale tool outputs—earlier test logs, full file dumps, or raw JSON payloads. Once the agent has acted on them, keeping raw outputs verbatim accelerates Context Rot.
Clear stale tool outputs before summarizing the whole conversation:
- Server-side: APIs such as Claude’s Context Editing automatically strip older
tool_resultand historicalthinkingblocks without custom summarization plumbing. - Client-side / custom harness: Before each request, once token usage crosses your watermark, keep the most recent $N$ tool turns intact and replace older bulky
tool_resultpayloads with a compact placeholder noting the tool name, key reference, and that the tool can be re-run if full output is needed.
Before clearing (Turn 8 — window bloated by stale logs):
[System + Tools] → [Turns 1..4: 38,000 tokens of raw logs/files] → [Turns 5..8: active work]
After clearing (structure preserved, stale payload released):
[System + Tools] → [Turns 1..4: compact placeholders (~200 tok)] → [Turns 5..8: full context]One hard protocol constraint applies across runtimes: never delete tool_use or tool_result blocks outright—model APIs enforce a strict 1:1 match on tool_use.id and reject orphaned blocks with invalid_request_error. Replace only the content payload.
Structured Compaction (Summarization)
When context remains near the watermark even after pruning tool results (for example above 70%), trigger Compaction. Whether using server-side compaction or a client-side summarization call, avoid vague “summarize the chat” prompts and preserve a fixed recovery structure:
- Goal and hard constraints: Non-negotiable architectural rules, security boundaries, and acceptance criteria.
- Confirmed facts and decisions: Root causes found, finalized interfaces, and rationale for key trade-offs.
- Modified files and verification state: Exact paths changed, tests passing, and checks still pending.
- Immediate next steps: What the next turn should execute first.
Drop dead-end debugging noise and discarded attempts. Replace old history with this structured summary while keeping static system rules intact so invariants do not dilute across repeated compactions.
Externalize Durable Memory (Filesystem / Memory Tool)
Treat the context window as working memory (RAM), not durable storage (Disk). Facts that must survive across sessions belong outside the transcript:
- Project conventions: Store in repo-root
AGENTS.md/CLAUDE.mdso every fresh session reloads them cleanly, unaffected by compaction (see Harness Engineering for AI Agents). - Long-horizon task state: Persist to
progress.md/tasks.mdor a scoped Memory Tool directory so sessions can recover cleanly after/clearor restarts (see AI Agent Architecture Patterns).
Isolate Noisy Exploration in Subagents
When a main task requires noisy side work—scanning 20 unfamiliar files, combing through thousands of log lines, or reviewing multiple modules in parallel—do not pour that raw exploration into the main window.
Delegate noisy exploration to a Subagent with its own isolated context window, and return only a concise, structured finding with exact file paths and line numbers to the parent session (see Multi-Agent Systems in Practice).
Production Diagnostics: Four Observable Failure Modes
Track four concrete signals instead of waiting for subjective “the model feels dumber” reports:
| Symptom | Observable Signal | Root Cause | Remediation |
|---|---|---|---|
| Hard truncation / overflow | 400 prompt is too long or model_context_window_exceeded |
No pre-flight count_tokens, or missing thinking/output headroom |
Enforce pre-flight token counting and auto-prune/compact at 70% |
| Cache hit-rate collapse | cache_read_input_tokens drops near zero, bill spikes |
Timestamps, random IDs, or unstable tool order in the prefix | Freeze Layers 1–2 and sort tool definitions deterministically |
| Tool-selection degradation | Wrong tools called, malformed args, skipped verification steps | Too many overlapping MCP servers crowding out task instructions | Trim active toolsets per task and sharpen neighboring tool descriptions |
| Amnesia and rule drift | Late-session turns violate early rules or repeat rejected ideas | Hard constraints lived only in early chat turns and diluted under compaction | Move invariants into AGENTS.md / System Prompt and use structured compaction |
The core rule of context management is simple: manage tokens like memory—freeze static prefixes for caching, fetch dynamic data just in time, prune stale tool outputs early, persist durable state to disk, and isolate noisy exploration in subagents.