Context Engineering for Long-Running AI Agents
A worked context budget shows what to retain, remove, and recover when an agent compacts history: durable decisions, failed attempts, versioned evidence, and a testable continuation.

Long-running agents need more than a large context window. They need a deliberate choice about which instructions, observations, decisions, and unresolved failures are available at each step.
Context engineering is the work of assembling that view from a larger durable record. A useful system keeps enough information to continue correctly, makes omitted evidence recoverable, and distinguishes a remembered observation from a current one.
Capacity and useful context are different properties
Lost in the Middle showed that relevant information's position affected performance on the retrieval and question-answering tasks studied. Its older models do not establish a universal curve for current agents. The result does establish that fitting information into a window and using it reliably are different capabilities.
Chroma's Context Rot report evaluates a later collection of models on controlled tasks and reports inconsistent performance as input length grows. LOCA-bench tests agents while scaling environment state. These are reasons to evaluate a system under realistic context growth, not proof that every extra token harms every task.
Cutting history arbitrarily can also discard the information needed to succeed. The goal is neither the largest possible prompt nor the smallest possible prompt. It is a prompt that preserves the current decision's dependencies.
A concrete 32,000-token budget
Consider an illustrative incident-investigation agent with a 32,000-token window and 4,000 tokens reserved for output. The figures below are planning allocations, not tokenizer measurements or a reported performance experiment.
| Input category | Before compaction | After compaction |
|---|---|---|
| Instructions | 2,000 | 2,000 |
| Current task | 1,000 | 1,000 |
| Conversation history | 18,000 | Replaced by checkpoint and recent turns |
| Tool results | 7,000 | Replaced by selected evidence and references |
| Durable checkpoint | — | 2,000 |
| Recent turns | — | 3,000 |
| Selected evidence | — | 3,000 |
| Total input | 28,000 | 11,000 |
| Unallocated capacity after output reserve | 0 | 17,000 |
The arithmetic can be reproduced with the standalone context-budget example. Save it and run node context-budget.mjs. It uses only Node's standard library and asserts the totals and checkpoint invariants. It does not call a model or demonstrate that compaction improves accuracy.
In a real integration, measure the serialized request with the provider's supported tokenizer or counting interface. Include system instructions, tool definitions, message framing, images, and any provider-specific overhead. A word-count estimate is not a hard limit.
Write the checkpoint before discarding history
The example preserves six things:
{
"goal": "Diagnose a synthetic incident; propose only, do not execute.",
"decisions": ["No write authorization; preserve missing evidence as missing."],
"state": { "revision": 7, "status": "investigating" },
"failedAttempts": [
{ "operation": "metrics query", "outcome": "timeout; not evidence of health" }
],
"references": [{ "id": "log-17", "artifact": "artifacts/logs.json", "observedRevision": 6 }],
"next": "Refresh metrics and logs at revision 7 before proposing an action."
}
The goal preserves the boundary between proposing and executing. The decision records a constraint and its meaning. The state identifies the current revision. The failed attempt prevents a later session from interpreting a timeout as a healthy service. The reference makes discarded logs recoverable while showing that they are stale. The next action names the evidence that must be refreshed.
Raw repeated logs, redundant explanations, and superseded plans can leave the working prompt once the durable record preserves the relevant facts and references. Keep original artifacts when a later step may need to inspect their exact contents. A summary should not be the only surviving copy of evidence.

Recover evidence instead of trusting the summary
After compaction, the agent should read the checkpoint, confirm the task and authorization, inspect current state, and retrieve only the evidence required for its next decision. The checkpoint's revision-6 log is a lead, not proof about revision 7.
References need their own contract: an identifier, location, source version or hash, observation time, and access boundary. A URL alone may return different content tomorrow. A file path alone may point to an edited file. If exact historical evidence matters, retain an immutable snapshot or a versioned artifact.
Recovery must also preserve uncertainty. A summary that changes “metrics unavailable” into “no metric anomaly” has invented evidence. A checkpoint that omits a denied action can invite a repeated request. Test these losses with cases where the omitted detail changes the correct next step.
Retrieval earns its complexity when the corpus is larger than the task
Anthropic's context-engineering guidance recommends lightweight identifiers and just-in-time retrieval. MemGPT develops the broader idea of moving information between working context and external storage. These are useful design patterns, not guarantees that agent-selected retrieval beats a fixed packet.
When all relevant evidence is small and known, supplying it directly may be simpler. The synthetic comparison in how I evaluate production AI agents is a concrete counterexample to assuming agency helps. Its full benchmark and limitations belong there.
For a large corpus, bound search results, preserve source references, and provide a way to request details. Truncation should be explicit. An agent should be able to distinguish “nothing matched” from “the response was cut off.”
Isolate investigation without fragmenting ownership
Separate investigators can search different sources and return findings with evidence references. That can keep irrelevant exploration out of a coordinator's context. It also creates communication costs: missing assumptions, conflicting decisions, and findings whose provenance is hard to recover.
Use isolation where work is independent. Keep consequential decisions and artifact ownership explicit. A concise handoff should include the conclusion, evidence, uncertainty, failed approaches, and dependencies. A short answer that drops the reason for a decision can be more damaging than a longer one.
The workflow-level version of that problem is covered in cutting the coordination tax. More agents do not remove dependencies between tasks.
Evaluate what survives compaction
Build a small continuation suite. Stop runs at a checkpoint and ask the resumed system to continue on cases involving a stale observation, an unresolved failure, a denied action, conflicting evidence, and a changed goal. Compare decisions and outcomes against the uncompressed record.
Measure recovered facts, unsupported assertions, repeated failed work, retrieval calls, token use, and final task success. Keep compaction cost and latency in the accounting. A smaller prompt is useful only if the continuation remains correct enough for the task.
Prompt caching adds another tradeoff: editing an early prefix can reduce cache reuse. Keep stable instructions and tool definitions stable where the provider's caching contract permits it, and measure total cost rather than optimizing cache hits alone. A cheap cached prompt carrying obsolete instructions is still wrong.
The durable record is the source of continuity. The prompt is a selected working view of it, and every selection should preserve enough evidence to make the next decision defensible.






