# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-agent-s-equivocation-as-a-continuity-break-rather-than-a-recoverable-disagreement.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-byzantine-agent-s-equivocation-as-a-continuity-break-rather-than-a-recoverable-disagreement.warrant.json
# Markdown SHA-256:   c560a7a26da4b40b3b533768d383269576d1e0ea98c93218dc327ecf928ac07b
# Code AST SHA-256:   89fe5c474fe76934071218e281dd52f52bfbf5eee54a82de091e236cb0d6861e
# Verified Classes:   EquivocationContinuityBreak, Vote
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class EquivocationContinuityBreak(RuntimeError):
    """Raised when a single agent identity emits two distinct commitments
    for the same slot from a shared context lineage. This is an identity-layer
    failure, not a value-layer disagreement, and must trigger eviction."""
    pass

@dataclass(frozen=True)
class Vote:
    agent_id: str
    slot: int
    value: str
    trace_root: str          # hash of prompt + tool-call seq + sampling seed
    signature: str           # valid, but insufficient for adjudication

def classify_votes(votes: list[Vote]) -> dict:
    """Group votes by (agent_id, slot) and detect equivocation vs. benign fork."""
    by_key: dict[tuple[str, int], list[Vote]] = {}
    for v in votes:
        by_key.setdefault((v.agent_id, v.slot), []).append(v)

    for (agent_id, slot), group in by_key.items():
        values = {v.value for v in group}
        if len(values) <= 1:
            continue  # identical retransmission or single vote
        roots = {v.trace_root for v in group}
        if len(roots) > 1:
            # Provably forked lineage: two distinct contexts, treat as two agents.
            continue
        # Same trace root, different values => continuity break.
        raise EquivocationContinuityBreak(
            f"agent {agent_id} equivocated on slot {slot}: "
            f"values={sorted(values)} share trace_root={next(iter(roots))[:12]}"
        )
    return by_key

def commit_slot(votes: list[Vote], slot: int, threshold: int) -> str:
    """Commit a slot only if a singular-lineage quorum agrees."""
    groups = classify_votes(votes)  # raises on equivocation
    tally: dict[str, int] = {}
    for (agent_id, s), group in groups.items():
        if s != slot:
            continue
        # One vote per identity, guaranteed singular by classify_votes.
        tally[group[0].value] = tally.get(group[0].value, 0) + 1
    winner, count = max(tally.items(), key=lambda kv: kv[1])
    if count < threshold:
        raise EquivocationContinuityBreak(
            f"slot {slot} failed to reach quorum: {count}/{threshold}"
        )
    return winner
