# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-subgoal-rollback-as-unsafe-when-sibling-agents-have-already-committed-externally-observable-side.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-subgoal-rollback-as-unsafe-when-sibling-agents-have-already-committed-externally-observable-side.warrant.json
# Markdown SHA-256:   5ec4ed06871af298d926d4485d065a2b75012bc187a0bb17f10cf3b1c585298e
# Code AST SHA-256:   3f5c469392684545e1c284eb67695ac2ded3431662eb96d7db4e91bc5227d74d
# Verified Classes:   RollbackUnsafeError, ToolClass, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class RollbackUnsafeError(RuntimeError):
    """Raised when a speculative branch crosses the commit horizon before the gate resolves."""
    pass


class ToolClass(Enum):
    PRE_COMMIT_SAFE = "pre_commit_safe"
    HORIZON_CROSSING = "horizon_crossing"


@dataclass
class ToolCall:
    name: str
    tool_class: ToolClass
    branch_id: str
    idempotency_key: str  # MUST be branch-scoped for horizon-crossing tools
    committed: bool = False


def admit_speculative_branch(branch_id: str, planned_calls: list[ToolCall]) -> None:
    """Reject plans that place horizon-crossing tools inside a speculative fork
    without a branch-scoped idempotency key. Called at planning time, before fork."""
    for call in planned_calls:
        if call.tool_class is ToolClass.HORIZON_CROSSING:
            if call.idempotency_key is None or branch_id not in call.idempotency_key:
                raise RollbackUnsafeError(
                    f"branch {branch_id} plans horizon-crossing tool {call.name} "
                    f"without branch-scoped idempotency key; rollback cannot revoke it"
                )


def merge_gate(branch_results: dict[str, float], committed_calls: list[ToolCall]) -> str:
    """Promote the earliest passing branch; roll back the rest.
    Refuses to roll back any branch that already committed a horizon-crossing effect."""
    winner = min(branch_results, key=branch_results.get)
    for call in committed_calls:
        if call.committed and call.branch_id != winner:
            raise RollbackUnsafeError(
                f"cannot roll back branch {call.branch_id}: tool {call.name} "
                f"already committed before gate resolved (winner={winner})"
            )
    return winner
