# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-byzantine-consensus-for-shared-state-multi-agent-plans-draw-the-line-between-equivocation-detection-and-legitimate-plan-revi.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-byzantine-consensus-for-shared-state-multi-agent-plans-draw-the-line-between-equivocation-detection-and-legitimate-plan-revi.warrant.json
# Markdown SHA-256:   c9897f518ee01702a188a62d7e5fb303e71a8d95f38b09c071faa45fd46c8339
# Code AST SHA-256:   a0db79de98afe333dc3fb87839c2b86dcc564c3c6fb856e1e6813cf9fec152bb
# Verified Classes:   IndeterminateRevisionError, SignedPlan, NewViewCert
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class IndeterminateRevisionError(RuntimeError):
    """Raised when two signed plan messages cannot be classified as
    equivocation vs. legal revision because the view-change certificate
    chain is missing or fails verification."""
    pass


@dataclass(frozen=True)
class SignedPlan:
    agent_id: str
    plan_id: str
    payload_hash: str
    epoch: int
    view: int
    signature: str


@dataclass(frozen=True)
class NewViewCert:
    from_epoch: int
    from_view: int
    to_epoch: int
    to_view: int
    quorum_signatures: tuple


def _cert_verifies(cert: NewViewCert, trusted_quorum: set) -> bool:
    signers = {sig.split(":")[0] for sig in cert.quorum_signatures}
    return len(signers & trusted_quorum) >= len(trusted_quorum) // 2 + 1


def classify(m1: SignedPlan, m2: SignedPlan, certs: list, trusted_quorum: set) -> str:
    if m1.plan_id != m2.plan_id:
        raise ValueError("messages concern different plans; not comparable")
    if m1.payload_hash == m2.payload_hash:
        return "consistent"

    same_cell = (m1.epoch, m1.view) == (m2.epoch, m2.view)
    if same_cell:
        return "equivocation"

    lo, hi = sorted([(m1.epoch, m1.view), (m2.epoch, m2.view)])
    bridging = [
        c for c in certs
        if (c.from_epoch, c.from_view) == lo and (c.to_epoch, c.to_view) == hi
    ]
    if not bridging:
        raise IndeterminateRevisionError(
            f"no NEW_VIEW cert bridges {lo} -> {hi} for plan {m1.plan_id}; "
            "quarantine votes, do not slash"
        )
    if not _cert_verifies(bridging[0], trusted_quorum):
        raise IndeterminateRevisionError(
            f"NEW_VIEW cert for {lo} -> {hi} failed quorum verification; "
            "quarantine votes, do not slash"
        )
    return "legal_revision"
