# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-agent-branch-before-its-commit-token-is-durably-reconciled.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-agent-branch-before-its-commit-token-is-durably-reconciled.warrant.json
# Markdown SHA-256:   5d1e60860ee92a8bcd267afff3f3361a8b77060e875a7b2a88ff1976225cea03
# Code AST SHA-256:   3fb96b98d9b3f314c3840ea9b01fb7a22580d6e9911177e3ec1404e73d737afc
# Verified Classes:   OrphanedSpeculativeBranchError, IntentRecord, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class OrphanedSpeculativeBranchError(RuntimeError):
    """Raised when a losing branch's side effects cannot be verified as reversed."""
    pass


@dataclass
class IntentRecord:
    branch_id: str
    tool: str
    args_hash: str
    idempotency_key: Optional[str]
    reversible_handle: Optional[str]
    verified_reversed: bool = False


@dataclass
class Branch:
    branch_id: str
    intents: list = field(default_factory=list)
    status: str = "running"  # running | committed | rolled_back | orphaned


def reconcile_commit(winner: Branch, losers: list, external_verifier) -> Branch:
    """
    external_verifier(intent) -> bool  confirms the external surface reflects reversal.
    """
    for loser in losers:
        for intent in loser.intents:
            if intent.reversible_handle is None and intent.idempotency_key is None:
                loser.status = "orphaned"
                raise OrphanedSpeculativeBranchError(
                    f"branch {loser.branch_id} executed irreversible side effect "
                    f"{intent.tool} (args_hash={intent.args_hash}) with no idempotency key; "
                    f"cannot roll back or safely commit winner {winner.branch_id}"
                )
            if not external_verifier(intent):
                loser.status = "orphaned"
                raise OrphanedSpeculativeBranchError(
                    f"branch {loser.branch_id} rollback of {intent.tool} "
                    f"(handle={intent.reversible_handle}) unverified against external state; "
                    f"commit of {winner.branch_id} blocked pending manual reconciliation"
                )
            intent.verified_reversed = True
        loser.status = "rolled_back"

    winner.status = "committed"
    return winner


def detect_orphan_reentry(inbound_event, rolled_back_intents) -> bool:
    h = hashlib.sha256(inbound_event.payload.encode()).hexdigest()
    for intent in rolled_back_intents:
        if intent.args_hash == h:
            raise OrphanedSpeculativeBranchError(
                f"inbound event matches rolled-back intent {intent.tool} "
                f"from branch {intent.branch_id}; quarantine before routing to fresh instance"
            )
    return False
