# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-when-parallel-agent-trajectories-commit-irreversible-external-side-effects-before-the-merge.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-merges-when-parallel-agent-trajectories-commit-irreversible-external-side-effects-before-the-merge.warrant.json
# Markdown SHA-256:   f02d22ff3bce0ed56b475bc28bb3d0b40eb900cf60492d1bcd723000b85a8eac
# Code AST SHA-256:   5ae2919ecd17adf19ce071a72ff5618b8b5f7807590441bf90320f409b2d921b
# Verified Classes:   EffectClass, SpeculativeMergeViolation, BranchState, Branch, ToolCallGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    MEMBRANED = "membraned"
    IRREVERSIBLE_EXTERNAL = "irreversible_external"


class SpeculativeMergeViolation(RuntimeError):
    """Raised when a discardable branch has already applied an irreversible external effect."""


class BranchState(Enum):
    SPECULATIVE = "speculative"
    PINNED = "pinned"
    COMMITTED = "committed"
    DISCARDED = "discarded"


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.SPECULATIVE
    applied_effects: list[str] = field(default_factory=list)


@dataclass
class ToolCallGate:
    """Gate every tool invocation from a speculative branch.

    The gate enforces: a branch may invoke an IRREVERSIBLE_EXTERNAL tool only if
    doing so immediately pins the branch (removing it from the discardable set).
    """
    classify: Callable[[str], EffectClass]

    def invoke(self, branch: Branch, tool_name: str, effect_id: str) -> None:
        if branch.state is BranchState.DISCARDED:
            raise SpeculativeMergeViolation(
                f"branch {branch.branch_id} is discarded; cannot invoke {tool_name}"
            )
        effect_class = self.classify(tool_name)
        if effect_class is EffectClass.IRREVERSIBLE_EXTERNAL:
            if branch.state is BranchState.SPECULATIVE:
                # Crossing the boundary: pin the branch so the merge cannot discard it.
                branch.state = BranchState.PINNED
            branch.applied_effects.append(effect_id)
            return
        # Membraned effect: buffered, safe to discard.
        branch.applied_effects.append(effect_id)


def merge(branches: list[Branch], preferred_id: str) -> list[Branch]:
    """Merge barrier: commit the preferred branch, discard the rest.

    Raises if any branch to be discarded has applied an irreversible external effect
    while still marked SPECULATIVE (i.e., the gate was bypassed).
    """
    committed: list[Branch] = []
    for b in branches:
        if b.branch_id == preferred_id:
            b.state = BranchState.COMMITTED
            committed.append(b)
            continue
        if b.state is BranchState.PINNED:
            # Pinned branches cannot be discarded silently; they must be reconciled.
            raise SpeculativeMergeViolation(
                f"branch {b.branch_id} is pinned with applied effects "
                f"{b.applied_effects}; merge must reconcile, not discard"
            )
        if b.state is BranchState.SPECULATIVE and b.applied_effects:
            # Defensive: a membraned branch should have no applied effects here.
            raise SpeculativeMergeViolation(
                f"branch {b.branch_id} discarded with applied effects "
                f"{b.applied_effects}; effect-ledger reconciliation required"
            )
        b.state = BranchState.DISCARDED
    return committed
