# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-agent-swarm-when-signed-plan-commitments-diverge-across-read-quorums.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-a-byzantine-agent-swarm-when-signed-plan-commitments-diverge-across-read-quorums.warrant.json
# Markdown SHA-256:   4a8e737fa64e6bc4894293d0d4854aa478359d0378020df7aaa64bb95524bf9c
# Code AST SHA-256:   ae0752e0123154d32ae48aa6d5d2806388e99d276d1013a2957c8bc70c96694f
# Verified Classes:   EquivocationDetected, Commitment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Set, Tuple


class EquivocationDetected(RuntimeError):
    """Raised when a sender is observed committing to conflicting plan hashes
    at the same epoch across the quorum intersection."""
    pass


@dataclass(frozen=True)
class Commitment:
    sender: str
    epoch: int
    plan_hash: str


def verify_commitment_set(
    local_accepted: Dict[str, Commitment],
    peer_testimony: Dict[str, Dict[str, Commitment]],
    quorum_intersection: Set[str],
) -> None:
    """
    Cross-check locally accepted commitments against testimony gathered from
    the quorum intersection. Raises on any sender whose accepted plan_hash
    diverges across observers at the same epoch.
    """
    seen: Dict[Tuple[str, int], Set[str]] = {}

    for sender, c in local_accepted.items():
        seen.setdefault((sender, c.epoch), set()).add(c.plan_hash)

    for peer in quorum_intersection:
        testimony = peer_testimony.get(peer)
        if testimony is None:
            # Missing testimony is not proof of equivocation, but it is not
            # clearance either. Caller must halt per decision rule 3.
            raise EquivocationDetected(
                f"no testimony from intersection peer {peer!r}; "
                f"cannot certify epoch — halt and escalate"
            )
        for sender, c in testimony.items():
            seen.setdefault((sender, c.epoch), set()).add(c.plan_hash)

    for (sender, epoch), hashes in seen.items():
        if len(hashes) > 1:
            raise EquivocationDetected(
                f"sender {sender!r} equivocated at epoch {epoch}: "
                f"conflicting plan_hashes {sorted(hashes)}"
            )
