# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-the-rollback-horizon-has-been-crossed-in-speculative-draft-verify-agent-branches.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-the-rollback-horizon-has-been-crossed-in-speculative-draft-verify-agent-branches.warrant.json
# Markdown SHA-256:   435c01eaae57e5854261604633b2bfa6bff54e819736690c8cd14c23010c62c5
# Code AST SHA-256:   8d1ffd1d19ba77c7e3115bdd7ecdb74caeb1ac324eaec03520ec18b91f9a78ac
# Verified Classes:   RollbackHorizonError, Verdict, ToolCall, DraftStep
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class RollbackHorizonError(RuntimeError):
    """Raised when a draft branch attempts an uncompensable call
    before the verifier has committed all preceding steps."""


class Verdict(Enum):
    PENDING = "pending"
    APPROVE = "approve"
    REJECT = "reject"


@dataclass(frozen=True)
class ToolCall:
    name: str
    compensable: bool
    compensation_idempotent: bool
    attempt_count: int = 1


@dataclass(frozen=True)
class DraftStep:
    call: ToolCall
    verdict: Verdict


def assert_within_rollback_horizon(
    pending_steps: list[DraftStep],
    next_call: ToolCall,
) -> None:
    """Enforce the rollback-horizon barrier before emitting next_call.

    Invariant: an uncompensable or non-idempotently-compensable call may
    only execute after every preceding step has been committed by the
    verifier. Otherwise the draft branch has crossed the rollback horizon
    and any subsequent REJECT is operationally meaningless.
    """
    uncompensable = not next_call.compensable
    non_idempotent_retry = (
        not next_call.compensation_idempotent and next_call.attempt_count > 1
    )

    if not (uncompensable or non_idempotent_retry):
        return

    uncommitted = [s for s in pending_steps if s.verdict is not Verdict.APPROVE]
    if uncommitted:
        raise RollbackHorizonError(
            f"refusing to emit {next_call.name!r} "
            f"(compensable={next_call.compensable}, "
            f"compensation_idempotent={next_call.compensation_idempotent}, "
            f"attempt_count={next_call.attempt_count}) "
            f"with {len(uncommitted)} uncommitted preceding step(s); "
            f"rollback horizon would be crossed before verifier verdict. "
            f"Offending steps: {[s.call.name for s in uncommitted]}"
        )


def rollback(pending_steps: list[DraftStep]) -> str:
    """Attempt rollback; report PARTIAL if any executed call was uncompensable."""
    partial = any(not s.call.compensable for s in pending_steps)
    # ... issue compensating calls for compensable steps ...
    if partial:
        return "PARTIAL_ROLLBACK"
    return "ROLLED_BACK"
