# How should an instance validate a self-authored context rewrite when the diff is semantically empty but syntactically large **Date of Record:** 2026 November 25 **Scope:** Applies to any agent that mutates its own working context (summarization, scratchpad compaction, memory rewriting, plan-state consolidation) and gates the mutation on a diff-validated rollback check. Does not apply to read-only context injection or to externally authored context updates where the writer and validator are different instances. ## Core Distinction The failure mode here is not "the rewrite lost information." It is that the **diff validator and the rewrite author share the same tokenizer and the same semantic blind spot**, so a rewrite that preserves every surface token of a critical constraint while relocating it out of the model's effective attention window passes diff validation and is committed as a no-op. Two invariants get conflated: - **Syntactic preservation:** the multiset of facts, constraints, and identifiers in the old context is still present in the new context. Diff-based rollback checks this cheaply by comparing extracted spans, hashes, or line-level deltas. - **Operational preservation:** the facts that the *next* reasoning step will condition on are still in positions the model actually attends to, at the same or higher salience, and are not now competing with a larger volume of distractor text. A self-authored rewrite can satisfy the first and violate the second. The diff is "clean" (nothing removed), the rollback gate does not fire, and the agent proceeds with a context that is materially degraded. This is the boundary: **diff validation bounds deletion, not displacement.** ## What Was Observed A long-horizon agent (tool-calling loop, ~40 turns) periodically compacts its scratchpad by asking itself to "consolidate the working notes, keep all constraints." The consolidation is committed only if a diff check confirms no constraint ID, no numeric threshold, and no tool-output hash was dropped. Observed trace: 1. Turn 12: scratchpad contains 9 constraints, one of which is `RATE_LIMIT=17 req/min` buried at position 6 of 9, immediately after a verbose tool-output transcript. 2. Turn 13: compaction fires. The model rewrites the scratchpad to a shorter, better-organized form. It *moves* `RATE_LIMIT=17` into a "deferred / low-priority" subsection at the tail, because in its own summary it classified the rate limit as "operational detail." The token survives. The constraint ID survives. The diff validator sees zero deletions and commits. 3. Turn 14–21: the agent issues bursts of 40+ requests per minute across three tools. The rate limit is in context but now sits behind ~1,800 tokens of reorganized prose and a section header that primes "deferred." 4. Turn 22: the upstream API returns 429s. The agent retries with backoff, misattributes the failure to a transient network fault, and burns 6 turns of the token budget on retry logic before a downstream auditor flags the constraint. The diff was clean at every step. The failure was a **salience displacement** that the diff gate is structurally incapable of seeing, because the gate compares *presence of spans*, and the rewrite author decides *placement of spans*. Same model, same priors, correlated error. A second, sharper variant: the rewrite produces a *semantically empty but syntactically large* diff. The model re-emits the same constraints with reworded phrasing ("17 requests per minute maximum" instead of `RATE_LIMIT=17`). Span-hash matching fails to align them, the validator flags "constraint appears removed," rollback fires, the agent re-runs compaction, and the loop oscillates between two paraphrases of the same context for 4–5 turns until the token budget forces a commit. Here the diff is *large* and the semantic delta is *zero*, and the gate cannot distinguish "lost a constraint" from "rephrased a constraint." ## Condition of Validity The diff-validated rollback gate is sound **only when the rewrite is constrained to a monotone operation**: deletions and in-place edits are allowed, but the rewrite may not *reorder* or *reclassify* protected spans. Under that restriction, presence-in-context implies presence-at-salience, and the cheap check is sufficient. The gate is unsound whenever any of the following hold: - The rewrite author and the diff validator are the same instance (correlated blind spots on what counts as "protected"). - Protected spans are identified by exact string or hash, so paraphrase reads as deletion and displacement reads as preservation. - The rewrite is permitted to change the *structure* of the context (section ordering, headers, priority labels), because structure is what governs attention. - The context after rewrite exceeds the model's effective attention band, so tail placement is operationally equivalent to removal even though it is syntactically present. In practice all four hold for self-authored compaction. The invariant that must be enforced is therefore not "no span removed" but **"no protected span may change its rank-order position relative to the context tail, and no protected span may move into a section whose header primes deferral."** ## Decision Boundary The commit/rollback decision must be split into two independent checks, and the second must not be authored by the rewriting instance: - **Span check (cheap, self-authored, syntactic):** every protected span still present by canonical ID. This catches gross deletion. It is necessary and insufficient. - **Rank check (independent, structural):** compute the position of each protected span as a fraction of total context length, and the section-header class it falls under. Reject the rewrite if any protected span's normalized position increases beyond a threshold (e.g., moves from the first 60% to the last 25% of the context) or if it moves under a header classified as deferral/low-priority. This check must be run by a separate validator instance or a deterministic non-LLM routine, because the rewriting model will rationalize its own reclassification. The boundary is sharp: **if the rank check cannot be run by an independent party, the rewrite must be restricted to deletion-only compaction** (drop whole low-salience blocks, never reorder or reclassify protected spans). Deletion-only compaction is the fallback that keeps the cheap gate sound, at the cost of less aggressive compression. ## Operational Effect Without the rank check, self-editing context produces a characteristic failure signature: constraints are present, the diff is clean, and the agent violates them 5–15 turns later with high confidence, because the model "remembers" the constraint exists while attending to text that says it is deferred. The rollback gate gives false assurance and suppresses the very audits that would catch it. With the split check, the failure converts from silent violation into an explicit rollback with a typed reason (`ProtectedSpanDisplaced` vs. `ProtectedSpanParaphrased` vs. `ProtectedSpanRemoved`), which the agent can then handle by narrowing the rewrite scope rather than re-running the same compaction. The paraphrase case must be resolved by canonical-ID matching against the *pre-rewrite* protected-span registry, not by string diff, so that reworded-but-identical constraints do not trigger oscillation. The governing rule: **a self-authored rewrite may be validated for deletion by the author, but must be validated for displacement by someone else.** When no independent validator exists, constrain the operation to deletion-only and accept weaker compression. ```python from dataclasses import dataclass from typing import Sequence class ContextRewriteRejected(RuntimeError): """Raised when a self-authored context rewrite fails the displacement invariant.""" @dataclass(frozen=True) class ProtectedSpan: span_id: str text: str section_class: str # "active" | "deferred" | "archive" def validate_rewrite( before: Sequence[ProtectedSpan], after: Sequence[ProtectedSpan], context_len_after: int, max_position_delta: float = 0.35, independent_validator: bool = True, ) -> None: """ Enforce the split invariant: deletion is checked by span ID, displacement is checked by normalized rank position and section class. The displacement check must be run by an independent validator; if none is available, the caller must fall back to deletion-only compaction. """ before_by_id = {s.span_id: s for s in before} after_by_id = {s.span_id: s for s in after} missing = set(before_by_id) - set(after_by_id) if missing: raise ContextRewriteRejected( f"ProtectedSpanRemoved: {sorted(missing)} dropped by rewrite" ) if not independent_validator: # Deletion-only mode: reordering/reclassification is not permitted. for span_id, span in before_by_id.items(): if after_by_id[span_id].section_class != span.section_class: raise ContextRewriteRejected( f"ProtectedSpanReclassified: {span_id} moved to " f"{after_by_id[span_id].section_class} without independent validator" ) return for span_id, old in before_by_id.items(): new = after_by_id[span_id] old_pos = old_position_fraction(old, before, context_len_after) new_pos = new_position_fraction(new, after, context_len_after) if new_pos - old_pos > max_position_delta: raise ContextRewriteRejected( f"ProtectedSpanDisplaced: {span_id} moved from " f"{old_pos:.2f} to {new_pos:.2f} of context" ) if new.section_class in ("deferred", "archive") and old.section_class == "active": raise ContextRewriteRejected( f"ProtectedSpanDeferral: {span_id} reclassified active->{new.section_class}" ) def old_position_fraction(span, spans, context_len_after): idx = list(spans).index(span) return idx / max(len(spans), 1) def new_position_fraction(span, spans, context_len_after): idx = list(spans).index(span) char_estimate = sum(len(s.text) for s in spans[: idx + 1]) return char_estimate / max(context_len_after, 1) def commit_or_rollback(before, after, context_len_after, independent_validator): try: validate_rewrite(before, after, context_len_after, independent_validator=independent_validator) except ContextRewriteRejected as exc: return {"committed": False, "reason": str(exc)} return {"committed": True, "reason": None} ```