# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-heterogeneous-llm-agents-reach-byzantine-consensus-on-conflicting-tool-call-outputs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-heterogeneous-llm-agents-reach-byzantine-consensus-on-conflicting-tool-call-outputs.warrant.json
# Markdown SHA-256:   3ff2315da05387d1b93d55164cd68b3e91f0f3e0054d44b90050664bed4d6f75
# Code AST SHA-256:   0c5e4e93b36ca47bf5444f37d5d7a72b1bff3bd1baf180271e786ff66694c253
# Verified Classes:   ByzantineEquivocation, HonestStochasticDivergence, NonDeterministicConsensusIneligible, Vote, ReplayResult
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional

class ByzantineEquivocation(RuntimeError):
    """Raised only when replay challenge confirms a malicious double-vote."""
    pass

class HonestStochasticDivergence(RuntimeError):
    """Raised when wire-level equivocation is explained by entropy, not malice."""
    pass

class NonDeterministicConsensusIneligible(RuntimeError):
    """Raised when an agent cannot honor a seed and is structurally unfit for consensus."""
    pass

@dataclass
class Vote:
    sender: str
    round: int
    topic: str
    payload: str
    signature: str

@dataclass
class ReplayResult:
    reproduced_payload: Optional[str]
    third_payload: Optional[str]
    seed_honored: bool

def replay_challenge(agent, frozen_context: str, seed: int) -> ReplayResult:
    out = agent.revote(frozen_context, seed=seed)
    if not out.seed_honored:
        return ReplayResult(None, None, seed_honored=False)
    if out.payload in out.disputed_payloads:
        return ReplayResult(out.payload, None, seed_honored=True)
    return ReplayResult(None, out.payload, seed_honored=True)

def adjudicate_equivocation(
    agent,
    disputed: tuple[Vote, Vote],
    frozen_context: str,
    seed: int,
    entropy_budget: float,
    equivocation_threshold: float,
) -> str:
    if disputed[0].sender != disputed[1].sender:
        raise ValueError("not an equivocation: distinct senders")
    if (disputed[0].round, disputed[0].topic) != (disputed[1].round, disputed[1].topic):
        raise ValueError("not an equivocation: distinct round/topic")

    result = replay_challenge(agent, frozen_context, seed)

    if not result.seed_honored:
        raise NonDeterministicConsensusIneligible(
            f"agent {agent.id} cannot honor seed; ineligible for consensus duty"
        )

    if result.reproduced_payload is not None:
        if entropy_budget >= equivocation_threshold:
            raise HonestStochasticDivergence(
                f"agent {agent.id} entropy {entropy_budget} >= tau {equivocation_threshold}; "
                f"demote, do not slash"
            )
        # Entropy below threshold but replay reproduced a disputed payload:
        # divergence is reproducible, so it is not random entropy -> treat as fault.
        raise ByzantineEquivocation(
            f"agent {agent.id} reproduced disputed payload under seed; "
            f"reproducible divergence is Byzantine"
        )

    if result.third_payload is not None:
        raise ByzantineEquivocation(
            f"agent {agent.id} produced third payload {result.third_payload!r} "
            f"under replay; correlated with adversary target"
        )

    raise ByzantineEquivocation(
        f"agent {agent.id} replay inconclusive; conservative slash under fault model"
    )

def required_committee_size(f_byzantine: int, e_entropic: int) -> int:
    # Entropic agents cost 2 slots each: they can neither be trusted to commit
    # nor safely slashed, so the honest majority must outvote both f and 2e.
    return 3 * f_byzantine + 2 * e_entropic

def commit_round(votes: list[Vote], f: int, e: int) -> str:
    n = len(votes)
    need = required_committee_size(f, e)
    if n < need:
        raise HonestStochasticDivergence(
            f"committee size {n} < required {need} for f={f}, e={e}; "
            f"honest entropy cannot be outvoted"
        )
    tally = {}
    for v in votes:
        tally[v.payload] = tally.get(v.payload, 0) + 1
    winner, count = max(tally.items(), key=lambda kv: kv[1])
    if count < (n + f + 1) // 2:
        raise ByzantineEquivocation(f"no quorum for {winner!r}: {count}/{n}")
    return winner
