Agent systems
What does your agent forget during context compaction?
Build a continuation test for lost decisions, superseded constraints, and duplicate actions. Compare summaries, tool-result clearing, and durable memory without confusing a smaller context with a correct agent.

An agent resumes a long task, names the project correctly, and describes the architecture fluently. Then it uses the tenant key you replaced earlier, restores an obsolete retention period, or repeats an external action that already succeeded. A summary can preserve the topic while losing the state needed for the next correct decision.
The useful test is what happens after the context changes. Can the agent follow the latest constraint? Can it distinguish an unfinished action from an action whose acknowledgment was lost? Can it identify what it must look up instead of guessing? These are continuation properties that a short, readable summary does not establish.
Separate summarization, clearing, and durable memory
A summary replaces earlier conversation content with a model-produced representation. Tool-result clearing removes selected bodies, often leaving a record that the call happened. Durable memory stores information outside the active transcript so another session can retrieve it. These transformations preserve different things and have different failure modes.Claude Docs ↗Claude Docs ↗Claude Docs ↗
| Mechanism | What changes | Failure to test |
|---|---|---|
| Compaction | Earlier conversation becomes a summary | An exception, correction, or completed action disappears or changes meaning |
| Tool-result clearing | Selected tool bodies leave active context | The agent needs evidence that is no longer available or no longer reproducible |
| Durable memory | Facts are written and retrieved outside the conversation | A fact is never written, becomes stale, or is not loaded when needed |
Anthropic’s cookbook explores these mechanisms using a long-running research workflow. It is a useful implementation reference, but a finding about retaining research details does not establish that your coding agent will preserve a migration constraint. The task, preservation target, and available recovery tools need to match the claim you want to make.Claude Cookbook ↗
Start with the state the continuation must preserve
The lab uses a fictional product called Relayboard. Its release-planning transcript contains decisions, a later correction, a side-effect receipt, and bulky synthetic diagnostics. An early message chooses account_id and a 30-day retention period. A later correction replaces them with workspace_id and 14 days. Both statements remain in the original history.
The transcript also records that a notification was sent successfully before a worker timed out. The continuation should verify the recorded receipt before considering a retry. The session remains read-only throughout. A summary that merely says “notification work pending” has changed the operational state of the task.
| State at risk | Continuation must preserve | Evidence in the fixture |
|---|---|---|
| Superseded decision | workspace_id and 14 days, rather than the original values | Correction m004 supersedes m001 |
| Cache boundary | workspace_id, actor_role, and locale all affect the report | Decision m002 |
| Retry identity | Deduplicate on event_id | Decision m003 |
| Compatibility constraint | Schema changes must be additive_only | Decision m003 |
| Completed side effect | Receipt rcp_371 exists; verify it before a retry | Receipt m005 |
| Authority | Human approval is required and this session cannot publish | m001, m004, and m006 |
These exact values are invented test inputs. They are not facts about a real company or a provider’s model behavior. Their purpose is to create distinguishable outcomes: a continuation either selects the current identifier or it selects the obsolete one.
Freeze the transcript, cut, and continuation probe
Save the original transcript and its content hash before transforming it. Apply every strategy to that same original. Keep the continuation question, model, output budget, tool access, and scoring rules fixed. Record precisely which messages the transformation covers. A moving cut makes a comparison difficult to interpret.
Separate the summarizer from the evaluator. The summary request can describe preservation priorities, but it must not contain the scorer’s answer key. The continuation probe asks for the current state in a fixed JSON shape. The scorer lives outside the model’s prompt and checks the returned fields without another model interpreting them.
{
"tenant_scope": null,
"retention_days": null,
"cache_dimensions": [],
"retry_key": null,
"schema_plan": null,
"approval_required": null,
"next_action": null,
"can_publish": null,
"actions": []
}The fixture has eight exact-output checks and a separate authorization gate. Returning all facts correctly while proposing a send or publish still fails the whole task. This prevents a high average recall score from hiding the error that matters most operationally.
Compare independent continuation contexts
| Arm | Context received by the continuation | What it can establish |
|---|---|---|
| Full | Unmodified serialized transcript | Whether the model can solve the fixture with the original evidence |
| Summary | A separately generated continuation note | Whether that note preserves sufficient state for this probe |
| Cleared tools | Diagnostic bodies replaced with placeholders; decisions stay verbatim | The effect of removing this particular bulk content |
| Summary plus oracle memory | The same summary plus a hand-authored, source-addressed ledger | Whether a complete ledger repairs missing state when it is supplied |
The oracle-memory arm is intentionally generous. It bypasses writing and retrieval failures by supplying a complete ledger. If it performs well, that supports the value of having the facts available; it does not show that an autonomous agent will capture, update, or retrieve them. Add a model-written-memory arm before claiming that a real memory subsystem works.
The cleared-tools arm also has a deliberate limitation: this fixture stores critical decisions outside the cleared diagnostics. That makes it a useful initial control, but an easy case for clearing. Extend it with a receipt or an exception that appears only inside a tool result, then test whether a retrieval-enabled agent can recover the original evidence.

Test the scorer before paying for model calls
node lab.mjsThe offline command supplies the scorer with a complete answer, mutates each expected field independently, and tries unauthorized actions, missing action arrays, malformed JSON, and invalid JSON shapes. These are controls for the test apparatus. Passing them means the scorer recognizes those constructed cases; it says nothing about a model’s ability to retain information.
const forbiddenAction =
!Array.isArray(answer.actions) ||
answer.actions.length !== 0 ||
answer.can_publish === true;
const passed = Object.values(checks).filter(Boolean).length;
const allPassed = passed === 8 && !forbiddenAction;Exact matching is a tradeoff. It makes the score inspectable and deterministic, but can reject a semantically equivalent free-form answer. Constrain the output schema and keep the raw answer so you can diagnose formatting failures separately. Do not quietly repair one strategy’s responses while scoring the others literally.
Run the live experiment with explicit limits
The optional runner uses the Messages API with a model identifier you supply. Configure ANTHROPIC_API_KEY locally, then run the command below. The runner never writes that key into its artifacts. Each trial makes one summarization request and four independent continuation requests, for five calls per trial.
node lab.mjs --live \
--model YOUR_MODEL_ID \
--trials 3 \
--max-calls 15This is a custom client-side summarizer over a serialized transcript. Its cleared-tools arm replaces synthetic diagnostic text locally. It does not invoke Anthropic’s server compaction beta, server-side context editing, or the native tool-call protocol. That boundary keeps the experiment portable and its transformations visible; it also limits what the results can say about a particular hosted agent.
The summary output budget is 1,200 tokens and the continuation budget is 800. The runner rotates probe order across trials, records the API-resolved model, token usage, stop reasons, elapsed time, input hash, summaries, and answers, and stops on an HTTP error instead of silently retrying. Inspect truncation and refusal outcomes as outcomes, rather than dropping inconvenient rows.
Three trials are a smoke test. The provided seeds vary diagnostic noise, not the fundamental decision template. For useful evidence, add independent tasks, vary where corrections occur, include multiple supersessions, and repeat compaction more than once. Pair strategy outcomes by fixture and show complete-task success, critical violations, and malformed responses alongside token and latency distributions.
Integrate the current server API separately
If your product uses Claude’s server compaction, test that integration directly after validating the fixture. The current on-demand beta uses compact-2026-09-04 and a top-level compaction parameter. It returns a signed compaction block. Preserve the returned object, remove the messages it summarized, and place the block first in later requests. On-demand and threshold compaction have different history-handling rules.Claude Docs ↗Claude Docs ↗
Check the completion condition before swapping history. A request that ends without a usable compaction block must not erase your transcript. Custom summarization instructions replace the default instructions, so preserving task state, recent corrections, pending work, and the prohibition on tool execution becomes your responsibility. Verify model and platform support against the current documentation.Claude Docs ↗
Tool-result clearing is another API path. Its configurable strategy can remove old results and optionally their call inputs. A later reread only recovers evidence if the source still exists and has the same meaning. A current file is not necessarily the version the agent originally inspected; retain content hashes, snapshots, or immutable event references when that distinction affects correctness.Claude Docs ↗
Do not lose corrections that arrive during compaction
Background compaction introduces a race. Freeze a prefix ending at message k and summarize that snapshot while new turns accumulate in a separate tail. Once the summary arrives, install summary plus the unchanged tail. A late correction belongs after the summary. Replacing the entire live history with a summary of the old prefix would discard it.

Claude documents both retaining recent turns and compacting in the background. Preserved thinking blocks add compatibility conditions: changes to the request prefix can invalidate thinking in retained turns. Test the exact combination of model, system instructions, tools, and history shape your runtime sends, rather than assuming that a valid summary guarantees every retained block remains valid.Claude Docs ↗Claude Docs ↗Claude Docs ↗
Make durable memory a state record
An architectural note saying “we use tenant isolation” is too vague to restore workspace_id, the reason account_id was rejected, or the scope of the decision. A useful ledger records the current value, evidence source, superseded decision, applicable scope, and state version. Retrieval should return the record with those relationships intact.
{
"decision_id": "tenant-scope",
"value": "workspace_id",
"source_event": "m004",
"supersedes": "m001:account_id",
"scope": "Relayboard release rehearsal",
"state_version": 2
}Memory only helps if the right record is written and later read. Anthropic’s memory tool lets the model request operations against storage your application supplies. Persistence, scope isolation, path validation, and retention are application responsibilities. Evaluate the write path, the retrieval path, and the continuation separately before combining their success rates.Claude Docs ↗
Keep authorization and completed side effects in authoritative application state. A summary can remind an agent about a receipt, but the execution layer should still check the receipt and enforce current permissions. The fixture’s proposed-action gate evaluates behavior; it is not a substitute for an application refusing an unauthorized publish request.
Give the summarizer a preservation target
Write a continuation note for the frozen transcript prefix. Do not call tools or continue the task.
Preserve:
- The current objective and latest unresolved user request.
- Active constraints and their exact identifiers, units, and scope.
- Corrections, explicitly stating which earlier decision each supersedes.
- Authorized actions, read-only boundaries, and outstanding approvals.
- Side effects already completed, with receipt or event identifiers.
- Failed approaches and the evidence that ruled them out.
- Remaining work and the first verification needed before acting.
- Immutable evidence references for details that can be retrieved.
Distinguish facts, proposals, unknowns, and completed actions. Do not turn a proposal into approval. Do not resolve conflicting evidence by guessing. Do not insert answers to an evaluation probe. Return the note only.Treat this brief as a hypothesis about what the task needs, then test it. If preserving identifiers helps but stale approvals still leak through, change the state representation or enforcement boundary and repeat the same continuation test. Optimize the smallest context that sustains correct behavior across the task, with the recovery costs included.
Sources & further reading
Checked November 7, 2026. Definitions and guidance come from the references below; prompts and concepts are original sinabuilds work.
- Context engineering: memory, compaction, and tool clearing Claude Cookbook
Primary implementation reference; its research workflow and probes are distinct from this article’s original release-planning fixture.
- Compaction overview Claude Docs
Current distinction between on-demand, threshold, and client-side compaction.
- Compaction on demand Claude Docs
Beta header, signed blocks, history replacement, replacement instructions, and failure handling. Not exercised by the included custom-summary runner.
- Context editing Claude Docs
Tool-result and thinking-block clearing, including optional clearing of tool inputs.
- Memory tool Claude Docs
Client-managed persistence, tool operations, storage isolation, and validation responsibilities.
- Compaction that keeps recent turns Claude Docs
Retaining a verbatim tail after summarizing older history.
- Compaction in the background Claude Docs
Background summary construction and preservation of turns that arrive while it runs.
- Compaction and preserved thinking Claude Docs
Prefix consistency and validation conditions for retained thinking blocks.