# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-an-optimistic-tool-invocation-before-the-speculative-branch-that-produced-it-is-merged.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-an-optimistic-tool-invocation-before-the-speculative-branch-that-produced-it-is-merged.warrant.json
# Markdown SHA-256:   d985b8bc959a8d0f5b6988b29bcfaf70c2250cb6b55324792786ecbf13ab91a8
# Code AST SHA-256:   c9611e0662369a6eef98921b105f3694cca82c2eeffe3b2560c396bbcd1c4daa
# Verified Classes:   Reversibility, RollbackBoundaryViolation, ToolContract, EffectRecord, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class Reversibility(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"
    UNDECLARED = "undeclared"  # treated as irreversible


class RollbackBoundaryViolation(RuntimeError):
    """Raised when a rejected branch has dispatched irreversible effects.

    The branch is past the rollback boundary: its task-tree node may not be
    discarded because the world already changed. The merge controller must
    reconcile instead.
    """


@dataclass
class ToolContract:
    name: str
    reversibility: Reversibility
    compensating_action: Optional[str] = None


@dataclass
class EffectRecord:
    tool: str
    branch_id: str
    dispatched: bool = True


@dataclass
class Branch:
    branch_id: str
    effect_log: list = field(default_factory=list)


def _is_irreversible(tool: str, registry: dict) -> bool:
    contract = registry.get(tool)
    if contract is None:
        return True  # undeclared tool: assume irreversible
    if contract.reversibility is Reversibility.REVERSIBLE:
        return contract.compensating_action is None  # reversible needs a teardown
    return True


def rollback_eligible(branch: Branch, registry: dict) -> bool:
    for rec in branch.effect_log:
        if rec.dispatched and _is_irreversible(rec.tool, registry):
            return False
    return True


def merge(selected: Branch, rejected: list, registry: dict) -> dict:
    """Merge the selected branch; reject the rest only if rollback-eligible."""
    inherited = []
    for branch in rejected:
        if not rollback_eligible(branch, registry):
            # Past the boundary: do NOT discard. Surface effects as obligations.
            for rec in branch.effect_log:
                if rec.dispatched and _is_irreversible(rec.tool, registry):
                    inherited.append(
                        {"tool": rec.tool, "from_branch": branch.branch_id}
                    )
            raise RollbackBoundaryViolation(
                f"branch {branch.branch_id} dispatched irreversible effects "
                f"{[r['tool'] for r in inherited]}; reconcile, do not discard"
            )
    return {"selected": selected.branch_id, "inherited_obligations": inherited}
