# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-verification-verdicts-after-speculative-branch-rollback-in-cost-aware-multi-agent-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-divergent-verification-verdicts-after-speculative-branch-rollback-in-cost-aware-multi-agent-pruning.warrant.json
# Markdown SHA-256:   ac9b36c8c43dc3795dbf5f11d5d043b425c0c9538199229f891232a97ac9c6d1
# Code AST SHA-256:   06cf67172b506cb599694bbfdd0f2a4423733098e4fb6f25dc8e3d53b4cbc21c
# Verified Classes:   RollbackClosureError, RollbackLedger, Commit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RollbackClosureError(RuntimeError):
    """Raised when a speculative commit is attempted against a pruned
    sibling whose rollback ledger is not closed or whose persisted
    effects intersect the commit's post-condition footprint."""


@dataclass
class RollbackLedger:
    branch_id: str
    reverted: set = field(default_factory=set)
    persisted: set = field(default_factory=set)
    non_revertible: set = field(default_factory=set)
    closed: bool = False

    def is_total(self) -> bool:
        return self.closed and not self.persisted and not self.non_revertible

    def footprint(self) -> set:
        return self.persisted | self.non_revertible


@dataclass
class Commit:
    branch_id: str
    postcondition_footprint: set


def reconcile_late_verdict(
    commit: Commit,
    pruned_ledger: RollbackLedger,
    late_verdict: Optional[str],
) -> str:
    """Decide how a late verdict for a rolled-back branch constrains a commit.

    Returns one of: 'discard', 'reverify', 'escalate'.
    Raises RollbackClosureError if the ledger is open and the orchestrator
    is about to make an unsound decision on incomplete information.
    """
    if not pruned_ledger.closed:
        raise RollbackClosureError(
            f"branch {pruned_ledger.branch_id}: rollback ledger not closed; "
            f"cannot adjudicate late verdict {late_verdict!r} against "
            f"commit {commit.branch_id}"
        )

    overlap = pruned_ledger.footprint() & commit.postcondition_footprint

    if pruned_ledger.non_revertible:
        # Branch was never prunable; its terminal verdict must gate the commit.
        return "escalate"

    if overlap:
        # Late FAIL (or any verdict) concerns a live effect touching the commit.
        return "reverify"

    if late_verdict == "FAIL" and pruned_ledger.is_total():
        # True counterfactual: clean rollback, disjoint footprint.
        return "discard"

    return "discard"


def commit_speculative(
    commit: Commit,
    pruned_ledgers: list[RollbackLedger],
    late_verdicts: dict[str, str],
) -> str:
    for ledger in pruned_ledgers:
        verdict = late_verdicts.get(ledger.branch_id)
        decision = reconcile_late_verdict(commit, ledger, verdict)
        if decision == "escalate":
            raise RollbackClosureError(
                f"branch {ledger.branch_id} invoked non-revertible tools "
                f"{sorted(ledger.non_revertible)}; commit {commit.branch_id} "
                f"cannot proceed without explicit accepted_risk waiver"
            )
        if decision == "reverify":
            raise RollbackClosureError(
                f"branch {ledger.branch_id} persisted effects "
                f"{sorted(ledger.footprint() & commit.postcondition_footprint)} "
                f"overlap commit {commit.branch_id} post-conditions; "
                f"re-verification required before commit"
            )
    return "committed"
