# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-when-byzantine-agents-commit-divergent-plans-under-quorum-signed-mcp-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-when-byzantine-agents-commit-divergent-plans-under-quorum-signed-mcp-handoffs.warrant.json
# Markdown SHA-256:   bd86bdefed3a5d89d5d7086edae761832b3029fa8d026171322b505eda140324
# Code AST SHA-256:   2053ddc266d0d172e430b5bc630270a2e5cc3bb898941026d86cc9eacd9a4b9d
# Verified Classes:   EquivocationDetected, Certificate, CommitmentLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass

class EquivocationDetected(RuntimeError):
    """Raised when two valid quorum certificates conflict for the same (round, view)."""
    pass

@dataclass(frozen=True)
class Certificate:
    plan_hash: str
    round: int
    view: int
    signers: frozenset  # signer_ids whose signatures cover the full tuple

def _cert_key(cert: Certificate) -> tuple:
    return (cert.round, cert.view)

class CommitmentLedger:
    def __init__(self, quorum: int, evidence_window: int = 2):
        self.quorum = quorum
        self.evidence_window = evidence_window
        self._certs: dict = {}  # (round, view) -> Certificate

    def commit(self, cert: Certificate) -> str:
        if len(cert.signers) < self.quorum:
            raise EquivocationDetected(
                f"insufficient quorum: {len(cert.signers)} < {self.quorum}"
            )
        key = _cert_key(cert)
        prior = self._certs.get(key)
        if prior is not None and prior.plan_hash != cert.plan_hash:
            # Both certificates are individually valid; this is transferable evidence.
            raise EquivocationDetected(
                f"equivocation at round={cert.round} view={cert.view}: "
                f"{prior.plan_hash} vs {cert.plan_hash}; "
                f"overlapping signers={prior.signers & cert.signers}"
            )
        self._certs[key] = cert
        self._prune(cert.round)
        return cert.plan_hash

    def _prune(self, current_round: int) -> None:
        cutoff = current_round - self.evidence_window
        for key in [k for k in self._certs if k[0] < cutoff]:
            del self._certs[key]
