# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-federated-agent-registry-as-authoritative-the-equivocation-tolerant-quorum-invariant-and-its-silent-fai.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-federated-agent-registry-as-authoritative-the-equivocation-tolerant-quorum-invariant-and-its-silent-fai.warrant.json
# Markdown SHA-256:   d8092438ef77ff740e9059a5586b019d3597dbe4e056eddfe577b357406474c3
# Code AST SHA-256:   8a3556930f7563c116cc3a48f9f7989217ecd1103771d0b303196c12d989e2a0
# Verified Classes:   RegistryEquivocationError, RegistryIndeterminateError, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable


class RegistryEquivocationError(RuntimeError):
    """Raised when a peer holds attestations for two distinct record digests
    at the same (agent_id, version), proving operator equivocation."""


class RegistryIndeterminateError(RuntimeError):
    """Raised when no digest-matched quorum can be assembled in the current
    epoch; the peer must fail closed rather than serve a stale view."""


@dataclass(frozen=True)
class Attestation:
    operator_id: str
    agent_id: str
    version: int
    record_digest: str
    epoch: int
    signature: bytes

    def is_fresh(self, current_epoch: int) -> bool:
        return self.epoch == current_epoch


def resolve_authoritative_digest(
    attestations: Iterable[Attestation],
    agent_id: str,
    version: int,
    current_epoch: int,
    operator_count: int,
) -> str:
    """Return the unique digest attested by a fresh majority of distinct
    operators, or raise. Never returns a digest on equivocation evidence."""
    quorum = operator_count // 2 + 1
    by_digest: dict[str, set[str]] = {}

    for att in attestations:
        if att.agent_id != agent_id or att.version != version:
            continue
        if not att.is_fresh(current_epoch):
            continue
        by_digest.setdefault(att.record_digest, set()).add(att.operator_id)

    # Any second digest with even one fresh attestation is equivocation
    # evidence. Freeze rather than wait for a full competing quorum.
    if len(by_digest) > 1:
        raise RegistryEquivocationError(
            f"equivocation on agent={agent_id} version={version}: "
            f"digests={sorted(by_digest)}"
        )

    if not by_digest:
        raise RegistryIndeterminateError(
            f"no fresh attestations for agent={agent_id} version={version}"
        )

    (digest, operators), = by_digest.items()
    if len(operators) < quorum:
        raise RegistryIndeterminateError(
            f"digest={digest} has {len(operators)} fresh attestations, "
            f"need {quorum}"
        )
    return digest


def verify_record(record: bytes, expected_digest: str) -> None:
    actual = hashlib.sha256(record).hexdigest()
    if actual != expected_digest:
        raise RegistryEquivocationError(
            f"record digest {actual} does not match attested {expected_digest}"
        )
