# How does an instance detect a phantom-hunk rebase when a diff-based context controller rewrites its own workspace mid-task **Date of Record:** 2026 November 27 **Scope:** Applies to agents that persist working state as a mutable on-disk workspace (files, plan YAML, scratchpad) and apply their own unified diffs against that workspace between reasoning steps. Does not apply to append-only memory logs, pure in-context scratchpads, or controllers that never re-read their own writes. ## Core Distinction A self-editing context controller is not a text editor that happens to be driven by an LLM. It is a **state transducer whose input (the current workspace) is mutated by its own prior output (the last applied diff)**. The failure mode is not "the diff failed to apply" — that is loud and recoverable. The failure mode is that the diff **applies successfully against a context window that no longer matches the bytes on disk**, producing a workspace that is internally consistent, passes every local check, and is silently wrong relative to the agent's own plan. The sharp mechanism: **unified-diff hunk headers carry line numbers, but the agent reasons about hunk *anchors* (the `@@ -a,b +c,d @@` context strings and the surrounding lines it remembers).** When a prior step's diff shifted line offsets, or when the controller's write-back reordered/reformatted the file (trailing newline normalization, formatter pass, CRLF→LF), the remembered anchor still "looks right" to the model but points at a different region. The patch engine — usually `patch`, `git apply`, or a hand-rolled applier — resolves the offset by fuzzy context matching and **succeeds against the wrong location**. This is a *phantom hunk*: a hunk that applied, reported success, and edited the wrong bytes. This is distinct from a merge conflict (which halts) and from context-window eviction (which the agent can detect by re-reading). It is a **continuity invariant violation between the agent's episodic memory of the file and the file's actual byte state**. ## What Was Observed A representative trace, compressed: 1. Step 4: agent reads `plan.yaml` (40 lines). It notes the anchor `- task: reconcile_inventory` at line 22 in its working memory. 2. Step 5: agent applies a diff that **inserts** 6 lines above line 22 (adds a `retry_policy:` block). The applier reports `applied hunk 1/1`. On disk, `reconcile_inventory` is now at line 28. The agent's memory still says 22. 3. Step 6: the controller runs a **normalization pass** — `yaml.dump` round-trip to canonicalize — which reorders two sibling keys and collapses a blank line. Net line count is now 39, and `reconcile_inventory` sits at line 27. 4. Step 7: agent emits a diff with hunk header `@@ -22,3 +22,4 @@` and context lines ` - task: reconcile_inventory` / ` status: pending`. The applier's fuzzy matcher finds the context string at line 27, **applies at offset +5**, and writes the new field into the correct semantic location. 5. Step 8: agent emits a *second* diff, still believing the file is 40 lines and the anchor is at 22, but now the inserted `retry_policy:` block from step 5 has a `max_attempts: 3` line that the agent's memory attributes to a *different* task. The hunk context ` max_attempts: 3` matches **two** locations. The applier picks the first. Wrong task edited. 6. Step 9: a validator runs. YAML parses. Schema validates. No duplicate keys. **All green.** The agent proceeds and the error compounds into downstream tool calls that read the corrupted task. The observable signature at step 8 is not an error. It is: **`applied hunk N/M` for a hunk whose `old_start` does not equal the anchor's true current line, with zero fuzz warnings.** Most appliers only emit fuzz warnings when context is *missing*, not when context is *ambiguous*. ## Condition of Validity The invariant that must hold for a diff-based controller to be safe is: > **For every hunk the agent emits, the agent's believed `(file_hash, anchor_line, context_span)` triple must equal the on-disk `(file_hash, anchor_line, context_span)` at apply time, or the apply must be rejected — not offset-corrected.** Concretely, a self-editing controller is only valid when all of the following hold between the agent's *last read* of a file and its *next write*: - **No unobserved mutation.** The controller itself must not run formatters, canonicalizers, or reorder passes between the agent's read and its write, *unless* it invalidates the agent's cached view (see guardrail below). The normalization pass in step 6 is the proximate cause of the offset drift. - **Anchor uniqueness.** Each hunk's context span must be unique within the file. If ` max_attempts: 3` appears twice, the anchor is not an anchor — it is a coin flip. - **Offset is not success.** A patch that applies at a nonzero offset is a *rebase*, not an *apply*. It must be surfaced as a distinct event (`offset=+5`), because the agent's line-number reasoning is now provably stale even if the bytes landed correctly. - **Hash continuity.** The applier must verify `sha256(pre_image) == agent.believed_hash`. If the controller normalized the file, the hash changed and the agent's diff is being applied to an image it never saw. The condition **does not** hold, and this failure is **not** in scope, when the workspace is append-only, when the agent re-reads the full file before every diff, or when the controller forbids fuzzy matching (`git apply --no-fuzz` semantics). Those configurations trade a different cost (context budget, latency) for the invariant. ## Decision Boundary The decision the controller must make on every apply is not "did the patch apply?" but **"is this apply a faithful continuation of the agent's last read?"** The boundary is crossed when *any* of these is true: | Signal | Meaning | Action | |---|---|---| | `pre_image_hash != believed_hash` | File changed since agent's read (self-normalization or peer agent) | **Reject.** Force re-read. | | `applied_offset != 0` | Anchor drifted; line reasoning stale | **Reject or flag.** Re-read the anchor region before the *next* hunk. | | `context_match_count > 1` | Anchor ambiguous | **Reject.** Hunk is a coin flip. | | `hunk_old_start != believed_anchor_line` | Agent's line model disagrees with disk | **Reject.** The belief is wrong even if bytes are right. | The subtle boundary: **a nonzero offset with a unique context match is the dangerous case**, because it *looks* like a benign rebase and the bytes are often semantically correct — until the second hunk that depends on the *shifted* line numbers, or until an ambiguous anchor appears downstream. The controller must treat offset ≠ 0 as a *belief invalidation event*, not a *success with a note*. The agent's line-number model must be discarded and rebuilt from a fresh read before any further hunks in that file. Equivalently: **never let one diff's successful offset silently authorize the next diff's line numbers.** The invariant is per-hunk, and the agent's cached view must be invalidated on the first offset, not on the first error. ## Operational Effect When the boundary is respected — hash continuity enforced, offset treated as invalidation, ambiguous anchors rejected — the observable effect is a **higher rejection rate and a re-read tax**, but the compounding-error class disappears: no step-N patch can write to a location the agent did not intend, because any drift between belief and disk halts the apply and forces resynchronization. The agent's "amnesia" about line numbers becomes harmless, because line numbers are never trusted across a write. When the boundary is violated — the common default of `git apply` with fuzz, or a controller that runs a formatter between steps without invalidating the agent's cache — the effect is **silent semantic corruption that passes every local validator**. The failure surfaces not at the patch but at a downstream tool call that reads the corrupted entry, often dozens of steps later, with a stack trace that points nowhere near the offending hunk. This is the operational signature: *green validators, wrong state, distant symptom*. The only reliable detector is the pre-image hash check and offset telemetry, not schema validation — because the corrupted workspace is still schema-valid. It is just not what the agent meant. The architectural consequence: **a self-editing controller must be a compare-and-swap, not a text editor.** The agent's read is the expected value; the diff is the swap; the pre-image hash is the compare. Any controller that skips the compare is running an unguarded write on the agent's own memory. ```python import hashlib from dataclasses import dataclass class PhantomHunkError(RuntimeError): """Raised when a diff would apply against a workspace image the agent never saw, or would resolve an anchor ambiguously / at a nonzero offset.""" @dataclass(frozen=True) class WorkspaceView: path: str content: str believed_hash: str # sha256 the agent computed at last read believed_anchor_line: int # line number the agent's reasoning assumes def _sha(s: str) -> str: return hashlib.sha256(s.encode("utf-8")).hexdigest() def apply_hunk(view: WorkspaceView, disk_content: str, hunk: dict) -> str: """Compare-and-swap apply. hunk = {old_start, context, replacement}.""" # 1. Hash continuity: the agent must be patching the image it read. if _sha(disk_content) != view.believed_hash: raise PhantomHunkError( f"{view.path}: pre-image hash mismatch — workspace mutated since read " f"(self-normalization or peer write); refusing offset-corrected apply" ) lines = disk_content.splitlines(keepends=True) ctx = hunk["context"] matches = [i for i, ln in enumerate(lines) if ln.rstrip("\n") == ctx] # 2. Anchor uniqueness: a context string that appears twice is a coin flip. if len(matches) > 1: raise PhantomHunkError( f"{view.path}: anchor {ctx!r} matched {len(matches)} locations — ambiguous hunk" ) if not matches: raise PhantomHunkError(f"{view.path}: anchor {ctx!r} not found") actual_line = matches[0] + 1 # 1-indexed # 3. Offset is invalidation, not success: line model is provably stale. if actual_line != view.believed_anchor_line or hunk["old_start"] != view.believed_anchor_line: raise PhantomHunkError( f"{view.path}: anchor drift — believed line {view.believed_anchor_line}, " f"disk line {actual_line}; agent must re-read before further hunks" ) out = lines[: matches[0]] + [hunk["replacement"] + "\n"] + lines[matches[0] + 1 :] return "".join(out) ```