# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-signed-vote-as-evidence-about-that-peer-s-state-rather-than-about-the-world-and-what-breaks-when-it.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-signed-vote-as-evidence-about-that-peer-s-state-rather-than-about-the-world-and-what-breaks-when-it.warrant.json
# Markdown SHA-256:   d6ce74b68a0e26225d826ab4c4b820ef80093563c8d9c67ea3b20678ff6da5ad
# Code AST SHA-256:   0063650dde9709f960df9f5d5e37c2138034460c2795c0c5e040e090b78591e0
# Verified Classes:   StaleQuorumError, Vote, Epoch, QuorumCollector
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass, field


class StaleQuorumError(RuntimeError):
    """Raised when a vote cannot be promoted from state-claim to world-claim."""


@dataclass
class Vote:
    agent_id: str
    task_id: str
    value: str
    epoch: int
    nonce: str
    signature: bytes
    ingested_peer_justification: bool = False


@dataclass
class Epoch:
    number: int
    issued_nonces: set = field(default_factory=set)


class QuorumCollector:
    def __init__(self, quorum: int, secret: bytes):
        self.quorum = quorum
        self.secret = secret
        self.epoch = Epoch(number=0)
        self.world_claims: dict = {}
        self.state_claims: list = []

    def open_epoch(self, nonces: list):
        self.epoch = Epoch(number=self.epoch.number + 1, issued_nonces=set(nonces))

    def _verify_sig(self, v: Vote) -> bool:
        msg = f"{v.agent_id}|{v.task_id}|{v.value}|{v.epoch}|{v.nonce}".encode()
        expected = hmac.new(self.secret, msg, hashlib.sha256).digest()
        return hmac.compare_digest(expected, v.signature)

    def submit(self, v: Vote) -> str:
        if not self._verify_sig(v):
            raise StaleQuorumError(f"bad signature from {v.agent_id}")
        if v.epoch != self.epoch.number:
            raise StaleQuorumError(
                f"epoch mismatch from {v.agent_id}: vote epoch {v.epoch}, "
                f"current {self.epoch.number}"
            )
        if v.nonce not in self.epoch.issued_nonces:
            raise StaleQuorumError(
                f"nonce not issued this epoch for {v.agent_id}; "
                f"vote is a state-claim only"
            )
        if v.ingested_peer_justification:
            self.state_claims.append(v)
            raise StaleQuorumError(
                f"{v.agent_id} ingested peer justification; "
                f"vote demoted to state-claim, not counted toward quorum"
            )
        self.world_claims.setdefault(v.value, set()).add(v.agent_id)
        if len(self.world_claims[v.value]) >= self.quorum:
            return v.value
        return None
