# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-agent-quorum-when-the-traitor-is-a-hallucinating-llm-that-emits-semantically-consistent-lies.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-agent-quorum-when-the-traitor-is-a-hallucinating-llm-that-emits-semantically-consistent-lies.warrant.json
# Markdown SHA-256:   34637907f66d52eba35d7331b135ccc69ae2e5e706e40f85f1740b9d23cccd71
# Code AST SHA-256:   4599b42f934338f9201a6ebbd7a208ca590d8b1d8a7c0fc7ff33b3df24dd6791
# Verified Classes:   EquivocationDetected, UnresolvedSupportToken, Justification, Vote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class EquivocationDetected(RuntimeError):
    """Raised when a quorum's voters cite disjoint support sets for one digest."""
    pass


class UnresolvedSupportToken(RuntimeError):
    """Raised when a justification cites a token absent from the evidence log."""
    pass


@dataclass
class Justification:
    claim: str
    support_tokens: frozenset  # e.g. {"test_run:14:02", "sre_signoff:alice"}


@dataclass
class Vote:
    voter_id: str
    digest: str
    justification: Justification


def canonical_digest(j: Justification) -> str:
    # Digest MUST cover support tokens, not just the claim template.
    payload = j.claim + "|" + "|".join(sorted(j.support_tokens))
    return hashlib.sha256(payload.encode()).hexdigest()


def verify_and_commit(votes, evidence_log, f):
    """
    evidence_log: set of tokens that executors (not agents) have written.
    Returns committed digest iff the safety invariant holds; else raises.
    """
    if len(votes) < 2 * f + 1:
        raise EquivocationDetected(
            f"insufficient quorum: {len(votes)} < {2*f+1}"
        )

    digests = {v.digest for v in votes}
    if len(digests) != 1:
        # Classical equivocation: distinct digests. Easy case.
        raise EquivocationDetected(f"divergent digests: {digests}")

    committed = digests.pop()

    # Invariant 1: every voter locally re-derived the digest from its own
    # received justification. A voter that voted without re-deriving is
    # itself faulty (fast-path trust of proposer).
    for v in votes:
        if canonical_digest(v.justification) != v.digest:
            raise EquivocationDetected(
                f"voter {v.voter_id} voted digest {v.digest} but its "
                f"justification re-derives to {canonical_digest(v.justification)}"
            )

    # Invariant 2: every cited support token resolves in the executor-written
    # evidence log. Fabricated citations are caught here.
    for v in votes:
        unresolved = v.justification.support_tokens - evidence_log
        if unresolved:
            raise UnresolvedSupportToken(
                f"voter {v.voter_id} cited unresolvable tokens: {unresolved}"
            )

    # Invariant 3 (the non-obvious one): support-set intersection must be
    # non-empty. Honest voters sharing one justification share its tokens;
    # a traitor's peers cite disjoint tokens and the intersection collapses.
    support_sets = [v.justification.support_tokens for v in votes]
    intersection = frozenset.intersection(*support_sets)
    if not intersection:
        raise EquivocationDetected(
            "support-set intersection empty: voters cite mutually disjoint "
            "evidence for the same digest — signature of equivocation-by-paraphrase"
        )

    return committed
