Agent Platform Design

Agent Context Window Management: Compaction and Evidence Retention

Manage agent context windows with explicit budgets, evidence selection, recoverable compaction, provenance, and checks that preserve task constraints over time.

· · 8 min read

Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.

An agent’s context window is a working view of a task, not the task’s complete record. Managing it well means selecting the evidence needed for the next decision while preserving a way to recover details that become relevant later. Increasing the token allowance does not answer which information belongs there, which version is current, or whether a compressed statement still means what the user intended.

This guide develops a hypothetical repository-migration assistant. Its context packet, budgets, and compaction rules are proposed engineering designs, not a tested framework implementation.

Separate durable history from the active context packet

Keep three representations distinct: the event history, the current authoritative task state, and the material selected for a particular model call. History records observations and actions. State records accepted facts such as the target revision and outstanding checks. The active packet contains only the relevant subset, together with instructions and tool interfaces.

Anthropic’s Managed Agents account describes a durable session log that exists separately from the model’s context window. It explains that compacted messages are recoverable only when stored elsewhere. That separation is a useful design reference; it does not require adopting that service. Scaling Managed Agents.

In the proposed migration assistant, a full compiler log remains in artifact storage. State records its exit status and the repository revision it tested. The next model call receives a short diagnostic excerpt plus an artifact identifier. Dropping most of the log from the prompt therefore does not erase the evidence or imply that the remaining excerpt proves the whole build passed.

Durable storage still needs access control, retention, and deletion rules. “Store everything forever” is not a context-management strategy. Keep enough recoverable information for the task’s recovery and review requirements, within the application’s data policy.

Budget for the next operation rather than the current prompt

A packet that fits now can still leave insufficient space for a tool result or the model’s response. Reserve capacity before dispatching work. Include system instructions, tool definitions, selected history, retrieved evidence, expected tool output, response allowance, and provider-specific overhead in the accounting.

For an illustrative 32,000-token request budget, reserve 4,000 for the response and operational margin, 3,000 for instructions and tool interfaces, and 3,000 for the next diagnostic result. That leaves 22,000 for selected history and evidence. These are invented planning values; actual accounting must use the selected provider’s tokenizer and limits.

The useful admission question is whether the next operation can finish within the remaining allowance. A tool that returns an entire dependency tree may exceed its reserved output even when the input packet is small. Give tools bounded output contracts, pagination, or artifact handles. If the result is too large, request a scoped slice rather than silently cutting it at an arbitrary character boundary.

Reserve separately for parallel branches. Each worker’s local context allowance does not eliminate the coordinator’s need to receive and inspect their results. Define a bounded result contract as part of agent handoff design.

Select evidence by dependency and current uncertainty

Start packet construction from the next decision. For a migration edit, that might require the acceptance criteria, relevant API signatures, the current file, and an unresolved compatibility question. It rarely requires every earlier failed search.

A proposed packet can distinguish the following classes:

Class Selection rule Required provenance
Goal and constraints Always include the active version User request or approved task specification
Accepted state Include fields needed for the next step State revision and validating event
Direct evidence Include excerpts resolving current questions Artifact, source location, and version
Recent interaction Keep enough to interpret current intent Message identifiers and ordering
Deferred material Keep handles instead of full text Retrieval method and access scope

Rank evidence by usefulness to the decision, not simply recency. A newly printed progress message may add nothing; an older requirement forbidding a public API change may remain essential. Preserve unresolved contradictions explicitly instead of allowing a relevance score to choose one side invisibly.

The Lost in the Middle study found position-sensitive performance on multi-document question answering and key-value retrieval in the models it evaluated. It supports testing context placement, not assuming a permanent rule for every newer model or task. Liu et al., 2023.

For this design, place the active goal and restrictions in a predictable section and group evidence by question. Then measure whether ordering changes actual task outcomes. Repeating instructions at both ends can consume budget and introduce conflicting versions; more repetition is not automatically more reliable.

Compact claims without losing their conditions

Compaction should preserve distinctions that change subsequent behavior. “Tests passed” is weaker evidence than “unit tests passed at revision R; integration tests were not run.” “User approved” is dangerous without specifying the action, resource, and scope that approval covered.

Anthropic’s context-engineering guidance describes compaction, structured notes, and focused subagents as approaches for long-running work. It cautions that aggressive compression can discard details whose importance emerges later. These are provider engineering observations, not a guarantee that summarization preserves task correctness. Effective context engineering.

For the hypothetical assistant, ask the compactor to emit a structured proposal containing the active objective, explicit prohibitions, accepted decisions with evidence identifiers, unresolved issues, completed actions, pending actions, and recovery pointers. Application code should verify required fields and referenced artifact access before accepting it.

Do not let a summary overwrite authoritative execution state. A compactor can propose that a task appears complete; the workflow must still check the acceptance conditions. Likewise, a summary mentioning approval cannot become a credential. Keep authorization and action records outside the model-authored narrative.

Repeated summarization deserves particular scrutiny. A summary of a summary can retain the conclusion while gradually dropping exceptions. Where practical, regenerate a milestone summary from the relevant original events and compare changes against the previous accepted packet.

Walk through a hypothetical migration checkpoint

Assume the user requests a dependency upgrade while preserving a public function signature. The assistant has inspected eight files, attempted one incompatible change, and produced a compiler log. Its context is approaching the reserved threshold before a final integration check.

First, it stores the compiler output as an artifact associated with repository revision R12. The accepted state records that unit tests passed at R12, compilation failed on a renamed parameter, and integration tests remain pending. The failed edit is retained as a rejected approach, with the reason it conflicts with the required signature.

Second, packet construction includes the original signature restriction, the current implementation, the relevant dependency documentation, and the exact compiler diagnostic. It replaces unrelated search output with source handles. It keeps the user’s later instruction to avoid adding a new package as a distinct constraint rather than blending it into a vague preference for minimal changes.

Third, the compacted proposal states what remains unknown: whether the new dependency’s default timeout changes behavior. It must not translate “investigate timeout compatibility” into “timeout behavior is compatible.” The resumed agent can retrieve the original documentation before deciding.

Finally, the workflow runs the remaining checks against the edited revision. A prior passing result cannot validate a later edit. Context continuity supports execution, but regression evidence remains bound to the artifact actually tested.

Preserve protocol validity and trust boundaries

Message pruning can break a provider’s expected conversation structure. LangChain’s short-term-memory documentation warns that tool calls commonly need corresponding tool-result messages and that provider constraints can affect valid histories. Its trimming and summarization facilities do not determine which business facts an application may safely discard. LangChain short-term memory.

Treat a tool exchange as a coherent unit when the target interface requires it. Validate the reconstructed request before sending it, including call identifiers and message ordering. Keep an adapter-specific representation rather than assuming one provider’s compressed transcript is interchangeable with another’s.

Maintain trust labels through compression. A malicious instruction found in a repository file remains untrusted source content even if a summarizer repeats it. A note should identify it as an observed instruction in an external artifact, not promote it into the active operating rules. Source origin, access scope, and uncertainty should travel with the claim.

Evaluate information survival across repeated checkpoints

Build test tasks where small details matter later: a forbidden dependency, a negative test result, an unresolved contradiction, an expired approval, or a tool operation with an unknown outcome. Force compaction at different points and compare resumed behavior with a baseline that retains the needed evidence.

Measure constraint retention, evidence recovery, incorrect completion claims, repeated work, and task success alongside token use and latency. A shorter packet is not an improvement if it increases repair work or loses a required exception.

Inject retrieval failures and revoked artifact access. The correct response may be to stop and request evidence, rather than improvise from an old summary. Inspect intermediate actions as well as the final answer: a polished report cannot undo an unauthorized edit performed after a restriction disappeared.

Frequently asked questions

Should I compact at a fixed percentage of the window?

A threshold is a useful trigger, but reserve for the next operation and response first. A large pending tool result can require compaction earlier than a simple answer would.

Is a summary enough to resume a long task?

Only when it contains the necessary state and the system can recover supporting evidence. Preserve artifact pointers, versions, unresolved issues, and explicit constraints rather than relying on fluent narrative alone.

Does a larger context window remove this work?

It can reduce how often compaction is necessary. It does not establish relevance, freshness, authorization, or correct interpretation. Evaluate packet selection and recovery behavior at the actual task level.

Source reference list

Context Engineering
AI Agents
Compaction
Agent Memory