What you need to know
Every request sends the whole context again: system prompt, tool definitions, the message history, tool results and thinking blocks. That is why long conversations get slower and more expensive even when each user message is short, and why the window eventually runs out. The goal is not to fit everything in; it is to fit the right things in.
Start from the breakdown
Before choosing a technique, find out what is filling the window. Each driver has its own remedy:
| What fills the window | Remedy |
|---|---|
| Old tool results the agent no longer uses | Context editing: clear older tool results automatically, keep recent ones |
| Old thinking blocks from earlier turns | Context editing that clears stale thinking |
| A very long conversation that must continue | Compaction: summarize older turns into one block |
| Facts that must last across separate conversations | Memory tool: a directory Claude reads and writes, with a backend you implement |
| A large document or code set loaded up front | Just-in-time retrieval: tools that fetch the section needed now |
| Hundreds of tool definitions | Tool search with deferred loading, and per-role tool allowlists |
| Hundreds of independent lookups whose results pile up | Programmatic tool calling, or a batch tool that returns a compact result |
| A stable prefix re-sent on every request | Prompt caching (cost and latency, not size) |
Compaction is a summary
Server-side compaction summarizes older turns when the input passes a threshold, so a conversation can continue past the window. It can drop details: a formatting rule the user gave early, or a record of sections already written. Two controls protect what matters:
- Steer the summary: say what it must keep (requirements, decisions, completed work).
- Store durable requirements outside the conversation, in a file or memory store the agent reads after compaction.
In Claude Code, add instructions after /compact to shape the summary, and use a SessionStart hook with the compact matcher to re-inject state after compaction; its plain-text output is added to the context. A PostCompact hook runs at the right time but is not the route back into the conversation.
Context editing and the cache
Clearing tool results changes the prompt from that point, which invalidates the cache after it. Clearing small amounts often pays the cache-write cost repeatedly. Set a minimum amount to clear so each invalidation frees enough tokens to be worth it.
Memory: what to keep, and for whom
| Store in memory | Look up fresh |
|---|---|
| Preferences, roles, ongoing projects, decisions | Budgets, dates, prices, counts, anything a system of record owns |
Entries should carry a date and source so they can be revised. Scope memory per user or per project, and review entries before they become shared: a note one session writes ("use the staging database for tests") can silently steer every other session that reads it. Memory is also an attack surface (see lesson 7.2).
Large tool catalogs
Many MCP servers expose dozens of tools. Loading 180 definitions into every request costs tokens and lowers selection accuracy. Two complementary fixes:
- Tool search with deferred loading: definitions load only when a search surfaces them.
- Per-role allowlists: enable only the tools each agent role needs; disable the rest of a server's tools by default.
Shortening descriptions to fit more tools makes selection worse, and describing tools as text in the system prompt makes them uncallable.
Changing instructions mid-conversation, cache-safely
Prompt caching matches an exact prefix in this order: tools, then system, then messages. Editing the system prompt or tool definitions mid-conversation invalidates everything cached after the change. When instructions must change (a customer upgrades their plan, a mode switches), append the new instruction later in the message history and leave the cached prefix untouched.
A policy for very long conversations
For agents that run for hundreds of turns under a cost ceiling, separate what must be remembered from what can be trimmed:
- record commitments and decisions as structured notes the agent reads every turn;
- compact or trim older turns once the context passes a threshold;
- never drop turns blindly or ask users to repeat themselves.
In the exam
Context items describe a long-running agent near its limit or its budget, often with a token breakdown. Identify the largest driver and pick the technique built for it; check whether the proposed change breaks the cache or loses something the agent still needs. Distractors raise max_tokens (an output limit), buy a bigger window, cache everything, compact every turn, or edit the system prompt dynamically.
Check your understanding
A log agent's context is mostly old 8,000-token search results, but its early decisions are still needed. Which policy fits?
Show answer
Answer: D. Context editing removes the stale tool output while keeping the decisions. Compaction rewrites everything, and max_tokens limits output, not input.
A customer upgrades mid-conversation, and the app edits the system prompt. Cache hits collapse. What is the cache-safe change?
Show answer
Answer: B. Content after the cached prefix can change freely. Any edit to tools or system changes the prefix and invalidates the cache.
A finance assistant must remember each user's currency and report style across conversations weeks apart. Which mechanism fits?
Show answer
Answer: C. Compaction extends one conversation; memory carries durable facts across conversations. Caching expires and is not memory.
Apply it: Set the context policy for Cobalt's triage agent
Cobalt's triage agent handles some long threads: a patient with a chronic condition may exchange 200 messages with the care team over weeks, in one conversation. The token breakdown for long threads is: 52% old search_protocols results, 18% lookup_patient and get_care_plan results repeated on many turns, 12% thinking from earlier turns, 10% system prompt and tools (cached), 8% conversation text. The privacy officer will not allow patient content in any store the team has not approved.
- Assign a technique to each driver in the breakdown.
- Decide what must never be lost when old turns are trimmed, and where it lives.
- Check your policy against the cache, and adjust it if needed.
- Say what you would not use, and why.
Show model answer
1. Techniques
| Driver | Technique |
|---|---|
| Old protocol search results (52%) | Context editing: clear tool results older than the last few, with a minimum clear amount |
| Repeated patient and care-plan results (18%) | Fetch fresh when needed; keep only a compact current summary in the conversation |
| Old thinking (12%) | Context editing that clears thinking blocks from earlier turns |
| System prompt and tools (10%) | Already cached; keep the prefix stable |
2. Must not be lost. Commitments made to the patient ("nurse will call Tuesday"), allergies flagged, and open follow-ups. They are written to a structured care-thread note in Cobalt's approved clinical record store (not a new memory store), and the agent reads it every turn.
3. Cache. Clearing invalidates the cache after the cleared point only, and the system prompt and tools stay cached. Setting a minimum clear amount (for example 30,000 tokens) avoids paying cache writes every few turns.
4. Not used. Compaction on every turn (lossy and costly for clinical commitments), a bigger window (cost grows with every turn), and a new memory store for patient facts (not approved by the privacy officer).