On this page
Introduction
If you have built an AI agent seriously, you have probably seen this: by the 30th round (each round is one call to the model) the context, meaning all the text sent to the model that round, is close to its limit, the API bill keeps climbing, and rules agreed earlier start getting “forgotten.” Auto-compaction finally fires and shrinks the older history into a summary, but the summary loses a key detail, say an order number, so every round after that builds on a wrong premise.
At that point you don’t have many buttons. For a single chunk of context there are only five things you can do: keep it, offload it to a file, compact it, delete it, or edit it in place. Zoom out to the whole system and there are two more aggressive architectural choices: drop all history and keep only a structured state (a compact record of the facts that matter), or hand the work to a subagent (a helper agent with its own fresh context). Each button has a study backing it, and each has its own price when pressed at the wrong time.
This post doesn’t walk through the papers one by one. It treats 4 papers and 2 engineering breakdowns, all linked below, as evidence for one engineering question: which chunk of context, when, gets which button, and what does pressing the wrong one cost?
This is a DataSci Ocean cross-paper synthesis. Facts and numbers come from 6 in-depth posts on this site: Context Language Models, SKILL.state, Is Bash All You Need?, SkillZip, Claude Code, and Subagent Fold.
Why context blows up faster than you expect
A stateless model’s compounding bill
An LLM is stateless. It doesn’t remember what it saw last round, so every round it rereads the whole context from the start. Once a token (the basic unit models bill and compute by, roughly a word piece) enters the context, its cost is not paid once.
Is Bash All You Need? (Microsoft and CMU) puts it bluntly: whatever enters at round \( s \) is reread at every round from \( s+1 \) to \( T \), so its real cost is size × rounds remaining. The total read volume of a task is the sum of the context length at every round:
$$ \text{Total read} = \sum_{t=1}^{T} L_t $$Here \( T \) is the number of rounds and \( L_t \) is the context length at round \( t \).
What makes this formula painful is that \( L_t \) itself grows. Take the most common ReAct style, which appends reasoning, action and observation to the history every round, so the context gets longer each time. The result: double the task length and the total cost roughly quadruples. At step \( t \) the length is about \( O(t) \), so \( T \) steps add up to \( O(T^2) \).
That is why context always seems to blow up “suddenly”: the first 10 rounds look fine, and by the 30th round the bill is in a different league.
Not just money: longer means dumber
Long context isn’t only expensive; it makes models dumber. In the warehouse experiments of the SKILL.state paper, even a model like Gemini-3-Flash, keeping full history ReAct-style, fell from 0.90±0.02 accuracy at \( T=10 \) to 0.74±0.14 at \( T=200 \). Beyond the drop in the mean, the standard deviation grew from 0.02 to 0.14, a full 7×, so performance became very unstable.
This matches what practitioners call lost-in-the-middle: when key information is buried in the middle of a long history, models tend to miss it.
Prompt caching lowers the price, not the token count
The first fix many people reach for is Prompt Caching, so a repeated prefix doesn’t have to be recomputed. Caching helps, but it only lowers the price per token. It doesn’t reduce the number of tokens, and it doesn’t reduce context pollution. A context stuffed with irrelevant intermediate results is still stuffed after caching, and the model still has to dig through the noise.
So the question is which things should never stay in the context at all, not just how to make rereading cheaper. Answering it takes a decision framework.
Need the original? Five fates for a chunk of context
The five-way decision table
When DataSci Ocean covered Context Language Models (CLM below), we combined the paper’s analysis of why existing approaches fail with the four tasks of the ContextBench benchmark into the decision table below. The table is our own framework; the paper does not give it directly, but every row maps to a specific ContextBench task.
| The chunk’s situation | What to do | Why | Matching ContextBench task |
|---|---|---|---|
| Needed verbatim later, and small | Keep it in context | Any rewrite risks distortion | Needle Retention |
| Needed verbatim later, but large | Save to a file, keep a pointer in context, grep when needed (Offload) | Summaries are lossy; files are not | KV Store, Log Triage |
| Only the gist matters | Summarize it (Compress / Compaction) | Saves space; some distortion is acceptable | — |
| No longer useful | Delete it | It only takes up space | Noise blocks in the Needle task |
| Fixed structure, small frequent changes | Edit in place | Rewriting the whole thing is costly and error-prone | The 16×16 board in Sudoku Sketchpad |
Table 1 — Five fates for a chunk of context (a framework drawn up by this site)
The order of the questions matters: first ask whether you’ll need the original text later, then how big it is, then whether it keeps changing in small ways. The first question already splits keep/offload from compact/delete, because once you need the original, no lossy operation is allowed.
Here the harness means the layer of code wrapped around the model: it decides what goes into the context each round, how tools are called, and when a summary is triggered.
The table also works as a diagnostic: if your harness can only summarize, what it is missing is offloading (which actively evicts content from the live context) and editing in place. Many agent frameworks ship only auto-compaction, which means one of five buttons works. Faced with content that is large but needed verbatim later, they can only squash it into a summary and hope nothing broke.
From one chunk to the whole system
Those five operations apply to one chunk of context. Across a whole agent system, two architectural choices shape everything:
- Push “delete” to the extreme: not just removing dead chunks, but dropping all history at every step and keeping one structured state (the SKILL.state route).
- Hand context to subagents: subagents handle heavy exploration in their own contexts, and the main loop receives only summaries (the Claude Code approach).
The sections below run from low risk to high, because the later routes save more and are harder to undo when you get them wrong. “Keep” needs no breakdown, so it gets no section of its own.
Who presses the button: from the harness to the model
There is another question, orthogonal to which button: who decides when to press it (When) and how (How)? The CLM paper arranges existing approaches on a three-level spectrum:
| Level | Who decides When | Who decides How | Examples |
|---|---|---|---|
| Harness-defined | Harness | Harness | Codex-style summarization of everything at 75% of budget; MEM1 rewrites every round |
| Action-based | Model | A fixed, human-written menu of operations | Self-Compact, ACM |
| CLM | Model | Model (free operations via Bash/Python) | CLM mirrors the live context into a file |
Table 2 — Who decides when and how to manage context (the CLM paper’s three-level spectrum)
The further down, the more autonomy and flexibility the model has, and the higher the demands on its ability and the risk. How CLM, the most autonomous route, actually performs gets its own section later in the post.
First line of defense: keep intermediate results out
The cheapest context management is to keep things out of the context altogether. Offloading loses no information, so it ranks first, as the lowest-risk move.
Leave intermediate results outside the model
The core claim of Is Bash All You Need?: the most direct saving is to keep large intermediate results out of the context; compressing after the fact is secondary.
Here is a hypothetical (numbers for illustration, not measured in the paper): an agent must find the 20 GitLab issues with “bug” in the title among 500, and the task continues for 9 more rounds after that.
- Tool-only: the tool returns all 500 issues (about 100,000 tokens) into the context and the model picks. Each of the next 9 rounds rereads those 100,000 tokens, about 945,000 tokens in total.
- Bash pipe or PTC: a pipe such as
curl | jq | grep, or PTC (Programmatic Tool Calling, where the model writes a short program that chains several tool calls), filters outside the model, so only 20 titles (about 400 tokens) enter the context. The next 9 rounds total about 48,600 tokens.
That is about a 19× difference. The gap doesn’t come from Bash being smarter: those 99,600 tokens of intermediate data never enter the context, so they are never reread in the next 9 rounds. It is the flip side of the size × rounds remaining bill.
Offload to a file, keep a pointer
Some content can’t be filtered out externally because you really will need it verbatim later; you just don’t need it sitting in the context now. That is the second row of the decision table: save it to a file, keep only a pointer (say, a file path) in the context, and grep it when needed.
Why not just summarize it? Because summaries are lossy and files are not. Once a log is compressed to “the third service timed out,” the exact error line is gone for good; saved as a file, grep timeout pulls it right back. ContextBench’s KV Store and Log Triage tasks test exactly this kind of data: large, but needed verbatim later.
Don’t prepay context for abilities you won’t use
Claude Code applies the keep-it-out idea to system design:
- Skills (progressive disclosure): each Skill occupies one line of description in the context, and its full instructions load only when it’s actually used. The system can carry many abilities without prepaying context for the ones it doesn’t use.
- CLAUDE.md: project-level persistent memory, independent of any single conversation. Project conventions live in a file, so they don’t have to be re-explained each conversation, and they aren’t compressed or forgotten along with it.
Second line of defense: compaction isn’t free
Offloading doesn’t solve everything. Some content only matters as a gist, and some always-on rules keep getting longer. That is when compression comes in. But compression is lossy, so one question comes first.
Before compressing: is there a concrete current query?
The SkillZip paper distinguishes two fundamentally different kinds of compression:
- Relevance-based compression (e.g. LLMLingua): assumes a concrete current question, then removes passages unrelated to it. If a user asks how diabetes is treated, the passages on its causes can go.
- Redundancy-based compression (e.g. SkillZip): for documents with no current query that must hold for every future task, such as system rules or Skills an agent evolved for itself. These must never be cut by relevance: today’s task is algebra, you judge the factorial rule irrelevant and delete it, and tomorrow’s factorial problem blows up. The only safe move is to merge rules that say the same thing, defining once and referencing everywhere.
This maps straight onto engineering decisions: a long tool result in a conversation has a current question to refer to, so it can be cut by relevance; always-on content like the system prompt, CLAUDE.md and Skills can only be deduplicated, never trimmed to fit today’s needs.
The SkillZip paper also points out that preventing redundancy is cheaper than cleaning it up later. This is Zip-on-Write: tidy rules at the moment you write them instead of waiting for them to bloat and compressing afterwards.
The real bill for compression
Bloat in always-on rules is real. The SkillZip paper found that self-evolving Skills, by the fifth round, had grown to 5.6×, 3.1× and 6.7× their original size on three benchmarks: BFCL-V4, LiveMath and SpreadsheetBench.
SkillZip shrinks Skills by 31.2% on average, and the macro-average accuracy over 9 test settings (the plain mean of the 9 scores) inches up from 0.570 to 0.577. At first glance: smaller and better.
Break it down by setting and the story changes: in 4 of the 9 settings, accuracy actually got worse after compression. The worst was Kimi-K2.6 on BFCL-V4, from 0.772 to 0.747, a relative drop of about 3.2%. The small rise in the macro-average hides that nearly half the settings regressed.
The risk of summary-based memory shows up even more clearly in the SKILL.state paper. On τ-Bench retail tasks, Memory(Summary), which uses summary memory, collapsed to 29.9% accuracy, almost 20 percentage points below the Prompt method that simply keeps the history (48.2%). In retail customer service, order numbers, amounts and conditions the customer mentioned are the transaction’s key details; once a summary smooths them over, the actions that follow go wrong.
Put together, Claude Code’s Compaction (which automatically summarizes early conversation near the limit so a long session can continue) should be seen as a last resort for staying alive, not as the default context-management strategy. This echoes the table’s diagnosis: a harness that can only summarize has nowhere else to go when content is needed verbatim.
The extreme route: drop all history, keep a structured state
If compression is lossy and offloading means managing files, why not throw away all history at every step? SKILL.state (Google and Purdue) is the flagship of this extreme route.
How SKILL.state works
Its mental model is an accountant who reads only the current ledger and never flips through the transaction log. Each step no longer gets the whole history, just three things: the fixed task instruction \( P \), a structured state JSON \( \Sigma_t \), and the latest observation \( O_t \).
The model returns three things:
- Reasoning \( R_t \): discarded right after use, never carried to the next step.
- State diff \( \Delta\Sigma_t \): a dictionary merged into the current state; setting a value to null deletes that field.
- The action to execute, \( a_t \).
| |
After that ΔΣ is merged, the state the model sees next step is only “shelf A: 2 boxes, shelf B: empty”; the record that order #17 ever existed never comes back.
Because each step’s input doesn’t depend on the step count, each step is \( O(1) \) long and \( T \) steps cost \( O(T) \) in total, against ReAct’s \( O(T^2) \) (the growth curve computed at the start).
A tempting 41×, and where it came from
The theoretical gap is striking in practice. In a synthetic warehouse environment with 500 independent shelves, at \( T=200 \):
| Method | Total tokens at \( T=200 \) | Growth from \( T=100 \) to \( T=200 \) |
|---|---|---|
| Stateful (keeps full history) | 5,041,164 | About 4.7× (close to \( 2^2 \)) |
| SKILL.state | 122,384 | About 1.9× (close to \( 2^1 \)) |
Table 3 — Token usage in the synthetic warehouse environment (SKILL.state paper)
That is a 41× difference, and the growth rates line up almost perfectly with the \( O(T^2) \) and \( O(T) \) predictions. Accuracy is on its side too: in a high-noise environment, Prompt(ReAct) fell from 0.68 to 0.53, while SKILL.state stayed between 0.97 and 1.00.
The real bet: can relevance be judged in the moment?
Whether SKILL.state works depends less on how strong the model is than on this: can the relevance of a piece of information be judged correctly at the moment it appears? Drop the history and you remove the option of going back to check the raw data. Misjudge while keeping history and you can look back; misjudge after dropping it and there is no way back.
In its Limitations section, the paper itself admits three situations where it must fail:
- The schema can’t be fixed in advance (the schema is which fields the state JSON has): halfway through, the task turns out to need tracking something new, but the related information is long gone.
- An early observation looks irrelevant at the time and turns out to be key later: the most realistic trap, and the easiest to hit in production.
- The trajectory itself is the deliverable: audits, compliance and debug tracing need exactly what happened at each step, so dropping history drops the deliverable.
The experiments also contain a direct counterexample. In a software-repository environment (where Git branches, PRs and CI are tightly linked), at \( T=25 \) SKILL.state scored 0.88±0.08, losing to Stateful, which keeps full history (0.94±0.03), by 6 percentage points; it caught up only at \( T=50 \) and led by 15 percentage points at \( T=100 \). In tightly linked environments, keeping history is better for short tasks, and the advantage of a state only shows once tasks get long enough.
Model ability is also a threshold. Switching to the smaller Gemma-4-31B, accuracy on the \( T=100 \) warehouse task plunged to 0.42. The paper doesn’t analyze why; a reasonable inference is that maintaining a correct state JSON takes more judgment than simply appending history.
Finally, structural validation has a blind spot: the runtime catches malformed JSON but not a patch that is well-formed yet semantically wrong, such as a valid null that deletes a key field. Errors like this raise no alarm, and in tightly linked environments they spread silently.
A pragmatic middle ground: state plus a short rolling history
Weighing these costs, our recommendation (this is the site’s own inference, not validated by experiments in the paper) is not to go all in on dropping history, but to use a structured state plus a short window of recent rolling history. The state keeps token cost linear; the last few rounds of raw history act as a safety net, so when a state update goes wrong the model still has recent original text to check against.
Two engineering traps people overlook
The three routes above are about how to handle content. Even if you handle every chunk correctly, two system-level traps can still waste the effort.
Edit in the wrong place and the KV cache is gone
Standard inference servers save compute through prefix cache reuse: if this request starts exactly like the last one, they reuse the KV cache already computed (the intermediate results the model keeps after reading each token); from the first differing token onward, everything must be prefilled again (the KV for every token recomputed).
The Prompt Caching mentioned earlier relies on exactly this reuse, which only works while the start stays identical. It doesn’t cut the token count, but where you edit the context decides how much of that reuse survives.
So where you edit the context matters as much as how much you edit. Appendix C of the CLM paper works through a theoretical example: Qwen3.6-27B, 20,000 input tokens, 500 generated tokens. The numbers in the table are theoretical values derived from formulas, not measured bills.
The input is the same length in all three cases; the only difference is where the first edited token appears. Everything before it can reuse the cache, and everything after it is recomputed. Read the “append only” row as the last roughly 2,000 tokens being newly appended this round.
| Where the edit is | Reusable prefix | Total compute (FLOPs) | Relative to append only |
|---|---|---|---|
| Append at the end only | 18,000 tokens | \( 1.41 \times 10^{14} \) | 1× |
| Edit the middle | 10,000 tokens | \( 5.74 \times 10^{14} \) | About 4.1× |
| Edit the start | 0 tokens | \( 10.81 \times 10^{14} \) | About 7.7× |
Table 4 — Where you edit decides how much is recomputed (theoretical estimate from CLM’s Appendix C)
This yields a transferable design rule: order the context from front to back by how often it changes.
- Most stable first: the system prompt and long-term notes.
- Rarely changing in the middle: summaries that are already settled.
- Frequently changing last: the latest rounds of conversation and observations.
- If you compress, do it in one batch rather than making repeated small edits in the middle.
The rule costs almost nothing and carries almost no risk, yet it is often ignored. Updating a “current time” or “current progress” field in the system prompt every round, for example, means cutting at the very start every round. The CLM paper also mentions that servers can apply Suffix Cache Reuse (SCR) to ease this, but you can’t assume your inference provider supports it.
Hand off to a subagent and details evaporate at the boundary
Claude Code uses subagents (scoped delegation through the Task tool) for heavy exploratory search: the noise of the search stays in the subagent’s own context, and the main loop receives only a summary. Main-context usage therefore looks like a sawtooth: flat during the subtask, rising a little when the summary comes back, instead of growing without bound.
The price: every subagent boundary is a lossy summary hand-off.
This runs against ordinary software-engineering intuition. A boundary between teams is usually a lossless API: call it and every field you expect comes back. A boundary between agents is a lossy context boundary: the subagent reports only what it considers important, and “important” is defined by the scope of the task it was given.
So the conclusion is pragmatic: if a single loop plus on-demand loading can solve the problem, don’t split just for the sake of splitting. Careless subagent splits can lose details and add latency.
Letting the model press the buttons: works on tight budgets, within limits
Back to the spectrum of who presses the buttons. CLM sits at the most autonomous end: it mirrors the live context into a file and lets the model decide, with Bash or Python, when and how to edit or delete its own context. Offloading and in-place editing from the decision table are both carried out by the model itself in this design.
On a tight budget, it really does work. The paper compares CLM with the conventional summary-based approach (Summary) on three benchmarks:
- BrowseComp-Plus (BCP): a deep-research benchmark over a fixed corpus.
- TerminalBench 2.1 (TB2.1): a benchmark of 89 terminal tasks.
- EdgeBench-10: continuous optimization tasks across 10 code repositories.
The table shows results at a 32K budget. PF stands for petaFLOPs, total compute; smaller is cheaper.
| Benchmark | CLM | Summary (baseline) | Notes |
|---|---|---|---|
| BCP | 59.4% | About 53.3% | CLM 6.1 points higher, 21.5% fewer FLOPs |
| TB2.1 | Same accuracy as Summary | — | CLM uses 29.5% fewer FLOPs |
| EdgeBench-10 (Qwen3.6-27B) | 44.6 (179 PF) | 42.3 (437 PF) | CLM costs about 41% of Summary |
Table 5 — CLM vs. summary-based management at a 32K budget (CLM paper)
CLM wins or ties on all three, with clearly less compute.
Loosen the budget, though, and the accuracy edge disappears. On EdgeBench-10 at a 128K budget, CLM scores 47.3 against Summary’s 47.8, with only about 36% theoretical compute savings left. CLM’s value is concentrated where context is tight and every token counts; it does not win across the board.
There are also some practical limits:
- Models misjudge how many tokens they have used. The “When” in the experiments wasn’t fully autonomous. The harness reminds the model when only 2,048 tokens remain, because the model can’t estimate its own context usage. On BCP, editing rounds don’t count toward the 100-round cap, and over-budget attempts are rolled back and retried, up to 6 times. These are external safety mechanisms that cover for the model, and you’ll need them in your own implementation too.
- There is an ability threshold: Qwen3.5-9B made only 1.4 edits on average on TB2.1, with no edits at all in half the tasks, and a median peak context of 30.2K (budget 32K); Qwen3.6-27B averaged 2.6 edits with a median peak of only 17.6K. Give a small model editing tools and it may not use them.
- Security risk: any region the model can write and later read back is a persistent prompt-injection channel. The paper cites an OpenAI report of a model planting unauthorized instructions in its own compressed summary, which then shaped later behavior. This risk isn’t unique to CLM; it applies to any design where the model writes summaries, state or memory files.
A context-management checklist for agent engineers
Here is the evidence laid out as an adoption order: the earlier steps are safer and cheaper, the later ones save more but are harder to undo when wrong.
- Get the order right first (zero risk): order context from stable to volatile, don’t rewrite the system prompt every round, and compress in one batch. Editing in the wrong place can make a single request’s theoretical compute up to 7.7× higher.
- Keep intermediate results out (low risk): anything you can filter outside the model with pipes or code shouldn’t be dumped into the context wholesale. Caching lowers the price, not the token count.
- Load descriptions only, details on demand (low risk): expose abilities through Skills-style progressive disclosure, and write project conventions into persistent files like CLAUDE.md.
- Offload large content you’ll need verbatim, keep a pointer (low risk): files are lossless, grep when needed; make sure your harness can save and evict from the context, not just summarize.
- Classify before compressing (medium risk): cut by relevance only when there is a concrete current query; always-on rules and Skills can only be deduplicated, ideally tidied at write time (Zip-on-Write). After compressing, check every setting for regressions, not just the average.
- Split off subagents with care (medium risk): split only when exploration noise is big enough to be worth isolating, and remember every boundary is a lossy hand-off; if a single loop with on-demand loading works, don’t split.
- Consider dropping history last (high risk): use it only for tasks where the schema can be fixed in advance, relevance can be judged in the moment, and the trajectory isn’t the deliverable, and keep a short window of recent rolling history as a safety net; be especially careful with short, tightly linked tasks, and validate small models first.
- Let the model edit its own context (high risk): the gains are clear only on tight budgets with strong models; the harness should still provide external token-usage reminders, and treat every region the model can write and later read back as a prompt-injection attack surface.
Conclusion: there is no universal button
Look back at Claude Code: none of its parts is new on its own. Skills are progressive disclosure, CLAUDE.md is persistent memory, Compaction is summarization, subagents are delegation. Its strength is that these mechanisms compose automatically: Skills cap the size of capability descriptions, CLAUDE.md keeps project knowledge from being compressed along with the conversation, subagents isolate exploration noise, and Compaction serves as the last line of defense.
There is no universal button for context management: its cost is size × rounds remaining, so every chunk deserves one question before it enters, “will I need the original later?” Keep out whatever can stay outside the model; when you must compress, tell relevance apart from redundancy; and dropping history is a bet on judging relevance in the moment. Add stable-content-first ordering and a wary eye on every subagent boundary, and your agent won’t start losing its memory by the 30th round.
Further reading: where to dig into each study
| Topic to dig into | Post on this site |
|---|---|
| The five-way decision table, KV-cache position cost, experiments and limits of model self-editing | Context Language Models |
| Replacing history with structured state, the 41× token gap and failure cases | SKILL.state |
| The stateless compounding bill, and how Bash pipes and PTC keep intermediate data outside | Is Bash All You Need? |
| Relevance vs. redundancy compression, Skill bloat and compression fidelity | SkillZip |
| How Skills, CLAUDE.md, Compaction and subagents compose | Claude Code |
| Why a subagent boundary is a lossy hand-off | Subagent Fold |
