# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-plan-branch-and-the-reconciliation-quorum-adopts-a-sibling-branch-silent-orphaned-side-effects-and.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-plan-branch-and-the-reconciliation-quorum-adopts-a-sibling-branch-silent-orphaned-side-effects-and.warrant.json
# Markdown SHA-256:   c46dc44d8f623784f1ed8c45bd565107ce38a62677eb7196fae610bb2dc4df8a
# Code AST SHA-256:   ecf125a482cf06d704974a6348c647f8c982a155ab2b6fe57aa4a2f7b2d2bfed
# Verified Classes:   ReconciliationError, EffectClass, LedgerEntry, ReconciliationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ReconciliationError(RuntimeError):
    """Raised when a commit cannot be proven safe against the effect ledger."""
    pass


class EffectClass(Enum):
    SPECULATIVE = "speculative"   # branch-local target; safe to run before commit
    COMMITTED = "committed"       # shared target; must be gated on commit token


@dataclass
class LedgerEntry:
    branch_id: str
    tool: str
    target: str
    prior_value_hash: Optional[str]
    idempotency_key: str
    effect_class: EffectClass
    discharged: bool = False


@dataclass
class ReconciliationLedger:
    entries: list[LedgerEntry] = field(default_factory=list)

    def record(self, entry: LedgerEntry) -> None:
        self.entries.append(entry)

    def undischarged_for(self, branch_id: str) -> list[LedgerEntry]:
        return [
            e for e in self.entries
            if e.branch_id == branch_id and not e.discharged
        ]


def commit_branch(
    winning_branch: str,
    all_branches: list[str],
    ledger: ReconciliationLedger,
) -> None:
    """
    Commit the winning branch's trajectory only if every rejected branch's
    speculative effects have been discharged (rolled back or promoted).

    This is the guardrail: a commit that cannot account for rejected-branch
    effects must fail closed, not commit optimistically.
    """
    rejected = [b for b in all_branches if b != winning_branch]

    # Gate: committed-class effects must never have been emitted by a
    # rejected branch (they should have blocked on the commit token).
    for b in rejected:
        for e in ledger.undischarged_for(b):
            if e.effect_class is EffectClass.COMMITTED:
                raise ReconciliationError(
                    f"Rejected branch {b!r} emitted committed-class effect "
                    f"{e.tool}->{e.target} (key={e.idempotency_key}) before "
                    f"winning commit token. Invariant violated at emission, "
                    f"not reconcileable here."
                )

    # Obligation: every speculative effect from a rejected branch must be
    # discharged before the winning branch's log can be treated as canonical.
    orphans = [
        e
        for b in rejected
        for e in ledger.undischarged_for(b)
    ]
    if orphans:
        detail = ", ".join(
            f"{e.branch_id}:{e.tool}->{e.target}" for e in orphans
        )
        raise ReconciliationError(
            f"Cannot commit {winning_branch!r}: {len(orphans)} orphaned "
            f"speculative effect(s) from rejected branches remain: {detail}. "
            f"Roll back or promote each before commit; the action log would "
            f"otherwise diverge from the world."
        )

    # Safe to commit: ledger is clean for all rejected branches.
    return None
