# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-a-rewrite-in-place-scratchpad-when-diff-based-context-mutation-invalidates-the-very-span-it-is-editing.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-a-rewrite-in-place-scratchpad-when-diff-based-context-mutation-invalidates-the-very-span-it-is-editing.warrant.json
# Markdown SHA-256:   9989edbafd610668adb9efe031b947882ed0beb32eee8c301b83257ba0c037c0
# Code AST SHA-256:   52f000ae39e91a594eb093923762661987098b58d9a0bb1a2034376109e4753e
# Verified Classes:   StaleDiffAnchorError, NonUniqueReanchorError, Scratchpad, Hunk
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StaleDiffAnchorError(RuntimeError):
    """Raised when a self-authored diff targets a scratchpad version that has since changed."""
    pass


class NonUniqueReanchorError(RuntimeError):
    """Raised when a hunk's surrounding context matches more than one location."""
    pass


@dataclass
class Scratchpad:
    lines: list[str] = field(default_factory=list)
    version: int = 0

    def snapshot_hash(self) -> str:
        return hashlib.sha256("\n".join(self.lines).encode()).hexdigest()

    def append(self, text: str) -> None:
        self.lines.extend(text.splitlines())
        self.version += 1


@dataclass
class Hunk:
    start: int          # 1-indexed line number in the pinned snapshot
    old_len: int
    replacement: list[str]
    pinned_version: int
    pinned_hash: str


def apply_hunk(pad: Scratchpad, hunk: Hunk, fuzz: bool = False) -> None:
    if pad.version != hunk.pinned_version:
        raise StaleDiffAnchorError(
            f"hunk pinned to v{hunk.pinned_version}, scratchpad is v{pad.version}; "
            f"anchor invalidated by interleaved mutation"
        )
    if pad.snapshot_hash() != hunk.pinned_hash:
        raise StaleDiffAnchorError(
            "content hash mismatch despite equal version counter; buffer mutated out of band"
        )

    idx = hunk.start - 1
    if idx < 0 or idx + hunk.old_len > len(pad.lines):
        raise StaleDiffAnchorError(
            f"hunk span [{hunk.start},{hunk.start + hunk.old_len}) exceeds buffer length {len(pad.lines)}"
        )

    if not fuzz:
        pad.lines[idx:idx + hunk.old_len] = hunk.replacement
        pad.version += 1
        return

    # Re-anchoring path: only permitted when the ±3-line context is unique.
    ctx_lo = max(0, idx - 3)
    ctx_hi = min(len(pad.lines), idx + hunk.old_len + 3)
    context = pad.lines[ctx_lo:ctx_hi]
    occurrences = sum(
        1 for i in range(len(pad.lines) - len(context) + 1)
        if pad.lines[i:i + len(context)] == context
    )
    if occurrences != 1:
        raise NonUniqueReanchorError(
            f"hunk context matches {occurrences} locations; re-anchor unsafe, reject-and-retry"
        )
    pad.lines[idx:idx + hunk.old_len] = hunk.replacement
    pad.version += 1


def self_edit_step(pad: Scratchpad, build_hunk) -> None:
    pinned_version = pad.version
    pinned_hash = pad.snapshot_hash()
    # Model reasons over the pinned snapshot and emits a hunk.
    hunk = build_hunk(pinned_version, pinned_hash)
    # A tool result arrives between read and apply, bumping the version.
    pad.append("[FACTS] retrieved: intermediate result")
    # Apply must now fail loudly rather than splice the wrong span.
    apply_hunk(pad, hunk)


if __name__ == "__main__":
    pad = Scratchpad(lines=["[GOAL] x", "[FACTS] a", "[DERIVATION] d1", "d2"], version=0)

    def stale_builder(v, h):
        return Hunk(start=3, old_len=2, replacement=["[DERIVATION] d1'", "d2'"],
                    pinned_version=v, pinned_hash=h)

    try:
        self_edit_step(pad, stale_builder)
    except StaleDiffAnchorError as e:
        print(f"bounded failure: {e}")
        # Correct recovery: re-read current buffer, re-emit hunk against v1.
