# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-sign-a-byzantine-quorum-certificate-equivocation-induced-witness-set-divergence-in-multi-agent-decision-aggregation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-sign-a-byzantine-quorum-certificate-equivocation-induced-witness-set-divergence-in-multi-agent-decision-aggregation.warrant.json
# Markdown SHA-256:   1566961b6f9f9f1a61a97f065c33415884a5dd9bb359d7a04e7f6fd9cbd241ad
# Code AST SHA-256:   8ae6f1da28ad0f1e7ef9f859aeaba315a0f3b47f22d37e0f8376eda8248d1809
# Verified Classes:   EquivocationDivergenceError, EpochReplayError, Proposal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class EquivocationDivergenceError(RuntimeError):
    """Raised when a signer's payload hash diverges from the coordinator-anchored digest."""
    pass


class EpochReplayError(RuntimeError):
    """Raised when an instance is asked to re-sign a different digest within an epoch it already signed."""
    pass


@dataclass(frozen=True)
class Proposal:
    epoch: int
    body: dict
    anchored_digest: str  # coordinator-signed H(canon(body, epoch))


def canon(body: dict, epoch: int) -> bytes:
    # Deterministic: sorted keys, no whitespace, epoch bound into the payload.
    return json.dumps(
        {"epoch": epoch, "body": body},
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
    ).encode("utf-8")


def digest(body: dict, epoch: int) -> str:
    return hashlib.sha256(canon(body, epoch)).hexdigest()


def sign_proposal(proposal: Proposal, already_signed: dict[int, str]) -> tuple[str, str]:
    """Return (digest, signature). Refuse if rendered digest diverges or epoch is replayed."""
    rendered = digest(proposal.body, proposal.epoch)

    if rendered != proposal.anchored_digest:
        raise EquivocationDivergenceError(
            f"epoch={proposal.epoch} rendered={rendered[:12]} "
            f"anchored={proposal.anchored_digest[:12]} — refusing to sign divergent hash"
        )

    prior = already_signed.get(proposal.epoch)
    if prior is not None and prior != rendered:
        raise EpochReplayError(
            f"epoch={proposal.epoch} prior={prior[:12]} new={rendered[:12]} "
            f"— re-signing a different digest under one epoch is equivocation evidence"
        )

    signature = hashlib.sha256(f"{rendered}:signer".encode()).hexdigest()
    return rendered, signature


def aggregate_quorum(
    votes: list[tuple[str, str]], anchored: str, threshold: int
) -> bool:
    """Count only votes whose digest matches the coordinator-anchored digest."""
    counted = sum(1 for d, _ in votes if d == anchored)
    distinct = {d for d, _ in votes}
    if len(distinct) > 1:
        raise EquivocationDivergenceError(
            f"witness-set split across {len(distinct)} hash domains; "
            f"counted={counted} threshold={threshold} — not a quorum"
        )
    return counted >= threshold
