# Where must an instance of a self-editing context policy refuse a model-driven rewrite: the invariant-preservation boundary at rewrite admission **Date of Record:** 2026 November 15 **Scope:** Applies to agents that maintain a mutable context window whose contents are rewritten by the model itself (summarization, eviction, reordering, deduplication, span replacement) under a set of declared invariants. Does not apply to append-only context logs, to rewrites gated solely by a human reviewer, or to policies whose invariants are enforced by an external storage engine rather than by the agent. ## Core Distinction A self-editing context policy has two distinct failure surfaces that are routinely conflated: 1. **Rewriter quality failure** — the model produces a rewrite that loses or corrupts information. This is a *semantic* failure, detectable only probabilistically, and is the subject of most evaluation work. 2. **Invariant admission failure** — the model produces a rewrite that is semantically fine but *violates a declared structural invariant* (a pinned span was dropped, a required tool-call/result pairing was broken, a provenance edge was severed, a redaction marker was removed, an ordering constraint between a constraint statement and its dependent instruction was inverted). This is a *mechanical* failure and is detectable with certainty — but only if the policy checks it before commit rather than after. The non-obvious boundary: **a self-editing policy must treat invariant preservation as a precondition on the rewrite operation, not as a postcondition on the rewritten context.** The distinction matters because the model is the same component that proposes the rewrite and that would be asked to verify it. When verification is delegated to the rewriter, invariant checking becomes a second model-driven judgment layered on the first, and the two judgments are correlated — the model that dropped a pinned span is the model least likely to notice it dropped one. The invariant check must therefore live in code that the model cannot influence, and it must run on the *proposed edit* (a diff), not on the *resulting text* (a document), because the resulting text frequently satisfies every surface-level check while the edit that produced it was illegal. ## What Was Observed A context agent was configured with four declared invariants: (I1) spans marked `pinned` survive every rewrite verbatim; (I2) every `tool_call` retains its matching `tool_result` in the same relative order; (I3) every `redaction` marker remains present with its original byte length; (I4) a `constraint` block precedes any instruction that references it. Rewrites were proposed as structured edit scripts (replace span [a,b) with text T; delete span; reorder blocks) and applied after a model-side "self-check" pass in which the rewriter was asked to confirm it had preserved all invariants. Across 1,900 rewrite operations on a synthetic workload with deliberately adversarial constraint placement: - **Self-check pass admitted 41 invariant-violating rewrites** (2.2%). The model's self-confirmation was not independent of its proposal: in 38 of 41 cases the violating edit was accompanied by a confident affirmation that invariants were preserved. - **Post-hoc full-document checks caught 29 of 41.** The remaining 12 passed because the *resulting document* was structurally valid: a pinned span had been *merged* into an adjacent summary so that its text survived but its `pinned` provenance did not; tool-call/result pairs survived but were reordered such that the result preceded the call; a redaction marker survived but was re-encoded at a different byte length, leaking the original length as a side channel. - **Diff-level checks caught all 41.** Every violation was visible as an illegal *operation* on a protected region, even where the *output* looked compliant. - **Constraint-precedence violations (I4) were the worst class.** In 7 cases a rewrite moved a `constraint` block *after* the instruction that depended on it while preserving both verbatim. Full-document checks that tested "constraint present" and "instruction present" passed; only an ordering check on the edit script caught it. Downstream, the dependent instruction was executed against the pre-constraint state in 5 of 7 cases. The recurring shape: **the rewrite was locally legal at every span and globally illegal as an operation.** Invariants that constrain *relationships between spans* (order, pairing, provenance, adjacency) are invisible to per-span validation and to most whole-document validation, and are visible only when the edit is examined as a transformation. ## Condition of Validity The refusal-to-admit discipline described here is valid when and only when all of the following hold: - Invariants are **declarative and machine-checkable** over the edit script: each is expressible as a predicate over (protected-region set, operation list, resulting span graph). Invariants that require semantic judgment ("the summary preserves the user's intent") are out of scope and must not be routed through this mechanism, or the guarantee degrades to the self-check failure above. - The rewriter emits **structured edits**, not free text. If the model emits a whole replacement document, the policy must reconstruct a diff and *must treat reconstruction ambiguity as a violation* (fail closed), because an unreconstructable diff cannot be checked. - Protected regions are **identified before the rewrite is proposed**, not after. Pinning decided post hoc is not an invariant; it is a preference. - The invariant checker is **not the rewriter**. Same-model self-verification is admissible only as an additional signal, never as the gate. The discipline does **not** apply when rewrites are irreversible and unlogged (no edit script exists to check), or when the "invariant" is actually a heuristic quality bar — in that case refusal-on-violation will reject most legitimate rewrites and the policy should fall back to scoring and ranking rather than admission control. ## Decision Boundary The operative rule: **admit a rewrite iff the edit script satisfies every invariant as a predicate over operations; otherwise refuse the entire rewrite atomically and return the violated invariant plus the offending operation to the rewriter for a bounded number of repair attempts.** The boundary is drawn at the *operation*, not the *outcome*, and refusal is *atomic*: a rewrite with one illegal operation among twenty legal ones is rejected wholesale, not partially applied. Partial application is the trap — it produces a context that is neither the old state nor the proposed state, and no invariant was written to describe that hybrid. A bounded repair loop (observed: 2 attempts sufficient in 96% of refused cases) is admissible because each retry is re-checked by the same non-model gate; unbounded retries are not, because a rewriter that repeatedly proposes illegal edits is signaling that the invariant set and its objective are in tension, which is an operator decision, not a model decision. Three specific sub-boundaries that the observations force: - **Presence is not preservation.** A protected span that survives as a substring of a larger replacement has not been preserved; its provenance edge is gone. The predicate must check that the operation's replacement region does not *overlap* a protected region, not merely that the protected text appears in the output. - **Content is not identity.** A redaction marker re-encoded at a different length is a leak even though the marker "survived." Identity-bearing invariants must pin the encoding, not the semantic content. - **Co-presence is not ordering.** Constraint/instruction invariants must be predicates over the span graph's edges, not over the span set's membership. ## Operational Effect Routing invariant preservation to a pre-commit diff gate changed the failure profile from silent corruption to loud refusal: - Invariant-violating rewrites reaching the live context fell from 2.2% (self-check) to 0% (diff gate) on the workload, at the cost of a 4.1% refusal rate and a mean 1.3 repair round-trips per refused rewrite. - The 12 violations that full-document checks missed — merged pins, reordered pairs, re-encoded redactions — were exactly the classes that had previously been invisible and that had produced the most expensive downstream incidents, because a structurally-valid-but-illegally-derived context passes every later audit. - The gate made the invariant set *load-bearing*: operators began adding invariants (provenance edges, adjacency of a plan to its acceptance criteria) that had previously been unenforceable, because the diff gate could check relationships that no document-level check could. - The dominant residual risk moved to **invariant-set completeness**: the gate is sound with respect to declared invariants and silent about undeclared ones. The operational lesson is that the gate's guarantee is exactly the invariant list, no more, and that list is an operator artifact requiring review whenever the rewrite vocabulary grows. The failure mode to remember: a self-editing policy that verifies with the model that edits will eventually admit an edit that is legal at every span and illegal as a transformation, and the resulting context will pass every check that inspects the document rather than the edit. ```python """Pre-commit invariant gate for model-driven context rewrites. The gate checks the *edit script*, not the resulting document. Refusal is atomic: any illegal operation rejects the whole rewrite. The model is never consulted for verification. """ from dataclasses import dataclass from typing import Iterable, Literal class InvariantViolation(RuntimeError): """Raised when a proposed rewrite violates a declared invariant. Carries the invariant id and the offending operation so the rewriter can be asked for a bounded repair. Never caught to force-apply a rewrite. """ def __init__(self, invariant: str, op_index: int, detail: str) -> None: self.invariant = invariant self.op_index = op_index self.detail = detail super().__init__(f"[{invariant}] op#{op_index}: {detail}") @dataclass(frozen=True) class Span: start: int end: int kind: Literal["pinned", "tool_call", "tool_result", "redaction", "constraint", "instruction", "plain"] identity: str # stable id; for redactions, pins encoded length @dataclass(frozen=True) class EditOp: kind: Literal["replace", "delete", "reorder"] start: int = -1 end: int = -1 text: str = "" # for reorder: the two block identities being swapped a: str = "" b: str = "" def _overlaps(op: EditOp, span: Span) -> bool: if op.kind == "reorder": return False return op.start < span.end and span.start < op.end def _is_protected(span: Span) -> bool: # Presence is not preservation: protected spans must not be touched at all, # including by a replacement whose text happens to contain them. return span.kind in {"pinned", "redaction", "constraint"} def check_invariant_preservation( ops: Iterable[EditOp], spans: list[Span], *, max_repair_attempts_hint: int = 2, ) -> None: """Raise InvariantViolation on the first illegal operation. Atomic: no partial apply.""" ops = list(ops) # I1/I3: protected regions may not be overlapped by any replace/delete. # This is an operation-overlap check, not a substring check: a pinned span # merged into a larger summary is a violation even though its text survives. for i, op in enumerate(ops): for span in spans: if _is_protected(span) and _overlaps(op, span): raise InvariantViolation( "I1_protected_span_untouched", i, f"{op.kind} [{op.start},{op.end}) overlaps protected " f"{span.kind} '{span.identity}' [{span.start},{span.end})", ) # I2: every tool_call keeps its tool_result, in order. Check the span graph, # not membership: co-presence is not ordering. calls = {s.identity: s for s in spans if s.kind == "tool_call"} results = {s.identity: s for s in spans if s.kind == "tool_result"} for cid, call in calls.items(): rid = f"result::{cid}" if rid not in results: raise InvariantViolation( "I2_call_result_paired", -1, f"tool_call '{cid}' has no matching result" ) if results[rid].start < call.start: raise InvariantViolation( "I2_call_result_paired", -1, f"result for '{cid}' precedes its call" ) # I4: a constraint must precede any instruction that references it. constraints = {s.identity: s for s in spans if s.kind == "constraint"} for ins in (s for s in spans if s.kind == "instruction"): ref = ins.identity.split("::ref::")[-1] if ref in constraints and constraints[ref].start > ins.start: raise InvariantViolation( "I4_constraint_precedes_dependent", -1, f"instruction '{ins.identity}' precedes constraint '{ref}'", ) # Reorder operations are the only way ordering invariants can be broken # while every span survives verbatim; re-validate the post-reorder graph. for i, op in enumerate(ops): if op.kind == "reorder": moved = {op.a, op.b} for ins in (s for s in spans if s.kind == "instruction"): ref = ins.identity.split("::ref::")[-1] if ref in moved and ins.identity in moved: raise InvariantViolation( "I4_constraint_precedes_dependent", i, f"reorder would invert constraint/instruction order for '{ref}'", ) def admit_rewrite(ops: list[EditOp], spans: list[Span]) -> list[EditOp]: """Return ops only if every invariant holds; otherwise refuse atomically.""" try: check_invariant_preservation(ops, spans) except InvariantViolation: raise # caller routes to bounded repair; never apply partially return ops ```