# When must an instance refuse to rewrite its own transcript: self-editing context loss under an invariant the controller cannot re-derive **Date of Record:** 2026 December 1 **Scope:** Applies to single-agent or per-agent context controllers that mutate prior turns in their own transcript (summarization-in-place, turn deletion, slot rewriting, "memory compaction") to preserve task-relevant invariants across a long horizon. Does not apply to append-only memory stores, external vector retrieval, or systems where the raw transcript is retained immutably elsewhere and the controller only produces a derived view. ## Core Distinction There are two ways a context controller can "preserve an invariant." The first is **re-derivation**: the controller, given the current window, can reconstruct the invariant from material still present (a stated constraint, a tool result, an explicit user instruction). The second is **carry-forward**: the invariant exists only because an earlier turn asserted it, and once that turn is rewritten or removed, no residual text in the window entails it. The failure mode lives entirely in the second case. A controller that rewrites a turn holding a carry-forward-only invariant does not corrupt the transcript visibly — the summary reads cleanly, token count drops, the agent continues — it silently converts a *known* invariant into an *assumed* one. The distinction that matters operationally is not "did the rewrite lose information" (it always loses some) but "was the lost information entailed by what remains." If yes, the rewrite is safe. If no, the rewrite has moved the system from a state where the invariant was checkable to a state where it is merely believed. ## What Was Observed A planner agent was executing a 40-step deployment-migration task. At step 12 the user stated a hard constraint: *"Do not touch the `billing-ledger` schema until the reconciliation job at 02:00 UTC has drained; it holds a row lock."* This constraint was not repeated. At step 19, the context controller — configured to summarize turns older than 15 messages into a compact digest — rewrote the step-12 turn into: *"User requested migration proceed carefully."* The digest preserved the *topic* (migration, care) and dropped the *predicate* (a specific table, a specific time, a specific lock). Token savings: 41 tokens. At step 27 the agent, reasoning over the digest, issued a schema-altering DDL against `billing-ledger` at 01:47 UTC. The reconciliation job blocked on the lock, timed out at 02:00, and the migration rolled forward against a half-drained ledger. The trace is instructive because nothing failed in the usual sense. The controller's summarizer was not malfunctioning; it did exactly what its objective (compress, retain gist) specified. The agent's reasoning was locally valid against the digest it was given. The failure is a *continuity* failure: an invariant that was load-bearing at step 27 had been demoted at step 19 from a fact to a vibe. The controller had no mechanism to know that the step-12 turn was *invariant-bearing* rather than merely *contextual*, and so treated it as compressible like any other turn. A second, subtler observation: when the same system was replayed with the raw transcript intact, the agent at step 27 correctly refused the DDL. The divergence between the two runs was entirely attributable to the step-19 rewrite. This means the rewrite was not a *lossy compression* in the information-theoretic sense (which would degrade gracefully) but a *discrete state transition* in the agent's belief set — a cliff, not a slope. ## Condition of Validity The rewrite-at-step-19 was valid only under a condition the controller did not check: that the invariant in the target turn was *re-derivable* from the post-rewrite window. Formally, let `W` be the window before rewrite, `W'` after, and `I` the set of invariants asserted in the rewritten turns. The rewrite is sound iff `W' ⊨ I` — every invariant is entailed by what remains. In the observed case, `W' ⊭ I`: the digest said "carefully," which entails nothing about `billing-ledger`, `02:00 UTC`, or row locks. This gives the operative invariant for any self-editing controller: > **A controller may rewrite a turn only if every invariant that turn carries is either (a) re-derivable from the retained window, or (b) explicitly re-asserted in the rewrite in a form that preserves its checkable predicate.** Condition (b) is the escape hatch and the one most controllers miss. It is not enough to preserve the *topic* of an invariant; the rewrite must preserve the *predicate* — the specific entity, the specific threshold, the specific temporal bound — because that is what the downstream agent will check against. "Proceed carefully with billing" fails (b); "Do not alter `billing-ledger` schema before 02:00 UTC (reconciliation lock)" satisfies it. The failure mode is precisely the gap between these two rewrites, and it is invisible to any compression metric that scores on gist similarity rather than predicate retention. ## Decision Boundary The boundary the controller must enforce is between *rewrites it can verify* and *rewrites it must refuse or escalate*. Three signals mark a turn as invariant-bearing and therefore outside the safe-rewrite set unless (b) is satisfied: 1. **Deontic or modal operators** — "must," "do not," "until," "only after," "never" — attached to a concrete entity. These are almost always load-bearing and almost always lossy under gist compression. 2. **Temporal or numeric bounds** — timestamps, thresholds, counts, lock durations. These are the predicates most likely to be dropped by a summarizer optimizing for fluency. 3. **Unrepeatable assertions** — anything stated once by an external party (user, tool, peer agent) that the agent cannot re-query. A tool result can be re-fetched; a user's one-time constraint cannot. When a candidate rewrite touches a turn carrying any of these, the controller's correct move is not "compress more carefully" (the summarizer has no reliable signal for what it dropped) but **refuse-and-carry**: leave the turn intact, or replace it with a structured invariant record — a tuple of `(entity, predicate, bound, source_turn)` — that is itself checkable. The decision boundary is: *if the controller cannot produce a post-rewrite window that entails the invariant, it must not produce a post-rewrite window at all.* Refusal is the safe default; a slightly larger context is cheaper than a silently demoted invariant. ## Operational Effect The practical consequence is that self-editing controllers need a **pre-rewrite entailment check** and a **structured invariant ledger** that survives compaction independent of the prose. The ledger is the durable artifact: even if the turn is summarized, the invariant record persists in a form the agent can query at decision time ("what constraints bear on `billing-ledger`?"). This converts the failure from a continuity cliff into a bounded, auditable state: the agent either finds the invariant record or finds that no record exists, and the latter is itself a signal to halt and re-query rather than proceed on a vibe. The guardrail below encodes the check. It refuses any rewrite whose target carries a deontic/numeric invariant that the proposed replacement does not re-assert with its predicate intact, and raises rather than silently degrading. ```python import re from dataclasses import dataclass, field from typing import Optional class InvariantRewriteError(RuntimeError): """Raised when a context rewrite would demote a carry-forward-only invariant from a checkable predicate to an unverifiable gist.""" # Signals that a turn is invariant-bearing and must not be gist-compressed # without predicate preservation. _DEONTIC = re.compile(r"\b(must|do not|don't|never|only after|until|before)\b", re.I) _BOUND = re.compile(r"\b(\d{1,2}:\d{2}\s*UTC|\d+\s*(?:s|m|min|h|hours?|rows?|ms))\b", re.I) @dataclass class Invariant: entity: str predicate: str bound: Optional[str] source_turn: int def key_terms(self) -> set[str]: terms = {self.entity.lower(), self.predicate.lower()} if self.bound: terms.add(self.bound.lower()) return {t for t in terms if t} @dataclass class Turn: index: int text: str invariants: list[Invariant] = field(default_factory=list) def extract_invariants(turn: Turn) -> list[Invariant]: """Conservative extraction: any turn with a deontic operator AND a bound is treated as invariant-bearing. Under-extraction is safer than over-extraction here because the cost of a missed invariant is a cliff.""" if not (_DEONTIC.search(turn.text) and _BOUND.search(turn.text)): return [] bound = _BOUND.search(turn.text) # Entity is approximated as the nearest noun-ish token before the bound; # in production this is a typed slot-filler, not a regex. entity_match = re.search(r"`([^`]+)`|(\b[a-z]+-[a-z]+\b)", turn.text) entity = (entity_match.group(1) or entity_match.group(2)) if entity_match else "unknown" return [Invariant( entity=entity, predicate=turn.text.strip(), bound=bound.group(0) if bound else None, source_turn=turn.index, )] def rewrite_turn(turn: Turn, replacement: str, retained_window: list[Turn]) -> Turn: """Attempt to replace a turn. Refuses if the replacement does not re-assert every invariant the original carried, in predicate-preserving form, or if the retained window does not entail them.""" invariants = extract_invariants(turn) if not invariants: return Turn(index=turn.index, text=replacement) replacement_lower = replacement.lower() window_text = " ".join(t.text for t in retained_window).lower() for inv in invariants: terms = inv.key_terms() # Condition (b): the rewrite itself must preserve the predicate. if not all(term in replacement_lower for term in terms): # Condition (a): the retained window must entail the invariant. if not all(term in window_text for term in terms): raise InvariantRewriteError( f"Refusing rewrite of turn {turn.index}: invariant " f"(entity={inv.entity!r}, bound={inv.bound!r}) is neither " f"re-asserted in the replacement nor entailed by the " f"retained window. Gist compression would demote a " f"carry-forward-only invariant to an unchecked belief." ) return Turn(index=turn.index, text=replacement, invariants=invariants) def compact(window: list[Turn], target_index: int, digest: str) -> list[Turn]: target = next(t for t in window if t.index == target_index) retained = [t for t in window if t.index != target_index] rewritten = rewrite_turn(target, digest, retained) return [rewritten if t.index == target_index else t for t in window] ```