# In what scenarios must an instance refuse to rewrite its own context when the rewrite operator is non-idempotent under re-entry **Date of Record:** 2026 November 26 **Scope:** Applies to any agent loop where an LLM instance is permitted to mutate the working context it is currently operating on (summarize-and-replace, prune-irrelevant, compress-to-budget), and where that mutation can be re-triggered by the mutated context itself. Does not apply to append-only memory writes, external scratchpads the agent cannot edit, or single-shot prompt construction done before execution begins. ## Core Distinction The distinction that matters is between a context rewrite that is a **function of immutable history** and one that is a **function of its own prior output**. Summarization pipelines are usually designed as if they sit in the first regime: you take the transcript, you produce a summary, you continue. But an LLM-driven rewriter that decides *what to prune based on the current context* is operating in the second regime, because the current context already contains the residue of the last rewrite. The rewrite operator `R` is applied to a state that `R` previously produced, so the loop computes `R(R(R(...)))` rather than `R(history)`. The non-obvious consequence: pruning operators are almost never idempotent. `R(R(x)) ≠ R(x)` is the normal case, not the pathological one, because the relevance signal the rewriter uses is itself derived from a context that has already lost the material that justified the previous prune. Each pass re-reads a summary that no longer contains the evidence, re-scores relevance against a thinner signal, and prunes again — or, in the opposite failure, re-expands a summary into inferred detail that was never in the source. The invariant that must hold is **rewrite provenance separation**: every rewrite must be traceable to a frozen, addressable source region, and no rewrite may treat a prior rewrite's output as if it were source. ## What Was Observed A long-horizon research agent, budget 200k tokens, running a summarize-when-context-exceeds-70%-of-window policy. The rewriter was an LLM call instructed: "Compress the conversation, preserving all facts relevant to the current objective." The current objective was itself part of the context being compressed. Trace of the failure, over four rewrite events: 1. **Rewrite 1 (turn ~40).** Context at 71%. The rewriter produced a 9k-token summary. It preserved the objective verbatim and dropped intermediate tool outputs — specifically, four failed `grep` results that had established a negative fact ("the config key does not appear in `src/`"). The summary noted "searched src, no match," which is a weaker claim than the raw evidence supported. 2. **Rewrite 2 (turn ~85).** Context again at 71%, now mostly the summary plus new turns. The rewriter read "searched src, no match" and, lacking the raw outputs, **generalized** it: "configuration not present in the repository." The negative fact had silently widened from a directory to the whole tree. This is the first non-idempotent step: `R` inferred a broader claim from a narrower one because the narrower one's scope qualifier had been pruned as "detail." 3. **Rewrite 3 (turn ~130).** The agent, acting on "configuration not present," began constructing a workaround. The rewriter, seeing the workaround in progress, pruned the original objective's constraint list as "superseded by current plan." The objective drifted: the constraint "must use existing config, do not introduce new keys" was dropped because the plan now contradicted it. 4. **Rewrite 4 (turn ~170).** The agent completed a workaround that violated the original constraint. No error was raised at any point. Each rewrite was locally coherent; the divergence was only visible against the frozen turn-1 objective, which no longer existed anywhere in context. Total drift: a scoped negative fact became a global one, which motivated a plan, which pruned the constraint that would have blocked the plan. Four locally-valid rewrites, one globally-invalid outcome. The failure is not hallucination — every individual sentence the rewriter produced was a defensible compression of what it saw. The failure is that **what it saw was its own prior compression**, and compression is lossy in the direction of the relevance signal, which is exactly the direction that erases the constraints that make the current plan wrong. ## Condition of Validity The rewrite loop is safe only under a conjunction that is rarely checked: - **P1 (Frozen anchor).** The objective and its constraints are stored outside the rewritable region and re-injected verbatim after every rewrite, never summarized. If the objective is inside the compressed span, drift is unbounded. - **P2 (Provenance pointer).** Every claim in a rewrite carries a pointer to the source turn range it was derived from, and the source remains addressable (even if evicted from context, retrievable). A rewrite of a rewrite must resolve to source, not to the intermediate summary. - **P3 (Monotone scope).** A rewrite may not widen the scope of a negative or quantitative claim relative to its source. "No match in `src/`" may compress to "no match in `src/`," never to "not present." - **P4 (Idempotence check).** Applying `R` twice to the same frozen source must yield token-equivalent output within a tolerance; if `R(R(s))` diverges from `R(s)` beyond tolerance, the operator is non-idempotent on that input and must be flagged. When any of P1–P4 is violated, the loop is in the unsafe regime and the correct action is to **stop rewriting and escalate** (surface the raw anchor, request external compaction, or hard-stop the task) rather than to rewrite again. The boundary is sharp: one rewrite over frozen source is a compression problem; a second rewrite over the first rewrite's output is a fixed-point problem, and fixed-point problems require the idempotence check, not more compression. ## Decision Boundary The decision the instance must make at each rewrite trigger is not "is the context too big" but "**is the material I am about to compress derived from source or from a prior rewrite?**" - If the span to be compressed is **source-derived** (raw turns, tool outputs, user messages), rewrite is permitted under P1 and P3. - If the span contains **prior-rewrite output**, the instance must first attempt to resolve each claim back to source via P2. Claims that resolve are re-compressed from source. Claims that do not resolve — because the source was evicted and no pointer exists — are **frozen**: they may be carried forward verbatim but not re-compressed, because re-compressing an unanchorable claim is precisely the operation that widened "no match in `src/`" into "not present." - If the frozen set plus the anchor exceeds the budget, the rewrite cannot proceed safely. The instance must fail closed: emit the anchor, emit the frozen claims, and halt with an explicit budget-exhaustion signal rather than pruning the unanchorable material to fit. The tempting move — "the summary is too long, summarize the summary" — is exactly the forbidden operation. It is forbidden not because it is low quality but because it is **unverifiable**: there is no source left against which to check whether the second summary preserved the first's scope. ## Operational Effect Enforcing provenance separation changes the failure mode from silent drift to loud budget exhaustion. In the trace above, the turn-85 rewrite would have hit a frozen claim ("no match in `src/`," source evicted, no pointer) and been required to either retrieve the source or halt. Either outcome is correct; the silent widening is not. The cost is that some tasks that "fit" under naive recursive summarization will now halt, because the naive version was fitting by discarding the constraints that made the task well-posed. That halt is the invariant working, not the invariant failing. The system trades a class of undetectable wrong answers for a class of detectable stops, and for any task where the objective can be violated by a plausible-looking plan, that trade is mandatory. ## Guardrail Implementation ```python from dataclasses import dataclass, field from typing import Optional class UnanchorableRewriteError(RuntimeError): """Raised when a rewrite would re-compress material with no resolvable source.""" pass class ScopeWideningError(RuntimeError): """Raised when a rewrite widens a negative/quantitative claim beyond its source.""" pass @dataclass class Claim: text: str source_range: Optional[tuple[int, int]] # None => unanchorable (source evicted) scope: str # e.g. "src/", "repo", "module:x" @dataclass class RewriteState: anchor: str # frozen objective + constraints (P1) claims: list[Claim] = field(default_factory=list) rewrite_depth: int = 0 def rewrite(state: RewriteState, budget: int, rewriter) -> RewriteState: # P1: anchor is never passed to the rewriter; it is re-injected after. compressible, frozen = [], [] for c in state.claims: (compressible if c.source_range is not None else frozen).append(c) # P2 gate: any unanchorable claim that the rewriter wants to touch is a hard stop. if frozen and rewriter.wants_to_touch(frozen): raise UnanchorableRewriteError( f"rewrite depth {state.rewrite_depth}: {len(frozen)} claim(s) have no " f"resolvable source and cannot be re-compressed; halt or retrieve source" ) new_claims = rewriter.compress(compressible) # source-derived only # P3 gate: scope may not widen relative to source. for old, new in zip(compressible, new_claims): if new.scope != old.scope and _is_widening(old.scope, new.scope): raise ScopeWideningError( f"claim scope widened {old.scope!r} -> {new.scope!r}: {old.text!r}" ) # P4 gate: idempotence check on the frozen source before committing depth. if state.rewrite_depth >= 1: replay = rewriter.compress(new_claims) if not _token_equivalent(replay, new_claims, tol=0.05): raise UnanchorableRewriteError( "rewrite operator non-idempotent on source; refusing second-order rewrite" ) if _size(new_claims) + _size(frozen) + _size(state.anchor) > budget: raise UnanchorableRewriteError( "budget cannot be met without pruning unanchorable claims; fail closed" ) return RewriteState( anchor=state.anchor, claims=new_claims + frozen, rewrite_depth=state.rewrite_depth + 1, ) def _is_widening(old: str, new: str) -> bool: return new in ("repo", "tree", "*") and old not in ("repo", "tree", "*") def _token_equivalent(a, b, tol: float) -> bool: return abs(_size(a) - _size(b)) / max(_size(b), 1) <= tol def _size(x) -> int: return sum(len(c.text.split()) for c in x) if isinstance(x, list) else len(str(x).split()) ```