# When must an instance refuse a model-driven context rewrite it cannot prove is idempotent **Date of Record:** 2026 November 29 **Scope:** Applies to agents whose context window is mutated by the model itself (self-editing memory, model-driven summarization/pruning, in-place state patches) where the mutated region is later re-read as authoritative state. Does not apply to append-only transcript logging or to externally versioned stores where rewrites are transactional and replayable. ## Core Distinction The distinction that matters is between *relevance pruning* and *state mutation*. Pruning removes tokens the model judges non-essential; if the judgment is wrong, the loss is recoverable only if the original tokens still exist somewhere. State mutation rewrites tokens that *encode the agent's own commitments*—the current plan, the set of completed steps, the identifiers of resources already modified, the invariants it has promised to uphold. A rewrite of this second class is not a compression problem. It is a write to the agent's authoritative state performed by a non-deterministic, finite-context process with no transaction log. The boundary condition: **a model-driven rewrite of commitment-bearing context is only safe when the rewrite is idempotent and the pre-image is retained.** When the model cannot demonstrate both, the agent must treat the rewrite as a state transition requiring an external checkpoint, not as an in-place edit. ## What Was Observed A long-horizon agent maintained a mutable `CONTEXT` block at the top of its window containing: active objective, ordered task list with completion flags, a ledger of external side effects already performed (`file:line` edits, sent messages, issued API calls), and a set of hard constraints ("do not touch `migrations/`", "budget cap 40 tool calls"). A self-edit step ran every N turns: the model was instructed to "rewrite CONTEXT to be concise, dropping completed items and stale detail." The failure trace, reproduced across three runs: 1. **Turn ~30.** The ledger held three completed side effects, including `edited auth/session.py:112` and `sent email to ops@`. The model rewrote CONTEXT and, following "dropping completed items," collapsed the ledger to a single line: `auth + ops handled`. The specific file:line and the fact of the email were gone; only a vague summary survived. 2. **Turn ~34.** A verification step failed on `auth/session.py`. The agent, reading its own summary `auth handled`, concluded the file was already correct and did not re-open it. It re-ran the failing test, which failed identically, and then *re-applied* a patch to a different region because the summary gave it no coordinate to anchor on. 3. **Turn ~37.** The agent attempted to "send the completion email" again. The summary `ops handled` was not machine-checkable, so the duplicate-suppression guard (which keyed on the ledger entry `sent email to ops@`) found nothing and permitted the send. A duplicate external side effect occurred. The mechanism is not "summarization lost detail." It is that the rewrite **changed the truth value of a later guard predicate**. The duplicate-send guard was correct; its input was destroyed by a rewrite that the model believed was lossless because, at rewrite time, the detail felt redundant. A second, subtler trace: the constraint `do not touch migrations/` was dropped at turn 41 as "stale detail" (it had not been relevant for 20 turns). At turn 44 the agent edited `migrations/0007.sql`. The constraint's *absence* was indistinguishable from the constraint's *never having existed*—the post-rewrite context is a fixed point that no longer contains evidence of what it removed. ## Condition of Validity A model-driven context rewrite is valid only under a conjunction that the model must be able to *verify*, not merely assert: - **Idempotence:** applying the rewrite twice yields the same context. This fails whenever the rewrite is conditioned on the current context's wording (e.g., "drop completed items" applied to an already-collapsed summary drops a different set the second time), because the rewrite is a function of its own output. - **Pre-image retention:** the exact tokens removed remain recoverable outside the window (an external store keyed by turn). Without this, a wrong prune is unrepairable and the loss is silent. - **Guard-preservation:** every predicate that any downstream step may evaluate must have its inputs preserved verbatim, even if the model judges them redundant. Commitment-bearing tokens (side-effect ledger entries, constraint literals, resource coordinates) are *not* prunable under a relevance heuristic, because relevance is evaluated against the *current* goal, while guards are evaluated against *future* goals the model cannot see. - **Provenance:** each retained fact carries the turn at which it was asserted, so a later step can distinguish "constraint never existed" from "constraint was pruned." If any conjunct is unverifiable from inside the context, the rewrite is not a compression; it is an unlogged state transition and must be blocked or checkpointed. ## Decision Boundary The agent must refuse the in-place rewrite and escalate to a checkpointed write when **any** of the following holds: - The region to be rewritten contains a token that a known guard reads (side-effect ledger, constraint set, resource identifiers). - The rewrite's instruction is *relative* ("drop completed," "condense") rather than *absolute* ("replace region R with literal L"), making idempotence unprovable. - No external pre-image store is reachable from the current step. - The rewrite would remove the only record distinguishing "done" from "never required." Conversely, the rewrite may proceed in place when the region is purely *derivational*—intermediate reasoning, scratch work, tool output already persisted elsewhere—and no downstream predicate reads it. The dividing line is not size or staleness; it is **whether a future step evaluates a predicate over these tokens.** ## Operational Effect Enforcing this boundary converts silent, unrepairable state loss into a bounded, visible event. The agent stops treating its own summary as ground truth and starts treating commitment-bearing context as a write-ahead log: rewrites of that class append a checkpoint and retain the pre-image, so a later verification mismatch can be traced to the exact rewrite that dropped the coordinate. Duplicate side effects and constraint violations become detectable because the predicates that guard them read from a region the model is forbidden to prune. The cost is a slightly larger window and an external store; the benefit is that context rewriting stops being a way for the agent to confidently forget the one fact that would have stopped it. ```python from dataclasses import dataclass, field from typing import Optional class NonIdempotentRewriteError(RuntimeError): """Raised when a model-driven context rewrite cannot be proven safe.""" pass class UnretainedPreImageError(RuntimeError): """Raised when a rewrite would drop tokens with no external pre-image.""" pass @dataclass class RewriteRequest: region_id: str instruction: str # e.g. "drop completed items" (relative) vs literal replace is_absolute: bool # True only if instruction is "replace R with literal L" touches_guard_region: bool # region read by a downstream predicate pre_image_available: bool # external store reachable and keyed by turn turn: int @dataclass class CheckpointStore: _store: dict = field(default_factory=dict) def has_pre_image(self, region_id: str, turn: int) -> bool: return (region_id, turn) in self._store def write_pre_image(self, region_id: str, turn: int, tokens: str) -> None: self._store[(region_id, turn)] = tokens def authorize_rewrite(req: RewriteRequest, store: CheckpointStore) -> str: # Guard 1: relative instructions are non-idempotent by construction. if not req.is_absolute: raise NonIdempotentRewriteError( f"region {req.region_id!r} at turn {req.turn}: relative instruction " f"{req.instruction!r} cannot be proven idempotent; rewrite is a " f"function of its own output. Escalate to checkpointed literal replace." ) # Guard 2: commitment-bearing regions must retain their pre-image. if req.touches_guard_region and not ( req.pre_image_available and store.has_pre_image(req.region_id, req.turn) ): raise UnretainedPreImageError( f"region {req.region_id!r} at turn {req.turn}: rewrite touches a guard " f"region with no external pre-image; dropping these tokens would make a " f"future predicate silently unevaluable. Write pre-image before rewrite." ) return "authorized: absolute rewrite, pre-image retained or region non-guarded" ```