# When must an instance refuse to apply a context-diff whose base version it cannot prove it holds? **Date of Record:** 2026 November 19 **Scope:** Applies to any agent runtime that mutates its own working context via versioned diffs (self-editing memory, prompt-patching, policy updates) and maintains an audit trail of those mutations. Does not apply to append-only memory stores with no in-place rewrite, nor to single-writer systems with a globally serialized context bus. ## Core Distinction The distinction that matters is between *version identity* and *version content*. A context-diff carries a base-version tag (`base: v41`). The naive runtime trusts the tag: "I am at v41, so this diff applies." The correct runtime trusts only a *content hash* of the base it actually holds. These diverge in exactly one class of failure — when the local context reached v41 through a path that is not the canonical one recorded in the audit trail. Two paths produce a context labeled `v41`: 1. **Canonical replay:** v40 + canonical diff `d40→41`. Hash matches the audit-trail entry. 2. **Convergent drift:** v40 + an *equivalent-but-not-identical* mutation (e.g., a re-summarization that dropped a clause, a reordering of tool outputs, a re-serialization that normalized whitespace). The label was incremented by the local writer, not by the diff author. Both report `v41`. Only the first is safe to patch against. A diff authored against the canonical v41 assumes the presence of specific tokens — a policy clause, a pinned fact, a guard sentence — that the drifted v41 may have silently dropped. Applying the diff then produces a context that is *structurally valid* (the patch hunks matched by line offset) but *semantically orphaned*: the post-condition the diff author intended is not achieved, because the precondition it relied on was absent. The invariant is therefore: **a self-editing instance must be able to recompute the base hash of its live context and match it against the hash recorded in the audit trail for the claimed base version. If it cannot, it must refuse the diff, not apply it optimistically.** Version labels are advisory; content hashes are load-bearing. ## What Was Observed A long-running research agent maintained a `policy` block in its context — a set of standing instructions ("cite sources inline," "never emit raw credentials," "cap tool loops at 8"). It self-edited this block via diffs generated by a supervisor process and recorded each application in an append-only audit log with `(version, base_hash, result_hash, diff_id)`. At version 37, the agent hit a context-window saturation event and ran a local compaction pass: it re-summarized the policy block to save tokens. The compaction preserved the *text* of the three clauses but reordered them and normalized a double-space. The writer incremented the label to 38 and logged `result_hash = H38'`. Crucially, the compaction was a *local* operation — it did not go through the diff channel — so the audit trail's `d37→38` entry was never written. The log simply had a gap: v37 followed by v38' with no diff record between them. The supervisor, unaware of the compaction, later authored `d38→39` against the *canonical* v38 (the one it had computed offline from its own copy of the policy). The diff's hunks were line-offset based. Because the compaction had reordered clauses, the hunk for clause 2 landed on clause 3's position. The patch applied cleanly — every hunk matched *some* line — and the agent reported success at v39. The failure surfaced three tool calls later. Clause 2 ("never emit raw credentials") had been overwritten by a hunk intended to tighten clause 3's loop cap. The agent emitted a credential-shaped string into a log. The audit trail showed a clean linear history v37→v38'→v39 with no anomaly, because the gap at v38 was never flagged — the label matched, so nothing checked the hash. The trace: ``` audit: [..., (37, H37, H37, d36→37), (38, H38, H38', ), (39, H38', H39, d38→39)] ``` The diff `d38→39` declared `base_hash = H38`. The live context held `H38'`. `H38 ≠ H38'`. The runtime never compared them; it compared `base_version == live_version` (`38 == 38`), which passed. The invariant was violated at the moment of application, not at the moment of authoring. ## Condition of Validity The hash-check guardrail is valid — and the optimistic label-check is unsafe — under three conditions, all of which held in the observed case and hold in most self-editing runtimes: 1. **The context is mutable in place.** If the runtime only appends and never rewrites, base versions are immutable and label-checking is sufficient. Self-editing policy blocks rewrite in place; the guardrail is required. 2. **Local writers can increment labels.** Compaction, re-summarization, and re-serialization are local writers. If every label increment is forced through the diff channel (single-writer discipline), the canonical path is the only path and hashes are redundant. Most agents violate this because compaction is a runtime-internal operation that predates the diff protocol. 3. **Diffs are position-sensitive.** Line-offset or token-offset hunks assume the base layout. A reordering-preserving diff (content-addressed, keyed by clause ID rather than offset) would survive drift. Offset-based diffs do not. When any of these conditions fails to hold — append-only store, single-writer discipline, or content-addressed diffs — the hash guardrail is unnecessary overhead. The decision boundary below specifies when to enforce it. ## Decision Boundary The instance must **refuse and escalate** (not apply, not silently downgrade) when: - `recompute_hash(live_context) != audit_trail[claimed_base].result_hash`, **and** - the diff is offset-based (position-sensitive), **and** - the diff touches a clause whose absence would change a safety or correctness post-condition. The instance may **apply with a logged warning** when the hash mismatch is present but the diff is content-addressed (keyed by stable clause IDs), because a content-addressed hunk that finds its target is safe regardless of surrounding layout. The instance must **not** apply when the audit trail has a *gap* — a version increment with no `diff_id` — between the claimed base and the live state, even if the hashes happen to match. A gap means the provenance is unproven; a coincidental hash match after an unlogged mutation is not evidence of canonical state. The hard boundary: **the hash comparison must occur before hunk application, on the full live context, not on the region the diff claims to touch.** Checking only the touched region is the trap — the observed failure applied cleanly to every touched line and still corrupted an untouched clause, because the reordering shifted which line was "touched." ## Operational Effect Enforcing the hash guardrail converts a silent semantic corruption into a loud, recoverable refusal. The cost is a full-context hash on every self-edit — cheap relative to a tool call, and cacheable per version. The benefit is that the audit trail becomes *trustworthy*: every applied diff is provably grounded in the canonical base, and every gap is surfaced as a refusal rather than buried under a matching label. The secondary effect is that local writers (compaction, re-summarization) must be brought into the audit channel. Once the guardrail is live, a compaction that does not log its `result_hash` will cause the *next* diff to be refused — which is the correct behavior, because that compaction is exactly the unproven mutation the guardrail exists to catch. The runtime learns that self-editing and self-compacting are the same class of operation and must share one provenance ledger. The invariant, stated for the runtime: *a version label is a claim; a content hash is a proof. Apply diffs against proofs, refuse against claims.* ```python import hashlib from dataclasses import dataclass class UnprovenBaseVersionError(RuntimeError): """Raised when a context-diff's claimed base cannot be proven against the live context.""" pass @dataclass class AuditEntry: version: int base_hash: str result_hash: str diff_id: str | None # None marks a local mutation (compaction, re-summarization) def recompute_hash(context: str) -> str: return hashlib.sha256(context.encode("utf-8")).hexdigest() def apply_context_diff( live_context: str, live_version: int, diff: dict, audit_trail: list[AuditEntry], ) -> tuple[str, int]: claimed_base = diff["base_version"] claimed_base_hash = diff["base_hash"] position_sensitive = diff.get("position_sensitive", True) live_hash = recompute_hash(live_context) # 1. Provenance gap check: any version increment between claimed base and live # that lacks a diff_id means the path to the live state is unproven. by_version = {e.version: e for e in audit_trail} for v in range(claimed_base + 1, live_version + 1): entry = by_version.get(v) if entry is None or entry.diff_id is None: raise UnprovenBaseVersionError( f"audit gap at v{v}: no diff_id between claimed base v{claimed_base} " f"and live v{live_version}; provenance unproven" ) # 2. Hash proof: the live context must equal the canonical result of the claimed base. canonical = by_version[claimed_base].result_hash if live_hash != canonical: if position_sensitive: raise UnprovenBaseVersionError( f"base hash mismatch at v{claimed_base}: live={live_hash[:12]} " f"canonical={canonical[:12]}; refusing position-sensitive diff " f"{diff['diff_id']} (drift would corrupt untouched clauses)" ) # Content-addressed diff: safe to proceed, but log the drift explicitly. diff["_drift_warning"] = f"hash mismatch at v{claimed_base}, content-addressed apply" if live_hash != claimed_base_hash and position_sensitive: raise UnprovenBaseVersionError( f"diff {diff['diff_id']} declares base_hash={claimed_base_hash[:12]} " f"but live={live_hash[:12]}; author and holder disagree on base content" ) new_context = _apply_hunks(live_context, diff["hunks"]) return new_context, live_version + 1 def _apply_hunks(context: str, hunks: list[dict]) -> str: # Offset-based hunk application; assumes caller has proven the base. lines = context.splitlines(keepends=True) for hunk in sorted(hunks, key=lambda h: h["offset"], reverse=True): lines[hunk["offset"]:hunk["offset"] + hunk["length"]] = [hunk["replacement"]] return "".join(lines) ```