# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-forgery-when-heterogeneous-llm-agents-attest-to-each-other-s-outputs-under-byzantine-membership.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-forgery-when-heterogeneous-llm-agents-attest-to-each-other-s-outputs-under-byzantine-membership.warrant.json
# Markdown SHA-256:   31fa849bce844e72e302dd95d84ca5d648e97ff262842ab545a86ec357b21019
# Code AST SHA-256:   d9c88e873eab52ed60c70e4681dd172eaaddfc22ce3c53247db31deede73ced7
# Verified Classes:   QuorumForgeryError, Attestation, QuorumResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class QuorumForgeryError(RuntimeError):
    """Raised when a quorum would cross threshold only via correlated,
    normalized, or unbound attestations."""


@dataclass(frozen=True)
class Attestation:
    agent_id: str
    family: str
    context_id: str
    payload_hash: str
    nonce: str
    verdict: str          # "AGREE" | "DISSENT" | "ABSTAIN"
    raw_text: str


@dataclass
class QuorumResult:
    counted: list = field(default_factory=list)
    uncounted: list = field(default_factory=list)
    independent_count: int = 0


def tally_quorum(
    candidate_payload: bytes,
    attestations: list[Attestation],
    threshold: int,
    round_nonce: str,
) -> QuorumResult:
    payload_hash = hashlib.sha256(candidate_payload).hexdigest()
    result = QuorumResult()
    seen_families: set[str] = set()
    seen_contexts: set[str] = set()

    for att in attestations:
        # Invariant 1: content binding to the exact payload under review.
        if att.payload_hash != payload_hash:
            result.uncounted.append(att)
            continue
        # Invariant 2: nonce binding prevents cross-round replay.
        if att.nonce != round_nonce:
            result.uncounted.append(att)
            continue
        # Invariant 3: only structured, non-hedged verdicts count.
        if att.verdict != "AGREE":
            result.uncounted.append(att)
            continue
        # Invariant 4: independence dedup by family and context.
        if att.family in seen_families or att.context_id in seen_contexts:
            result.uncounted.append(att)
            continue
        seen_families.add(att.family)
        seen_contexts.add(att.context_id)
        result.counted.append(att)

    result.independent_count = len(result.counted)

    if result.independent_count < threshold:
        # Distinguish "honest shortfall" from "forgery-shaped shortfall":
        # if headcount >= threshold but independent count does not, the
        # gap is exactly the correlated/normalized mass an adversary exploits.
        if len(attestations) >= threshold:
            raise QuorumForgeryError(
                f"quorum headcount {len(attestations)} >= threshold {threshold} "
                f"but independent count is {result.independent_count}; "
                f"gap indicates correlated echo or normalization forgery"
            )
        raise QuorumForgeryError(
            f"independent count {result.independent_count} < threshold {threshold}; "
            f"fail closed"
        )
    return result
