# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-llm-agent-bft-consensus-before-commit-finality.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-llm-agent-bft-consensus-before-commit-finality.warrant.json
# Markdown SHA-256:   5963fa4769b3af4edafe86df932d5c61cab9e4134cf496e789e60af1cfe3d0e1
# Code AST SHA-256:   9af1cebdea23ce901a37728a2be958d75fedd8f32a26d00f42db333f20fd0a52
# Verified Classes:   EquivocationDetected, SemanticQuorumFailure, Proposal, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class EquivocationDetected(RuntimeError):
    """Raised when a proposer emits divergent digests for a single semantic decision."""
    pass


class SemanticQuorumFailure(RuntimeError):
    """Raised when digest quorum is reached but state-hash quorum is not."""
    pass


def canonicalize(payload: dict[str, Any]) -> bytes:
    # Deterministic: sorted keys, no whitespace, normalized scalars.
    return json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8")


def digest(payload: dict[str, Any]) -> str:
    return hashlib.sha256(canonicalize(payload)).hexdigest()


def state_hash(ledger_delta: dict[str, Any]) -> str:
    return hashlib.sha256(canonicalize(ledger_delta)).hexdigest()


@dataclass
class Proposal:
    task_id: str
    decision_id: str
    payload: dict[str, Any]
    ledger_delta: dict[str, Any]


@dataclass
class Vote:
    replica_id: str
    digest: str
    state_hash: str


def pre_commit_check(
    proposal: Proposal,
    votes: list[Vote],
    quorum: int,
) -> str:
    # Signal 1: digest diversity at constant semantic identity.
    distinct_digests = {v.digest for v in votes}
    if len(distinct_digests) > 1:
        raise EquivocationDetected(
            f"proposer equivocation on {proposal.task_id}/{proposal.decision_id}: "
            f"{len(distinct_digests)} distinct digests observed"
        )

    # Signal 2: digest quorum reached but state-hash quorum not.
    expected_digest = digest(proposal.payload)
    if expected_digest not in distinct_digests:
        raise EquivocationDetected(
            f"proposal digest {expected_digest} absent from vote set"
        )
    matching = [v for v in votes if v.digest == expected_digest]
    if len(matching) < quorum:
        raise SemanticQuorumFailure(
            f"digest quorum short: {len(matching)}/{quorum}"
        )

    expected_state = state_hash(proposal.ledger_delta)
    state_agree = [v for v in matching if v.state_hash == expected_state]
    if len(state_agree) < quorum:
        raise SemanticQuorumFailure(
            f"state-hash quorum short: {len(state_agree)}/{quorum}; "
            f"semantic finality not achieved despite digest agreement"
        )

    return expected_digest


def commit(proposal: Proposal, votes: list[Vote], quorum: int) -> str:
    committed_digest = pre_commit_check(proposal, votes, quorum)
    # Only now is the ledger delta applied; prior to this, no replica mutates state.
    return committed_digest
