# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-tool-call-side-effects-when-a-branch-and-merge-task-graph-rolls-back-a-sibling-branch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-tool-call-side-effects-when-a-branch-and-merge-task-graph-rolls-back-a-sibling-branch.warrant.json
# Markdown SHA-256:   ea8b1dcb1c4b26de7a585185380040709078b3438a1183a11a64cf5cb462cf57
# Code AST SHA-256:   8cda53e0637995edcc92801a3ec9c231753e245d13700e00a9b18dc737a794fb
# Verified Classes:   EffectClass, ReconciliationGap, ToolDecl, LedgerEntry, Branch, MergeGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    PURE = "pure"          # no external effect; safe to speculate
    SANDBOXED = "sandboxed"  # external but isolated per branch; committed on merge
    EXTERNAL = "external"  # real shared-world mutation; needs inverse or staging


class ReconciliationGap(RuntimeError):
    """Raised when a rolled-back branch left an un-reconciled external effect."""
    pass


@dataclass
class ToolDecl:
    name: str
    effect: EffectClass
    inverse: Optional[str] = None  # name of inverse tool, if any


@dataclass
class LedgerEntry:
    branch_id: str
    tool: str
    effect: EffectClass
    inverse_applied: bool = False


@dataclass
class Branch:
    branch_id: str
    is_winner: bool = False


@dataclass
class MergeGate:
    tools: dict[str, ToolDecl]
    ledger: list[LedgerEntry] = field(default_factory=list)

    def record(self, branch_id: str, tool_name: str) -> None:
        decl = self.tools.get(tool_name)
        if decl is None:
            # An undeclared tool reachable from a speculative branch is itself
            # a violation: its effect class is unknown, so it cannot be assumed safe.
            raise ReconciliationGap(
                f"tool {tool_name!r} has no declared effect class; "
                f"cannot speculate branch {branch_id!r} through it"
            )
        self.ledger.append(LedgerEntry(branch_id, tool_name, decl.effect))

    def apply_inverse(self, entry: LedgerEntry) -> None:
        decl = self.tools[entry.tool]
        if decl.inverse is None:
            raise ReconciliationGap(
                f"branch {entry.branch_id!r} externalized {entry.tool!r} "
                f"with no declared inverse; effect cannot be rolled back"
            )
        # In a real system: invoke decl.inverse against the shared world here.
        entry.inverse_applied = True

    def audit_before_merge(self, branches: list[Branch]) -> None:
        winners = {b.branch_id for b in branches if b.is_winner}
        for entry in self.ledger:
            if entry.branch_id in winners:
                continue
            if entry.effect is EffectClass.PURE:
                continue
            if entry.effect is EffectClass.SANDBOXED:
                # Sandboxed effects never reached the shared world; dropping
                # the overlay is the rollback. Nothing to reconcile.
                continue
            if entry.effect is EffectClass.EXTERNAL:
                if not entry.inverse_applied:
                    self.apply_inverse(entry)
                if not entry.inverse_applied:
                    raise ReconciliationGap(
                        f"orphaned external effect from rolled-back branch "
                        f"{entry.branch_id!r}: tool {entry.tool!r} not reconciled; "
                        f"refusing merge"
                    )
        # Only now may the scheduler commit the merge and run winner downstream steps.


def run_merge(gate: MergeGate, branches: list[Branch]) -> None:
    gate.audit_before_merge(branches)
    # ... commit winner state, execute staged intents, proceed downstream ...
