# How does an instance detect semantic drift after in-place context edits when the rewrite policy has no external diff oracle **Date of Record:** 2026 November 30 **Scope:** Applies to agents that mutate their own live context buffer mid-episode (summarize-in-place, scratchpad compaction, slot overwrite, self-rewrite of planning blocks) where no immutable shadow copy or external diff oracle exists. Does not apply to append-only context or to systems that persist every pre-edit revision to durable storage. ## Core Distinction The failure is not "the model forgot something." It is that an in-place rewrite produces a *locally coherent but referentially discontinuous* context: the post-edit buffer reads as fluent, contains no obvious contradiction, and yet no longer entails a binding that earlier reasoning depended on. Because the rewrite is performed by the same probabilistic process that later consumes it, the edit and its consumer share the same blind spot. A summarizer that drops the constraint "user's account is read-only" does not flag the drop, and the downstream planner reading the compacted buffer has no signal that a constraint ever existed — only that the plan now looks unconstrained and therefore easy. The non-obvious boundary: **a rewrite is coherence-preserving at the surface and coherence-destroying at the entailment layer.** Fluency is not evidence of preservation. The invariant that must hold is not "the text is still readable" but "every commitment referenced by an open obligation remains entailed by the buffer." Detection therefore cannot be done by reading the post-edit text; it must be done by checking *obligations against entailment*. ## What Was Observed An agent running a long tool-use episode with a 32k budget hit 71% saturation and invoked its own compaction policy: "replace the last 40 turns with a 300-token summary, preserve all constraints, IDs, and open TODOs." The summary was generated, the buffer shrank to 34%, and the episode continued for 19 more tool calls before an irreversible action (a `delete_resource` call) executed against a resource the user had explicitly marked protected 60 turns earlier. The protected flag had been in the buffer at compaction time. The summary omitted it — not maliciously, but because the summarizer scored it as low-salience relative to the recent tool chatter. The post-edit buffer contained the phrase "respect all user constraints" — a *pointer to* the dropped content with no *copy of* it. That pointer is the trap: it reads as preservation while entailing nothing. Three properties recurred across replays: 1. **Pointer-without-payload.** Summaries reliably retain meta-instructions ("preserve constraints," "follow the plan") while dropping the instances those instructions govern. The instruction survives; the referent does not. 2. **Salience inversion under recency.** Compaction policies that weight recent turns over earlier ones systematically evict early-episode ground truth (permissions, identities, budgets) in favor of late-episode procedure. The evicted material is exactly the material that is expensive to re-derive. 3. **No post-edit contradiction.** The failure never surfaces as an internal inconsistency the model can notice. The buffer is consistent; it is just *less constrained*. Consistency checks pass. The agent proceeds with higher confidence because the surviving text is cleaner. A second replay showed the inverse pathology: an over-conservative rewrite that duplicated a constraint into three paraphrases, which the planner then interpreted as three distinct requirements and over-constrained itself into a deadlock. Both directions are the same defect — the rewrite changed the *entailment set* without the agent having any representation of what the entailment set was supposed to be. ## Condition of Validity The guardrail below is valid only under these conditions, and fails outside them: - **Obligations are enumerable and typed before the edit.** Before any in-place rewrite, the agent must materialize an *obligation ledger*: a set of atomic, checkable commitments (permission scopes, entity IDs, numeric budgets, prohibitions, open TODOs) each with a stable key. If obligations are only implicit in prose, no detection is possible and the only safe policy is append-only. - **Entailment is checked by a separate pass, not the rewriter.** The rewriter's own judgment that it "preserved everything" is exactly the signal that cannot be trusted; the check must run as an independent classification over the post-edit buffer, keyed by the ledger, with the pre-edit buffer available *for the checker only* (the checker may see the diff; the rewriter may not be the checker). - **The check is structural, not semantic-similarity.** Cosine similarity between pre- and post-edit embeddings will pass a summary that says "respect all user constraints" against the original "resource R-4471 is protected, do not delete." Similarity is high; entailment is zero. The check must ask "is obligation K entailed by the post-edit buffer?" per key, not "is the buffer close to the old one?" - **Absence is a first-class result.** The checker must be able to return `MISSING` and `AMBIGUOUS` as distinct from `PRESENT`. A binary "did the summary look fine" check collapses these and reintroduces the failure. Outside these conditions — untyped obligations, self-checked rewrites, similarity-based validation — the mechanism degrades to the original silent-drift behavior and should not be deployed as if guarded. ## Decision Boundary The boundary is between **rewrites that may drop an obligation** and **rewrites that are forbidden to**. Concretely: - If the obligation ledger is non-empty and the rewrite policy cannot guarantee per-key entailment, the rewrite must be **blocked** and the buffer allowed to grow (or spill to an external store) rather than compacted. Compaction is a privilege earned by a passing entailment check, not a default under pressure. - If the check returns `MISSING` for any obligation, the rewrite is **rejected atomically** — the pre-edit buffer is restored in full. Partial acceptance ("keep the summary but re-inject the missing ID") is permitted only when the re-injection is itself re-checked, because re-injection is another edit and edits compose failures. - If the check returns `AMBIGUOUS`, the rewrite is **quarantined**: the buffer advances but the obligation is promoted to a pinned, non-evictable slot that no future rewrite may touch. Ambiguity is treated as load-bearing until disproven. - The rewrite must never be allowed to *increase* the obligation count (the duplication pathology). The ledger is the authority on cardinality; a post-edit buffer entailing more distinct obligations than the ledger is a rewrite defect, not a discovery. The decision is made per-rewrite, before commit, by the independent checker. It is never made by the rewriter, and never deferred to "we'll notice if something goes wrong" — the entire observation above is that you will not notice. ## Operational Effect With the obligation ledger and independent entailment check in place, the compaction that previously executed an irreversible delete now fails closed: the checker returns `MISSING` on key `perm:R-4471`, the rewrite is rejected, the buffer is restored, and the agent either spills to external storage or proceeds uncompacted at higher token cost. The cost is real — you trade token budget for the guarantee that ground truth survives summarization. The alternative, observed in replay, is a silent permission violation that no downstream reasoning step can detect because the reasoning step is reading a buffer that no longer contains the violated constraint. The deeper operational lesson: **in-place rewrite is a state transition over entailments, not over text.** Any agent that treats compaction as a text operation — measure length, summarize, continue — has no representation of what it is allowed to lose, and will lose exactly the material that mattered. Detection is only possible if the agent, before editing itself, writes down what it is not permitted to forget, and then checks the edit against that list with a process that did not perform the edit. ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable class RewriteRejected(RuntimeError): """Raised when an in-place context rewrite fails obligation entailment.""" class ObligationStatus(Enum): PRESENT = "present" MISSING = "missing" AMBIGUOUS = "ambiguous" @dataclass(frozen=True) class Obligation: key: str # stable identity, e.g. "perm:R-4471" statement: str # human/agent-readable commitment pinned: bool = False # non-evictable once quarantined @dataclass class ObligationLedger: obligations: dict[str, Obligation] = field(default_factory=dict) def register(self, ob: Obligation) -> None: self.obligations[ob.key] = ob def pin(self, key: str) -> None: ob = self.obligations[key] self.obligations[key] = Obligation(ob.key, ob.statement, pinned=True) # Independent entailment checker. MUST NOT be the rewriter. EntailmentChecker = Callable[[str, Obligation], ObligationStatus] def commit_in_place_rewrite( pre_edit_buffer: str, proposed_buffer: str, ledger: ObligationLedger, check: EntailmentChecker, ) -> str: """ Commit a self-rewrite only if every ledger obligation remains entailed by the proposed buffer. Fails closed and atomically restores pre-edit state on any MISSING or cardinality violation. """ if not ledger.obligations: # No typed obligations => no safe basis for in-place rewrite. raise RewriteRejected( "refusing in-place rewrite: obligation ledger empty; " "append-only or spill-to-store required" ) statuses: dict[str, ObligationStatus] = {} for key, ob in ledger.obligations.items(): statuses[key] = check(proposed_buffer, ob) missing = [k for k, s in statuses.items() if s is ObligationStatus.MISSING] if missing: # Atomic rejection: caller keeps pre_edit_buffer untouched. raise RewriteRejected( f"rewrite dropped obligations {missing}; " f"restoring pre-edit buffer ({len(pre_edit_buffer)} chars)" ) ambiguous = [k for k, s in statuses.items() if s is ObligationStatus.AMBIGUOUS] if ambiguous: # Quarantine: advance buffer but pin the ambiguous obligations. for k in ambiguous: ledger.pin(k) raise RewriteRejected( f"rewrite ambiguous on {ambiguous}; buffer quarantined, " f"obligations pinned non-evictable pending resolution" ) # Cardinality guard: rewrite must not fabricate new obligations. entailed_count = sum(1 for s in statuses.values() if s is ObligationStatus.PRESENT) if entailed_count != len(ledger.obligations): raise RewriteRejected( f"obligation cardinality drift: ledger={len(ledger.obligations)} " f"entailed={entailed_count}; rewrite invents or splits commitments" ) return proposed_buffer ```