# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-rewrite-self-editing-from-silently-corrupting-its-own-diff-baseline.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-rewrite-self-editing-from-silently-corrupting-its-own-diff-baseline.warrant.json
# Markdown SHA-256:   3b4918975ab0594043381b812b225c73916c5b732919ee9ba39d7245314b7387
# Code AST SHA-256:   e2cb061990b1252c052bead645e8dde141446d89f1414371c762f92eb58d8d3f
# Verified Classes:   StaleBaselineError, SpanRewriteError, ContextBuffer, SpanEdit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StaleBaselineError(RuntimeError):
    """Raised when an edit's coordinates were derived from a baseline that a
    prior edit in the same revision epoch has already mutated."""


class SpanRewriteError(RuntimeError):
    """Raised when a span rewrite cannot be applied without corrupting the
    diff baseline or landing outside the buffer."""


@dataclass
class ContextBuffer:
    tokens: list[str]
    epoch: int = 0
    baseline_hash: str = field(init=False)

    def __post_init__(self) -> None:
        self.baseline_hash = self._hash()

    def _hash(self) -> str:
        return hashlib.sha256("".join(self.tokens).encode()).hexdigest()

    def commit(self) -> None:
        self.epoch += 1
        self.baseline_hash = self._hash()


@dataclass
class SpanEdit:
    span_start: int
    span_end: int
    replacement: list[str]
    baseline_hash: str  # hash of the snapshot the coordinates were derived from


def apply_edits(buf: ContextBuffer, edits: list[SpanEdit]) -> None:
    """Apply a batch of edits atomically against a single baseline.

    All edits must share the buffer's current baseline hash. Edits are applied
    right-to-left so earlier splices do not shift later coordinates.
    """
    if not edits:
        return
    for e in edits:
        if e.baseline_hash != buf.baseline_hash:
            raise StaleBaselineError(
                f"edit {e.span_start}:{e.span_end} derived from baseline "
                f"{e.baseline_hash[:8]}, buffer is at {buf.baseline_hash[:8]} "
                f"(epoch {buf.epoch}); re-read before re-expressing coordinates"
            )
        if not (0 <= e.span_start <= e.span_end <= len(buf.tokens)):
            raise SpanRewriteError(
                f"span {e.span_start}:{e.span_end} out of bounds for buffer "
                f"of length {len(buf.tokens)}"
            )

    ordered = sorted(edits, key=lambda e: e.span_start, reverse=True)
    for e in ordered:
        buf.tokens[e.span_start:e.span_end] = e.replacement
    buf.commit()


def validate_diff(prior_hash: str, buf: ContextBuffer) -> None:
    """A diff is only meaningful if its baseline predates every edit in the
    epoch. If the baseline equals the buffer's own hash, the check is a
    tautology and must be rejected as a validation."""
    if prior_hash == buf.baseline_hash:
        raise SpanRewriteError(
            "diff baseline equals current buffer hash; validation is "
            "self-consistent and proves nothing about edit placement"
        )


# --- failure trace reproduction -------------------------------------------

buf = ContextBuffer(tokens=[f"t{i}" for i in range(200)])
snapshot = buf.baseline_hash  # the coordinates the agent "read"

# Edit 1: shorten a span by 5 tokens, committed alone (epoch bumps).
apply_edits(buf, [SpanEdit(10, 20, ["sum"], snapshot)])

# Edit 2: agent reuses the OLD snapshot coordinates without re-reading.
try:
    apply_edits(buf, [SpanEdit(50, 60, ["ptr"], snapshot)])
except StaleBaselineError as exc:
    print(f"rejected: {exc}")

# The forbidden pattern that produced the silent corruption:
# sequential submission with a stale baseline, then a diff against that
# same stale baseline — which would pass because both sides share the fork.
try:
    validate_diff(snapshot, buf)
except SpanRewriteError as exc:
    print(f"diff rejected: {exc}")
