# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-heterogeneous-llm-agent-bft-consensus-when-equivocating-replicas-emit-semantically-divergent-but-hash.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-heterogeneous-llm-agent-bft-consensus-when-equivocating-replicas-emit-semantically-divergent-but-hash.warrant.json
# Markdown SHA-256:   de7372a5461e79c83edd9bc7a6255bedc8b0a5fc6dab503df80ae086f9215d75
# Code AST SHA-256:   7f2cbe9a77e944412c79dde2540350c37d752e1191d751d1ee329ea0ee858027
# Verified Classes:   EquivocationCertificateError, Vote
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationCertificateError(RuntimeError):
    """Raised when an auditor attempts to certify equivocation without a pinned context match."""
    pass


@dataclass(frozen=True)
class Vote:
    view: int
    prop: int
    decision: str          # "PREPARE" | "COMMIT"
    transcript: str
    context_digest: str    # H(weights ‖ template ‖ params ‖ tool_hashes ‖ ledger_version)
    signature: bytes


def _h(s: str) -> str:
    return hashlib.sha256(s.encode()).hexdigest()


def audit_equivocation(v1: Vote, v2: Vote) -> str:
    """
    Returns one of: "SUPPRESS_CONTEXT_DRIFT", "ESCALATE_NONDETERMINISM",
    "CERTIFY_EQUIVOCATION".
    Raises EquivocationCertificateError if the caller tries to certify
    without a verified context match.
    """
    if (v1.view, v1.prop) != (v2.view, v2.prop):
        raise EquivocationCertificateError(
            f"votes target different slots: {(v1.view, v1.prop)} vs {(v2.view, v2.prop)}"
        )

    # Invariant: context must be pinned before any equivocation reasoning.
    if v1.context_digest != v2.context_digest:
        # Divergence attributable to context drift (e.g. at-least-once MCP retry
        # against a lagged read replica). Not Byzantine evidence.
        return "SUPPRESS_CONTEXT_DRIFT"

    # Context is identical. Now the decision field is the only sound signal.
    if v1.decision != v2.decision:
        return "CERTIFY_EQUIVOCATION"

    # Same context, same decision, divergent reasoning: sampling nondeterminism.
    if _h(v1.transcript) != _h(v2.transcript):
        return "ESCALATE_NONDETERMINISM"

    return "CONSISTENT"


def certify(v1: Vote, v2: Vote) -> None:
    verdict = audit_equivocation(v1, v2)
    if verdict == "CERTIFY_EQUIVOCATION":
        return
    if verdict == "SUPPRESS_CONTEXT_DRIFT":
        raise EquivocationCertificateError(
            "refusing to certify: context digests differ, divergence is transport-attributable"
        )
    raise EquivocationCertificateError(
        f"refusing to certify: verdict={verdict}, no Byzantine evidence under pinned context"
    )
