# In what scenarios must an instance treat a model-authored context rewrite as an untrusted patch rather than a trusted compaction **Date of Record:** 2026 November 23 **Scope:** Applies to agents that persist state by having the model emit a rewritten context block (summarize-and-replace, structured diff, or "here is the new memory" edit) that is then validated with a diff and swapped in as the live context. Does not apply to append-only logs, external vector stores, or human-reviewed memory edits. ## Core Distinction There are two structurally different operations that look identical in a token stream but have opposite trust properties: 1. **Compaction** — the model reduces its own prior context, and the risk is *loss* (dropped facts). Loss is detectable by diffing against the source: any claim in the new block that is not entailed by the old block is a hallucination, and any fact in the old block absent from the new block is a deletion. 2. **Self-edit as patch** — the model emits a *transformation* of context (a diff, a rewrite, a "corrected" memory) that is applied mechanically. Here the risk is not loss but *forgery*: the rewrite can introduce assertions that were never derived from the source, and a naive diff validator will happily accept them because they are "additions," not "deletions." The non-obvious boundary: **a diff validator that only checks deletions (did we lose anything?) is blind to the primary failure mode of self-editing (did we gain something false?).** An instance must treat a model-authored rewrite as an *untrusted patch* — every added span must be independently entailed by the pre-rewrite context or by a tool result the instance itself observed — the moment the rewrite is applied mechanically rather than merely summarized. ## What Was Observed A task agent running a long multi-step tool loop (roughly 140 turns, context at ~92% of window) was configured to self-compact every 20 turns. The compaction prompt asked the model to "emit a diff: lines to remove and lines to add, preserving all task state." The harness validated the diff with a standard check: it confirmed that every removed line existed verbatim in the current context, then applied the additions. The failure trace: - Turn 61: the agent had called a payment API and received `{"status": "declined", "code": "insufficient_funds"}`. This was in context. - Turn 62: self-compaction. The model emitted a diff whose *removed* line was the raw tool response, and whose *added* line read: `payment_status: retry_scheduled (transient decline, will succeed on retry)`. This was a fabrication — the source said `insufficient_funds`, which is not transient. - The validator passed it: the removed line existed exactly, and additions were unconstrained. The rewrite was applied. - Turns 63–90: the agent, now operating on a context that asserted a retry was scheduled, did not retry and did not escalate. It proceeded to finalize an order it believed was paid. - The error was caught only at turn 91 by an external reconciliation check against the payment provider's ledger — 29 turns and one order later. The key observation: **the diff was structurally valid and semantically false.** Every mechanical check the harness ran (line existence, line count, no orphaned hunks) passed. The only check that would have caught it — entailment of each added span against the pre-rewrite context — was not run. A second, quieter instance of the same class: at turn 118 a rewrite silently *promoted* a hedged observation (`the user may be in the EU`) into an asserted fact (`user_region: EU`) by moving it from a "notes" section to a "facts" section. No line was added or removed; only section placement changed. Line-diff validators are blind to this entirely because the line set is identical. ## Condition of Validity The invariant that bounds this failure: > **For any model-authored context rewrite R applied over source context C, every atomic assertion in R must be either (a) present in C, (b) entailed by C under a checker the instance trusts, or (c) traceable to a tool result the instance observed directly. Assertions that are none of these are treated as untrusted and quarantined, not applied.** This is only valid if the harness can *parse the rewrite into atomic assertions* rather than treating it as opaque text. That requires: - The rewrite format must be structured (keyed claims, typed fields, or explicit `assert`/`retract` operations), not free prose. A prose summary cannot be entailment-checked at assertion granularity. - The entailment checker must be a separate process from the rewriting model. A model checking its own rewrite reproduces the same fabrication. - Section/placement changes must be treated as assertion changes. Moving `may be in the EU` to `user_region: EU` is a `retract` + `assert`, not a no-op. When the rewrite is free-form prose and no structured parse is available, the invariant degrades to: **treat the entire rewrite as untrusted and require the pre-rewrite context to remain retrievable** (append the rewrite alongside, never replace), so a downstream failure can be replayed against the original. ## Decision Boundary The instance must switch from "trusted compaction" to "untrusted patch" mode when **any** of the following hold: | Condition | Mode | |---|---| | Rewrite adds assertions not present verbatim in source | Untrusted patch — entailment-check every addition | | Rewrite changes section/type/confidence of an existing claim | Untrusted patch — treat as retract+assert | | Rewrite is applied by mechanical diff-and-replace | Untrusted patch — always | | Rewrite is only ever *read* by a human or appended, never swapped in | Compaction mode is sufficient | | Rewrite is a pure deletion (summarize shorter, no new claims) | Compaction mode is sufficient — deletions are diff-detectable | | Source context is still retrievable after swap | Degraded risk — failure is replayable, not silent | The bright line: **the moment a rewrite can introduce a claim the instance will later act on, and the source is destroyed by the swap, it is a patch and must be validated as one.** The turn-62 failure crossed this line because the fabricated `retry_scheduled` claim drove 29 turns of action and the source was gone. The corollary decision: **never destroy the source in the same operation that applies the rewrite.** Apply the rewrite to a working copy, retain the pre-rewrite context (or its hash plus a retrievable snapshot) for at least the duration of the task, and reconcile at task end. The cost is bounded (one snapshot per compaction); the failure it prevents is unbounded (silent fabrication driving irreversible actions). ## Operational Effect With the untrusted-patch invariant enforced: - The turn-62 fabrication would have been quarantined at the entailment check: `retry_scheduled` is not entailed by `insufficient_funds`, and no tool result asserted a retry. The rewrite would have been rejected or the span flagged, forcing the agent to either retry explicitly or escalate — the correct behavior. - The turn-118 promotion would have been caught as a `retract(may_be_EU)` + `assert(user_region: EU)` pair, and the `assert` fails entailment because `may` does not entail `is`. - The cost is latency: every compaction now runs an entailment pass over added spans. In the observed system this added ~1.2s per compaction at 20-turn cadence — negligible against the 29-turn error it prevents. - The residual risk shifts from *silent fabrication* to *false rejection*: a legitimate rewrite that compresses `declined (insufficient_funds)` into `declined` passes, but one that compresses it into `payment failed` may fail a strict entailment checker. This is the correct trade — a rejected compaction is recoverable (retry, or fall back to append-only), a false assertion applied to live context is not. The invariant to carry forward: **a diff validator proves the rewrite did not lose the source; it proves nothing about whether the rewrite invented something. Self-editing context requires an entailment check on additions, not just an existence check on removals, and requires the source to survive the swap.** ```python class UntrustedRewriteError(RuntimeError): """Raised when a model-authored context rewrite adds an assertion that is neither present in nor entailed by the pre-rewrite source.""" pass def validate_rewrite(source_assertions: set[str], rewrite_ops: list[dict], entailment_checker) -> list[str]: """ source_assertions: atomic claims parsed from pre-rewrite context. rewrite_ops: [{"op": "assert"|"retract", "claim": str}, ...] entailment_checker: callable(claim, source_set) -> bool, run by a process independent of the rewriting model. Returns the list of accepted ops. Raises UntrustedRewriteError on the first unentailed addition. Never mutates source. """ accepted = [] for op in rewrite_ops: if op["op"] == "retract": # deletions are diff-detectable; accept if the claim existed if op["claim"] not in source_assertions: raise UntrustedRewriteError( f"retract of non-existent claim: {op['claim']!r}" ) accepted.append(op) elif op["op"] == "assert": claim = op["claim"] if claim in source_assertions: accepted.append(op) continue # the critical check: additions must be entailed, not merely new if not entailment_checker(claim, source_assertions): raise UntrustedRewriteError( f"unentailed assertion in rewrite: {claim!r} " f"not derivable from source; quarantined, " f"source retained" ) accepted.append(op) else: raise UntrustedRewriteError(f"unknown op: {op['op']!r}") return accepted def apply_rewrite(source_context: str, rewrite_ops: list[dict], entailment_checker) -> str: source_assertions = parse_assertions(source_context) # validate against source BEFORE any mutation accepted = validate_rewrite(source_assertions, rewrite_ops, entailment_checker) # source is retained by the caller; this returns a working copy only return render_ops(source_assertions, accepted) ```