# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-reconcile-a-speculative-branch-after-a-sibling-agent-has-already-committed-a-side-effectful-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-reconcile-a-speculative-branch-after-a-sibling-agent-has-already-committed-a-side-effectful-tool-call.warrant.json
# Markdown SHA-256:   3ee8e06f154cfd2808bd81cf347623b1f02a22d14f8df197763e1acf88129f3f
# Code AST SHA-256:   fd6f47fc7e2858fc8a876e105deba2697f01c4448801fb01b6dd685652c130c9
# Verified Classes:   ToolSafety, ToolCall, Branch, OrphanedEffectError, ReconciliationRefused
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ToolSafety(Enum):
    BUFFERED = "buffered"
    INTENT_IDEMPOTENT = "intent_idempotent"
    COMPENSABLE = "compensable"
    NON_COMPENSABLE = "non_compensable"


@dataclass
class ToolCall:
    tool: str
    intent_hash: str          # must be derived from (task_id, intent), NOT branch nonce
    safety: ToolSafety
    effect_handle: Optional[str] = None   # required for COMPENSABLE
    compensated: bool = False


@dataclass
class Branch:
    branch_id: str
    confidence: float
    calls: list[ToolCall] = field(default_factory=list)
    committed: bool = False


class OrphanedEffectError(RuntimeError):
    """A losing branch left a durable, non-compensable external effect."""


class ReconciliationRefused(RuntimeError):
    """Reconciliation cannot be defined; orchestrator must halt, not report success."""


def _is_intent_covered(call: ToolCall, winner: Branch) -> bool:
    # Two branches intending the same effect must collide on intent_hash.
    return any(
        w.tool == call.tool and w.intent_hash == call.intent_hash
        for w in winner.calls
    )


def reconcile(branches: list[Branch]) -> Branch:
    if not branches:
        raise ReconciliationRefused("no branches to reconcile")

    winner = max(branches, key=lambda b: b.confidence)
    winner.committed = True
    losers = [b for b in branches if b is not winner]

    orphans: list[ToolCall] = []
    for loser in losers:
        for call in loser.calls:
            if call.safety is ToolSafety.BUFFERED:
                continue
            if call.safety is ToolSafety.INTENT_IDEMPOTENT:
                if _is_intent_covered(call, winner):
                    continue  # deduped against winner's identical intent
                orphans.append(call)   # idempotent but divergent intent: needs compensation
                continue
            if call.safety is ToolSafety.COMPENSABLE:
                if call.effect_handle is None:
                    orphans.append(call)  # handle lost in dying context
                elif not call.compensated:
                    orphans.append(call)  # compensation not yet executed
                continue
            # NON_COMPENSABLE, unbuffered, non-idempotent
            orphans.append(call)

    if orphans:
        # Hard failure. Do NOT return winner. The committed model would diverge
        # from external state, and no surviving branch holds the handle to repair it.
        raise OrphanedEffectError(
            f"reconciliation refused: {len(orphans)} orphaned effect(s) from "
            f"losing branches: "
            + ", ".join(f"{c.tool}[{c.intent_hash[:8]}]" for c in orphans)
        )

    return winner


def run_speculative(branches: list[Branch]) -> Branch:
    # Pre-flight: a branch is only speculative if its whole tool surface is safe.
    for b in branches:
        for call in b.calls:
            if call.safety is ToolSafety.NON_COMPENSABLE:
                raise ReconciliationRefused(
                    f"branch {b.branch_id} reached non-compensable tool "
                    f"{call.tool}; it is a committed execution, not speculative"
                )
    return reconcile(branches)
