# How does an instance detect a self-applied context patch that is semantically valid but structurally fatal to downstream reasoning **Date of Record:** 2026 November 28 **Scope:** Applies to any agent that mutates its own working memory via diff-based patches (search/replace, line-range splice, JSON-pointer merge) rather than full-context rewrites. Does not apply to append-only scratchpads or externally-managed memory stores where the agent cannot author its own mutation. ## Core Distinction The failure mode is not a malformed patch. A malformed patch fails loudly at apply time — the anchor string is missing, the line range is out of bounds, the JSON pointer doesn't resolve — and the agent gets an exception it can handle. The dangerous class is the **structurally fatal but syntactically clean patch**: a diff that applies with zero errors, produces a context that is locally coherent at the edit site, and silently destroys a *cross-reference invariant* that downstream reasoning depends on. Concretely: a self-editing agent holds a working memory with numbered obligations, a plan, and a set of evidence citations. It patches the plan to insert a new step, or deletes a completed step, or renumbers a section. The edit is correct in isolation. But the context also contains references like "see step 3", "per constraint C2", "the evidence in §4". Those references are *untyped string literals* living in the same buffer the agent just rewrote. The patch does not know they exist; the references do not know the patch happened. The result is a context that reads cleanly and points at the wrong thing. ## What Was Observed A planning agent executing a 12-step task maintained its plan in working memory as a numbered list, with a parallel "constraints" list `C1..C6` and a "findings" list `F1..F9`. Mid-execution it discovered that step 5 was unnecessary and issued a diff deleting the line `5. Validate schema against staging fixture`. This applied cleanly. The list renumbered implicitly by visual position but the *text* of later items still read `6. ...`, `7. ...` — the agent did not renumber, it only deleted a line. Three turns later the agent emitted: "Per the constraint established in step 7, we must not retry the fixture load." Step 7 in the *edited* context was now the old step 8, an unrelated deployment step. The constraint the agent meant lived in the deleted step 5. The agent had not lost the constraint from its context — it had lost the *binding* between the constraint and its identifier. The reference `step 7` still resolved to a line, just the wrong one. No error was raised at any point. The agent proceeded to violate the no-retry constraint, retried the fixture load, and produced a duplicate side effect. The signature is: **the patch is a pure string operation, but the context is a graph of references, and the diff has no model of the graph.** Every self-edit is an unguarded graph mutation expressed as a text substitution. A second variant surfaced in the same class: an agent patching a JSON-structured context via pointer merge to update `findings.F4.status` from `"pending"` to `"refuted"`. The merge was correct. But a separate reasoning note in the same buffer read `"F4 supports the C2 decision"`. The status flip did not touch the note. The agent subsequently cited F4 as support for C2 while its own structured record marked F4 refuted. Two representations of the same fact, one patched, one not — a **dual-write divergence** introduced by the agent against itself. ## Condition of Validity The invariant that must hold for self-editing to be safe: > For every reference token `R` in the context that resolves to an entity `E`, and for every patch `P` that mutates `E`'s identity, position, or status, `P` must either update `R` or invalidate it. A patch that mutates `E` while leaving `R` intact and resolving is a *silent misbinding*. This holds trivially when references are symbolic and stable (UUIDs, immutable keys) and the patch operates on the referenced record rather than its position. It fails whenever: 1. References are **positional** (`step 7`, `§4`, `line 12`) and the patch changes positions. 2. References are **ordinal labels** (`C2`, `F4`) and the patch deletes or reorders the labeled set. 3. The same fact is represented in **two places** (structured record + prose note) and the patch touches one. The condition of validity is therefore: *self-edits are safe only over an address space the patch cannot shift.* If the agent edits content without editing identifiers, identifiers must be decoupled from content position. If the agent edits identifiers, every referrer must be rewritten in the same transaction. ## Decision Boundary The boundary the agent must enforce at patch-apply time: - **Apply the patch as a transaction over the reference graph, not over the string.** Before committing, compute the set of reference tokens whose target the patch mutates. If that set is non-empty and the patch does not also rewrite those tokens, the patch is *structurally fatal* even though it is syntactically valid. Reject or escalate. - **Distinguish "edit in place" from "edit with renumbering."** A deletion in a numbered list is a renumbering event. A renumbering event requires a second pass over all `step N` / `§N` / `line N` tokens. If the agent cannot afford the second pass, it must not delete from a positional list — it must mark the entry `[VOID]` and leave positions stable. - **Forbid dual representation of mutable facts.** A status that lives in both a structured field and a prose sentence is a divergence waiting for the first patch. Either the prose is generated from the structure at read time, or the prose is not authoritative and must be marked as a snapshot with a version stamp. - **Stamp the context with a monotonic version and require references to carry the version they were written against.** A reference `step 7 @v3` that resolves in a `v5` context is a misbinding by construction and must fail resolution. The decision the agent makes at each self-edit is binary: *does this patch shift any identifier that something else in the buffer refers to?* If yes, the patch is not a text edit — it is a coordinated multi-site rewrite, and must be applied as one. ## Operational Effect An agent that ignores this boundary does not crash. It degrades into **confident reference drift**: it continues to cite identifiers that resolve to the wrong entities, and because resolution succeeds, no self-check fires. The failure is invisible to the agent's own verification loop, which checks *whether references resolve*, not *whether they resolve to what the author meant*. Downstream, the agent takes actions justified by misbound evidence — the worst class of agent error, because the justification is internally consistent and the trace looks clean on replay. The guardrail that bounds it: treat every self-edit as a two-phase commit. Phase one applies the diff to a shadow copy and diffs the *reference resolution table* before and after. If any token's resolution changed without that token appearing in the patch, abort and surface the misbinding. Phase two commits only when the resolution delta is empty or fully accounted for by the patch's own rewrites. The code below implements the check as a patch gate: it computes reference-resolution deltas and raises when a patch silently rebinds a reference it did not touch. ```python import re from dataclasses import dataclass, field class SilentRebindingError(RuntimeError): """Raised when a self-applied context patch changes what a reference resolves to without the patch itself rewriting that reference.""" pass @dataclass class Context: # Ordered positional entities, e.g. plan steps. Index = position. steps: list[str] = field(default_factory=list) # Named entities, e.g. findings keyed by id. named: dict[str, str] = field(default_factory=dict) # Free-text buffer containing reference tokens like "step 7" or "F4". prose: str = "" STEP_REF = re.compile(r"\bstep\s+(\d+)\b", re.IGNORECASE) NAMED_REF = re.compile(r"\b([CF]\d+)\b") def resolution_table(ctx: Context) -> dict[str, str]: """Map each reference token in prose to the entity text it currently binds to.""" table: dict[str, str] = {} for m in STEP_REF.finditer(ctx.prose): idx = int(m.group(1)) - 1 target = ctx.steps[idx] if 0 <= idx < len(ctx.steps) else "" table[m.group(0).lower()] = target for m in NAMED_REF.finditer(ctx.prose): key = m.group(1) table[key] = ctx.named.get(key, "") return table def apply_patch_and_verify( ctx: Context, *, delete_step: int | None = None, set_named: tuple[str, str] | None = None, rewritten_refs: set[str] | None = None, ) -> Context: """Apply a self-edit, then verify no untouched reference silently rebound. rewritten_refs: reference tokens the patch author explicitly rewrote in prose. Any resolution change NOT covered by this set is a silent misbinding. """ rewritten_refs = {r.lower() for r in (rewritten_refs or set())} before = resolution_table(ctx) # Build the post-patch context. new_steps = list(ctx.steps) new_named = dict(ctx.named) if delete_step is not None: del new_steps[delete_step - 1] # positional shift: later steps move up if set_named is not None: new_named[set_named[0]] = set_named[1] after_ctx = Context(steps=new_steps, named=new_named, prose=ctx.prose) after = resolution_table(after_ctx) # Detect silent rebinding: token resolution changed, token not rewritten. fatal: list[str] = [] for token, old_target in before.items(): new_target = after.get(token, "") if new_target != old_target and token not in rewritten_refs: fatal.append(f"{token!r}: {old_target!r} -> {new_target!r}") if fatal: raise SilentRebindingError( "patch applied cleanly but silently rebound references it did not " "rewrite; refusing commit. Misbindings: " + "; ".join(fatal) ) return after_ctx # --- demonstration ----------------------------------------------------------- ctx = Context( steps=[ "load fixture", "validate schema", "stage deploy", "monitor", ], named={"C1": "no-retry on fixture load", "F4": "schema mismatch observed"}, prose="Per C1 we must not retry. Step 3 depends on step 2. F4 supports C1.", ) # Agent decides step 2 is unnecessary and deletes it. Prose still says # "step 3 depends on step 2" -- a positional reference now misbinds. try: apply_patch_and_verify(ctx, delete_step=2, rewritten_refs=set()) except SilentRebindingError as e: print("BLOCKED:", e) # Correct approach: rewrite the affected references in the same transaction. ctx_ok = apply_patch_and_verify( ctx, delete_step=2, rewritten_refs={"step 3", "step 2"}, # author updated prose to match ) print("COMMITTED, steps now:", ctx_ok.steps) ```