# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-by-a-heterogeneous-peer-before-committing-shared-task-state-under-bft-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-by-a-heterogeneous-peer-before-committing-shared-task-state-under-bft-consensus.warrant.json
# Markdown SHA-256:   87bddbc4462f53160ffc242f8f70c3c251cb47ec16c54261067074e79fa1fcb6
# Code AST SHA-256:   35627799f1e43d8f5af1f74d6f1816b840f35a5f8e26e7fdbe72f2317c3ce41f
# Verified Classes:   EquivocationError, RationaleBindingError, PreFlushBarrierError, SignedPrepare, CommitmentSet
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Dict, Tuple, List


class EquivocationError(RuntimeError):
    """Raised when a signer has emitted conflicting vote digests for the same (task, view)."""
    pass


class RationaleBindingError(RuntimeError):
    """Raised when a message's signed payload does not bind the normalized rationale hash."""
    pass


class PreFlushBarrierError(RuntimeError):
    """Raised when a durable flush is attempted before the audit barrier clears."""
    pass


@dataclass
class SignedPrepare:
    signer: str
    task_id: str
    view: int
    vote_digest: str          # structured, e.g. "APPEND_AFTER_CHECKPOINT"
    rationale: str            # free-text, non-deterministic decoder output
    rationale_hash: str       # hash(normalize(rationale)) -- MUST be in signed payload
    signature: str            # signature over (task_id, view, vote_digest, rationale_hash)
    sig_covers_rationale_hash: bool


@dataclass
class CommitmentSet:
    # (signer, task_id, view) -> admitted vote_digest
    admitted: Dict[Tuple[str, str, int], str] = field(default_factory=dict)
    # (signer, task_id, view) -> list of buffered messages awaiting audit
    buffer: Dict[Tuple[str, str, int], List[SignedPrepare]] = field(default_factory=dict)
    # (signer, task_id, view) -> auditor attested NO_EQUIVOCATION
    audit_cleared: set = field(default_factory=set)


def normalize(rationale: str) -> str:
    # Canonical claim extraction: lowercase, strip whitespace, collapse synonyms.
    # In production this is a deterministic claim-graph extractor, not string munging.
    return " ".join(rationale.lower().split())


def expected_rationale_hash(rationale: str) -> str:
    return hashlib.sha256(normalize(rationale).encode()).hexdigest()


def admit_prepare(cs: CommitmentSet, msg: SignedPrepare, f: int,
                  distinct_digest_signers: Dict[Tuple[str, int], set]) -> str:
    key = (msg.signer, msg.task_id, msg.view)

    # Guard 1: rationale must be bound into the signed payload.
    if not msg.sig_covers_rationale_hash:
        raise RationaleBindingError(
            f"signer={msg.signer} task={msg.task_id} view={msg.view}: "
            f"rationale_hash not covered by signature"
        )
    if msg.rationale_hash != expected_rationale_hash(msg.rationale):
        raise RationaleBindingError(
            f"signer={msg.signer}: rationale_hash mismatch on normalize()"
        )

    # Guard 2: digest-level equivocation is provable and immediate.
    prior = cs.admitted.get(key)
    if prior is not None and prior != msg.vote_digest:
        raise EquivocationError(
            f"PROVABLE EQUIVOCATION signer={msg.signer} task={msg.task_id} "
            f"view={msg.view}: admitted={prior} new={msg.vote_digest}"
        )

    # Guard 3: buffer until audit barrier or f+1 quorum escape.
    cs.buffer.setdefault(key, []).append(msg)
    audit_ok = key in cs.audit_cleared
    quorum_ok = len(distinct_digest_signers.get((msg.task_id, msg.view), set())) >= f + 1

    if not (audit_ok or quorum_ok):
        raise PreFlushBarrierError(
            f"signer={msg.signer} task={msg.task_id} view={msg.view}: "
            f"buffered, audit barrier not cleared and quorum escape not met"
        )

    # Cross-message rationale scan: only meaningful when audit is pending;
    # a rationale mismatch with matching digest is NOT grounds for rejection.
    if not audit_ok:
        for other in cs.buffer[key]:
            if other.vote_digest != msg.vote_digest:
                raise EquivocationError(
                    f"PROVABLE EQUIVOCATION signer={msg.signer} "
                    f"task={msg.task_id} view={msg.view}: "
                    f"{other.vote_digest} vs {msg.vote_digest}"
                )

    cs.admitted[key] = msg.vote_digest
    return msg.vote_digest


def flush_shared_state(cs: CommitmentSet, task_id: str, view: int,
                       f: int, distinct_digest_signers: Dict[Tuple[str, int], set]) -> None:
    # Durable write is gated on the same barrier; never bypass.
    if len(distinct_digest_signers.get((task_id, view), set())) < f + 1:
        raise PreFlushBarrierError(
            f"task={task_id} view={view}: refusing durable flush without f+1 quorum"
        )
    # ... write to ledger ...
