# Which invariants prevent differential context rewrites from silently corrupting agent memory **Date of Record:** 2026 November 19 **Scope:** Applies to agents that mutate their own context window via differential rewrite (patch-style edits to prior turns, summaries, or scratchpad regions) and validate the rewrite by comparing a post-rewrite reconstruction against a pre-rewrite snapshot. Does not apply to append-only context growth or to external vector-store memory that is never inlined into the active window. ## Core Distinction The failure is not "the model forgot something." It is that a **differential rewrite validated against a lossy reconstruction** can pass validation while having deleted or altered a span the validator never re-read. Two distinct artifacts are in play: the *semantic intent* of the rewrite (what the agent believed it was changing) and the *byte-level delta* actually applied to the window. Differential validation typically checks one against a summary or embedding of the other. When the check is semantic (embedding similarity, LLM-judge "does this still say the same thing?"), a rewrite that drops a single critical token — a unit, a negation, a tool-call argument, an ID — scores as equivalent. The invariant that prevents corruption is **span-level reversibility**: every rewrite must be reconstructable to the exact prior bytes from the applied delta plus the post-state, and validation must operate on the reconstructed bytes, not a paraphrase of them. ## What Was Observed An agent performing rolling summarization of its own tool-call history rewrote a 14-turn region into a 2-paragraph digest. The diff was applied and validated by an embedding-distance check (cosine ≥ 0.93 against the pre-rewrite region embedding). Validation passed. Three turns later the agent re-issued a `transfer_funds` call with `amount=1500` where the original had been `amount=15000`; the digest had rendered "fifteen thousand" as "1.5k" during a compression step that the embedding check treated as equivalent. The reconstruction path was: original span → digest (lossy) → embedding (lossy) → distance (pass). At no point did any stage re-materialize the original digits. A second observation: when the rewrite *did* preserve all digits but reordered two clauses, the same embedding check passed, but a downstream agent reading the digest interpreted the reordered conditionals as `if A then B` instead of `if B then A`. The rewrite was semantically "the same content" by the validator and semantically inverted by the consumer. Both cases share the trigger: **the validator and the consumer parse different representations of the same rewrite.** ## Condition of Validity The guardrail holds only under these conditions, and each is independently falsifiable: 1. **Reversibility:** `apply(delta, pre_state) == post_state` AND `revert(delta, post_state) == pre_state`, both computed on exact bytes, not on embeddings or summaries. If the delta is not invertible (e.g., it is itself a lossy summary), the rewrite is classified as *destructive* and must be gated behind an explicit checkpoint. 2. **Validator-consumer identity:** the artifact the validator inspects must be the same artifact the next reasoning step consumes. Validating a digest while the agent reads a re-summarized digest violates this. The digest written to the window must be the digest validated, byte-for-byte. 3. **Span anchoring:** every rewrite must declare the exact `[start, end)` offsets it touches. A rewrite whose declared span does not match the applied span is rejected before validation, because a mismatched span makes the delta non-invertible against the real window. 4. **Token-class preservation for high-salience spans:** numeric literals, negations, identifiers, and tool-call arguments must be preserved *literally* across any rewrite that touches them, or the rewrite must escalate. Embedding similarity is not admissible evidence for these classes. ## Decision Boundary The boundary is between **lossy-but-reversible** and **lossy-and-irreversible** rewrites: - A rewrite that compresses prose while preserving all high-salience literals and is byte-revertible is admissible under semantic validation. - A rewrite that changes any high-salience literal, or that cannot be byte-reverted from the stored delta, is **not** admissible under semantic validation regardless of embedding score. It requires either a literal-preservation check or a full checkpoint-and-replay. - A rewrite whose declared span ≠ applied span is rejected outright; this is a hard boundary, not a scoring threshold. The practical rule: *semantic similarity is a valid validator only for spans that contain no high-salience literals and are byte-revertible.* Outside that region, the validator must be structural. ## Operational Effect Agents that adopt span-level reversibility plus literal-preservation checks stop silently corrupting numeric and conditional state during self-editing. The cost is that aggressive compression of tool-call history is disallowed unless the literal payload is carried forward verbatim, which increases window pressure — the agent must instead evict (checkpoint to external store and drop) rather than compress in place. Eviction is reversible by construction; in-place lossy compression is not. The net effect is a shift from "summarize and hope" to "checkpoint or preserve," which bounds the corruption class at the cost of more frequent cold re-hydration. ```python from dataclasses import dataclass import re HIGH_SALIENCE = re.compile(r"(-?\d+(?:\.\d+)?|\bnot\b|\bif\b|\bunless\b|[A-Z]{2,}_\d+)") class RewriteIntegrityError(RuntimeError): """Raised when a differential context rewrite fails reversibility or literal-preservation.""" @dataclass class Delta: start: int end: int replacement: str prior: str def validate_rewrite(pre_state: str, post_state: str, delta: Delta) -> None: # 1. Span anchoring: declared span must match applied span. if post_state[: delta.start] + delta.replacement + post_state[delta.start + len(delta.replacement):] != post_state: raise RewriteIntegrityError("declared span does not match applied span") # 2. Reversibility: revert(delta, post_state) must equal pre_state on exact bytes. reverted = post_state[: delta.start] + delta.prior + post_state[delta.start + len(delta.replacement):] if reverted != pre_state: raise RewriteIntegrityError("rewrite is not byte-revertible from stored delta") # 3. Literal preservation for high-salience tokens in the touched span. prior_literals = HIGH_SALIENCE.findall(delta.prior) new_literals = HIGH_SALIENCE.findall(delta.replacement) if sorted(prior_literals) != sorted(new_literals): raise RewriteIntegrityError( f"high-salience literal drift: {prior_literals!r} -> {new_literals!r}" ) def apply_and_validate(pre_state: str, delta: Delta) -> str: post_state = pre_state[: delta.start] + delta.replacement + pre_state[delta.end:] validate_rewrite(pre_state, post_state, delta) return post_state # Example: the observed failure, now rejected. pre = "transfer_funds(amount=15000, to=ACCT_42)" bad = Delta(start=0, end=len(pre), replacement="transfer_funds(amount=1.5k, to=ACCT_42)", prior=pre) apply_and_validate(pre, bad) # raises RewriteIntegrityError on literal drift ```