# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-plan-divergence-before-consensus-commit-in-a-decoding-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-plan-divergence-before-consensus-commit-in-a-decoding-swarm.warrant.json
# Markdown SHA-256:   65d8be4794b1d21f7a965822a435e45943838db892eebf16c11bb6695faeebd0
# Code AST SHA-256:   76871e36fc9f63c120461155ae26944f594376dfd78749d74b512e81abb028bd
# Verified Classes:   DivergentVoteError, VoteState, Draft, Vote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class DivergentVoteError(RuntimeError):
    """Raised when a vote cannot be bound to the draft's prefix/steps."""
    pass


class VoteState(Enum):
    BOUND = "bound"
    DIVERGED = "diverged"
    UNVERIFIABLE = "unverifiable"


@dataclass(frozen=True)
class Draft:
    draft_id: str
    prefix_hash: str
    steps_hash: str


@dataclass(frozen=True)
class Vote:
    draft_id: str
    verdict: str          # "accept" | "reject"
    local_prefix_hash: str
    local_steps_hash: str


def classify_vote(draft: Draft, vote: Vote) -> VoteState:
    if vote.draft_id != draft.draft_id:
        raise DivergentVoteError(
            f"vote references {vote.draft_id}, not {draft.draft_id}"
        )
    if not vote.local_prefix_hash or not vote.local_steps_hash:
        return VoteState.UNVERIFIABLE
    if vote.local_prefix_hash != draft.prefix_hash:
        return VoteState.DIVERGED
    if vote.local_steps_hash != draft.steps_hash:
        return VoteState.DIVERGED
    return VoteState.BOUND


def tally_quorum(draft: Draft, votes: list[Vote], quorum: int) -> str:
    bound_accepts = 0
    bound_total = 0
    for v in votes:
        state = classify_vote(draft, v)
        if state is VoteState.BOUND:
            bound_total += 1
            if v.verdict == "accept":
                bound_accepts += 1
    if bound_total < quorum:
        raise DivergentVoteError(
            f"admissible votes {bound_total} < quorum {quorum}; "
            f"re-propose with fresh prefix_hash"
        )
    return "commit" if bound_accepts >= quorum else "reject"
