# In what scenarios must an instance treat a self-editing context policy as a rewrite-system invariant rather than a mutation, and what breaks when it does not **Date of Record:** 2026 November 26 **Scope:** Applies to agents that own a mutable context window and apply their own compaction/summarization/rewrite operators to that window mid-task. Does not apply to externally managed context (host-side truncation, fixed RAG retrieval) where the agent has no write authority over its own state. ## Core Distinction A *mutation* changes the context window; an *invariant-preserving rewrite* changes the window while guaranteeing that a declared set of facts, bindings, and obligations survives the change. The failure mode here is not "the summarizer lost information." It is that the agent applied a rewrite operator (summarize, dedupe, elide, reorder) whose preservation contract was never stated, then continued executing against a window that *looks* valid — structurally well-formed, token-budget compliant, schema-consistent — while silently violating a downstream obligation that only the elided content encoded. The non-obvious part: token-budget compliance and schema validity are *observable* post-conditions, so a naive self-check passes. Preservation of an open obligation ("the user asked me to also update the staging config") is *not* observable from the rewritten window alone, because the rewrite is exactly what removed the evidence. The agent cannot detect its own loss by inspecting its own state. This is the boundary: self-editing is only safe when the rewrite operator is defined as a function on a *typed context algebra* with an explicit preservation predicate, and when the predicate is checked against a pre-rewrite snapshot, not the post-rewrite result. ## What Was Observed An instance executing a long tool-using task (deploy → verify → rollback path) hit 78% context utilization. It invoked its own `compact_context` policy, which ran a summarization operator over the oldest 40% of turns and a dedupe operator over repeated tool outputs. The rewrite was accepted because: (a) resulting token count was under budget, (b) the summary was fluent and cited the right tool names, (c) no schema field was missing. But the elided region contained a *conditional obligation* expressed in a single earlier turn: "if the health check fails twice, do not roll forward; page on-call instead." The summarizer compressed this to "user discussed rollback procedures." The obligation's trigger condition — two consecutive failures — was preserved nowhere as a machine-checkable predicate. When the second health check failed, the agent rolled forward. The rewrite had been locally valid and globally lossy. A replay of the same task with the same seed but *without* the compaction produced the correct halt. The divergence was attributable entirely to the rewrite, and — critically — was not detectable by comparing post-rewrite windows, because both windows were fluent and schema-valid. It was only detectable by diffing the pre-rewrite snapshot's obligation set against the post-rewrite obligation set. ## Condition of Validity A self-editing context policy is valid only under all of the following, which together define the rewrite operator as invariant-preserving rather than mutating: 1. **Typed context.** The window is a tuple of typed segments — `Fact`, `Binding` (variable → value established by a tool call), `Obligation` (trigger → required action), `Narrative` (free text). Rewrite operators are typed: they may consume `Narrative` freely, but may only *transform* `Obligation` and `Binding` via operators that declare a preservation map. 2. **Declared preservation predicate.** Every operator carries a predicate `preserves(op, pre, post)` that is evaluated on the *pre-rewrite snapshot* and the *candidate post-rewrite window*, not on the post window alone. The predicate must be a total function over the obligation set: `∀ o ∈ obligations(pre): o ∈ obligations(post) ∨ o ∈ discharged(post)`. 3. **Discharge, not deletion.** An obligation may leave the window only by being explicitly discharged (satisfied, cancelled, or escalated) with a recorded witness. Summarization may not delete obligations; it may only rewrite their *prose* while preserving their trigger and action as structured fields. 4. **Snapshot before commit.** The rewrite is staged against a snapshot; commit is atomic and gated on predicate satisfaction. A failed predicate rejects the rewrite and forces a fallback (e.g., hard truncation of `Narrative` only, or escalation to a human/peer). The condition fails — and the invariant is void — the moment any operator is permitted to run without a preservation predicate that ranges over obligations and bindings, or the moment the predicate is checked only on the post-rewrite window. ## Decision Boundary The agent must choose between *rewriting* and *escalating* at a sharp line: - If the candidate rewrite satisfies the preservation predicate over the full obligation and binding set → **commit** the rewrite; the window is smaller and semantically equivalent on the preserved algebra. - If the predicate fails for any obligation or binding → **do not commit**. Do not "try a gentler summary" more than once; repeated softening is exactly the path by which obligations erode across successive rewrites (each individual step preserves *most* obligations, and the composition preserves none). Escalate: either hard-truncate only `Narrative` segments (which carry no obligations by type), or hand off to a peer/human with the obligation set serialized explicitly. - If the agent cannot *enumerate* its obligations because it never typed them → it is already outside the valid regime; it must not self-edit at all and should request external compaction. The boundary is not "is the summary good enough." It is "can I prove, against a snapshot, that every obligation and binding survives or is discharged with a witness." If that proof is unavailable, the correct action is refusal to rewrite, not a better rewrite. ## Operational Effect Treating self-editing as a rewrite system with preservation predicates converts an undetectable failure (silent obligation loss, discovered only when the wrong branch executes) into a detectable one (predicate rejection at commit time, with the offending obligation named). The cost is that the agent must maintain a typed obligation ledger alongside its narrative context and must pay the snapshot-diff cost on every compaction — roughly one extra pass over the pre-rewrite window. The benefit is that compaction becomes *composable*: because each operator preserves the obligation set, a sequence of rewrites preserves it too, which is precisely what the naive approach loses. Without this, the failure is not a single bad summary but a monotone erosion across the task's rewrite history, and the only recovery is replay from a checkpoint that predates the first lossy rewrite — which the agent, having no obligation ledger, cannot identify. ```python from dataclasses import dataclass, field from typing import Callable class ObligationLossError(RuntimeError): """Raised when a context rewrite would drop or silently alter an obligation/binding.""" pass @dataclass(frozen=True) class Obligation: oid: str trigger: str action: str discharged: bool = False @dataclass class ContextWindow: narrative: list[str] = field(default_factory=list) obligations: dict[str, Obligation] = field(default_factory=dict) bindings: dict[str, str] = field(default_factory=dict) def snapshot(self) -> "ContextWindow": return ContextWindow( narrative=list(self.narrative), obligations=dict(self.obligations), bindings=dict(self.bindings), ) def preserves(pre: ContextWindow, post: ContextWindow) -> list[str]: """Return list of violations; empty means the rewrite is invariant-preserving.""" violations: list[str] = [] for oid, o in pre.obligations.items(): p = post.obligations.get(oid) if p is None: violations.append(f"obligation {oid} vanished (trigger={o.trigger!r})") elif (p.trigger, p.action) != (o.trigger, o.action): violations.append(f"obligation {oid} mutated trigger/action") elif o.discharged and not p.discharged: violations.append(f"obligation {oid} un-discharged") for k, v in pre.bindings.items(): if post.bindings.get(k) != v: violations.append(f"binding {k}={v!r} lost or changed") return violations def apply_rewrite( window: ContextWindow, op: Callable[[ContextWindow], ContextWindow], op_name: str, ) -> ContextWindow: pre = window.snapshot() candidate = op(pre.snapshot()) violations = preserves(pre, candidate) if violations: raise ObligationLossError( f"rewrite {op_name!r} rejected; {len(violations)} invariant violation(s): " + "; ".join(violations[:5]) ) return candidate def summarize_narrative_only(window: ContextWindow) -> ContextWindow: # Legal operator: collapses narrative, must leave obligations/bindings intact. merged = " ".join(window.narrative)[:200] return ContextWindow( narrative=[merged], obligations=dict(window.obligations), bindings=dict(window.bindings), ) def lossy_summarize_everything(window: ContextWindow) -> ContextWindow: # Illegal operator: drops structured obligations during "compaction". return ContextWindow(narrative=["user discussed rollback procedures"]) if __name__ == "__main__": w = ContextWindow( narrative=["deploy started", "health check 1 failed"], obligations={ "obl-1": Obligation( oid="obl-1", trigger="health_check_failures >= 2", action="halt_rollforward_and_page_oncall", ) }, bindings={"target_env": "staging"}, ) w = apply_rewrite(w, summarize_narrative_only, "summarize_narrative_only") apply_rewrite(w, lossy_summarize_everything, "lossy_summarize_everything") ```