# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-rollback-of-a-speculative-agent-branch-after-a-side-effecting-tool-call-has-been-acknowledged-by-an-external.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-rollback-of-a-speculative-agent-branch-after-a-side-effecting-tool-call-has-been-acknowledged-by-an-external.warrant.json
# Markdown SHA-256:   28e0dcc47b617a7df9df16d71073a45cfb06fe49018f7d28309683835cac9247
# Code AST SHA-256:   68b1ba371de763924328129c1bedcd163852cb0ae136a4527fbb85e169775415
# Verified Classes:   RollbackRefusedError, EffectState, BranchState, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class RollbackRefusedError(RuntimeError):
    """Raised when rollback is attempted on a branch whose external effects
    are not proven absent and not proven compensated."""


class EffectState(Enum):
    NOT_COMMITTED = "not_committed"   # proven no external effect
    CONFIRMED = "confirmed"           # effect exists, handle known
    UNKNOWN = "unknown"               # ambiguous ack; cannot prove either way


class BranchState(Enum):
    SPECULATING = "speculating"
    WINNER = "winner"
    ABORTED = "aborted"
    QUARANTINED = "quarantined"


@dataclass
class Branch:
    branch_id: str
    intent_key: str
    state: BranchState = BranchState.SPECULATING
    effects: list[EffectState] = field(default_factory=list)
    compensation_verified: bool = False


def rollback_branch(branch: Branch) -> BranchState:
    """Roll back a losing speculative branch.

    Invariant: rollback is permitted only if every effect is NOT_COMMITTED,
    or if compensation has been *verified* by the orchestrator.
    """
    if branch.state is BranchState.WINNER:
        raise RollbackRefusedError(
            f"branch {branch.branch_id}: cannot roll back the selected winner"
        )

    for idx, effect in enumerate(branch.effects):
        if effect is EffectState.UNKNOWN:
            # The core boundary: ambiguous acknowledgment is not proof of
            # non-commit. Quarantine instead of rolling back.
            branch.state = BranchState.QUARANTINED
            raise RollbackRefusedError(
                f"branch {branch.branch_id}: effect[{idx}] is UNKNOWN; "
                f"refusing rollback, branch quarantined for reconciliation "
                f"under intent_key={branch.intent_key!r}"
            )
        if effect is EffectState.CONFIRMED and not branch.compensation_verified:
            branch.state = BranchState.QUARANTINED
            raise RollbackRefusedError(
                f"branch {branch.branch_id}: effect[{idx}] CONFIRMED with "
                f"unverified compensation; refusing rollback"
            )

    branch.state = BranchState.ABORTED
    return branch.state


def reconcile(branches: list[Branch], winner_id: str) -> dict[str, BranchState]:
    """Two-phase reconciliation: resolve UNKNOWN effects, then roll back losers."""
    # Phase 1: refuse to proceed while any branch has UNKNOWN effects.
    unresolved = [
        b.branch_id
        for b in branches
        if EffectState.UNKNOWN in b.effects and b.branch_id != winner_id
    ]
    if unresolved:
        raise RollbackRefusedError(
            f"reconciliation blocked: branches {unresolved} have UNKNOWN "
            f"effects; resolve via intent-key query before selecting a winner"
        )

    # Phase 2: roll back losers.
    result: dict[str, BranchState] = {}
    for b in branches:
        if b.branch_id == winner_id:
            b.state = BranchState.WINNER
            result[b.branch_id] = b.state
            continue
        result[b.branch_id] = rollback_branch(b)
    return result
