# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-proposers-in-bft-multi-agent-task-commitment-when-signed-views-disagree-across-a-quorum-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-proposers-in-bft-multi-agent-task-commitment-when-signed-views-disagree-across-a-quorum-boundary.warrant.json
# Markdown SHA-256:   48211ed22d97b35cc7222fd21dabff69dd449f9fc601f653201033654b55c58d
# Code AST SHA-256:   d67cdc6864a3a13fb3f46176d32dbc94a02a55d60766133a2dbea147d8ab7124
# Verified Classes:   EquivocationProofRequired, SignedPrepare, EquivocationGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EquivocationProofRequired(RuntimeError):
    """Raised when an agent holds two conflicting signed messages from one signer
    in the same view and is therefore obligated to emit a proof and force a
    view change, rather than continuing to wait for quorum."""
    pass


@dataclass(frozen=True)
class SignedPrepare:
    signer: str
    view: int
    task_id: str
    payload_hash: str
    signature: str  # assumed verified upstream


def payload_digest(task_id: str, body: str) -> str:
    return hashlib.sha256(f"{task_id}:{body}".encode()).hexdigest()


class EquivocationGuard:
    """Deterministic pre-reasoning check. MUST run before any LLM deliberation
    about whether to trust a peer message."""

    def __init__(self) -> None:
        # key: (signer, view) -> first seen SignedPrepare
        self._first_seen: Dict[Tuple[str, int], SignedPrepare] = {}

    def observe(self, msg: SignedPrepare) -> None:
        if not msg.signature:
            # Invalid signature is corruption, not equivocation. Drop it.
            return

        key = (msg.signer, msg.view)
        prior = self._first_seen.get(key)

        if prior is None:
            self._first_seen[key] = msg
            return

        # Same signer, same view, conflicting payload => proven equivocation.
        if prior.payload_hash != msg.payload_hash:
            raise EquivocationProofRequired(
                f"Equivocation proven: signer={msg.signer} view={msg.view} "
                f"first={prior.task_id}/{prior.payload_hash[:8]} "
                f"second={msg.task_id}/{msg.payload_hash[:8]} "
                f"-> broadcast PROOF_OF_EQUIVOCATION and force view change"
            )
        # Identical payload: benign re-send, deduplicate silently.
        return


def handle_incoming_prepare(guard: EquivocationGuard, msg: SignedPrepare) -> str:
    try:
        guard.observe(msg)
        return "accepted"
    except EquivocationProofRequired:
        # Re-raise: the caller must broadcast the proof and advance the view.
        # The LLM is never consulted on whether the proof exists.
        raise


if __name__ == "__main__":
    g = EquivocationGuard()
    h1 = payload_digest("T1", "scope: read-only")
    h2 = payload_digest("T2", "scope: read-write")
    handle_incoming_prepare(g, SignedPrepare("A3", 4, "T1", h1, "sig-a"))
    # A3 now equivocates to a disjoint partition; the conflicting message
    # arrives via gossip. This MUST raise, not stall.
    handle_incoming_prepare(g, SignedPrepare("A3", 4, "T2", h2, "sig-b"))
