# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-equivocation-and-honest-rollback-in-a-bft-agent-commit-protocol.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-equivocation-and-honest-rollback-in-a-bft-agent-commit-protocol.warrant.json
# Markdown SHA-256:   2c9cb8af59e38796886e4ebe1fbef4f252ae34cc9c4da788f38b309befdb68b0
# Code AST SHA-256:   3f6a3f4f2b9aa95599ffae227accf6a743d9e23d17d2f3dacb33521e2f01a5c9
# Verified Classes:   EquivocationMisclassification, UnwitnessedRevote, Vote, WitnessStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass
from typing import Optional


class EquivocationMisclassification(RuntimeError):
    """Raised when an honest rollback is about to be treated as Byzantine equivocation."""


class UnwitnessedRevote(EquivocationMisclassification):
    """The agent is about to emit a vote for a round it cannot prove it did not already vote."""


@dataclass
class Vote:
    round: int
    subtask: str
    claim: str
    nonce: str


class WitnessStore:
    """Durable, compaction-exempt record of (round -> vote nonce). Must outlive context."""

    def __init__(self, key: bytes):
        self._key = key
        self._witness: dict[int, str] = {}

    def record(self, vote: Vote) -> None:
        # Witness-before-broadcast: this must complete before the vote leaves the agent.
        digest = hmac.new(self._key, f"{vote.round}:{vote.nonce}".encode(), hashlib.sha256).hexdigest()
        self._witness[vote.round] = digest

    def has_voted(self, round_no: int) -> bool:
        return round_no in self._witness


def emit_vote(agent_id: str, vote: Vote, witness: WitnessStore, context_log_intact: bool) -> Vote:
    """
    Emit a vote only if the agent can prove it has not already voted this round.
    Honest amnesia (context_log_intact=False and no witness) must NOT re-derive a vote.
    """
    if witness.has_voted(vote.round):
        # Safe rollback: re-broadcast the original signed vote, never re-derive.
        raise UnwitnessedRevote(
            f"agent {agent_id} already witnessed a vote for round {vote.round}; "
            f"re-broadcast original nonce, do not emit {vote.nonce}"
        )

    if not context_log_intact:
        # The agent lost its log tail. It cannot distinguish 'never voted' from 'voted and forgot'.
        # This is the boundary: refuse to vote, escalate as RECOVERY_REQUEST.
        raise EquivocationMisclassification(
            f"agent {agent_id} has truncated context and no witness for round {vote.round}; "
            f"emitting a vote here is indistinguishable from equivocation. "
            f"Emit RECOVERY_REQUEST(round={vote.round}, agent={agent_id}) instead."
        )

    witness.record(vote)
    return vote


def handle_conflicting_vote(agent_id: str, round_no: int, receipts: list[Vote], witness: WitnessStore) -> str:
    """
    Auditor-side classification: a conflict is Byzantine only with positive evidence
    of a witnessed prior vote. Absence of witness is not evidence of equivocation.
    """
    if not witness.has_voted(round_no):
        return "RECOVERY_REQUEST"  # honest amnesia path, not a slash
    nonces = {r.nonce for r in receipts if r.round == round_no}
    if len(nonces) > 1:
        return "SLASH"  # witnessed prior vote + a different nonce = true equivocation
    return "DEDUPE"
