# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-coalition-commit-to-a-plan-that-no-member-endorsed-equivocation-tolerant-voting-under-heterogeneous-tool-semantics.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-coalition-commit-to-a-plan-that-no-member-endorsed-equivocation-tolerant-voting-under-heterogeneous-tool-semantics.warrant.json
# Markdown SHA-256:   da3018a5922879fdb38e1ef0a3ef0d87dcc310eaac3d99e19f0300cd118a53f0
# Code AST SHA-256:   02ade39fa6df4cca5168b3ce253adc1ee75dff0b946dc8eb829b0d3ae535261d
# Verified Classes:   SemanticEquivocationError, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Mapping

CANONICALIZER_VERSION = "referent-canon-v3"


class SemanticEquivocationError(RuntimeError):
    """Raised when a quorum of votes shares a label but not a referent digest."""


@dataclass(frozen=True)
class Vote:
    agent_id: str
    label: str
    referent_digest: str          # sha256 over canonicalized referent
    canonicalizer_version: str


def canonicalize_referent(raw_tool_output: Mapping) -> str:
    # Shared, versioned canonicalizer. NOT the agent's own adapter.
    canonical = "|".join(
        f"{k}={raw_tool_output[k]}" for k in sorted(raw_tool_output)
    )
    return hashlib.sha256(
        f"{CANONICALIZER_VERSION}:{canonical}".encode()
    ).hexdigest()


def tally_referent_quorum(
    votes: list[Vote], n: int, f: int
) -> str:
    """Return the winning referent digest, or raise on semantic equivocation."""
    quorum = 2 * f + 1
    buckets: dict[str, list[Vote]] = {}

    for v in votes:
        if v.canonicalizer_version != CANONICALIZER_VERSION:
            # Discard non-canonical votes; they cannot be trusted to agree.
            continue
        buckets.setdefault(v.referent_digest, []).append(v)

    winners = [d for d, vs in buckets.items() if len(vs) >= quorum]
    if len(winners) == 1:
        return winners[0]
    if len(winners) > 1:
        # Two disjoint quorums on distinct referents: BFT safety violation.
        raise SemanticEquivocationError(
            f"multiple referent quorums: {winners}"
        )

    # No single referent reached quorum. Check whether the *label* would have
    # reached quorum — that is the equivocation signature.
    label_counts: dict[str, int] = {}
    for v in votes:
        label_counts[v.label] = label_counts.get(v.label, 0) + 1
    for label, count in label_counts.items():
        if count >= quorum:
            digests = sorted(
                {v.referent_digest for v in votes if v.label == label}
            )
            raise SemanticEquivocationError(
                f"label {label!r} reached quorum={count} across "
                f"{len(digests)} distinct referents {digests}; "
                f"commit-on-label would have succeeded with zero true endorsers"
            )

    raise SemanticEquivocationError(
        "no referent quorum and no label quorum; reconciliation required"
    )
