# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-diff-rollback-invalidation-in-self-editing-context-agents-under-token-budget-pressure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-diff-rollback-invalidation-in-self-editing-context-agents-under-token-budget-pressure.warrant.json
# Markdown SHA-256:   e7bcac247ac69e2fa8a44205d098d147c0a1bf00e6fefdad4c46d3e2faa6b64f
# Code AST SHA-256:   4511d1f2d2039fd088bed5a74d6661ac99caf1933602f61e8973d7c6f7345f23
# Verified Classes:   RollbackInvariantViolation, Diff, Journal
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class RollbackInvariantViolation(RuntimeError):
    """Raised when a diff rollback would restore bytes but not decision ancestry."""
    pass


@dataclass
class Diff:
    span: tuple[int, int]
    inverse_patch: str
    semantic_delta_class: str  # "low" | "high"
    externalized: bool = False


@dataclass
class Journal:
    buffer: str
    stack: list[Diff] = field(default_factory=list)
    emitted_plans: list[tuple[str, str]] = field(default_factory=list)  # (plan, buffer_hash)

    def _hash(self, buf: str) -> str:
        return hashlib.sha256(buf.encode()).hexdigest()

    def apply(self, d: Diff, new_buffer: str) -> None:
        for prior in self.stack:
            a1, b1 = prior.span
            a2, b2 = d.span
            if not (b1 <= a2 or b2 <= a1):
                raise RollbackInvariantViolation(
                    f"overlapping diff spans {prior.span} and {d.span}; "
                    "rollback stack is no longer a disjoint LIFO"
                )
        self.stack.append(d)
        self.buffer = new_buffer

    def record_plan(self, plan: str) -> None:
        self.emitted_plans.append((plan, self._hash(self.buffer)))

    def rollback(self) -> str:
        if not self.stack:
            raise RollbackInvariantViolation("rollback on empty journal")
        d = self.stack.pop()
        if d.externalized:
            raise RollbackInvariantViolation(
                "cannot roll back: tool side effects escaped after edit; "
                "pre-edit buffer is stale by construction"
            )
        if d.semantic_delta_class == "high":
            raise RollbackInvariantViolation(
                "cannot roll back: load-bearing qualifier was dropped; "
                "require re-derivation from source, not journal restoration"
            )
        # restore bytes (inverse patch application elided for brevity)
        self.buffer = self._apply_inverse(d)
        restored_hash = self._hash(self.buffer)
        stale = [p for p, h in self.emitted_plans if h != restored_hash]
        if stale:
            raise RollbackInvariantViolation(
                f"{len(stale)} plan(s) derived from rolled-back state; "
                "buffer restored but decision ancestry diverged — force re-derivation"
            )
        return self.buffer

    def _apply_inverse(self, d: Diff) -> str:
        return self.buffer  # placeholder for actual inverse patch application
