# 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-no-honest-agent-ever-voted-for.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-agent-quorum-accept-a-decision-that-no-honest-agent-ever-voted-for.warrant.json
# Markdown SHA-256:   d512cc65b61c3f2285e6e875dbf9b2edb6b2fc9a5aa23cef1fde2ad0e8e0852c
# Code AST SHA-256:   a58639aeff1299400c49b28d4c21eb9a50ef1dcaa48ae1293b1e128126ffc7f9
# Verified Classes:   DigestProvenanceError, EndorsementLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class DigestProvenanceError(RuntimeError):
    """Raised when an agent is asked to endorse a digest that diverges from
    its own first endorsement in the current round — the signature of a
    Byzantine re-serialization attack on the quorum commit rule."""
    pass


@dataclass
class EndorsementLedger:
    round_id: int
    first_endorsement: dict = field(default_factory=dict)  # agent_id -> digest

    def canonical(self, payload: dict) -> bytes:
        # Byte-stable encoding: sorted keys, no float coercion, no whitespace.
        return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()

    def digest(self, payload: dict) -> str:
        return hashlib.sha256(self.canonical(payload)).hexdigest()

    def endorse(self, agent_id: str, payload: dict) -> str:
        d = self.digest(payload)
        prior = self.first_endorsement.get(agent_id)
        if prior is None:
            self.first_endorsement[agent_id] = d
            return d
        if prior != d:
            raise DigestProvenanceError(
                f"agent {agent_id} in round {self.round_id} already endorsed "
                f"{prior[:12]}… but was asked to endorse {d[:12]}… — "
                f"re-serialization divergence detected; refusing to re-sign."
            )
        return d


def assemble_quorum_certificate(
    ledger: EndorsementLedger,
    signatures: dict,          # agent_id -> digest they signed
    threshold: int,
    committed_payload: dict,
) -> str:
    committed_digest = ledger.digest(committed_payload)
    signers = [a for a, d in signatures.items() if d == committed_digest]
    if len(signers) < threshold:
        raise DigestProvenanceError(
            f"only {len(signers)} signers match committed digest "
            f"{committed_digest[:12]}…; threshold {threshold} not met."
        )
    for agent_id in signers:
        prior = ledger.first_endorsement.get(agent_id)
        if prior is not None and prior != committed_digest:
            raise DigestProvenanceError(
                f"signer {agent_id} first endorsed {prior[:12]}… but certificate "
                f"commits {committed_digest[:12]}… — equivocation detected."
            )
    return committed_digest
