Cruxly › AI engineering › Agentic Systems
Context Engineering for Long-Horizon Agents
tool results fill the window, cost grows with the square of the run length, and a summary can silently drop a rule
Open the interactive lessonPrompt: "Our coding agent migrates a service to a new database client. A typical run reads 30 files, runs the tests a dozen times, and takes 60+ steps. By step 40 it is slow, expensive, and has started to forget things we told it at the start, including 'never touch the production config'. How do you keep the context under control?"
35 minutes first. Do two pieces of arithmetic on the whiteboard: where the tokens in a long run actually come from, and what the whole run costs when every step re-sends the transcript. Then say what you would keep, shrink, or move out of the window.
Why a long task fills the window, and who pays for it
In a long run the tool results dominate the context, not the model's reasoning. Take a coding agent for example. Each step has a short model message (a thought and a tool call, say 300 tokens) and a tool result that can be anything from 50 tokens (a "tests passed" line) to 6,000 (a whole file, a long stack trace, a page of search hits). A run that reads 30 files and runs 12 test suites has easily put hundreds of thousands of characters of tool output in the transcript, and almost all of it was useful for exactly one decision.
The window is not just a size limit, it is a cost and quality limit. Three things go wrong well before you hit the maximum.
- Cost. Every step re-sends the whole transcript as input, so you pay for old tool output again on every later step.
- Latency. Longer inputs take longer to process, so step 40 is slower than step 4 even if the model does the same thing.
- Attention. Models tend to use information at the very start and end of a long input more reliably than the middle, and a transcript full of stale logs makes the instruction that matters harder to find. Treat that as a tendency you should measure on your own task, not a fixed law.
Worked example (illustrative numbers). A system prompt of 3,000 tokens. Each step adds 2,000 tokens to the transcript (1,500 of tool result plus 500 of model message). Step k sends 3,000 + 2,000 x (k - 1) input tokens.
| Steps in the run | Input tokens summed over all steps | What changed |
|---|---|---|
| 5 | 5 x 3,000 + 2,000 x (0+1+2+3+4) = 35,000 | baseline |
| 20 | 20 x 3,000 + 2,000 x 190 = 440,000 | 4x the steps, about 12.6x the tokens |
| 40 | 40 x 3,000 + 2,000 x 780 = 1,680,000 | 2x the steps of the 20-step run, about 3.8x the tokens |
The reason is the sum 0 + 1 + 2 + ... + (n-1), which is n(n-1)/2, so the growing part of the cost is quadratic in the number of steps. A run that is twice as long is not twice as expensive. That is why "just give it a bigger window" is not a plan: a bigger window lets you reach step 200, and the bill for step 200 is the part that hurts.
Keep, summarize, or move out: sorting what is in the window
Treat the context as a budget and give every piece of content one of three fates. The mistake is a single policy for everything, usually "keep it all until the window is full, then summarize it all".
| Bin | What goes in it | Why |
|---|---|---|
| Keep verbatim | The task goal, hard constraints ("never edit prod.yaml"), the tool definitions, the last 2-3 steps in full, any exact value the agent must copy such as an ID, a path or an error string it is fixing | A summary is lossy, and these are the things where one changed word changes the outcome |
| Summarize | The reasoning and decisions of older steps: "tried approach A, it failed because the client lacks batch(); chose approach B" | The conclusion matters later, the 1,500 tokens of working do not |
| Move out | Large artifacts that are re-fetchable or that will be needed later but not now: a file's full text, a long log, a spec section | Keep a pointer (a path, a query, a stable ID) in the window and let the agent re-read on demand |
Two tests decide the bin. Could the agent recompute or re-fetch it cheaply? Then move it out and keep a stub. Does a wrong paraphrase cause a wrong action? Then keep it verbatim, or in a structured field that is never paraphrased.
Trim old tool results first, because it is the cheapest win. A tool result that has been used and is more than a few steps old can be replaced in place by a stub such as [read_file src/db.py, 1,480 tokens, trimmed; re-read if needed]. The agent keeps the fact that it read the file and where, and loses only the bulk. Do the trimming in code with a simple rule (older than 3 steps and larger than 500 tokens), not by asking the model to decide what to forget.
Re-run the arithmetic with trimming on. Same example as before: 3,000 token system prompt, 2,000 tokens per step. Keep the last 3 steps in full. Older steps shrink to 600 tokens each (the 500-token model message plus a 100-token stub).
- Steps 1 to 3 send 3,000, 5,000 and 7,000, total 15,000.
- From step 4 on, step k sends
9,000 + 600 x (k - 4). Over steps 4 to 20 that is17 x 9,000 + 600 x 136 = 234,600. - Run total: 249,600 input tokens, against 440,000 untrimmed, about 43 percent less, and the line is now flatter, though still not flat.
Once the cost is lower, do not tell the model it can stop remembering. Trimming only removes bulk the agent has already used. If a later step needs the file again, it re-reads it; that costs one tool call, which is far cheaper than carrying the file for 30 steps.
Notes the agent re-reads, and sub-agents that return short summaries
Two patterns do the heavy lifting once trimming is not enough: external notes and delegated exploration.
1. Structured notes the agent writes and re-reads. Give the agent a scratch file (or a memory tool) and tell it to keep it current: a few lines per heading, rewritten rather than appended forever.
GOAL: migrate orders-service to db-client v3
CONSTRAINTS: never edit prod.yaml; keep public API of OrdersRepo unchanged
DONE: repo layer (8 files) migrated, unit tests green
OPEN: integration tests fail on 2 files, see notes/failures.md
NEXT: fix transaction wrapper in checkout.py
The notes survive a trim, a compaction, or even a crashed-and-resumed run, because they live outside the transcript. The agent starts a step by re-reading roughly 150 tokens instead of scrolling back through 30,000. This is the same idea as the working and procedural memory in the Agent Memory lesson: a small, curated, rewritable state, not an append-only log.
- Make the format structured. Fixed headings stop the notes from drifting into a diary.
- Rewrite, do not append. Notes that only grow become the new problem.
- Treat them as untrusted if any part came from a tool result. A file the agent summarized into its notes can carry an injected instruction; pinned constraints should never be editable by the agent's own note-taking.
2. Sub-agents that return short summaries. For work that is wide and mostly throwaway, such as "find every caller of db.execute across 200 files", spawn a sub-agent with its own fresh context. It might use 40,000 tokens reading and grepping. It returns a 400-token answer: the list of call sites and the three unusual ones. The main agent's window grew by 400 tokens, not 40,000.
The trade-offs are real. A sub-agent's cost is its own full run, so you are moving tokens out of the main window, not deleting them. The summary can omit the detail the parent needed. And parent and child can disagree if the child lacked context that the parent had. Mitigate by giving the child a precise question, an output format and a length cap, and by letting the parent ask a follow-up rather than trusting one shot. The honest summary of the pattern: it protects the main window, and the best candidates are tasks where the output is much smaller than the work.
When compaction drops a constraint, and how to protect pinned instructions
The dangerous failure of compaction is not a lost file, it is a lost rule. Compaction means the transcript gets replaced by a model-written summary when it nears the limit. A summary keeps what looked important at the time. The user's early sentence "do not touch the production config" looks like background, while "the migration of the repo layer is done" looks like progress, so the summary keeps the second and drops the first. Forty steps later the agent, now missing the rule, edits prod.yaml because the task seems to call for it.
This is a design bug, not a bad-luck bug, because constraints and goals are exactly the content that summaries are bad at preserving. A few concrete protections:
- Pin the instructions outside the compactable region. The system prompt and a "constraints" block are re-sent as fixed text on every request and are never part of what gets summarized. Compaction operates on the middle of the transcript only.
- Re-inject after compaction. If the summary replaces the history, the next request starts with the pinned block again, then the summary, then the recent steps.
- Store constraints as structured data, not prose. A list
constraints: ["never edit prod.yaml"]is copied across, a narrative paragraph gets paraphrased. - Make the summarizer's job explicit. Instruct it to carry forward, verbatim, every instruction the user gave and every unresolved error, and to list them under their own heading.
- Enforce the important ones in code anyway. A write tool that refuses any path matching
prod*does not depend on the model remembering. This is the lesson from Guardrails for an Agent That Takes Real Actions: the window is advisory, the tool layer is the boundary. - Test compaction like any other component. Build a small eval: plant 5 constraints in the first 5 turns, run a long filler task past the compaction point, then check whether each constraint is still obeyed, or ask the agent to list the rules it is working under. Run it whenever you change the summarizer prompt or model.
:::warn A summary is a new, unreviewed document Whatever the compactor writes becomes the agent's memory of the whole task. If it is wrong, every later step builds on the wrong version, and nothing flags it, because nobody compared it with the transcript it replaced. Log the pre-compaction transcript somewhere durable so you can diff it when a run goes strange. :::
Follow-ups they will ask
"How do you decide when to compact?" On a token threshold well below the limit (for example at 60 to 70 percent of the window, so there is room for the summary and the next steps), or at a natural boundary such as the end of a subtask. Waiting for the hard limit means the summary itself has to be written in a nearly full window.
"Is a bigger window not simply the answer?" It raises the ceiling and leaves the quadratic cost and the attention problem in place. Use the room, but still trim and pin.
"Prompt caching, does that fix the cost?" It cuts the price of the repeated prefix a lot, but only while the prefix stays byte-identical. Editing or trimming an earlier part of the transcript invalidates the cached tail after it, so trim in batches rather than every step, and put the trimming boundary where the cache break costs least. See Agent Cost and Latency Budgets for the arithmetic.
"What should the agent never be allowed to forget?" The goal, the hard constraints, the definition of done, and any open error it was in the middle of fixing. Write those into the pinned block by name.
"How do you know your context management works?" A long-horizon eval with planted constraints and planted facts, scored on whether they are obeyed at step 60, plus cost per task and success rate before and after the change. If success drops when you trim, you trimmed something the agent needed.
"How is this different from RAG?" RAG pulls knowledge from an outside corpus into the window for a question. Context engineering manages what is already in the window as a run proceeds, and decides what to push back out.
How to say it in the interview
"A long agent run fills its window mostly with tool results, not with the model's own words: file reads, test logs and search hits. And because every step re-sends the whole transcript, the cost of the run grows with the square of its length, so doubling the steps roughly quadruples the input tokens. I would sort everything in the context into three bins. Pinned instructions and the goal stay verbatim, always, outside anything that gets compacted. Old tool results get trimmed to a one-line stub once they have been used. Anything the agent will need much later goes into a notes file or memory that it re-reads on purpose. For wide exploration I would hand the reading to a sub-agent that returns a short summary. And I would test the compaction itself: after a summary, ask whether every constraint survived, because a summary that drops 'never touch production' is the dangerous failure, not the lost file contents."
Checklist
- Say that tool results dominate a long run's context and are re-sent on every later step.
- Show the quadratic growth with a small worked example: input per step grows linearly, the total grows with the square of the steps.
- Sort context into keep verbatim, summarize and move out, with the two tests: re-fetchable, and does a wrong paraphrase cause a wrong action.
- Trim used tool results to stubs in code with a simple rule, instead of asking the model what to forget.
- Give the agent a structured, rewritable notes file it re-reads, and treat anything from tool output as untrusted when it is written there.
- Use sub-agents to absorb wide exploration and return a short answer, and say the tokens moved rather than disappeared.
- Pin goals and constraints outside the compactable region, re-inject them after compaction, and enforce the critical ones in the tool layer.
- Test compaction with planted constraints and facts at the start of a long run, and track success and cost before and after.
Related lessons
- The Agent Loop in Depth: ReAct, Plan-and-Execute, Reflection and Stop Conditions
- Designing Tools an Agent Can Actually Use
- Agent Memory: Working, Episodic, Semantic and Procedural, Without the Rot
- Frameworks, Protocols and Durable Execution: MCP, A2A and Long-Running Agents
- Reliable Agents: Retries, Idempotency, Checkpoints and Sagas
- MCP Servers, Prompt Injection, and Tamper-Evident Audit