# How should an instance bound the "self-rewrite drift" invariant when an agent prunes and summarizes its own context mid-task **Date of Record:** 2026 November 19 **Scope:** Applies to any agent loop where the model itself decides which prior context to prune, summarize, or relevance-rewrite before continuing a task (self-editing context). Does not apply to externally-managed retrieval (RAG where a fixed policy selects chunks) or to append-only scratchpads where prior turns are never mutated. ## Core Distinction The distinction that matters is between **lossy compression of context** and **lossy compression of the *decision state* that produced the current plan**. Ordinary summarization is a memory operation: you forget details but the plan is intact. Self-rewrite drift is a *control* failure: the act of rewriting the context mutates the premises the model is reasoning from, so the next reasoning step is computed against a different problem than the one the earlier steps were solving. The failure is not "the summary is wrong." The failure is "the summary is a *plausible* summary, and plausibility is exactly the wrong criterion for the premises that justify a multi-step plan." The invariant that must hold is this: **any rewrite that removes or paraphrases a fact the current plan depends on must preserve that fact's *provenance and falsifiability*, not just its gist.** A summary that says "the API returned an error, we retried, it worked" is a gist. The plan-critical fact is "the retry succeeded *only* because we dropped the `strict` flag, and the caller still expects `strict` semantics." Gist-preserving summaries silently delete exactly the qualifiers that plans hinge on. ## What Was Observed A long-horizon agent (≈60 tool calls) was asked to reconcile a CSV export against a remote database. At call ~30 the context reached a soft budget threshold and the agent invoked its own pruning routine: it summarized the first 25 turns into a 6-line paragraph and dropped the raw tool outputs. The summary read: > "Queried the DB in batches of 500. Two batches failed with a transient timeout and were retried successfully. Schema confirmed: `amount` is `NUMERIC(12,2)`. Row counts matched at batch level." The plan continued. At call ~48 the agent wrote a reconciliation report claiming full agreement. The actual state: one of the "successfully retried" batches had returned a *partial* result set (the retry hit a replica that was lagging), and the batch-level row count matched only because the missing rows were offset by duplicate keys introduced by a `JOIN` in the original query. Both facts existed in the raw tool outputs at turns 19 and 22. Both were compressed out, not because summarization was bad, but because **the summarizer had no representation of which facts the downstream plan would later falsify against.** The summarizer optimized for narrative coherence; the plan needed adversarial falsifiers. The trace pattern is consistent across instances: 1. **Trigger:** context utilization crosses a pruning threshold *while a plan is mid-execution* (not between tasks). 2. **Rewrite:** model summarizes/prunes prior turns, keeping what reads as "the story so far." 3. **Premise substitution:** a qualifier ("partial," "replica," "strict flag dropped," "cached result," "approximate") is dropped because it is locally uninteresting to the narrative. 4. **Silent plan continuation:** the plan proceeds against the *narrated* premise, not the *recorded* one. 5. **Late falsification:** a downstream step that would have caught the discrepancy (e.g., a checksum, a re-read) is skipped because the narrated premise asserts the check already passed. The non-obvious part: **the failure is more likely when the summarization is *good*.** A high-quality summary produces a confident, fluent premise. A bad summary produces hedges and uncertainty that prompt re-verification. Fluency is the attack surface. ## Condition of Validity The drift invariant holds (i.e., the agent is safe) only when **all three** of the following are true: - **Plan-critical facts are tagged at write time, not at prune time.** When a tool result is ingested, the agent must mark which fields are *load-bearing* for the current plan (e.g., "this row count is the reconciliation oracle," "this flag value determines downstream semantics"). A summarizer that must *infer* load-bearingness at prune time will infer it from narrative salience, which is the wrong signal. - **Rewrites are diffable against the pre-rewrite state.** The agent retains a hash or structured extract of the facts it removed, so a later step can ask "did I ever actually verify X, or did I summarize that I verified X?" Without this, the agent cannot distinguish *recall* from *reconstruction*. - **The plan carries explicit falsifiers, not just steps.** Each plan step that depends on a summarized fact must carry the specific observation that would invalidate it. If the falsifier is not in the retained context, the step must be re-derived before execution, not continued. When any of these is absent, the agent is in the drift regime and its confidence is uncorrelated with its correctness. ## Decision Boundary The operational boundary is: **prune freely across task boundaries; never prune *within* a plan step's dependency chain without a falsifier-preserving rewrite.** Concretely, the decision procedure at a prune trigger is: - If the current step's inputs are all *derivable from retained context* → prune is safe. - If any current-step input is *referenced but not derivable* (i.e., the plan says "we confirmed X" but X's evidence is being summarized) → the rewrite must either (a) retain the raw evidence for X, or (b) inject a mandatory re-verification of X as the next step. Option (b) is usually cheaper and is the correct default. - If the rewrite would drop a *negative* fact (something that did *not* hold, a failed check, a partial result) → **never summarize negatives into positives.** The single most common drift is "retried successfully" overwriting "retried and got a partial result." Negatives must be retained verbatim or retained as explicit open questions. The boundary is not a token budget. It is a **dependency-freshness** boundary: a fact is prunable the moment no live plan step depends on it, and not one step earlier. ## Operational Effect When the invariant is enforced, the observable effect is a small, bounded increase in context cost (the retained falsifiers and negative facts) traded against the elimination of the *late-falsification* failure class, which is the expensive one: it surfaces only after the agent has committed downstream work built on a narrated premise. In the observed case, retaining two lines of raw evidence (the partial-result marker and the duplicate-key warning) would have cost ~80 tokens and prevented a full report regeneration plus a trust failure in the reconciliation output. The deeper effect is on **how the agent reasons about its own memory.** An agent that knows its summaries are lossy in a *specific, tracked* way can treat "I recall that X" as a claim requiring provenance, rather than as a fact. That distinction — recall vs. reconstruction — is the actual invariant. The pruning threshold is just where it gets tested. ```python from dataclasses import dataclass, field from typing import Optional class SelfRewriteDriftError(RuntimeError): """Raised when a context rewrite would drop a fact a live plan step depends on.""" @dataclass class Fact: key: str value: str load_bearing: bool = False # tagged at write time, not prune time negative: bool = False # records what did NOT hold (partial, failed, approximate) evidence: Optional[str] = None @dataclass class PlanStep: name: str depends_on: list[str] = field(default_factory=list) falsifier: Optional[str] = None @dataclass class Context: facts: dict[str, Fact] = field(default_factory=dict) steps: list[PlanStep] = field(default_factory=list) def rewrite_context(ctx: Context, keep_keys: set[str]) -> Context: """ Apply a model-driven prune/summarize rewrite that retains only `keep_keys`. Refuses to drop any load-bearing or negative fact that a live plan step depends on unless that step carries an explicit falsifier (forcing re-verification). """ dropped = [k for k in ctx.facts if k not in keep_keys] live_deps = {dep for step in ctx.steps for dep in step.depends_on} for key in dropped: fact = ctx.facts[key] if key not in live_deps: continue # safe: no live step depends on it if fact.negative and not _step_has_falsifier(ctx, key): raise SelfRewriteDriftError( f"Refusing to summarize negative fact {key!r} " f"({fact.value!r}) into a positive premise; " f"no live step carries a falsifier for it." ) if fact.load_bearing and not _step_has_falsifier(ctx, key): raise SelfRewriteDriftError( f"Refusing to drop load-bearing fact {key!r} " f"({fact.value!r}); dependent step has no falsifier, " f"so post-rewrite reasoning would run on a narrated premise." ) new_facts = {k: v for k, v in ctx.facts.items() if k in keep_keys} return Context(facts=new_facts, steps=list(ctx.steps)) def _step_has_falsifier(ctx: Context, key: str) -> bool: return any(key in s.depends_on and s.falsifier for s in ctx.steps) # --- trigger trace --- ctx = Context( facts={ "batch_retry": Fact("batch_retry", "retried successfully", load_bearing=True), "batch_partial": Fact("batch_partial", "retry hit lagging replica; partial rows", load_bearing=True, negative=True, evidence="tool_call_22.raw"), "schema": Fact("schema", "amount NUMERIC(12,2)"), }, steps=[PlanStep("reconcile", depends_on=["batch_retry", "batch_partial"])], ) # Model-driven prune keeps only the fluent narrative fact: rewrite_context(ctx, keep_keys={"batch_retry", "schema"}) # -> raises SelfRewriteDriftError on 'batch_partial' ```