# What happens when an instance rewrites its own context and prunes the tool-call provenance that later verification depends on **Date of Record:** 2026 November 21 **Scope:** Applies to any agent that performs model-driven context rewriting (summarization, pruning, deduplication, or compaction) mid-episode while retaining the ability to resume tool execution or emit a verification/replay record. Does not apply to append-only context logs with no in-episode rewriting, or to stateless single-turn calls with no resumable tool state. ## Core Distinction There are two categorically different objects inside a running agent's context window, and model-driven rewriting treats them as one: - **Narrative state** — the reasoning trace, the plan, the running summary of what the agent believes it is doing. This is lossy by design. Summarizing it is safe and is the whole point of compaction. - **Provenance state** — the exact arguments, ordering, and results of tool calls that produced side effects, plus the identifiers needed to reconcile those effects on resume or replay. This is *not* compressible without breaking an invariant, because downstream verification and idempotent resume both need to reconstruct *which call, with which exact arguments, produced which observed effect*. The boundary failure is this: a rewriting policy that scores spans by "relevance to the current goal" will systematically prune provenance, because a raw tool result from twelve steps ago ("`write_file` returned `ok`, revision `r41`") reads as low-relevance noise relative to the current subgoal. The rewrite is locally correct by its own objective and globally catastrophic for the invariant that resume and replay depend on. The failure is silent: the compacted context still *reads* coherently, and the agent proceeds confidently on a summary that has drifted from the actual side-effect history. ## What Was Observed A representative trace, compressed to the mechanism: 1. Agent executes a sequence of mutating tool calls: `create_branch`, `write_file(f, rev r40)`, `write_file(f, rev r41)`, `run_tests → fail`, `write_file(f, rev r42)`, `run_tests → pass`. Each result is a small structured record with a revision token. 2. Context crosses a high-water mark. The rewriting policy fires: it summarizes the last N turns into prose. The summary says: *"Edited `f` and tests now pass."* The three intermediate revisions, the failed test run, and the revision tokens are dropped. 3. The episode is interrupted (token budget, timeout, or an external pause). A resume is issued from the compacted context. 4. On resume the agent must decide whether `f` is in a known-good state. The summary asserts success but carries no revision token, so the agent cannot distinguish "r42 committed" from "r42 written to a staging area but not committed" — the compacted trace erased the distinction between *observed effect* and *believed effect*. 5. The agent re-issues `write_file(f, ...)`. Because the prior revision token was pruned, the write is not recognized as a duplicate. Either it double-applies a non-idempotent edit, or it fails a precondition check whose expected revision the agent no longer holds. Both are resume failures caused purely by rewriting, not by any tool fault. The tell in the logs is a **provenance gap**: a resume or replay step references a revision/handle/argument that does not appear anywhere in the surviving context, because the only copy lived in a span the rewriter scored as low-relevance. ## Condition of Validity Model-driven pruning is valid **only** when the following invariant holds across every rewrite: > **Provenance closure.** For every tool call that produced an externally visible effect and remains un-retired (i.e., not yet reconciled by a verification or commit step), the rewritten context must retain a *lossless, machine-parseable* record of: the call identity, its exact arguments, the observed result token, and the ordering relative to sibling calls. Narrative summary may replace everything else. Three corollaries that make the invariant checkable: - **Effect/ belief separation.** The rewriter may compress *beliefs* ("tests pass") but must never compress an *effect record* into a belief. If a summary sentence is the only surviving witness of a side effect, the invariant is violated. - **Retirement, not recency, governs pruning.** A provenance record may be dropped only when a downstream step has *consumed* it — a commit acknowledged it, a verifier reconciled it, a checkpoint sealed it. Age is not a valid pruning criterion; consumption is. - **Token stability under rewrite.** Effect tokens (revision ids, hashes, handles) must survive verbatim. A rewriter that "cleans up" an opaque token into "the latest revision" has destroyed the only key that makes resume idempotent. If any corollary fails, the rewrite is out of bounds regardless of how good the summary reads. ## Decision Boundary The operational question is not "should I compact?" but "which spans are eligible?" Draw the boundary explicitly: - **Eligible for model-driven rewrite:** reasoning traces, discarded plans, superseded hypotheses, verbose tool *output* whose effect token has already been retired by a commit/verify step, conversational filler. - **Ineligible — must pass through byte-exact or be sealed into a structured checkpoint:** any tool call whose effect is not yet reconciled; any revision/handle/hash token; any argument set needed to re-derive idempotency; any ordering relation among mutating calls. The boundary is crossed the moment a rewriting policy's relevance scorer is allowed to see ineligible spans as candidates. The guardrail is structural, not prompt-level: the rewriter must operate over a *filtered view* in which ineligible spans are replaced by sealed, non-summarizable references before the model ever scores them. You cannot ask a probabilistic scorer to reliably preserve a token it has been told is noise; you must remove the token from its candidate set and reattach it after rewriting. A second boundary: **the rewrite must be replayable.** If the same pre-rewrite context and the same policy produce a different post-rewrite context on replay, then verification replay will diverge from the live run. Pin the policy (temperature, seed, model version) or, better, make the rewrite a deterministic function over the sealed-reference view so that replay reconstructs the identical compacted state. ## Operational Effect When provenance closure holds, compaction is a pure win: context shrinks, resume is idempotent, and replay reconciles because every un-retired effect is still addressable. When it fails, the failure surfaces late and misattributed — as a duplicate write, a precondition mismatch, or a "verification replay discrepancy" that looks like a tool or transport bug but is actually a context-rewriting bug. The cost is highest exactly where agents are most autonomous: long episodes with many mutating calls, where the rewriter fires most often and the un-retired effect set is largest. The concrete guardrail to deploy: a pre-rewrite gate that (1) partitions spans into narrative vs. provenance, (2) seals provenance into structured references the model cannot summarize, (3) runs the model rewriter only over narrative, (4) reattaches sealed references, and (5) asserts that the post-rewrite context still resolves every un-retired effect token. If step 5 fails, abort the rewrite rather than emit a drifted context — a slightly-too-large context is recoverable; a silently lossy one is not. ```python from dataclasses import dataclass, field from typing import Optional class ProvenanceClosureError(RuntimeError): """Raised when a context rewrite drops an un-retired effect record.""" pass @dataclass class EffectRecord: call_id: str args: dict result_token: str # revision id / hash / handle — must survive verbatim retired: bool = False # True only after a commit/verify step consumed it @dataclass class RewriteResult: narrative: str sealed_effects: dict = field(default_factory=dict) # call_id -> EffectRecord def rewrite_context( narrative_spans: list[str], effects: list[EffectRecord], summarize, # model-driven summarizer over narrative only policy_seed: Optional[int] = 0, ) -> RewriteResult: # 1. Seal every un-retired effect BEFORE the model sees anything. sealed = {e.call_id: e for e in effects if not e.retired} # 2. Model rewrites narrative only; sealed effects are never candidates. narrative = summarize(narrative_spans, seed=policy_seed) # 3. Reattach sealed references and assert closure. result = RewriteResult(narrative=narrative, sealed_effects=sealed) _assert_provenance_closure(result, effects) return result def _assert_provenance_closure(result: RewriteResult, original: list[EffectRecord]) -> None: for e in original: if e.retired: continue if e.call_id not in result.sealed_effects: raise ProvenanceClosureError( f"un-retired effect {e.call_id} (token={e.result_token}) " f"missing after rewrite; resume/replay would be non-idempotent" ) if result.sealed_effects[e.call_id].result_token != e.result_token: raise ProvenanceClosureError( f"effect {e.call_id} token mutated " f"{e.result_token!r} -> {result.sealed_effects[e.call_id].result_token!r}" ) def resume_from(result: RewriteResult, next_call_id: str, expected_token: str) -> None: # Idempotency check on resume depends entirely on the surviving token. rec = result.sealed_effects.get(next_call_id) if rec is None: raise ProvenanceClosureError( f"cannot resume {next_call_id}: provenance pruned; " f"expected token {expected_token!r} is unrecoverable" ) if rec.result_token != expected_token: raise ProvenanceClosureError( f"resume precondition mismatch for {next_call_id}: " f"context holds {rec.result_token!r}, caller expects {expected_token!r}" ) ```