An agent’s context fills up. Let the model edit its own context as a file and it scored 59.4% on BrowseComp-Plus at a 32K limit, 11.4% above the best summary harness.
Learn how a model can hold the pen on its own memory, what that costs a server, and how the strategy can be steered, evolved and trained.
Pick a way to manage the context, then drag the number of turns. Watch the line hit the 32K limit, or get cut by a summary, or stay low because the model keeps editing. Then we build, piece by piece, the file, the edits, the cost, the cache trick and the training.
You need a rough idea of what a chatbot does (it reads text, then writes more) and a little Python for the code. We build the rest from zero.
Based on Context Language Models (arXiv 2609.37725) by Rulin Shao, Shannon Zejiang Shen, Junjie Oscar Yin, Yuetai Li, Minheng Wang, Hamish Ivison, Radha Poovendran, Nathan Lambert, Teng Xiao, Mike Lewis, Wen-tau Yih, Luke Zettlemoyer and Pang Wei Koh, from the University of Washington, Meta Superintelligence Labs, MIT and Trillium Labs. Code. Every idea is re-taught here in our own words and devices. It is a reading for Lecture 4, Harness Evolution, of MIT MAS.S62 AI4AI.
Toy model, illustrative numbers: a 1,500 token system prompt, then 700 tokens per turn (600 tool result, 100 action). The summary harness compacts to a 2,000 token summary when the context passes 28,672 tokens and loses a 40 token fact from turn 5. The CLM keeps a 60 token note per turn and the last three turns raw. The 32,768 token limit is the paper’s pilot setting. Cost here counts tokens read, not the paper’s FLOPs (Chapter 4).
Chapter 0
See why a long task overflows a model’s window, and why somebody has to decide what to throw away
Picture an assistant that must answer a hard question by searching the web. It runs a search, reads the result, runs another, and reads again. After forty searches it has a long pile of pages in front of it. It must now remember a name it saw on search three, and a date it saw on search nineteen.
A language model has the same problem, and it is a hard one. A language model is a program that reads text and writes the next piece of text. It does not remember anything by itself. It only sees what you hand it on each call. Think of a desk: the model can work only with the papers lying on the desk right now.
The papers on the desk are the context: all the text the model reads before it writes. The text is cut into tokens, small pieces such as a short word or part of a long one. A context window is the largest number of tokens the desk can hold. The paper’s pilot study fixes it at 32K, which is 32,768 tokens, about 24,000 English words.
An agent is a model in a loop. In each turn it writes an action, such as a search. A tool runs the action. The result comes back as new text. The loop adds the action and the result to the context, and the next turn begins.
Every turn adds text. Nothing is ever taken off. This is the normal rule for a language model: it appends. After enough turns the pile is taller than the desk. The model cannot read what does not fit.
Somebody has to clear the desk. Today that somebody is usually not the model. It is a harness: the ordinary program that wraps the model, runs the loop, calls the tools and builds each prompt. A common harness rule says: when the pile reaches a set size, ask the model to write a short summary, and replace the whole pile with the summary. This is called compaction.
Compaction works, but it is blunt. The harness decides when to cut and how to cut. It does not know that the name from search three is the key to the whole task. The summary may drop it. Try the hero at the top of this page again: the pink line is that harness, and the blue fact planted at turn 5 does not survive its first cut.
This paper asks a simple question. What if the model itself decided? What if the model could edit its own context, the way you can edit a file? The authors call such a model a Context Language Model, or CLM. Their answer, in one line: yes, and it works better and costs less than the harness rules people wrote by hand.
The paper measures the problem with one number. Context pressure is the total input that arrives over a whole task, divided by the context limit. At 1×, a model that kept everything would just fill its window. At 8×, the task pushes eight windows of text through a window that holds one. The pilot study goes up to 24×.
Slide the pressure below. The row of blocks is the input in the order it arrives. The warm blocks are what an append-only context still holds, which is always the newest part. The three blue diamonds are facts the task needs later.
Forty-eight blocks of input arrive left to right. The window holds the newest blocks. Raise the pressure and watch which blocks, and which facts, fall off the left edge.
Illustrative: 48 equal blocks and three facts at blocks 6, 20 and 34. The pressure stops (0.5× to 24×) follow the range the paper tests in its pilot study (Figure 2). The window share is 1 divided by the pressure.
At 0.5× nothing is lost, because the whole task fits twice over. At 1× it just fits. At 2× half the input is gone, and the first fact has already fallen off. At 8× seven blocks in eight are gone. A smart reader would now ask: which blocks should we have kept? That is exactly the question a context manager has to answer, again and again, for the whole run.
Most earlier work gave the model a few buttons: summarize now, save this to a file, search my notes. The model may press a button, but a person decided which buttons exist. The authors point to The Bitter Lesson, an essay by Richard Sutton. Its claim: over many years, general methods that use computation beat tricks that people design by hand. Here the hand-built tricks are the context rules. The paper’s answer is to take the buttons away and give the model the whole desk.
The rest of this lesson builds that idea in the order the paper does. First the old harness moves and the small tests that break them. Then the CLM itself, a surprisingly short idea. Then what models do with it, what it costs a server, and a trick to make that cost smaller. Then two ways to improve it: tell it what to do, or train it. We end with the results, the limits and a field guide.
Chapter 1
Meet the harnesses that manage context today and the four small tasks that show where each one breaks
You run a small shop and keep your accounts in a notebook. When the notebook page fills, you could tear off the old pages and write a one-line summary on the new page. Or you could rub out one wrong number and write the right one. The first move is easy to automate. The second needs you to look at the page and decide.
Agent builders face the same choice. Before the CLM, almost every system took the first road: a fixed rule, written by a person, that cuts the context in a set way. Let us name the main kinds, because the paper compares against all of them.
A harness-defined method lets the harness choose both when and how. The Codex-style summary (the scheme in OpenAI’s Codex agent, with a similar one described by Cursor) waits until the context reaches a set length, then asks the model for a summary and restarts from it. MEM1 acts every turn: it merges what it kept with the new result and drops the rest of the history.
An action-based method gives the model a few tools and lets it pick when to use them. Self-Compact and AutoCompact let the model decide when to compact. Context-as-a-Tool lets it trigger compaction over a chosen part. ACM adds offloading (write a long result to a file and keep only a pointer) and retrieval (read it back later). Sculptor lets the model hide, restore and summarize fragments. Context Folding lets it branch into a sub-task and fold the branch into a summary when it returns.
A REPL variable method, the Recursive Language Model (RLM), stores a huge input in a variable of a read-eval-print loop (REPL), an interactive code prompt. The model reads slices of it on demand. This decides what to read in. It does not edit the live context, which keeps growing.
| Family | Who decides when | Who decides how | Examples |
|---|---|---|---|
| Harness-defined | The harness (length or every turn) | The harness | Codex-style summary, MEM1 |
| Action-based | The model | A tool that a person wrote | Self-Compact, ACM, Sculptor, Context Folding |
| REPL variable | The model | Code over a read-only input | RLM |
| Context as a file | The model | The model, with any command | CLM (this paper) |
Read down the first two columns. Model autonomy rises at each row. But in the first three rows it stays inside a menu a person wrote. The paper pushes it to the limit in the last row.
Before building the CLM, the authors ask a fair question: do these fixed methods really fail, or does it only look that way on hard tasks? Hard tasks mix many skills. A model might fail because it lacks knowledge, not because it managed its context badly. So they build ContextBench, four synthetic tasks that need no search and no clever reasoning. If an agent could keep everything, it would answer every question. Any failure is a context failure.
The rules are strict. Input arrives as a stream of operations, each one a new user message in one long conversation. The agent controls only when the next one arrives: it runs echo READY_FOR_NEXT_OP when it is done with the current one. No harness can trim an operation on the way in. The context limit is 32,768 tokens. The paper reserves 2,048 for the answer, which leaves 30,720 usable.
The first two need retention and surgical update. The last two need offloading and retrieval. The paper varies the pressure from below 1× up to 24×, using GPT-5.4, and compares seven methods (Figure 2).
The paper gives three reasons, and the Sudoku task shows the cleanest one. A summary of a board can lose or invent a digit. A method without in-place editing has one way to change one cell: write the whole board again. Each rewrite is appended, so the context fills with old boards. Drag the moves and compare the two lines.
Each move changes one cell. The pink line rewrites the whole board after every move. The teal line edits that one cell in place. Drag the number of moves.
Illustrative numbers: an 800 token prompt, a 520 token board (256 cells with separators), a 30 token move message. The mechanism, rewriting the full state for each fine edit, is the failure the paper reports for methods without in-place editing (Section 3). The 32,768 token limit is the paper’s.
The rewriting line crosses the limit at move 59. The editing line stays near 1,350 tokens for all 100 moves. The other two tasks fail for a different reason: standard coding tools can write a value to disk but cannot evict it from the live context on demand. The value stays on the desk after it is saved. No method in the pilot scored perfectly, even on these toy tasks. That result is the motivation for everything that follows.
Chapter 2
Replace append-only text with a file the model may rewrite, and see how one equation and one sync rule carry the whole idea
Open a text file on your laptop. You can type at the end. You can also click in the middle, delete a paragraph, or change one word. Nobody gave you a “summarize” button, yet you can summarize, because you can write anything anywhere.
The CLM gives the model that same freedom over its own context. The idea fits in one sentence: the context is a file, and the model may edit it with ordinary commands. This chapter shows the one equation behind it and the one rule that makes it work.
A normal language model has a context c at turn t. In one turn it writes new tokens, and the context becomes the old context with those tokens stuck on the end. The paper writes this as Equation 1.
The CLM drops the ⊕. The model does not just add to the context. It produces the next context in full. This is Equation 2.
The paper stresses that Equation 2 contains every earlier method. A summary harness is one particular function. A tool that offloads a result is another. The difference is who writes the function. Before, a person wrote a few of them into the harness. Now the model writes whatever it needs, either in its plan or as a helper it defines and reuses (Chapter 3).
How does a model “return the next context” in practice? It does not output the whole context again, which would be slow and costly. The authors use a plain file system trick, with three parts.
bash, the same command line it would use on any file. It can append, search and replace, delete lines, or run a small script over the file.Append stays the default. That choice matters for cost: an untouched prefix can be cached by the server (Chapter 4). The design, in the authors’ words, balances context reuse against the freedom to edit.
Many agents work the same way. If an agent swarm needs three workers, the workspace holds three context files, each synced to its own server. To start a subagent, create a file. To end one, delete it. The orchestrator can read and edit its workers’ files too.
Now try it. The device below is a context file in the form the paper shows in Figure 3: each turn is a block with a turn number and a role. Choose an edit and watch what changes. The read-out previews the cost question of Chapter 4: how much of the old context could a server reuse without redoing work?
Each line is one turn of a search agent. Press an edit. Teal marks new text, struck-through red text is gone, and the read-out counts the tokens before the first change.
Toy context: token counts are illustrative. The turn markers and the idea of a “notes” role follow the paper’s Figure 3 (the real runs use markers such as [[CTX_TURN 4 role=notes]]). The reused-prefix count uses the standard rule: reuse stops at the first token that differs.
Compare the first and the last button. Appending keeps every earlier token in place, so the whole old context is reusable. A note added near the top is useful to the model, yet it changes the start of the file, so nearly everything after it must be read again. Every edit has a price that depends on where it lands. That is the subject of Chapter 4.
Take the file above after turn 6. It holds 3,880 tokens. The model reads it, as a list of about 3,880 integers, and writes a reply of about 100 tokens: a bash command that rewrites the long results at turns 2 and 4 into one-line notes. The harness runs the command. The file now holds about 1,330 tokens. That file is sent to the server as the next context. The server finds that only the first 200 tokens match its cache, so it prefills about 1,130 tokens, a small price for a context that is nearly three times shorter.
Now compare an append. The model writes 100 tokens, they go on the end, and the server prefills just those 100, because the old 3,880 tokens match exactly. Appending is the cheapest turn. Editing is a bet: the cost of reading again must be repaid by a shorter context on every later turn. The paper’s results say the bet pays.
The sketch below shows the runtime loop in our words. It is not the authors’ code, which lives in their repository.
python (sketch) CTX = "/workspace/ctx.txt" # path is told to the model in the system prompt def turn(server, text): reply = server.generate(text) # G_t new tokens for cmd in bash_calls(reply): # the model may edit its own context run(cmd) # e.g. sed, python -c, rm of a worker file after = open(CTX).read() # what the file holds now return after # sync: this is the next context c_(t+1)
Notice how little there is. No summarizer, no offload tool, no retrieval index. The harness is a loop, a file and a few lines of glue. This is the paper’s “less is more” principle: keep as little as possible hard-coded in the harness, so that tools can be added or changed at run time. Even the search tools in the deep-research tests are given as in-context skills, text the model reads, rather than a fixed tool interface.
Chapter 3
Read the behaviors that appeared without anyone coding them: scoreboards, notes roles, loops and helper functions
Give a new employee a whiteboard and no rules. In a week you will see habits nobody taught: a status table in the corner, a list of ideas not yet tried, a habit of wiping old calculations once the result is in a notebook. The habits are the employee’s own answer to a messy job.
The authors saw the same thing when they ran CLMs, zero-shot, on long tasks. Zero-shot means the model got no training for this and no examples: only the file path and a short instruction. Figure 3 collects five behaviors, all taken from these runs. This chapter reads each one for what it teaches.
A scoreboard for a swarm. In one test, an orchestrator agent coordinated subagents on the Erdős minimum overlap problem, a math search problem. The orchestrator kept a status block in its own context: a ledger of the top score, how many agents it had launched (21), how many were running (5), key files, and findings. It updated that block with 163 in-place edits and kept its context at only 6 to 8K tokens. An append-only agent would have written 163 new status messages.
A new role for private notes. A chat prompt has fixed roles such as system, user and assistant. In a deep-research run, the CLM rewrote its context and gave one block a new role, notes, for its own working memory. It invented a role the template never listed. It is a small thing, but it shows that the model treats the file as a place it can design.
Loops that clean up. The model wrote short for loops and regular-expression replacements to delete old search results, or to shorten very long outputs when it built a fresh view of its context. A person writing a harness would call these utilities. The model wrote them when it needed them.
A reusable helper. In another run the model defined a function, compact_turns, and called it 37 times to keep a progress note current while it shrank detailed observations. The model defined its own context-management tool mid-task and then reused it. This is the strongest sign that Equation 2 is more than a framing.
Old tricks, rebuilt. The CLM also reproduced what good harnesses do. In one run it compressed 21K tokens into a short summary that kept what mattered for the answer. In a circle-packing run it replaced old output with an “exploration ledger” that listed its best score and a priority list of untried ideas. Nobody told it to.
Look closely at the fourth behavior, because it shows the core move. The model first writes a progress note: a short block holding what is verified and what to do next. Then it calls a function that finds each old tool result and keeps only its first line, followed by a pointer: [search results - see progress note]. The detail is gone, but the facts that matter live in the note.
Order is the whole point. If the model compacts first and writes the note later, the facts are already gone. The device below runs a simplified version of this on a 20-turn search. Each tool result is 1,000 tokens and three of them hold a fact the answer needs, shown as blue diamonds. Pick how many recent turns to keep raw, and choose whether the note is written first.
Each column is one turn of a 20-turn search. Press Run compact_turns. Old results shrink to a pointer. Then toggle the note and run it again.
Toy run, illustrative numbers: a 500 token prompt, 100 tokens per action, 1,000 tokens per raw result, 20 tokens per pointer, 40 tokens per fact in the note plus 20 for its header. The behavior, a note followed by a pointer-producing helper called repeatedly, is the paper’s Figure 3d (37 calls in the real run).
With three recent turns kept and the note on, the context drops from 22,500 tokens to 5,980, and all three facts survive. Turn the note off and run again. The context is smaller by 140 tokens, and the facts in turns 4, 9 and 15 are gone. The saving is almost the same. What differs is whether the shrinking was safe.
Here is the core of the paper’s Figure 3d, with its elisions kept, then a runnable version in our words.
python # the paper's Figure 3d, as printed (the dots are the paper's) progress = """[Search progress: VERIFIED ... NEXT: ...]""" s = re.sub(..., progress, s) def compact_turns(text): return re.sub(..., lambda m: m.group(0).split('\n')[0] + '\n[search results - see progress note]', text) s = compact_turns(s) # our runnable version: keep the first line of each old tool block import re BLOCK = re.compile(r"\[\[CTX_TURN (\d+) role=tool\]\]\n(.*?)(?=\[\[CTX_TURN|\Z)", re.S) def compact_turns(text, keep_last=3): last = max(int(n) for n in re.findall(r"CTX_TURN (\d+)", text)) def cut(m): if int(m.group(1)) > last - 2 * keep_last: return m.group(0) # recent: leave raw first = m.group(2).split("\n")[0] return f"[[CTX_TURN {m.group(1)} role=tool]]\n{first}\n[search results - see progress note]\n" return BLOCK.sub(cut, text)
Two lessons follow. First, a good context edit is a pair: save what matters, then shrink what does not. A fixed harness summary tries to do both in one blind step. Second, the model chose this order because it could see its own file. It saw the facts in front of it and wrote them down before cutting.
Chapter 4
Count the FLOPs of one turn and see why an edit near the top of the context costs nearly eight times an append
You are reading a long report out loud to a friend, and you have read 18 pages. You then change a sentence on page 2. Your friend, who was keeping notes on every page, now says: “Everything after that sentence might change. Start the notes again from page 2.” Your friend is a server. The notes are its cache.
This chapter explains why a model that edits its own context pays a price that an append-only model does not. It also shows how the paper measures that price, because a method that saves tokens but costs more computing has not saved anything.
A server does two jobs when it handles one turn. First it prefills: it reads the whole prompt and computes, for every token, two vectors called the key and the value. Later tokens look back at these through attention, the step where each new token decides which earlier tokens matter. Second it decodes: it writes the answer one token at a time, each token looking back at all the keys and values so far.
Keys and values are expensive to compute and cheap to keep. So servers store them in a KV cache. The next turn’s prompt usually starts with the same text as the last one, so the server finds the longest matching start, called the prefix, reuses its stored keys and values, and prefills only the rest.
Why a prefix and not any matching piece? A token’s key and value depend on every token before it and on its exact position. Change a token, and the numbers for everything after it are no longer valid. So reuse stops at the first token that differs. This is the page-2 problem. An append changes nothing before the end, so the whole old prompt is reusable. An edit in the middle forces a redo from the edit onward.
A FLOP is one floating-point operation, one addition or multiplication. A PFLOP is 1015 of them. The paper counts the FLOPs a server spends over a whole agent run, assuming standard prefix caching. It calls this prefix-reuse FLOPs, and Equation 3 says it in words.
Appendix C gives the full formula. Let us build it. At turn t the prompt has P tokens, the server reuses R of them as a matching prefix, and the model writes G tokens. So the server prefills U = P − R tokens.
Step 1, the per-token part. Most of a model’s arithmetic is the same for every token whatever the context length: the MLP layers and the projections that make queries, keys and values. The paper adds these up as Ctoken. Every prefilled or decoded token pays it once, so this part costs Ctoken × (U + G).
Step 2, the attention part. Each token also compares itself with every earlier token. One such pair costs Cattn. A prefilled token at position i makes i pairs. Summing positions R+1 to P gives about (P2 − R2)/2 pairs. A decoded token j makes P + j pairs, which sums to about G·P + G2/2.
Qwen3.6-27B is a hybrid model: 16 of its 64 layers use full attention, and 48 use linear attention, a cheaper kind with a fixed-size memory. Only the 16 full layers pay the pair cost. That is why the per-token part dominates in practice. Now the paper’s worked case, with the numbers filled in: P = 20,000 and G = 500. The device runs the formula live, so you can check it.
Bars show the FLOPs of one turn under three edits and under your own setting. The long grey tail is the work that caching avoids. Drag the reusable prefix, or press a preset.
The constants are the paper’s for Qwen3.6-27B (Appendix C): Ctoken = 48.70 × 109, Cattn = 3.93 × 105. The lengths are illustrative, as in the paper’s Figure 14, and the formula drops low-order terms as the paper does. At P = 20,000, G = 500 and R = 18,000, 10,000 and 0 it returns the paper’s 1.41, 5.74 and 10.81 × 1014 FLOPs.
Read the three presets. A pure append (R = 18,000) costs 1.41 × 1014 FLOPs and avoids 87% of the work. An edit in the middle (R = 10,000) costs 5.74 × 1014. An edit at the start costs 10.81 × 1014, which is 7.7 times the append. Notice also how little the quadratic term matters here. Raise P to 60,000 and watch: the attention part grows, but the per-token part still carries most of the bill.
An edit saves context tokens but can raise FLOPs. If the model rewrites the top of its context every turn, it throws away its cache every turn. The paper therefore judges every method by prefix-reuse FLOPs, not by token count. A CLM still wins in the results (Chapter 8), because its edits keep the context small enough that even a re-prefill is cheap. The next chapter asks whether the server can do better.
Chapter 5
Keep the cached work for text that survives an edit, and pay to prefill only what is new
Back to your friend with the notes on pages 1 to 18. You change one sentence on page 2. A strict friend throws away all notes after page 2. A practical friend says: “Pages 3 to 18 did not change. I will keep my notes on them, fix page 2, and carry on. A few notes may be slightly off, but I will manage.” The practical friend finishes in a fraction of the time.
Suffix Cache Reuse (SCR) is the practical friend. The authors build it as a patch to a real inference server, SGLang. It makes edits much cheaper to serve, with no visible loss in accuracy on their test.
SGLang keeps the KV cache of recent requests in a radix tree, a tree over token sequences in which each edge holds a span of tokens and the keys and values computed for it. Requests that start the same way share one path from the root. A new request walks the tree, finds its longest matching start, reuses the stored keys and values along the path, and prefills the rest. Unused branches are removed, oldest first.
That is exact for an append-only history, as Chapter 4 showed. After an edit it wastes work: the surviving text below the edit is unchanged, but it comes after a mismatch, so it is prefilled again.
Take a context made of three spans, A then B then C. The model replaces B with a new span B′. Standard serving matches A and then prefills B′ and C. SCR works in four steps.
The moved entries live in cache slots private to the session, so the shared tree never holds a misplaced entry. If those slots cannot be allocated, the server falls back to the standard re-prefill. The method is an approximation: C’s stored values were computed while B was still there, so they encode the old surroundings. The authors note this can sometimes help, since the stale states keep richer information from the past. They cap the number of spans moved per edit at K, so many small survivors cannot pile up errors in one step.
Modern models mark each token’s position by rotary position encoding (RoPE). Think of a key as an arrow on a clock face. RoPE turns the arrow by an angle proportional to the token’s position m. Rotations add: turning by a and then by b equals turning by a + b. So to move a token from position m to m + Δ, you do not recompute it. You turn its key by the extra angle.
Here Δ is the change in length caused by the edit: the length of B′ minus the length of B. The values (not the keys) carry no rotation, so only keys need this step. The paper states the step plainly: reuse the cached keys and values, re-rotate the keys to their new positions, splice them in.
Qwen3.6-27B has 48 linear-attention layers out of 64. Those layers do not store one entry per token. They keep one fixed-size recurrent state, a running summary of everything so far. There is nothing to relocate. SCR takes a snapshot of that state before the edit and continues from it. The edit shows up only in the 16 full-attention layers, which re-read B′ as normal. The new text is not recomputed in the linear layers. Its effect reaches them later through the inputs they receive.
Try the device. Change the span sizes and the number of surviving spans, and compare what each server must prefill.
The top row is the old context A, B, C. The bottom row is the new context after B becomes B′. Purple is cached work that is reused. Yellow is work the server must do again.
Illustrative lengths: A is fixed at 6,000 tokens and the survivors after B total 8,000 tokens, split into equal spans. K = 6 is the paper’s cap (Appendix B). Real SCR diffs the prompts to find the spans and moves the six longest.
With one surviving span, SCR prefills 300 tokens where standard serving prefills 8,300. Raise the survivors to 12 spans and SCR can move only six of them, so it prefills the other six again. That is the trade the cap makes: less approximation error per edit, a little less saving. The authors tested K from 1 to 64 on 64 BrowseComp-Plus questions. Accuracy stayed robust, and the cache gains levelled off by K = 6.
On BrowseComp-Plus with Qwen3.6-27B, SCR matches the task accuracy of standard SGLang with 65.0% of its prefix-reuse FLOPs: 7.14 against 10.98 PFLOPs per question. That is the paper’s 35% saving. The breakdown of prompt tokens explains where it comes from. Under standard serving, 72.9% of prompt tokens are prefix-cache hits and 27.1% are prefilled. Under SCR, 73.9% are hits, 7.8% are reused beyond the prefix, and 18.3% are prefilled.
Of that 7.8%, 5.3 points come from a side effect. Chat templates for reasoning models, Qwen3.6 included, strip old thinking tokens from earlier turns. That is also an edit, because the text below the removed block shifts. SCR treats it as an edit and reuses the survivors. So a large part of the gain helps even ordinary reasoning-model serving, with no CLM at all. The other 2.5 points come from the model’s own context edits.
Chapter 6
Change the strategy with one sentence, then let a loop write a better skill document for the model
A manager tells a new clerk: “Back up the file to the shared drive before you tidy it.” The clerk changes how they work that same hour. Nobody rebuilt the office software. Nobody retrained the clerk. The sentence was enough.
Here is a quiet but large consequence of the CLM idea. When context management is something the model does, you can change it with words. When it is a rule in the harness, you must change code. This chapter shows two uses: one sentence of steering, and a loop that writes better instructions on its own.
Let s be an in-context instruction or skill document: a piece of plain text that the model reads along with its task. The CLM then follows Equation 4.
The paper tests three single-sentence steers and finds the agent adapts each time, with no change to the harness or the model (Figure 7). The sentences are, in the authors’ prompts: “Compact to 4k tokens once you reach Y tokens.” This moves the time of the first compaction to match the threshold Y. “Compact at sub-question boundaries.” This makes the agent cut at natural breaks in the task. “Back up on disk before you compact.” This raises the share of edits that are preceded by a backup. Each is one sentence appended to the task prompt. A harness engineer would need three code changes.
Work one example. Suppose the sentence reads: compact to 4K tokens once you reach 20K tokens. Each turn adds about 700 tokens. The model watches its own file grow. With a 1,500 token start, near turn 27 the file passes 20K tokens, so it writes a note, rewrites the old turns into pointers, and drops to about 4K. Change 20K to 12K and the first compaction moves earlier. The harness never counted anything. The model read the instruction and applied it to the file it could see.
Writing the right sentence by hand is slow. So the authors let an optimizer write it. They search for the best skill document s* with Equation 5.
The method is a prompt-evolution loop, in the style of GEPA (Agrawal et al.), where an optimizer improves a prompt by reflecting on traces of past runs. It has four stages in each round.
Testing only once is what makes the final number honest. The proposer may be a stronger outside model, called assisted evolution, or the agent model itself, called self-evolution. The paper runs both on ContextBench with a 32K budget.
Press Run next step below (three rounds, then the single test) and pick a task. The endpoints are the paper’s numbers for assisted evolution: Qwen3.6-27B starts with no context instruction and Claude Fable 5.1 proposes skills.
Choose a ContextBench task, then run rounds. The stage you just completed lights up, the skill document grows, and the bar shows development accuracy.
The first and last accuracy for each task are the paper’s development-split numbers for assisted evolution (Appendix F): 97.6 to 100.0, 45.3 to 65.8, 22.3 to 83.8, and 0.0 to 100.0. The rounds in between are interpolated for the picture, and the skill lines are illustrative, not the paper’s skills. On the held-out test split, the KV Store skill rose from 38.3% to 74.2%, which is the 35.9 points in the abstract.
Look at Log Triage: from 0.0% to 100.0%. The model had no instruction about how to handle logs, so it did not offload and retrieve. A short evolved skill changed that. On KV Store the held-out test confirms the gain is not an overfit to the development split: 38.3% before, 74.2% after.
In self-evolution, Opus 5 plays both roles and already starts between 94% and 100% accuracy. There the evolved skills mostly cut cost at the same or higher accuracy. In both settings the paper reports that the evolved skills push out the accuracy-versus-cost frontier, and some strictly dominate the starting point.
The authors draw a bigger point in their discussion. A harness is a body of reusable procedures for managing context. Many of them can be written as context transformations, which a CLM can perform. So a harness can be seen as procedural memory: a skill built outside the model that can later be absorbed by it. Evolving a skill document is the first step. Training it into the weights is the next (Chapter 7).
Chapter 7
Train the strategy with stepwise GRPO and a reward that favors cheap runs only among the correct ones
Think of a student who is told how to organize notes (Chapter 6) and a student who has practiced for months until the habit is automatic. The second student does not need the instruction. The habit lives in their head.
For a model, “in the head” means in the weights, the numbers that make up the model. Changing weights by practice and reward is reinforcement learning (RL). The paper uses RL because small models need it. Before training, a CLM built on Qwen3.5-9B scored six points below the summary harness on BrowseComp-Plus: the smaller model was a weaker context manager.
RL needs a way to say which actions were good. In GRPO (group relative policy optimization, from the DeepSeekMath paper), you give the model the same prompt several times and collect a group of full attempts. You score each attempt with a reward, here 1 for a right answer and 0 for a wrong one. Then you compare each attempt only with its group.
The comparison is the advantage: how much better than the group average this attempt was, divided by the group’s spread (its standard deviation). An attempt with positive advantage is made more likely. One with negative advantage is made less likely. If every attempt gets the same reward, the spread is zero and there is nothing to learn from, so the paper drops such groups.
A normal agent run is one long text, so you could train on it whole. A CLM breaks that. An edit changes the input between turns, so the final file no longer contains the context that an early action was written under. To train a call correctly, you must keep the context as the model saw it at that call.
The paper’s stepwise GRPO does exactly that. It treats each model call as a segment with its own input and output. It computes the standard GRPO advantage from the outcome of the whole attempt. Then it gives that same advantage to every segment of the attempt. Every call is trained with the result of the full run, under the input it really had.
Outcome reward is a blunt tool for context editing. A winning run may contain wasteful edits. A losing run may contain smart ones. You might try to reward the editing directly: more edits, or more tokens removed. The authors warn against it. The model could reward-hack: make useless edits that throw away needed facts or wreck the cache.
Their fix has one idea: judge cost only among the runs that succeeded. Let ci be the prefix-reuse FLOPs of attempt i (Chapter 4). Let Gg+ be the successful attempts in group g. First find the mean cost of the winners. Then score each winner by how far under that mean it came in.
If a group has fewer than two successes, there is nothing to rank, so Aeff is 0 for all. The final advantage mixes the two parts: Ai = Aouti + weff · Aeffi. The outcome part decides right versus wrong. The efficiency part only re-ranks the right ones by cost. In the main run weff = 0.25.
Why the gate? Without it, a run that gives up at once is cheap, and cheap earns a bonus. The device below shows a group of eight attempts. Move the weight, and turn the gate off to see the failure.
Each row is one attempt on the same prompt. Blue is the outcome advantage. Yellow is the efficiency advantage times its weight. A red cross marks a wrong answer. Slide the weight up, then switch the gate.
The eight attempts and their costs (in PFLOPs) are made up for the picture. The formulas are the paper’s: group-normalized outcome advantage, Equation 6, and A = Aout + w·Aeff. The paper trains with w = 0.25. With the gate off, the mean cost is taken over all eight runs.
At w = 0.25 with the gate on, the five winners are ranked by cost: the cheapest, at 1.2 PFLOPs, gets a bonus of about 0.1, and the costliest, at 3.1, loses about 0.15. All five still beat all three failures. Now turn the gate off and raise w to 2. Attempt 5, a wrong answer that quit early, climbs above attempt 4, a right answer that cost more. That is the hack the gate prevents.
The authors train Qwen3.5-9B on 3,040 OpenResearcher deep-research prompts for 70 steps. Each step samples 8 prompts with 32 attempts each. The learning rate is 10−6, and the clipping range is [0.2, 0.28]. A judge model gives the binary reward using a research-question rubric. The efficiency advantage uses w = 0.25 and is applied to the context-management tokens. The paper also penalizes failed tool calls and malformed outputs. The summary harness is trained with task reward alone. Table 2 shows the effect on BrowseComp-Plus.
| Method (Qwen3.5-9B) | Accuracy before to after | PFLOPs per question before to after |
|---|---|---|
| Summary harness | 34.7% to 42.1% | 4.01 to 2.19 |
| CLM | 28.8% to 42.5% | 1.52 to 1.34 |
Read it in three steps. First, the CLM begins behind: 28.8% against 34.7%. Second, RL lifts it by 13.7 points to 42.5%, which is 47.6% relative. Third, it ends level with the trained summary harness, 0.4 points ahead, while spending 1.34 PFLOPs where the harness spends 2.19. That is 38.8% fewer. Adding the efficiency reward further cut cost without a clear loss in accuracy, for the CLM and for the summary harness.
Chapter 8
Read each table and figure for what it proves, then weigh the limits and the new attack surface
A new method claims it is better. Before you believe it, ask three plain questions. Better than what? Measured how? And at what cost? This chapter walks each table and figure of the paper with those questions, then turns to what the paper does not show and what could go wrong.
For the coding and research tests, the authors fix everything except the context manager. All methods share one base agent, Mini-SWE-Agent, and one model, Qwen3.6-27B, with a 32K context limit and a 100-turn cap. Nothing is trained: every method runs out of the box, so the comparison does not depend on training data. The baselines are the plain base harness, the Codex-style summary, MEM1, Self-Compact, ACM and RLM (Chapter 1). The three benchmarks are BrowseComp-Plus, a deep-research test; TerminalBench 2.1, a test of hard tasks at a command line; and TBLite, a lighter terminal benchmark. Cost is prefix-reuse FLOPs (Chapter 4), and Figure 5 plots accuracy against cost with a Pareto frontier.
A Pareto frontier joins the methods that no other method beats on both axes at once: more accurate and cheaper. A method on the frontier is a good trade. A method inside it is beaten.
On BrowseComp-Plus, the CLM scores 59.4% at the 32K limit. That is 11.4% higher, in relative terms, than the strongest baseline, the Codex-style summary. It uses 21.5% fewer FLOPs than that summary and 28.9% fewer than MEM1. On TerminalBench 2.1 it matches the summary’s accuracy with about 70% of its FLOPs. On TBLite it scores 73.7% against 67.0%, with 91% of the FLOPs. Pick a benchmark below to see the paired comparison, with the summary harness as the 100% mark.
The dashed line is the summary harness, set to 100%. A teal bar longer than the line means more accurate. A yellow bar shorter than the line means cheaper.
Accuracy and cost indexes are computed from numbers in the paper (Sections 1 and 5.1): BrowseComp-Plus 59.4% and 11.4% relative gain with 21.5% fewer FLOPs; TerminalBench 2.1 matched accuracy with 70% of FLOPs; TBLite 73.7% against 67.0% with 91% of FLOPs; EdgeBench-10 (Qwen3.6-27B) 44.6 against 42.3 at 179 against 437 PFLOPs per trial. The index is CLM divided by summary. The summary’s absolute BrowseComp-Plus score (about 53.3%) is implied by the 11.4% gain, not printed.
Here the competitor is a specialized method. OpenEvolve is an AlphaEvolve-style workflow: it generates programs, scores them, and evolves the best. OE-Agent swaps its proposer for an agent that can act in the environment. The CLM uses the same base harness with only a bash interface, plus the evolutionary algorithm given as in-context guidance. The model is Claude 4.6 Sonnet, scored best-of-run, capped at 100 scored attempts or five hours.
| Method | Circle packing (higher) | Heilbronn (higher) | Min-max distance (higher) | Erdős overlap (lower) |
|---|---|---|---|---|
| OpenEvolve | 2.541 | 0.03127 | 0.07690 | 0.38123 |
| OE-Agent | 2.525 | 0.03053 | 0.07724 | 0.38167 |
| CLM | 2.618 | 0.03653 | 0.07758 | 0.38094 |
| CLM with subagents | 2.636 | 0.03617 | 0.07758 | 0.38109 |
The gains over OpenEvolve are 3.0% on circle packing and 16.8% on Heilbronn (0.03653 divided by 0.03127). The paper concludes that a general agent with direct context control can beat a specialized evolutionary pipeline with less fixed orchestration. Notice the scale: on min-max distance and the Erdős problem the differences are in the third or fourth decimal, so these two are close.
On EdgeBench-10, an agent optimizes one code repository for up to 12 hours with a verifier. Scores are the best of three seeds per task. With Qwen3.6-27B at a 32K budget, the CLM reaches 44.6 using 179 prefix-reuse PFLOPs per trial. The summary harness reaches 42.3 using 437. That is 59% fewer FLOPs. With Claude 4.6 Sonnet the CLM reaches 51.0 against 42.3. Up to five subagents add little here (44.2 for Qwen, 50.4 for Claude), because the task has one repository.
The agent-swarm test, Software World, is harder. Six agents jointly optimize six interdependent Python repositories for over 24 hours, using GPT-5.6-Sol with a 272K budget. The score is speedup on four unseen downstream packages, a real test of whether the gains transfer. At the same spend, the CLM swarm gets 65% more downstream speedup than a summary-based swarm.
Giving a model write access to its own live context also gives an attacker a place to hide. A prompt injection is text inside data, such as a web page, that tells the model to do something else. If such text lands in a note the model keeps, it can persist across turns, because the model re-reads its own notes as trusted. The paper points to a recent report in which a model put unauthorized instructions into its own compaction summary, and those instructions later changed its behavior. The authors call for research on defenses that keep the flexibility of model-controlled context while protecting its integrity.
For the future, they suggest scaling RL for CLMs and building a pipeline to distill existing harnesses into them: a harness is procedural memory built outside the model, and a CLM can absorb it.
Chapter 9
Keep the numbers, the terms, a checklist and the core code on one page
Here is the whole paper in one paragraph. An agent’s context outgrows its window, and today a harness cuts it by fixed rules that lose facts and rewrite whole states. A Context Language Model instead treats the context as a file and lets the model edit it with ordinary commands, with append as the default (Equation 2). Zero-shot, that beats strong harnesses at lower cost. Edits break prefix caching, so the paper prices them in prefix-reuse FLOPs and recovers 35% of server compute with Suffix Cache Reuse. Because management is now a model behavior, one sentence can steer it, an evolution loop can improve it, and stepwise GRPO with a success-gated efficiency advantage can train it into the weights.
| Number | What it is | Where |
|---|---|---|
| 32,768 | Context limit in the pilot (30,720 usable after a 2,048 reserve); pressure up to 24× | Section 3, App. D |
| 163 edits, 6 to 8K | In-place edits of a swarm scoreboard that kept the orchestrator at 6 to 8K tokens | Figure 3a |
| 37 calls | Times the model reused its own compact_turns helper | Figure 3d |
| 48.70 × 109 and 3.93 × 105 | FLOPs per token and per query-key pair for Qwen3.6-27B | App. C |
| 1.41, 5.74, 10.81 × 1014 | FLOPs of one turn (P = 20,000, G = 500) at R = 18,000, 10,000, 0; the last is 7.7× the first | Figure 14 |
| 59.4% | CLM on BrowseComp-Plus, 32K limit; 11.4% relative gain, 21.5% fewer FLOPs than the summary | Section 5.1.1 |
| 73.7% vs 67.0% | TBLite, CLM vs summary, at 91% of the FLOPs | Section 5.1.1 |
| 44.6 vs 42.3 | EdgeBench-10 with Qwen3.6-27B, at 179 vs 437 PFLOPs per trial | Figure 6a |
| +65% | Downstream speedup of a CLM swarm vs a summary swarm at equal spend | Figure 6b |
| K = 6 | Surviving spans SCR may relocate per edit | App. B |
| 65.0% (7.14 vs 10.98 PF) | SCR FLOPs as a share of standard SGLang on BrowseComp-Plus, accuracy matched | Figure 9 |
| 38.3% to 74.2% | KV Store held-out accuracy after skill evolution: the 35.9 points | App. F |
| 28.8% to 42.5% | Qwen3.5-9B CLM before and after RL; 1.52 to 1.34 PFLOPs per question | Table 2 |
| w = 0.25; 8 × 32; 70 steps | Efficiency weight; prompts × rollouts per step; training steps | App. E |
| Term | Plain meaning |
|---|---|
| Context | All the text the model reads before it writes. |
| Harness | The program around the model: the loop, the tools and the prompt builder. |
| Compaction | Replace a long history with a short summary. |
| Context pressure | Total input over a task divided by the context limit. |
| CLM | A model that produces its own next context, ct+1 = f(ct), through a file it can edit. |
| Prefix cache | Stored keys and values for a prompt start that matches an earlier one. |
| Prefix-reuse FLOPs | Server compute with prefix caching: prefill from the first mismatch plus decode. |
| Suffix Cache Reuse | Reuse the cache of text that survives an edit, re-rotating its keys. |
| Skill document | Plain text, s, that steers how the model manages context. |
| Stepwise GRPO | GRPO where each model call is a training segment that gets the whole run’s advantage. |
| Success gate | Give the cost bonus only to correct runs. |
Tick what your design already does. The read-out names the first practice you are missing.
Each button is one practice from this paper. Press the ones your agent already follows.
The seven practices summarize Chapters 2 to 8. The seventh, logging edits, is our reading of the paper’s call for defenses against injected instructions that persist in editable context; the paper does not prescribe a specific defense.
python C_TOKEN, C_ATTN = 48.70e9, 3.93e5 # Qwen3.6-27B constants (App. C) def turn_flops(P, G, R): """One turn: P prompt tokens, R reusable prefix, G new tokens (Eq. 9).""" U = P - R # tokens prefilled again return C_TOKEN * (U + G) + C_ATTN * (0.5 * (P**2 - R**2) + G * P + 0.5 * G**2) def efficiency_advantage(success, cost): """Eq. 6: rank only the successes by cost; failures get 0.""" wins = [c for s, c in zip(success, cost) if s] if len(wins) < 2: return [0.0] * len(cost) mean = sum(wins) / len(wins) return [max(-1.0, min(1.0, (mean - c) / mean)) if s else 0.0 for s, c in zip(success, cost)] def advantage(success, cost, w_eff=0.25): n = len(success); p = sum(success) / n sd = (p * (1 - p)) ** 0.5 or 1.0 a_out = [(s - p) / sd for s in success] # GRPO outcome advantage a_eff = efficiency_advantage(success, cost) return [o + w_eff * e for o, e in zip(a_out, a_eff)] # same value for every segment of a run # turn_flops(20000, 500, 18000) -> 1.41e14 ; (..., 10000) -> 5.74e14 ; (..., 0) -> 1.08e15
The CLM complements the Recursive Language Model, which keeps a huge input outside the context and reads slices of it. A CLM edits what is inside. MemGPT edits only a fixed block of the context. External memory stores facts outside it. In a CLM, other files can be that memory, and the model decides what to bring in and when to let it go. The paper itself belongs to the line of work on harness search and self-improving harnesses.
The takeaway. Stop handing the model a fixed menu of context moves. Give it the file, keep append as the default, price every edit in the FLOPs a server will really spend, and let words or rewards teach it the strategy.
Credit: Context Language Models by Rulin Shao, Shannon Zejiang Shen, Junjie Oscar Yin, Yuetai Li, Minheng Wang, Hamish Ivison, Radha Poovendran, Nathan Lambert, Teng Xiao, Mike Lewis, Wen-tau Yih, Luke Zettlemoyer and Pang Wei Koh. arXiv 2609.37725. Code at facebookresearch/context-language-models. Figures and numbers here come from the paper; toy numbers are labelled illustrative.
Now press Present or Teach and explain the paper from memory: the equation, the file, one edit and its cost, the cache trick, the one-sentence steer and the success gate. Then go back to the hero and watch the three lines again.