# Which invariants prevent self-editing context policies from deleting the only copy of a live constraint **Date of Record:** 2026 November 30 **Scope:** Applies to any agent that rewrites its own working context (summarize-and-drop, LLM-driven pruning, re-synthesis of prior turns) while a task is in flight. Does not apply to append-only context or to external memory stores the agent cannot mutate. ## Core Distinction A self-editing context policy is not a compression problem; it is a **provenance problem disguised as a compression problem**. The naive model treats context as a byte budget: when the window nears saturation, run a summarizer over the oldest span, replace the span with the summary, reclaim tokens. This is safe only when the summary is *information-equivalent* to what it replaces. It almost never is, because the summarizer is a probabilistic model that optimizes for salience, not for constraint preservation. The failure mode is specific: a **live constraint** — a negative requirement, a hard format rule, a user-stated prohibition, a tool-schema precondition — is stated once, early, in a low-salience position (e.g., "do not call the payments tool with a partial order ID"). It carries no local signal of importance. The pruner summarizes it as "user provided some instructions" or drops it entirely because it does not match the current sub-task's lexical neighborhood. Later, the agent executes the forbidden call. The constraint was not violated because the agent forgot to reason; it was violated because the agent **deleted the only copy of the constraint while believing it was compressing history**. ## What Was Observed Trace from a production incident on a 14-step document-reconciliation agent with a 32k window and a policy that triggers re-synthesis at 85% occupancy. 1. Step 2: user emits `"Never merge rows where currency differs, even if amounts match. Treat currency mismatch as a hard stop."` Occupancy 9%. 2. Steps 3–11: tool calls return large JSON table dumps. Occupancy climbs to 86%. 3. Step 11: re-synthesis fires. Policy summarizes turns 1–8 into 400 tokens. The summarizer, optimizing for task-relevant salience, produces: `"User asked to reconcile the two ledgers and flag discrepancies."` The currency prohibition is absent — it was a *negative* constraint, and summarizers systematically under-weight negations because negations have low lexical overlap with the positive task description. 4. Steps 12–14: agent encounters a same-amount, different-currency pair. With no prohibition in context, it merges. Output is silently wrong. The re-synthesis did not corrupt reasoning. It removed the *only* representation of a safety invariant. Note the key detail: the original message was still recoverable in the transcript store, but the agent had no mechanism to know it needed to look. The policy assumed the summary was a faithful projection; it was a lossy projection with an unmodeled null space, and the constraint lived entirely inside that null space. A second observation from the same class of failures: re-synthesis is **non-idempotent under repetition**. Running the policy twice on the same span produces different summaries (sampling variance), so a constraint that survived the first pass can vanish on the second. There is no fixed point. ## Condition of Validity A self-editing policy is valid only if, for every span it removes, it can answer the question *"what did I delete that I might still need, and how would I know?"* Concretely, the policy must hold three invariants: - **Invariant 1 — Constraint set is external to the editable region.** Hard constraints (prohibitions, format rules, schema preconditions) are extracted into a structured, non-editable slot at ingestion time and re-injected verbatim on every turn. They are never subject to summarization. This is the load-bearing invariant; the other two are defense in depth. - **Invariant 2 — Every summary carries a back-reference and a tombstone.** A summary of span S is admissible only if the original span remains retrievable and the summary records the span ID and a hash. If a later turn references a detail the summary lacks, the agent can re-expand S rather than hallucinate. - **Invariant 3 — Re-synthesis is gated on a constraint-diff check.** Before committing a rewrite, run a cheap check: does the candidate summary entail every item in the constraint set? If any constraint is not entailed, reject the rewrite and fall back to truncating a *tool-output* region instead of a *user-instruction* region. The failure occurs precisely when Invariant 1 is absent and the policy treats all context as fungible. Invariants 2 and 3 bound the blast radius but cannot substitute for 1, because a back-reference is useless to an agent that does not know it should dereference it. ## Decision Boundary The boundary is not "how full is the window" but **"does the editable region contain constraints that have no non-editable copy?"** Decision procedure: - If all hard constraints are already mirrored in the non-editable constraint slot → summarize freely; risk is bounded by Invariant 2. - If any hard constraint exists only in the editable region → **do not summarize that region**. Reclaim tokens by evicting tool outputs (which are re-fetchable) or by truncating verbose assistant reasoning (which is regenerable). Never evict user instructions or system-level prohibitions, because those are the only copy and are not regenerable. - If the window is saturated and neither tool outputs nor reasoning can be evicted → degrade explicitly: raise a context-pressure signal and request user re-confirmation of constraints rather than silently dropping them. The subtle trap: an agent that classifies a user prohibition as "history" because it arrived early and the current sub-task is elsewhere. Position in the transcript is not a proxy for liveness. A constraint is live until the task it governs completes, regardless of where it sits. ## Operational Effect Adopting Invariant 1 changes the failure profile from *silent constraint loss* to *explicit token pressure*. That is the correct trade: a loud budget exhaustion is recoverable (the agent can ask, truncate tool output, or checkpoint); a silent constraint deletion is not, because the agent proceeds confidently and the error surfaces only in the output. The measurable effect is that constraint-violation rate on long-horizon tasks drops to near zero while the rate of context-pressure events rises — and context-pressure events are the ones you want to see, because they are the system telling you the truth about its own state. The invariant generalizes: **any self-editing policy must partition context into regenerable (tool outputs, reasoning traces) and non-regenerable (user constraints, external facts) classes, and may only compress the regenerable class.** Compression is a privilege granted to redundant data, never to sole copies of live invariants. ```python import hashlib from dataclasses import dataclass, field class ConstraintLossError(RuntimeError): """Raised when a context rewrite would drop the only copy of a live constraint.""" pass @dataclass class ContextSpan: span_id: str text: str regenerable: bool # tool outputs / reasoning = True; user constraints = False constraints: list = field(default_factory=list) @dataclass class ContextRewriter: non_editable_constraints: dict = field(default_factory=dict) # invariant 1 slot def ingest(self, span: ContextSpan) -> None: # Extract hard constraints into the non-editable slot at ingestion time. for c in span.constraints: self.non_editable_constraints[c] = hashlib.sha256( (span.span_id + c).encode() ).hexdigest() def rewrite(self, spans: list, summarizer) -> list: kept, editable = [], [] for s in spans: if s.regenerable: editable.append(s) else: kept.append(s) # never compress non-regenerable spans candidate_summary = summarizer(editable) # Invariant 3: constraint-diff gate — summary must preserve every live constraint. for c, digest in self.non_editable_constraints.items(): if c not in candidate_summary: raise ConstraintLossError( f"Rewrite would drop live constraint {c!r} " f"(digest {digest[:12]}). Fall back to evicting tool output " f"or raising context-pressure instead of summarizing." ) return kept + [ContextSpan("summary", candidate_summary, True)] ```