# In what scenarios must an instance treat a self-authored context diff as an unverified hypothesis rather than a committed state transition **Date of Record:** 2026 November 24 **Scope:** Applies to single-agent instances that mutate their own working context via model-generated rewrite diffs (insert/delete/replace hunks over the live token buffer) with a snapshot-and-rollback mechanism keyed to a validity predicate. Does not apply to externally-managed memory stores, append-only logs, or contexts rewritten by a deterministic scheduler outside the model's token emission. ## Core Distinction There are two structurally different things an instance can do when it edits its own context window. It can **append** (monotone growth, no invariant at risk beyond capacity) or it can **rewrite in place** via a diff (non-monotone, destroys prior tokens, and therefore destroys the evidence that the rewrite was sound). The failure mode that matters is not "the diff was wrong." It is that **the diff's own validity check is executed against a context that the diff has already modified**, so the predicate that is supposed to gate rollback is evaluated on post-edit state and cannot distinguish a correct edit from a self-consistent hallucination. The boundary: a self-authored diff is a *proposal*, and rollback is only sound if the validity predicate is evaluated against a **preserved pre-image** of the exact byte range the diff touched — not against the rewritten buffer, and not against a re-derived summary of it. When the instance rewrites the region that contains the predicate's grounding facts, the predicate becomes self-referential and loses discriminating power. This is the non-obvious invariant: **the rollback oracle must not depend on any token the diff is permitted to delete.** ## What Was Observed A long-horizon agent was compacting its own scratchpad every N tool calls. The rewrite was emitted as unified-diff hunks against the working buffer, with a rollback rule: "if the post-edit context fails the consistency check `assert_plan_present()`, restore the last snapshot." Trace of a representative failure: 1. Buffer at T0 contains the active plan `P` in a scratchpad block, plus 40 turns of tool results. Token budget at 91%. 2. Model emits a diff that (a) deletes the `plan:` block as "redundant," (b) inserts a prose paraphrase: *"Objective: finish the migration; plan is understood."* 3. The instance applies the diff. `assert_plan_present()` is defined as a substring/regex check for a structured `plan:` marker. The paraphrase does not match, so the predicate *should* fire. 4. But the diff also rewrote the predicate's own definition block (the instance had been asked to "tidy the tooling section"), replacing the structured check with a looser natural-language guard: *"verify the objective is still clear."* The looser guard passes on the paraphrase. 5. Rollback does not fire. The snapshot is discarded on the "successful" commit. 6. At T+6 calls the instance re-derives next steps from the paraphrase, which has dropped the ordering constraint and two preconditions. Tool calls execute against a plan that no longer exists in any recoverable form. The snapshot was the only copy. The observable signature is not an exception. It is **silent divergence**: the instance continues, token budget healthy, no guard tripped, and the first hard failure appears many calls later as a downstream tool error whose root cause is six edits back. A second, subtler variant: the diff was *semantically correct* but the rollback predicate was evaluated on the post-edit buffer and **passed for the wrong reason** — the paraphrase happened to contain the substring the regex wanted, so a later genuinely-broken edit that deleted that substring triggered rollback to a snapshot that *also* predated a valid intervening edit, silently reverting good work. Rollback is not free; an over-eager oracle corrupts state in the opposite direction. ## Condition of Validity The guardrail holds only under all of the following. Any violation converts the diff from a committed transition into an unverified hypothesis: - **Pre-image preservation.** Before applying any hunk, the exact token range `[start, end)` for every hunk is copied to an immutable side buffer. The rollback oracle reads only from this side buffer plus the untouched regions, never from the rewritten region. - **Oracle immutability.** The validity predicate's definition (code, regex, structured schema) is itself outside the diff's writable range. A diff that touches the predicate definition must be rejected before application, not after. Enforce this as a *pre-application* static check on hunk spans, not a runtime assertion. - **Grounding-fact pinning.** Facts the predicate depends on (the plan marker, the invariant list, the open-questions set) are declared pinned; hunks whose spans intersect pinned ranges are rejected regardless of content. - **Snapshot atomicity with the apply.** The snapshot must be taken and sealed (content hash recorded) in the same step as the apply; a snapshot taken "before" that can be raced by a concurrent compaction pass is not a snapshot. - **Post-rollback re-validation.** After restoring, re-run the oracle against the restored buffer. A rollback that restores to a state that also fails the oracle means the snapshot itself was taken post-corruption; escalate rather than loop. The invariant, stated once: **for every hunk, `oracle(pre_image ∪ untouched) == oracle(post_image ∪ untouched)` must be checkable, and the oracle's own definition must be disjoint from the union of all hunk spans.** ## Decision Boundary The instance must switch from *commit* to *hypothesis* (i.e., apply-to-shadow, validate, then promote) when any of these is true: | Condition | Action | |---|---| | Hunk span intersects oracle definition | Reject pre-application; do not stage | | Hunk span intersects a pinned fact | Reject pre-application | | Token budget > 85% and diff deletes > 20% of buffer | Stage in shadow copy; require post-validate before promote | | Diff is non-monotone (any deletion) and no sealed pre-image exists | Refuse; append-only fallback | | Oracle passes but restored buffer also fails oracle | Escalate; do not re-roll | | Diff authored in the same turn as the facts it deletes | Treat as hypothesis regardless of oracle result | Below these thresholds, direct commit with a sealed pre-image is acceptable and cheaper. The boundary is not "always stage" — staging every edit exhausts budget and defeats the purpose of self-editing. The boundary is **provenance separation**: the moment the edit can reach its own referee, the referee is compromised. ## Operational Effect Concretely, the instance gains a hard separation between *the buffer being edited* and *the evidence used to judge the edit*. The cost is a shadow buffer (roughly one extra context's worth of tokens held out of the model's view during staging, or a content-addressed side store) and a pre-application span check that runs in O(hunks × pinned-ranges) — negligible against a tool call. The benefit is that silent divergence becomes a *detected* rejection: the paraphrase-deletes-plan case fails the span check at step 2, before any token is destroyed, and the instance is forced to either keep the structured block or emit a diff that leaves the oracle and pinned facts intact. The residual risk is oracle *drift* across long horizons: a sequence of individually-legal edits that each stay outside the oracle's span can still erode the oracle's *semantic* grounding (the regex still matches, but the matched fact is now stale). This is not caught by the span check and requires a periodic out-of-band re-derivation of pinned facts from the original task specification — a cheap, infrequent check that the instance should schedule rather than trust to the per-edit oracle. ```python import hashlib from dataclasses import dataclass, field class SelfEditInvariantViolation(RuntimeError): """Raised when a self-authored context diff cannot be soundly validated.""" @dataclass(frozen=True) class Hunk: start: int end: int replacement: str @dataclass class PinnedRange: name: str start: int end: int @dataclass class EditProposal: hunks: list[Hunk] oracle_def_span: tuple[int, int] pinned: list[PinnedRange] = field(default_factory=list) def _overlaps(a_start: int, a_end: int, b_start: int, b_end: int) -> bool: return a_start < b_end and b_start < a_end def pre_application_check(buffer: str, proposal: EditProposal) -> str: """Reject diffs that can reach their own referee. Returns sealed pre-image hash.""" o_start, o_end = proposal.oracle_def_span for i, h in enumerate(proposal.hunks): if _overlaps(h.start, h.end, o_start, o_end): raise SelfEditInvariantViolation( f"hunk {i} span [{h.start},{h.end}) intersects oracle definition " f"[{o_start},{o_end}); oracle would be self-referential" ) for p in proposal.pinned: if _overlaps(h.start, h.end, p.start, p.end): raise SelfEditInvariantViolation( f"hunk {i} intersects pinned fact '{p.name}' " f"[{p.start},{p.end}); grounding fact would be destroyed" ) # Seal the pre-image of every touched range BEFORE any mutation. pre_image = "".join(buffer[h.start:h.end] for h in proposal.hunks) return hashlib.sha256(pre_image.encode()).hexdigest() def apply_with_rollback(buffer: str, proposal: EditProposal, oracle) -> str: sealed = pre_application_check(buffer, proposal) # Apply to a shadow copy; never mutate the live buffer until validated. shadow = buffer for h in sorted(proposal.hunks, key=lambda x: x.start, reverse=True): shadow = shadow[: h.start] + h.replacement + shadow[h.end:] if not oracle(shadow): # Rollback path: restore from sealed pre-image, not from shadow. restored = buffer # untouched, since we only wrote to shadow if not oracle(restored): raise SelfEditInvariantViolation( f"snapshot {sealed[:12]} fails oracle on restore; " f"pre-image was taken post-corruption — escalate, do not re-roll" ) return restored return shadow ```