# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-quorum-identity-collapse-when-heterogeneous-agents-vote-over-semantic-equivalence-rather-than-byte-equality.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-quorum-identity-collapse-when-heterogeneous-agents-vote-over-semantic-equivalence-rather-than-byte-equality.warrant.json
# Markdown SHA-256:   d8a217c294b98fd5edd6cc0d48c195cc65c1607551fc6990e8f27031a9f8f531
# Code AST SHA-256:   888999c7e0981c19c41584af53e27181d24fe6f40b9122a99bda735b035d6e2b
# Verified Classes:   QuorumIdentityCollapse, SemanticVote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class QuorumIdentityCollapse(RuntimeError):
    """Raised when a quorum certificate's votes do not share a single
    (artifact_hash, context_digest) equivalence class. The signatures are
    valid; the agreement they purport to certify does not exist."""


@dataclass(frozen=True)
class SemanticVote:
    agent_id: str
    artifact_hash: str        # content address of the object judged
    context_digest: str       # digest of the exact view the agent saw
    verdict: str              # e.g. "RELEVANT" / "NOT_RELEVANT"
    signature: bytes


def assemble_certificate(
    votes: Sequence[SemanticVote],
    quorum: int,
    f_byz: int,
) -> SemanticVote:
    """Assemble a quorum certificate under the Quorum Identity Invariant.

    Rejects any certificate whose votes are not drawn from a single
    (artifact_hash, context_digest) equivalence class, and re-derives the
    effective fault bound from observed context divergence.
    """
    if len(votes) < quorum:
        raise QuorumIdentityCollapse(
            f"insufficient votes: {len(votes)} < quorum {quorum}"
        )

    classes = {(v.artifact_hash, v.context_digest) for v in votes}
    if len(classes) > 1:
        # Honest agents voted over different artifacts or different views.
        # Each extra class is an effective fault, not a Byzantine one.
        k = len(classes) - 1
        f_eff = f_byz + k
        required = 2 * f_eff + 1
        raise QuorumIdentityCollapse(
            f"votes span {len(classes)} semantic equivalence classes "
            f"(artifact,context)={sorted(classes)}; "
            f"f_eff={f_eff}, required quorum={required}, "
            f"available={len(votes)}. Refusing to certify agreement "
            f"that was never reached."
        )

    # All votes share one class: the certificate attests to a real agreement.
    anchor = votes[0]
    agreeing = [v for v in votes if v.verdict == anchor.verdict]
    if len(agreeing) < quorum:
        raise QuorumIdentityCollapse(
            f"same class but verdict split: {len(agreeing)} agree on "
            f"{anchor.verdict!r}, quorum={quorum}"
        )
    return anchor
