# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-committed-task-quorum-silently-exceeds-its-epistemic-horizon-equivocation-tolerant-consensus-without-knowledge-provena.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-committed-task-quorum-silently-exceeds-its-epistemic-horizon-equivocation-tolerant-consensus-without-knowledge-provena.warrant.json
# Markdown SHA-256:   8a102cea52c9f86526aaf1b0239b76b5c51ef4f237f8d9b2456e95d0c49936e6
# Code AST SHA-256:   00b83559d7b37d65e67e9b378c924cc09b92f07e0f94cb777eab2dd3f5652047
# Verified Classes:   UngroundedCommitmentError, SignedVote, ProvenanceBundle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Sequence


class UngroundedCommitmentError(RuntimeError):
    """Raised when a BFT-committed task fails epistemic intersection non-emptiness."""


@dataclass(frozen=True)
class SignedVote:
    voter_id: str
    proposal_id: str
    precondition_digest: str  # digest of the *values* checked, not the schema
    snapshot_digest: str      # digest of the voter's local state at vote time
    signature: str


@dataclass
class ProvenanceBundle:
    proposal_id: str
    votes: list[SignedVote] = field(default_factory=list)
    horizon_skew_budget: int = 0  # max tolerated digest-distance, in sync-ticks


def _digest_distance(a: str, b: str) -> int:
    # Proxy for snapshot divergence: Hamming distance over hex nibbles.
    return sum(x != y for x, y in zip(a, b))


def verify_commitment_grounding(
    bundle: ProvenanceBundle,
    quorum_size: int,
    required_quorum: int,
) -> None:
    """Enforce EINE: at least one honest voter must be able to reconstruct
    a joint state consistent with every other honest voter's evidence."""
    if len(bundle.votes) < required_quorum:
        raise UngroundedCommitmentError(
            f"quorum shortfall: {len(bundle.votes)} < {required_quorum}"
        )

    # 1. Precondition digests must agree — voters checked the *same* predicate
    #    against *their* state. Divergence here is a genuine equivocation.
    preconds = {v.precondition_digest for v in bundle.votes}
    if len(preconds) > 1:
        raise UngroundedCommitmentError(
            f"precondition equivocation across voters: {preconds}"
        )

    # 2. Snapshot digests must lie within the horizon skew budget. If not,
    #    the quorum agreed on a predicate none of them jointly observed.
    snapshots = [v.snapshot_digest for v in bundle.votes]
    for i in range(len(snapshots)):
        for j in range(i + 1, len(snapshots)):
            if _digest_distance(snapshots[i], snapshots[j]) > bundle.horizon_skew_budget:
                raise UngroundedCommitmentError(
                    f"horizon skew exceeded between {bundle.votes[i].voter_id} "
                    f"and {bundle.votes[j].voter_id}: "
                    f"{_digest_distance(snapshots[i], snapshots[j])} > "
                    f"{bundle.horizon_skew_budget}"
                )

    # 3. At least one voter must have a snapshot that dominates the union —
    #    i.e., can reconstruct the joint state. Here approximated by requiring
    #    that the *minimum* pairwise distance is zero (a shared anchor).
    if min(
        _digest_distance(snapshots[i], snapshots[j])
        for i in range(len(snapshots))
        for j in range(i + 1, len(snapshots))
    ) > 0:
        raise UngroundedCommitmentError(
            "no shared snapshot anchor: EINE violated, commitment is "
            "Byzantine-safe but epistemically void"
        )


def commit_task(bundle: ProvenanceBundle, required_quorum: int) -> str:
    verify_commitment_grounding(bundle, len(bundle.votes), required_quorum)
    return hashlib.sha256(
        b"".join(v.signature.encode() for v in bundle.votes)
    ).hexdigest()
