# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-agent-quorum-accept-a-decision-that-a-single-honest-auditor-can-disprove.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-agent-quorum-accept-a-decision-that-a-single-honest-auditor-can-disprove.warrant.json
# Markdown SHA-256:   a20a41973d051d1fad03178182f46d86a696778525e4252c0a6d4e0474d100e2
# Code AST SHA-256:   d2aaf4abad37adb97c514032b9d64a4eb0d943fc465201ad442f6ebe2cc19b21
# Verified Classes:   QuorumSafetyViolation, Vote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class QuorumSafetyViolation(RuntimeError):
    """Raised when a quorum would commit on votes that are not evidence-bound
    or that span rounds/nonces, i.e. the equivocation-compatible regime."""


@dataclass(frozen=True)
class Vote:
    agent_id: str
    round_no: int
    nonce: str
    digest: str            # H(evidence_object) -- NOT H(prose)
    evidence: Optional[dict]  # canonical, machine-checkable; None = rationale-only
    signature_valid: bool


def count_toward_quorum(
    vote: Vote,
    expected_round: int,
    seen_nonces: set[str],
    own_context_sufficient: bool,
    own_evidence_digest: Optional[str],
) -> bool:
    if not vote.signature_valid:
        return False
    if vote.round_no != expected_round:
        raise QuorumSafetyViolation(
            f"stale-round vote from {vote.agent_id}: "
            f"round {vote.round_no} != {expected_round}"
        )
    if vote.nonce in seen_nonces:
        raise QuorumSafetyViolation(
            f"nonce replay from {vote.agent_id}: equivocation suspected"
        )
    if vote.evidence is None:
        raise QuorumSafetyViolation(
            f"rationale-only vote from {vote.agent_id}: "
            f"payload not bound to digest, cannot count"
        )
    if not own_context_sufficient or own_evidence_digest is None:
        # Honest-but-saturated: must abstain, never defer to rationale majority.
        raise QuorumSafetyViolation(
            f"verifier context insufficient to re-derive evidence for "
            f"{vote.agent_id}; abstain rather than count"
        )
    return vote.digest == own_evidence_digest


def commit_decision(votes: list[Vote], n: int, f: int, expected_round: int) -> str:
    threshold = 2 * f + 1
    seen: set[str] = set()
    counted = 0
    for v in votes:
        if count_toward_quorum(v, expected_round, seen, True, v.digest):
            seen.add(v.nonce)
            counted += 1
    if counted < threshold:
        raise QuorumSafetyViolation(
            f"only {counted}/{n} evidence-bound votes; threshold {threshold} not met"
        )
    return "COMMIT"
