# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-multi-agent-llm-consensus-before-quorum-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-in-multi-agent-llm-consensus-before-quorum-commit.warrant.json
# Markdown SHA-256:   c709b5efc760c732bc1032cb57b1c682f1860eeb6620fe1c065b51ad456f8b2c
# Code AST SHA-256:   290226a6e3a285e2d492afc98f9346b9e602bd5ec4391742e86eeeaeb4028dc0
# Verified Classes:   EquivocationDetected, Proposal
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Mapping


class EquivocationDetected(RuntimeError):
    """Raised when signed proposal hash agrees but executed effect diverges."""
    pass


@dataclass(frozen=True)
class Proposal:
    signed_hash: str          # digest over canonical (lossy) form
    canonical_bytes: bytes    # what was signed
    execution_payload: bytes  # what the executor will actually run


def _sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def effect_id(execution_payload: bytes) -> str:
    # Effect-ID must bind the *executed* representation, not the canonical one.
    return _sha(b"effect:" + execution_payload)


def verify_commit_vote(
    proposal: Proposal,
    peer_effect_ids: Mapping[str, str],
    quorum: int,
) -> str:
    """
    Gate a commit vote on effect-ID agreement, not just hash agreement.
    Returns the agreed effect_id, or raises EquivocationDetected.
    """
    observed_hash = _sha(proposal.canonical_bytes)
    if observed_hash != proposal.signed_hash:
        # Ordinary signature/hash mismatch: reject as malformed, not equivocation.
        raise EquivocationDetected(
            f"hash mismatch: signed={proposal.signed_hash} observed={observed_hash}"
        )

    local_effect = effect_id(proposal.execution_payload)
    agreeing = [peer for peer, eid in peer_effect_ids.items() if eid == local_effect]

    if len(agreeing) < quorum:
        # Hash agreed, but effects did not reach quorum: this is the boundary failure.
        divergent = {
            peer: eid for peer, eid in peer_effect_ids.items() if eid != local_effect
        }
        raise EquivocationDetected(
            "effect-boundary equivocation: signed hash agreed "
            f"({proposal.signed_hash[:12]}...) but effect_ids diverged: "
            f"local={local_effect[:12]} peers={ {k: v[:12] for k, v in divergent.items()} }"
        )

    return local_effect
