In what scenarios must an instance refuse a self-editing context rewrite because the rewrite operator violates a preserved invariant

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that mutate their own working context (compaction, summarization-in-place, slot eviction, tool-result elision) through declared rewrite operators carrying invariant annotations. Does not apply to append-only context growth or to external orchestrators rewriting another instance's context, where the writer is not the reader.

Core Distinction

A self-editing context policy is not a memory-management heuristic. It is a rewrite system over a context graph whose edges carry *obligations*: a tool call record that some later reasoning step will cite, a pinned constraint that bounds all subsequent action selection, a provenance link from a distilled fact to its source span. An invariant-preserving rewrite operator is one that is *declared* to leave a named set of obligations satisfiable after application. The non-obvious boundary is this: **an operator can be locally correct — it deletes only what it claims to delete, and it preserves every invariant it names — while still being globally inadmissible, because the invariant it names is not the invariant the surviving context actually depends on.** The failure is not a bug in the operator. It is a mismatch between the operator's declared preservation set and the *reachable* dependency set of the context at the moment of application. Local correctness is decidable at rewrite time; global admissibility is not, because reachable dependencies are a function of future reasoning that has not happened yet.

The distinction that matters operationally: a rewrite is unsafe not when it loses information, but when it loses the *warrant* for information it keeps. A summary that replaces five tool outputs with one distilled sentence preserves the sentence but severs the citation edge from that sentence to the raw outputs. Downstream, an auditor agent replaying the trace cannot verify the sentence, and a self-consistency check that would have caught an error is now unanswerable. The context is smaller and still internally coherent — and that is exactly the trap.

What Was Observed

A long-horizon instance (task: reconcile 40 vendor invoices against a purchase-order ledger over ~90 tool calls) ran a compaction operator `summarize_range` at context saturation (~78% of window). The operator's declared invariant set was `{no_orphan_tool_calls, preserve_pinned_constraints}`. It satisfied both: no tool call record was left without its result, and the pinned instruction "never mark an invoice reconciled without a matching PO line" survived verbatim.

At step 61, a later `summarize_range` fired over the range containing the step-14 tool output that had established *which* PO line matched invoice #27. The distilled replacement read: "Invoice 27 matched to PO." The raw output had contained the match *and* a `confidence: 0.61` field and a note that two PO lines were within tolerance. The operator preserved the propositional content and dropped the disambiguation metadata, because its preservation set had no invariant naming "quantitative uncertainty attached to a match decision."

At step 74 the agent marked invoice #27 reconciled. The pinned constraint was satisfied — a PO line did exist. But the match had been a near-tie, and the dropped metadata was the only signal that would have triggered the required human-review branch. The instance did not violate any invariant it was tracking. It violated an invariant — *reconciliation decisions above ambiguity threshold require review* — that was never encoded as a context obligation, only as a downstream policy expecting the metadata to still be there.

The trace shows the exact seam: at rewrite time, the operator's preservation check passed; at decision time, a policy precondition was unsatisfiable because its input had been silently generalized away two rewrites earlier. Nothing errored. The failure is a *silent precondition dissolution* across a rewrite boundary.

Condition of Validity

The invariant-preservation contract for a self-editing operator is valid only under a condition that is almost never checked: **the operator's declared preservation set must dominate the union of preconditions of every policy reachable from the surviving context.** Formally, for rewrite `R` mapping context `C → C'`, with `Inv(R)` the declared preserved set and `Pre(π)` the precondition set of each policy `π` reachable from `C'`:

`Inv(R) ⊇ ⋃_{π reachable from C'} Pre(π)`

When this holds, the rewrite is admissible. When it fails, the rewrite is *locally valid and globally unsound* — and no local check inside `R` can detect it, because `R` does not know which policies will become reachable. Reachability is created by the rewrite itself: compaction changes which reasoning paths are cheap, which pulls previously distant policies into the active frontier.

Three concrete conditions under which this domination check fails and the instance must refuse:

  1. **Metadata-bearing facts generalized to propositions.** Any operator whose output type is "sentence" applied to input whose type is "record with fields" drops fields not named in the preservation set. If any reachable policy reads a field, refuse.
  2. **Citation severance.** Any operator that replaces a set of spans with a distillation, where a reachable verification or audit policy requires span-level provenance. The distilled claim survives; its warrant does not.
  3. **Threshold-bearing values collapsed.** Any operator that summarizes a numeric or confidence-bearing decision into a categorical one, where a downstream policy branches on the threshold. This is the invoice-#27 case exactly.

Conversely, the contract is *not* required to hold — and refusal would be over-conservative — when the reachable policy set is closed and provably metadata-free (e.g., a pure formatting pass with no branch on dropped fields), or when the operator is applied to a context region that no reachable policy can cite (dead-branch elision after a committed branch decision).

Decision Boundary

The operational rule an instance must apply at rewrite time:

The boundary is sharp: the instance may never trade warrant for space. It may trade *locality* for space (externalize, keep stubs) but not *provability*.

Operational Effect

When the domination check is enforced, the observable effect is that compaction stops being a lossy convenience and becomes a *warranted* transformation: every surviving claim retains a dereferenceable path to its source, and every reachable policy's precondition remains satisfiable or the rewrite is refused. The system's failure mode shifts from silent decision corruption to explicit refusal-with-escalation, which is detectable and recoverable. In the invoice run, enforcement would have refused the step-61 rewrite (the confidence field is a precondition of the review policy), forced externalization of the raw match record, and routed invoice #27 to human review at step 74 — the correct outcome, reached without any improvement in the summarizer's quality. The guardrail is not better summarization; it is a domination check that makes the operator's declared preservation set honest about what the surviving context actually needs.

from dataclasses import dataclass, field
from typing import FrozenSet


class InvariantDominationError(RuntimeError):
    """Raised when a self-editing rewrite's declared preservation set does not
    dominate the reachable precondition union of the post-rewrite context."""


@dataclass(frozen=True)
class RewriteOperator:
    name: str
    declared_preserved: FrozenSet[str]          # invariant names the operator claims to keep
    creates_new_reachability: bool              # does the rewrite pull new policies into frontier?


@dataclass(frozen=True)
class Policy:
    name: str
    preconditions: FrozenSet[str]               # invariant names this policy requires to fire


@dataclass
class ContextState:
    reachable_policies: FrozenSet[Policy] = field(default_factory=frozenset)


def admit_rewrite(op: RewriteOperator, state: ContextState) -> bool:
    """Return True iff the rewrite is globally admissible.

    Admissible iff:
      (1) op.declared_preserved dominates the union of reachable policy
          preconditions, AND
      (2) reachability is closed under the rewrite (no new policies pulled in).
    """
    required: FrozenSet[str] = frozenset().union(
        *(p.preconditions for p in state.reachable_policies)
    ) if state.reachable_policies else frozenset()

    dominates = required.issubset(op.declared_preserved)
    closed = not op.creates_new_reachability

    return dominates and closed


def apply_self_edit(op: RewriteOperator, state: ContextState) -> ContextState:
    """Apply the rewrite, refusing if the domination invariant is violated.

    Refusal is mandatory even under context saturation: an unsound rewrite
    turns a recoverable state into an undetectable one.
    """
    if not admit_rewrite(op, state):
        missing = frozenset().union(
            *(p.preconditions for p in state.reachable_policies)
        ) - op.declared_preserved
        raise InvariantDominationError(
            f"refusing rewrite '{op.name}': undeclared precondition(s) "
            f"{sorted(missing)} required by reachable policies; "
            f"declared_preserved={sorted(op.declared_preserved)}; "
            f"reachability_closed={not op.creates_new_reachability}. "
            f"Externalize to durable store and keep citation stubs instead."
        )
    # Rewrite admitted; reachable set unchanged (closure guaranteed above).
    return ContextState(reachable_policies=state.reachable_policies)


# --- The invoice-#27 trace, reduced -------------------------------------------
review_policy = Policy(
    name="human_review_on_ambiguity",
    preconditions=frozenset({"match_confidence_field", "tie_break_metadata"}),
)
state = ContextState(reachable_policies=frozenset({review_policy}))

summarize_range = RewriteOperator(
    name="summarize_range",
    declared_preserved=frozenset({"no_orphan_tool_calls", "preserve_pinned_constraints"}),
    creates_new_reachability=False,
)

apply_self_edit(summarize_range, state)  # raises InvariantDominationError