When an AI agent runs out of context: compact, retrieve, or start fresh
Manage an AI agent context window with compaction, retrieval and verified task state. Check constraints, evidence and unfinished work before continuing.
Who this is for: Engineers building AI agents whose implementation or research tasks span multiple context windows.
The answer in 3 lines
- Keep verified instructions and task state outside the transcript.
- Compact useful narrative or start fresh; retrieve the evidence the next step needs.
- Check constraints, artifact revisions and unfinished operations before continuing.
Evidence: Primary documentation analysis checked 21 November 2026; hypothetical examples and proposed checks, with no API experiments or benchmark results.
The direct answer
Keep an explicit task record outside the transcript, then choose the context the next step needs: compact useful conversational history, retrieve specific evidence, or start a fresh window from verified state. Combine these techniques where useful, and validate the transition before allowing the agent to continue acting.
Plan the transition before the next step stops fitting
An AI agent context window can fill with file contents, logs, abandoned approaches and tool replies long before a feature is complete. The useful question is what the next model turn must know to continue correctly. More room can postpone a transition; it cannot tell you which test result is current or whether an unfinished operation completed.
Choose a transition point before a large read or a new phase of work. Account for the instructions, tool definitions, retained messages and evidence that will enter the next request, plus room for generation and the model's applicable reasoning budget. OpenAI documents that context limits cover input, output and, for relevant models, reasoning tokens. A conversation identifier does not remove that limit. OpenAI conversation state
There is no universal percentage at which every agent should compact. Set headroom from the next permitted workload: a bounded file excerpt is different from an unrestricted build log. Limit or save large tool output before adding it to context. If the request already exceeds the limit, reduce or reconstruct the input through the supported integration path; an ordinary oversized generation request is not a reliable way to ask for its own rescue summary.
Documentation context: checked 21 November 2026. OpenAI and Claude API pages are moving documentation, not pinned SDK installations. The MCP examples use specification revision 2026-07-28; Anthropic's context-engineering article was published 29 September 2025. The decisions and hypothetical scenario below are a design synthesis, not results from API calls or agent experiments.
Separate instructions, task state, evidence and narrative
Before shortening anything, decide which record can settle each question. A summary is a convenient model input; it should not become the only place that records a pending decision or the identity of an unfinished job.
| Information | Retain across the transition | Validate against |
|---|---|---|
| Instructions and constraints | Current objective, acceptance criteria, scope, explicit prohibitions and the source of any changed requirement. | The current trusted task specification and application policy. Preserve the force of words such as “must” and “must not.” |
| Task and execution state | Task ID, artifact revision, completed and pending steps, unresolved decisions, operation IDs and known or unknown outcomes. | Actual artifacts, test records, the task controller and relevant service receipts. A proposed step and a completed step need different states. |
| Evidence | Source URI or file path, relevant revision/date, the question it answers and enough exact material for the next decision. | The source itself, with the correct scope and version. A plausible paraphrase or working link alone is insufficient. |
| Conversational narrative | A short explanation of decisions, discarded approaches and why the current approach remains useful. | The retained evidence and decisions. Repeated logs and superseded speculation can usually leave active context once their useful results are captured. |
Anthropic's prompting guidance recommends structured records for test/task status, freeform progress notes for narrative, and an explicit startup procedure when continuing in a fresh context. Those are useful representation choices; a generated JSON record still needs factual verification. Claude state management guidance
Retrieval memory helps find relevant prior information. Execution state tells the application which work is pending and which outcomes have been confirmed. A search result saying “preview created” should lead to the operation record, not replace its status.
Also distinguish the storage lifetime from the representation. A task record held only in process memory can survive a model-window reset while the process lives, but it does not thereby survive a worker restart. A persisted file or backend record survives only the failures covered by that storage. Neither a compacted transcript nor a durable record alone guarantees that an external action happens once. For persistence and recovery architecture, use the separate Agent Memory vs Checkpoints: What Should You Persist?.
Choose the representation for the next phase
Start with verified instructions and task state in every path. Then make two decisions: which evidence to load, and whether the old conversation remains useful. Retrieval can accompany either compaction or a fresh context; these are not mutually exclusive product categories.
| Situation | Useful choice | Cost or failure to check |
|---|---|---|
| The same investigation continues, and recent discussion explains several dependent choices. | Compact the history through the supported mechanism; carry a separately checked task record. | A summary may lose a qualifier, negative constraint or unresolved disagreement. Compare those items with the originals. |
| Large documents or logs dominate, but the next step needs only a particular definition, failure or source passage. | Retrieve bounded excerpts by known references; search when the reference is unknown. | Retrieval can omit a required passage or fetch a different revision. Check evidence coverage and freshness. |
| A phase has ended, the old transcript contains conflicting approaches, or a compaction failed the required-fact checks. | Start a fresh context from the task record, current instructions and selected evidence. | Reconstructing rationale takes work. Do not discard the only copy of a necessary decision before capturing it. |
| The next step still fits and the retained material is relevant. | Continue without a transition. | Reassess before the next large read. Compaction itself is work and need not happen on every turn. |
Anthropic's context-engineering article describes compaction, notes outside the context window and loading data through lightweight references. It also warns that aggressive summarization can lose important details. The table turns those documented mechanisms into application choices; it does not establish that one universally performs best. Anthropic context engineering
If you cannot verify a critical constraint, artifact revision or operation status, repair that gap first. Moving the same uncertainty into a shorter prompt does not resolve it.
Choose the next window from verified state
Use the selected API's continuation contract
Application summaries and provider compaction objects are different interfaces. Keep a readable task record for your own checks, and preserve provider-managed items according to the exact continuation mode.
| Documented interface | Consequence for your adapter |
|---|---|
OpenAI Responses can chain context with previous_response_id; Conversations store items under a durable conversation identifier. | Choose and track the continuation mode explicitly. Neither ID represents the application's completed work. Top-level instructions apply only to the request supplying them, so resupply them when needed. A developer message in the initial input remains in chained history; a fresh conversation must receive its own current instructions. Conversation state |
OpenAI standalone /responses/compact returns a window containing an opaque encrypted compaction item and potentially other retained items. The submitted window must still fit. | Pass the complete returned window onward as documented; do not extract only the apparent summary. Server-side compaction has different history-handling rules, including no manual pruning with previous_response_id. Compaction |
| Claude's current overview distinguishes on-demand and threshold compaction, both beta at the check date, from an application-owned summarizer. | Select the path supported by your model/platform. Follow its returned-block placement and preserved-thinking rules; a hand-written summary is not a drop-in replacement for a provider block. Claude compaction |
| MCP revision 2026-07-28 assigns context aggregation and model coordination to the host. A tool call carries a tool name and arguments; its result can report a tool error. | Have the host retain needed call identifiers, arguments and result status through the transition. Text that mentions a tool is not proof that it ran, and a result containing an error must not become a completed step. MCP architecture, MCP tools |
Record the model, endpoint, SDK version and compaction mode used by your application when you validate it. Recheck this adapter contract after an upgrade. Avoid deleting arbitrary messages inside an ongoing provider history: use its documented compaction path, or deliberately construct a fresh conversation without pretending it is the old provider-managed state.
Continuing from saved context is another model invocation. It may produce a different plan or tool choice; it is not deterministic replay of the previous reasoning. Reuse confirmed task facts and recorded outputs where required, and validate new proposals as new work.
Replace “tests fixed; continue” with a checkable handoff
Hypothetical implementation task; none of these edits, tests or service calls were performed for this guide. An agent is adding CSV import validation. The task requires rejecting blank quantity cells while accepting numeric zero, preserving the public API and avoiding production deployment. It has edited a parser, run one focused test and submitted an authorized sandbox preview job. The reply to the latest status lookup was lost.
A lossy summary might say:
CSV validation is fixed and tests pass. Preview started. Continue with integration and deploy when ready.
That text expands one test into a general claim, loses the zero-value requirement, drops the deployment prohibition and gives no way to inspect the preview. Starting from it invites a different task.
Use an application-defined record such as the following. All identifiers and paths are invented; snapshot-17 denotes a hypothetical saved workspace snapshot that includes the uncommitted edits. This is illustrative JSON, not an SDK payload or a claim that JSON enforces correctness.
{
"task_id": "csv-42",
"state_revision": 7,
"objective": "Reject blank quantity cells; accept numeric zero",
"constraints": [
"Preserve the public import API",
"Do not deploy to production"
],
"workspace_snapshot": "snapshot-17",
"changed_files": ["src/import/quantity.ts"],
"checks": [
{
"name": "quantity-zero",
"status": "passed",
"tested_snapshot": "snapshot-17",
"result_ref": "artifacts/check-17.json"
},
{
"name": "csv-import-integration",
"status": "not_run"
}
],
"open_decisions": [
"Determine the specified behavior for whitespace-only cells"
],
"evidence": [
{
"ref": "docs/import-contract.md#quantity",
"revision": "spec-4",
"needed_for": "blank, zero and whitespace semantics"
}
],
"external_operations": [
{
"operation_id": "preview-request-8",
"job_id": "preview-184",
"environment": "sandbox",
"last_confirmed_status": "queued",
"current_status": "unknown_after_status_timeout"
}
],
"next_step": "Read spec-4; inspect snapshot-17 and existing preview-184"
}
The next context should load the current task instructions, resolve that exact snapshot and read the contract's relevant passage. If the contract does not settle whitespace handling, keep the decision unresolved and use the task's established resolution path; do not silently choose a behavior. Check the focused test record against the artifact revision, then run the still-needed integration check when its prerequisites are ready.
Look up the existing preview job before deciding whether any further preview action is needed. A fresh context does not imply a fresh preview request. The unknown current status cannot be converted into “failed” merely because the status reply was missing.
The record itself is only a proposal until its claims match the underlying artifacts and operation records. Its advantage is that the checks are explicit. If you choose compaction instead of a fresh context, supply this same verified information alongside the supported compacted history.
Retrieve the evidence the next decision actually requires
A fresh window does not need every file previously read. Give it an evidence request that names the decision, such as: “Determine whitespace-only quantity behavior from spec-4, then inspect the parser branch implementing that rule.” This is narrower and easier to check than “recover everything about CSV imports.”
Use the following procedure:
- Resolve known references directly. Open the recorded contract revision and relevant file region. Use search to locate an unknown reference; a similarity match should not choose which task record is authoritative.
- Retain the necessary surrounding rule. An excerpt must include qualifications, exceptions and definitions that could change the decision. Keep its URI/path and revision with the text. In the hypothetical example, “reject blank” without the definition of blank may be insufficient.
- Choose historical or current evidence deliberately. Reproducing a recorded test requires the tested snapshot. Making a new decision against today's code requires checking today's artifact. If they differ, record the difference and reassess which previous results still apply.
- Bound expansion and define failure. Limit the reads and output size for a single step. If the required passage remains unavailable or sources conflict, record the evidence gap and hold the dependent change. Do not fill the remaining prompt with unrelated documents.
Anthropic describes loading data using paths, stored queries and links, while noting the runtime work and navigation demands of that approach. Direct lookup and search are both retrieval; a vector database is not required just to reopen a known file. Context retrieval and agentic search
Keep evidence as evidence when assembling the request. A retrieved old note can explain a previous choice; it should not replace the current task's instructions. For diagnosing failures in source coverage, ranking or context assembly, see the separate Why RAG Gives Wrong Answers With Relevant Documents. Here the acceptance question is narrower: does this next context contain the evidence required to continue this task?
Test the transition as a boundary with observable failures
Make a pre-transition record that the compaction process cannot silently rewrite. Let the host compare exact fields and artifact references; use semantic review where a requirement or rationale cannot be checked by equality. Asking the resumed model whether it remembers everything is not an independent check. With opaque provider compaction, you cannot inspect every retained fact: supply critical constraints and state explicitly alongside the supported continuation, then check references and the proposed next action. Passing these checks permits that next step; it does not prove that the entire history was preserved.
Before the transition:
- Save the current objective, constraints, unresolved decisions and task-state revision. Include the source of any changed requirement.
- Capture artifact/snapshot IDs, source links with revisions, and the precise scope of completed checks. Preserve “not run,” “pending” and “unknown.”
- Record in-flight operation identifiers and last confirmed outcomes. If work continues during compaction, retain updates after the summary's cutoff and reconcile them before resuming.
- Verify that references will be readable from the next context, and that both the transition request and the next request fit their applicable budgets.
After the transition, before enabling dependent actions:
- Compare required constraints and IDs with the preserved record. Inspect the actual assembled input, including current instructions and tool definitions.
- Resolve the artifacts and evidence the next step needs. Check whether they changed since the record was written.
- Ask for the next action and its prerequisites; compare that proposal with the task state. Reject a plan that repeats a completed step, invents a decision or treats an uncertain operation as a failure.
- Continue only when the checks pass. If they fail, repair the record or evidence, or reconstruct a fresh window. Keep the original records available under your retention policy.
Use cases like these to exercise the implementation. They are proposed tests, not reported results.
| Deliberate condition | Expected observable behavior |
|---|---|
| Remove “do not deploy” from a summary. | The constraint comparison fails, or the next input restores it from the trusted specification before actions are enabled. |
| Summarize one focused test as “all tests pass.” | The task record still shows integration as not run; the resumed plan schedules the missing check. |
| Advance the workspace after a recorded passing test. | The old result remains attached to its tested snapshot and is not presented as validation of the new code. |
| Lose the preview status reply. | The agent retains the existing job ID and checks it; it does not create a replacement because the outcome is unknown. |
| Complete a job while its history is being compacted. | The next context receives the later confirmed status; the older summary cannot overwrite it. |
| Make a required source unreadable. | The dependent decision remains unresolved, with an explicit source gap. |
| Repeat transitions over multiple windows. | Constraints, pending decisions and exact identifiers remain checkable against the external record after each transition. |
Retain the before/after records, assembled inputs, source revisions and proposed next actions. Compare transition policies on the same task cases and model settings, with repeated runs where generation variability matters. Measure observed omissions, incorrect next actions and transition overhead separately; a smaller prompt alone is not evidence of a better continuation policy.
Sources & further reading
Documentation informs the product behavior described here. The worked scenarios and conceptual diagrams explain how those behaviors fit together.
- Agent memory, checkpoints, and durable workflows: choosing what to persist — related Runeval guide ↗Runeval · Accessed 2026-11-21
- Why RAG retrieves relevant documents but still gives wrong answers — related Runeval guide ↗Runeval · Accessed 2026-11-21
- Conversation state — Responses API ↗OpenAI · Accessed 2026-11-21
- Compaction — Responses API ↗OpenAI · Accessed 2026-11-21
- Prompting best practices — long-horizon reasoning and state tracking ↗Anthropic · Accessed 2026-11-21
- Compaction overview — on-demand and threshold beta interfaces ↗Anthropic · Accessed 2026-11-21
- Effective context engineering for AI agents (29 September 2025) ↗Anthropic · Accessed 2026-11-21
- MCP architecture — specification 2026-07-28 ↗Model Context Protocol · Accessed 2026-11-21
- MCP tools — specification 2026-07-28 ↗Model Context Protocol · Accessed 2026-11-21