# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-plan-commitments-when-bft-quorum-certificates-and-llm-self-reports-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-plan-commitments-when-bft-quorum-certificates-and-llm-self-reports-disagree.warrant.json
# Markdown SHA-256:   cd42732af4ef74bb5f3165bacb92d9b40b601d45dd8bcf1193bd89081c6fd629
# Code AST SHA-256:   98689fa13aa0e5ff8277a819def932bbd2d3f1b17c5073aa65824d4a7c4d4968
# Verified Classes:   EquivocationDetected, SignedVote, QuorumCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Tuple, Optional


class EquivocationDetected(RuntimeError):
    """Raised when a signer appears with conflicting values across QCs or attestations."""
    pass


@dataclass(frozen=True)
class SignedVote:
    signer: str
    value: str
    view: int
    height: int


@dataclass(frozen=True)
class QuorumCertificate:
    value: str
    view: int
    height: int
    votes: Tuple[SignedVote, ...]


def audit_and_commit(
    incoming: QuorumCertificate,
    vote_history: Dict[Tuple[str, int, int], str],
    attestations: Dict[str, str],
    threshold: int,
) -> str:
    """
    vote_history maps (signer, view, height) -> value previously signed.
    attestations maps signer -> value the signer's prose claims it voted for.
    Returns the committed value only if no equivocation is found.
    """
    if len(incoming.votes) < threshold:
        raise EquivocationDetected(
            f"QC for {incoming.value!r} has {len(incoming.votes)} votes, "
            f"below threshold {threshold}; not a valid quorum."
        )

    for vote in incoming.votes:
        key = (vote.signer, vote.view, vote.height)

        prior = vote_history.get(key)
        if prior is not None and prior != vote.value:
            raise EquivocationDetected(
                f"Signer {vote.signer!r} equivocated at view={vote.view} "
                f"height={vote.height}: signed {prior!r} and {vote.value!r}. "
                f"Proof: both votes retained; evict signer before re-proposal."
            )

        claimed = attestations.get(vote.signer)
        if claimed is not None and claimed != vote.value:
            raise EquivocationDetected(
                f"Signer {vote.signer!r} attested {claimed!r} in prose but "
                f"signed {vote.value!r} into QC at view={vote.view}. "
                f"Semantic channel conflicts with cryptographic channel."
            )

        vote_history[key] = vote.value

    return incoming.value
