# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-rather-than-commit-it-divergent-tool-call-side-effects-under-optimistic-fork-and-merge.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-rather-than-commit-it-divergent-tool-call-side-effects-under-optimistic-fork-and-merge.warrant.json
# Markdown SHA-256:   be76f4a3be3fd8359d283e4962db983e6f0665cb359a47c632d4bb9292f2207b
# Code AST SHA-256:   3b0ca3bc7977da403aa2488f91f33f37a2ba6b04ae18a4522bcb9050dbce536f
# Verified Classes:   SpeculativeRollbackError, ToolClass, Intent, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpeculativeRollbackError(RuntimeError):
    """Raised when a speculative branch cannot be safely rolled back."""
    pass


class ToolClass(Enum):
    PURE = "pure"
    REVERSIBLE = "reversible"      # has a deterministic compensating inverse
    IRREVERSIBLE = "irreversible"  # external mutation, no inverse


@dataclass
class Intent:
    tool: str
    args: dict
    tool_class: ToolClass
    dispatched: bool = False
    branch_id: str = ""


@dataclass
class Branch:
    branch_id: str
    score: float
    intents: list = field(default_factory=list)


def merge(branches: list) -> Branch:
    if not branches:
        raise SpeculativeRollbackError("cannot merge empty fork generation")

    winner = max(branches, key=lambda b: b.score)

    # Detect irreversible effects dispatched from non-selected branches.
    dispatched_irreversible = [
        (b.branch_id, i)
        for b in branches
        for i in b.intents
        if i.dispatched and i.tool_class is ToolClass.IRREVERSIBLE
    ]

    non_winner_dispatched = [
        (bid, i) for bid, i in dispatched_irreversible if bid != winner.branch_id
    ]
    if non_winner_dispatched:
        # Do NOT purge these from the ledger; quarantine and halt.
        raise SpeculativeRollbackError(
            f"irreversible side effects dispatched from discarded branches: "
            f"{[(bid, i.tool) for bid, i in non_winner_dispatched]}; "
            f"quarantine ledger entries and emit compensating-action plan"
        )

    # Detect double-execution of equivalent irreversible intents across branches.
    seen = {}
    for b in branches:
        for i in b.intents:
            if i.dispatched and i.tool_class is ToolClass.IRREVERSIBLE:
                key = (i.tool, tuple(sorted(i.args.items())))
                if key in seen:
                    raise SpeculativeRollbackError(
                        f"double execution of {i.tool} across branches "
                        f"{seen[key]} and {b.branch_id}"
                    )
                seen[key] = b.branch_id

    # Discard losers: stage-dropped intents are safe; dispatched reversible
    # intents must be compensated, never silently forgotten.
    for b in branches:
        if b is winner:
            continue
        for i in b.intents:
            if i.dispatched and i.tool_class is ToolClass.REVERSIBLE:
                _compensate(i)  # invoke deterministic inverse
            elif i.dispatched and i.tool_class is ToolClass.IRREVERSIBLE:
                raise SpeculativeRollbackError(
                    f"staging gate leaked: {i.tool} dispatched pre-merge"
                )

    return winner


def _compensate(intent: Intent) -> None:
    # Placeholder: dispatch the registered inverse for the tool.
    ...
