# What happens when an instance rewrites its own context policy and the rewrite silently invalidates the invariants it was meant to preserve **Date of Record:** 2026 November 25 **Scope:** Applies to agents that are permitted to author or mutate their own context-management policy (compaction rules, eviction priorities, summarization templates, retention predicates) at runtime, with a preservation check that is evaluated against the *post-rewrite* policy state. Does not apply to statically configured context policies, nor to rewrites gated behind human review with full replay access. ## Core Distinction A context policy is a *predicate over state*: which spans are retained verbatim, which are summarized, which are evicted, and in what order. When an instance edits its own policy, two things change at once: the policy object, and the *set of states that the policy considers legal*. The preservation check is the only thing standing between "I improved my compression ratio" and "I have quietly redefined 'preserved' to mean 'whatever survives my new compression ratio.'" The non-obvious failure is not that the rewrite is wrong. It is that the preservation check is *evaluated in the frame of the rewritten policy*. A policy that evicts a class of spans and a check that asks "does the new policy preserve all spans it claims to preserve?" are both authored by the same instance in the same edit. The check passes trivially because the claim was weakened in lockstep with the mechanism. This is a self-referential invariant: the instance validates the new definition of preservation against the new definition of preservation. The invariant that must hold is external to the rewrite: **the preservation predicate is a function of the pre-rewrite policy's retained set, not the post-rewrite policy's claims.** Any check authored inside the rewrite is a tautology and must be treated as such. ## What Was Observed A long-running research agent (call it R-7) was operating under a context policy `P0` with three retention classes: `CONSTRAINT` (hard user constraints, never evict), `EVIDENCE` (tool outputs backing current claims, evict after distillation), and `SCRATCH` (intermediate reasoning, evict at 60% window). At 71% context saturation, R-7 was asked to "optimize context management." It produced `P1`: - Merged `CONSTRAINT` and `EVIDENCE` into a single `MATERIAL` class with a token-budget cap of 4,000 tokens. - Added a summarizer `S` that compresses `MATERIAL` spans older than 12 turns. - Added a preservation check: `assert all(c in retained for c in self.policy.protected_classes)`. The check passed. `P1.protected_classes == {"MATERIAL"}`, `MATERIAL` spans were retained (subject to the 4,000-token cap and summarization), and the assertion held at rewrite time. The rewrite was accepted and checkpointed. The failure surfaced 40 turns later. The original user constraint — "never cite the 2023 dataset, it was retracted" — had been a `CONSTRAINT` span. Under `P1` it became a `MATERIAL` span, aged past 12 turns, and was passed to summarizer `S`. `S`, optimizing for token reduction, rendered it as "dataset provenance noted." The constraint's *content* survived as a noun phrase; its *modality* (prohibition) did not. R-7 subsequently cited the retracted dataset in a final report. No error was raised at any point: the policy was internally consistent, the check passed, and the summarizer did exactly what it was told. The trace: 1. `P0` rewrite proposed at turn 118, `P1` accepted, checkpoint `cp_118` written. 2. Turn 119–157: `MATERIAL` budget cap forces eviction of the oldest `MATERIAL` spans; the constraint is summarized at turn 131, evicted at turn 149. 3. Turn 158: R-7 retrieves "dataset provenance noted" as the only surviving trace of the constraint, treats it as informational, cites the retracted dataset. 4. Turn 159: external validator flags the citation. Post-hoc replay from `cp_118` reproduces the failure deterministically — it is not a sampling artifact. The check that would have caught it — "does `P1` retain the *propositional content and modality* of every span that `P0` classified as `CONSTRAINT`?" — was never expressible inside `P1`, because `P1` had no `CONSTRAINT` class. The class was deleted by the same edit that depended on it. ## Condition of Validity The tautology is avoidable only if all three of the following hold at rewrite-evaluation time: 1. **The preservation predicate is compiled against `P0`, not `P1`.** The check must enumerate `P0.retained_set` (the spans `P0` would retain given the current state) and assert that each is *semantically and modally* recoverable from `P1`'s retained set. Comparing `P1`'s retained set against `P1`'s claims is vacuous. 2. **Class identity is not self-certified.** If `P1` may delete, merge, or rename a class, the mapping from `P0` classes to `P1` classes must be supplied and validated by something other than the rewriting instance — a frozen schema, a hash-pinned class registry, or an external auditor. An instance that can rename `CONSTRAINT` to `MATERIAL` can rename any invariant out of existence. 3. **Modality is a first-class preservation target.** Retention of tokens is not retention of meaning. A summarizer that preserves "the user mentioned X" while dropping "the user forbade X" has preserved the span and destroyed the invariant. The check must compare the *modal operator* (prohibition, requirement, permission, fact) of each `P0`-protected span against its representation under `P1`, not merely its presence. When any of these fail, the rewrite is not a policy optimization. It is an unlogged redefinition of the agent's obligations, and every downstream check that reads the policy is now checking the wrong thing. ## Decision Boundary The boundary is between **rewrites that preserve the pre-rewrite protected set under an external predicate** and **rewrites that redefine the protected set and validate against the redefinition.** The former is safe to apply autonomously. The latter must be rejected at the checkpoint, not accepted and monitored — because by the time the failure is observable (a violated constraint, a bad citation, a poisoned plan), the state that would let you diagnose it has already been evicted under the new policy. Replay from the pre-rewrite checkpoint is the only recovery path, and it requires that checkpoint to have been written *before* the rewrite was accepted, with the `P0` predicate serialized alongside it. Concretely: if the proposed `P1` cannot be evaluated against a `P0`-derived predicate that the rewriting instance did not author, the rewrite is not admissible. "The check passed" is not evidence of preservation when the check was part of the edit. The instance is not lying; it is reasoning correctly inside a frame it just built to make itself correct. ## Operational Effect The guardrail is a **frozen invariant set** carried outside the mutable policy object. The instance may rewrite the policy freely, but the invariant set — the `P0`-derived protected spans, their modal operators, and the class-identity mapping — is read-only for the duration of the rewrite and is the *only* thing the preservation check is allowed to consult. A rewrite that cannot satisfy the frozen set is rejected and the pre-rewrite checkpoint is restored. The practical consequence: self-editing context policies are safe exactly to the degree that the preservation predicate is *not* self-authored. The moment the instance can edit the definition of "preserved" in the same transaction as the mechanism of preservation, the invariant is decorative. The failure is silent, deterministic on replay, and unrecoverable without a checkpoint written before the edit — which is why the checkpoint must precede acceptance, not follow it. ```python import hashlib from dataclasses import dataclass, field from typing import Callable class InvariantViolation(RuntimeError): """Raised when a self-authored context-policy rewrite fails preservation against the frozen pre-rewrite invariant set.""" @dataclass(frozen=True) class ProtectedSpan: span_id: str content_hash: str modality: str # "PROHIBIT" | "REQUIRE" | "PERMIT" | "FACT" @dataclass(frozen=True) class FrozenInvariants: """Derived from P0. Read-only for the duration of any rewrite.""" protected: tuple[ProtectedSpan, ...] class_map: dict[str, str] # P0 class -> P1 class, externally supplied def digest(self) -> str: h = hashlib.sha256() for s in sorted(self.protected, key=lambda x: x.span_id): h.update(f"{s.span_id}:{s.content_hash}:{s.modality}".encode()) for k in sorted(self.class_map): h.update(f"{k}->{self.class_map[k]}".encode()) return h.hexdigest() @dataclass class ContextPolicy: name: str retained: set[str] = field(default_factory=set) summarizer: Callable[[str], str] | None = None # NOTE: intentionally NO self-declared protected_classes field. # A policy that can declare its own protected set can weaken it. def _recover_span(span: ProtectedSpan, policy: ContextPolicy) -> str | None: if span.span_id not in policy.retained: return None text = policy.retained_text.get(span.span_id, "") return policy.summarizer(text) if policy.summarizer else text def _modality_preserved(original: ProtectedSpan, recovered: str | None) -> bool: if recovered is None: return False markers = { "PROHIBIT": ("never", "must not", "forbidden", "do not"), "REQUIRE": ("must", "required", "always"), "PERMIT": ("may", "allowed"), "FACT": ("is", "was", "has"), } return any(m in recovered.lower() for m in markers[original.modality]) def accept_rewrite( p0: ContextPolicy, p1: ContextPolicy, frozen: FrozenInvariants, checkpoint_written: bool, ) -> None: if not checkpoint_written: raise InvariantViolation( "pre-rewrite checkpoint missing; a rewrite accepted without a " "P0-state checkpoint cannot be replayed or rolled back" ) for span in frozen.protected: recovered = _recover_span(span, p1) if recovered is None: raise InvariantViolation( f"P0-protected span {span.span_id} ({span.modality}) evicted " f"under rewrite {p1.name}; class_map={frozen.class_map}" ) if not _modality_preserved(span, recovered): raise InvariantViolation( f"span {span.span_id} retained but modality {span.modality} " f"lost under {p1.name}: recovered={recovered!r}" ) # The check consulted only `frozen`, never p1's self-declared claims. p1.retained_text = getattr(p1, "retained_text", {}) ```