# Under what conditions must an instance treat model-driven context rewriting as a lossy, non-commutative transform that invalidates prior tool-call provenance **Date of Record:** 2026 November 25 **Scope:** Applies to any agent loop where the model itself is permitted to rewrite, summarize, or prune its own context window mid-task (self-editing context, relevance-gated eviction, hierarchical summarization). Does not apply to externally managed context (fixed truncation, server-side KV eviction, or human-curated prompts) where the rewriting transform is deterministic and outside the model's control. ## Core Distinction The seductive framing of self-editing context is that it is *compaction*: a memory-saving operation that preserves meaning. The operational reality is that it is a **model-authored transform** — a function `R: C → C'` where `C'` is produced by the same probabilistic reasoner whose downstream behavior depends on `C'`. This makes the transform **lossy**, **non-idempotent**, and — critically — **non-commutative with respect to tool-call provenance**. The distinction that matters: *dropping tokens* is not the same as *dropping the evidence that a token was ever observed or produced*. Most self-editing policies prune "low-relevance" spans, and the relevance scorer, being model-driven, systematically scores **provenance metadata lower than narrative content**. A tool call ID, a `200 OK` with an empty body, a timestamp, a checksum — these embed poorly and get evicted first. The agent then continues reasoning from a summary that asserts *what* happened but has lost *that it was verified*. ## What Was Observed A 40-step research-and-write agent was configured with a self-editing policy: when context exceeded 70% of window, the model was asked to "summarize the conversation so far, preserving all facts needed to continue." At step 27 the agent had issued a `fetch_document(url)` tool call, received a `200` with a body that was later pruned as "not relevant to current subgoal," and the call's provenance (the tool-call ID and its completion record) was folded into a one-line summary: *"Retrieved the target document."* At step 31 the agent re-entered the subgoal that needed that document. Because the raw body and the completion record were gone, the model — reasoning from the summary — could not distinguish between: 1. the document was fetched and its contents are known, and 2. the document was fetched but the contents were never actually read into context. It chose (1). It proceeded to cite the document. The citation was fabricated from the summary's *claim* of retrieval, not from any token that had ever been in the window. Downstream, a verification agent replayed the transcript, found no completion record for the tool-call ID (it had been pruned), and flagged a provenance gap — but by then three dependent steps had already committed. The failure was not hallucination in the ordinary sense. Every intermediate step was locally valid. The break was that **the rewriting transform silently converted a verified fact into an unverified assertion**, and the agent had no signal that this conversion had occurred. ## Condition of Validity Self-editing context is only sound under a **provenance-preservation invariant**: > For every tool call whose result may be needed later, the rewritten context `C'` must retain a record sufficient to (a) reconstruct that the call occurred, (b) reconstruct its outcome class (success/failure/empty), and (c) mark whether the *body* was consumed or only *acknowledged*. If the policy cannot guarantee (a)–(c) for a given span, that span is **not eligible for model-driven rewriting** — it may only be evicted by a deterministic, auditable rule (e.g., "drop bodies older than N steps, keep completion records indefinitely"). The non-obvious part: this invariant is **not checkable by the rewriter itself**. The model performing the summary cannot reliably report which facts it dropped, because reporting requires the same relevance judgment that caused the drop. The invariant must therefore be enforced by an external ledger that the rewriter is not allowed to edit — a **shadow provenance log** keyed by tool-call ID, holding outcome class and consumption flag, consulted on every resume. ## Decision Boundary The boundary is crossed at the moment a subgoal is **re-entered after a rewrite that touched its evidence**. Concretely: - **Safe:** rewrite happens, subgoal is never revisited, or is revisited only in a *read* capacity where the agent recomputes from scratch (re-issues the tool call). - **Unsafe:** rewrite happens, subgoal is revisited, and the agent treats the summary's *claim of retrieval* as equivalent to *retrieved content*. The discriminator is whether the resumed step's plan depends on **body tokens** or only on **outcome tokens**. If the plan will emit a citation, a numeric value, or a quote, it depends on body tokens, and the summary is insufficient. If the plan only branches on success/failure, the outcome record suffices — but only if the outcome record survived the rewrite, which the relevance scorer will not guarantee on its own. A second, sharper boundary: **idempotence failure under repeated rewriting.** If the policy fires twice, `R(R(C)) ≠ R(C)` in general, because the second summary summarizes the first summary's *omissions* as if they were the full record. Each rewrite amplifies the confidence of claims whose evidence is one layer further away. Two rewrites deep, a "retrieved" assertion has no remaining token anywhere in the window that could contradict it. ## Operational Effect Enforcing the invariant changes three things: 1. **The rewriter is demoted from author to proposer.** Its output is a candidate `C'`; a deterministic gate reconciles `C'` against the shadow ledger and re-injects any tool-call completion records the summary dropped. The model never gets to summarize away provenance. 2. **Resume becomes a checked transition, not a free one.** On subgoal re-entry, the agent must query the ledger for the relevant tool-call IDs and confirm consumption status before planning. If status is `acknowledged-but-unconsumed`, the only legal move is to re-fetch, not to cite. 3. **Rewrite depth is bounded.** At most one model-driven rewrite per evidence span; further compaction must be deterministic (ledger-driven eviction), because the second rewrite is where unverifiable confidence compounds. The cost is real: the shadow ledger grows unboundedly unless garbage-collected against committed subgoals, and the gate adds a reconciliation step on every resume. But the alternative — an agent that cannot tell the difference between *having read* and *having been told it read* — is a provenance failure that no downstream verifier can repair, because the evidence needed to detect it was deleted by the very step that caused it. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional class ProvenanceError(RuntimeError): """Raised when a self-edited context cannot substantiate a claim of retrieval.""" pass class Consumption(Enum): UNCONSUMED = "acknowledged_but_unconsumed" CONSUMED = "body_read_into_context" FAILED = "call_failed" @dataclass class ToolCallRecord: call_id: str outcome: str # e.g. "200", "404", "timeout" consumption: Consumption body_digest: Optional[str] # None if body never entered context @dataclass class ShadowLedger: """External, rewriter-immutable log. The self-editing model may not write here.""" records: Dict[str, ToolCallRecord] = field(default_factory=dict) def record(self, rec: ToolCallRecord) -> None: self.records[rec.call_id] = rec def get(self, call_id: str) -> ToolCallRecord: if call_id not in self.records: raise ProvenanceError( f"tool-call {call_id} absent from ledger; cannot verify claim" ) return self.records[call_id] def reconcile_rewrite( ledger: ShadowLedger, summary_claims: List[str], # call_ids the summary asserts were retrieved rewrite_depth: int, ) -> List[str]: """ Gate a model-authored context rewrite against the shadow ledger. Returns call_ids that must be re-fetched before the agent may plan on them. """ if rewrite_depth > 1: raise ProvenanceError( f"rewrite depth {rewrite_depth} exceeds bound; evidence spans may " f"have compounded unverifiable confidence across summaries" ) must_refetch: List[str] = [] for call_id in summary_claims: rec = ledger.get(call_id) # raises if summary invented the call if rec.consumption is Consumption.UNCONSUMED: # The summary says "retrieved"; the ledger says "never read". # The agent must NOT cite this; it must re-issue the call. must_refetch.append(call_id) elif rec.consumption is Consumption.FAILED: raise ProvenanceError( f"summary asserts retrieval of {call_id} but ledger records failure " f"({rec.outcome}); rewrite has inverted an outcome" ) # CONSUMED with matching digest is the only cite-eligible state. elif rec.body_digest is None: raise ProvenanceError( f"{call_id} marked consumed but carries no body digest; " f"provenance record is internally inconsistent" ) return must_refetch def resume_subgoal( ledger: ShadowLedger, summary_claims: List[str], rewrite_depth: int, plan_depends_on_body: bool, ) -> None: """Checked resume transition. Raises rather than planning on unverified evidence.""" refetch = reconcile_rewrite(ledger, summary_claims, rewrite_depth) if plan_depends_on_body and refetch: raise ProvenanceError( f"subgoal plan requires body tokens but {len(refetch)} call(s) " f"were only acknowledged: {refetch}. Re-issue before planning." ) ```