# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-branch-divergence-from-branch-corruption-at-a-speculative-multi-agent-consensus-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-branch-divergence-from-branch-corruption-at-a-speculative-multi-agent-consensus-checkpoint.warrant.json
# Markdown SHA-256:   e3d872b4ca806ab5669b8355de92926df3d3fc4e2f08e0e08386affefe1ba397
# Code AST SHA-256:   c83760d6f881bebbc56918e7b8751a3c3b476af1a19fe88597c20ed28f21b452
# Verified Classes:   CheckpointError, BranchVerdict, Branch, CheckpointDecision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class CheckpointError(RuntimeError):
    """Raised when a consensus checkpoint cannot soundly decide to commit or prune."""


class BranchVerdict(Enum):
    CLEAN = "clean"
    QUARANTINE = "quarantine"


@dataclass(frozen=True)
class Branch:
    branch_id: str
    output: str
    provenance_hash: str
    provenance_verified: bool
    upstream_cause: str | None  # shared defect tag, if any


@dataclass(frozen=True)
class CheckpointDecision:
    action: str  # "commit" | "escalate" | "rerun"
    committed_output: str | None
    quarantined: tuple[str, ...]


def classify_and_decide(
    branches: list[Branch],
    supermajority: int,
) -> CheckpointDecision:
    if not branches:
        raise CheckpointError("empty branch set: nothing to reconcile")

    unverified = [b for b in branches if not b.provenance_verified]
    if len(unverified) == len(branches):
        raise CheckpointError(
            "no branch has verified provenance; agreement is uninterpretable"
        )

    # Correlated dissent detection: group by upstream cause.
    cause_groups: dict[str, list[Branch]] = {}
    for b in branches:
        if b.upstream_cause is not None:
            cause_groups.setdefault(b.upstream_cause, []).append(b)

    quarantined: set[str] = set()
    for cause, group in cause_groups.items():
        if len(group) >= 2:
            # Two or more branches sharing an upstream defect are not
            # independent votes, regardless of whether they agree.
            quarantined.update(b.branch_id for b in group)

    clean = [b for b in branches if b.branch_id not in quarantined]

    if len(clean) < supermajority:
        # Cannot reach a sound supermajority on independent branches.
        return CheckpointDecision(
            action="escalate",
            committed_output=None,
            quarantined=tuple(sorted(quarantined)),
        )

    votes: dict[str, int] = {}
    for b in clean:
        votes[b.output] = votes.get(b.output, 0) + 1

    winner, count = max(votes.items(), key=lambda kv: kv[1])

    if count < supermajority:
        # Independent but split: divergence, not corruption. Do not prune.
        return CheckpointDecision(
            action="escalate",
            committed_output=None,
            quarantined=tuple(sorted(quarantined)),
        )

    if len(votes) > 1:
        # Minority exists among clean branches: preserve as signal, but the
        # supermajority is sound only if the minority is uncorrelated.
        minority = [b for b in clean if b.output != winner]
        if len({b.upstream_cause for b in minority}) < len(minority):
            raise CheckpointError(
                "minority branches share an upstream cause but were not "
                "quarantined; provenance tagging is inconsistent"
            )

    return CheckpointDecision(
        action="commit",
        committed_output=winner,
        quarantined=tuple(sorted(quarantined)),
    )
