# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-peers-when-heterogeneous-llm-agents-disagree-on-what-the-same-proposal-means.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocating-peers-when-heterogeneous-llm-agents-disagree-on-what-the-same-proposal-means.warrant.json
# Markdown SHA-256:   e41e5877a087e11c300ca889a26f758f8a850d784149d9f0f350f870e46b69dc
# Code AST SHA-256:   84b591669054eaa2a12af1ccc93c84dbc7387e5d4bd0722b78fcc25bd99ea384
# Verified Classes:   EquivocationAdjudicationError, SignedVote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationAdjudicationError(RuntimeError):
    """Raised when a node attempts to adjudicate equivocation on digests
    whose provenance is model-dependent and therefore non-adjudicable."""
    pass


@dataclass(frozen=True)
class SignedVote:
    sender: str
    digest: str
    canonicalizer: str  # "reference" or "agent-local:<model-id>"


def adjudicate_conflicting_digests(
    sender: str,
    votes: list[SignedVote],
    reference_artifact: bytes | None,
) -> str:
    """
    Decide whether conflicting digests from one sender constitute
    provable equivocation, or are merely canonicalization divergence.

    Returns one of: "equivocation", "divergence", "ill_formed".
    Raises EquivocationAdjudicationError if the caller demands an
    accusation that the evidence cannot support.
    """
    digests = {v.digest for v in votes if v.sender == sender}
    if len(digests) <= 1:
        return "divergence"  # no conflict at all

    # Any vote signed over an agent-local canonicalization voids the
    # equivocation invariant for this sender in this round.
    local = [v for v in votes if v.sender == sender and v.canonicalizer != "reference"]

    if reference_artifact is None:
        # No pinned serialization: the round has no equivocation semantics.
        return "ill_formed"

    ref_digest = hashlib.sha256(reference_artifact).hexdigest()

    if local:
        # Re-derive: did every conflicting digest actually match the
        # reference artifact? If not, the conflict is canonicalization
        # noise, not equivocation.
        for v in votes:
            if v.sender != sender:
                continue
            if v.digest != ref_digest and v.canonicalizer != "reference":
                # This vote was computed against a model-local reading.
                # We cannot prove the sender emitted divergent *values*;
                # we can only prove divergent *readings*.
                return "divergence"

    # All conflicting votes were signed over the reference artifact and
    # still disagree -> the sender signed two different reference digests.
    if len(digests) > 1 and all(v.canonicalizer == "reference" for v in votes if v.sender == sender):
        if any(v.digest != ref_digest for v in votes if v.sender == sender):
            return "equivocation"

    raise EquivocationAdjudicationError(
        f"Cannot adjudicate sender {sender!r}: digest conflict present "
        f"({sorted(digests)}) but provenance is mixed or reference "
        f"artifact {ref_digest[:12]} does not bind all votes. "
        f"Refusing to emit fraud proof on non-adjudicable evidence."
    )


def require_byzantine_safe_round(reference_artifact: bytes | None) -> None:
    if reference_artifact is None:
        raise EquivocationAdjudicationError(
            "Round has no pinned reference serialization; consensus is "
            "running in best-effort agreement mode and MUST NOT be "
            "recorded as Byzantine-safe."
        )
