# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-commitment-equivocation-from-view-change-re-proposal-in-a-byzantine-fault-tolerant-task-commitment-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-commitment-equivocation-from-view-change-re-proposal-in-a-byzantine-fault-tolerant-task-commitment-ledger.warrant.json
# Markdown SHA-256:   c622fa464408f51b6b946d3504bba4d2647211b0c0030878cb5de51c67ea406d
# Code AST SHA-256:   edc807de444ad3ce87e01281c319de2234fdb762b9782f7f40f8b791c2e6bfc3
# Verified Classes:   CommitmentSafetyError, Proposal
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional


class CommitmentSafetyError(RuntimeError):
    """Raised when a commitment cannot be safely accepted or rejected."""


@dataclass(frozen=True)
class Proposal:
    task_id: str
    agent_id: str
    epoch: int
    config_epoch: int
    nonce: int
    prev_commit_hash: str
    qc_signers: FrozenSet[str]
    qc_certified_view: int


def _epoch_membership(config_epoch: int) -> FrozenSet[str]:
    # Placeholder: real implementation reads the epoch-bound validator set.
    raise CommitmentSafetyError(f"no validator set registered for config_epoch={config_epoch}")


def classify(new: Proposal, committed: Proposal) -> str:
    """Return 'reproposal', 'equivocation', or 'stale_quorum'."""
    if new.task_id != committed.task_id or new.agent_id != committed.agent_id:
        raise CommitmentSafetyError("classify() called on unrelated commitments")

    if new.config_epoch < committed.config_epoch:
        raise CommitmentSafetyError(
            f"proposal config_epoch {new.config_epoch} regresses committed {committed.config_epoch}"
        )

    if new.qc_certified_view < 0:
        raise CommitmentSafetyError("QC certified_view must be non-negative")

    members = _epoch_membership(new.config_epoch)
    if not new.qc_signers.issubset(members):
        return "stale_quorum"

    f = (len(members) - 1) // 3
    if len(new.qc_signers) < 2 * f + 1:
        raise CommitmentSafetyError(
            f"QC undersized: {len(new.qc_signers)} < 2f+1={2 * f + 1}"
        )

    if new.prev_commit_hash != committed.prev_commit_hash:
        # Different chain head for same logical commitment: equivocation unless
        # the new QC certifies a view strictly after the committed one.
        if new.qc_certified_view > committed.qc_certified_view:
            return "reproposal"
        return "equivocation"

    if new.nonce > committed.nonce:
        return "reproposal"

    raise CommitmentSafetyError(
        f"nonce {new.nonce} not monotonic over committed {committed.nonce}"
    )


def assert_no_double_assignment(
    a: Proposal, b: Proposal, members: FrozenSet[str]
) -> None:
    f = (len(members) - 1) // 3
    if a.task_id != b.task_id:
        return
    if a.agent_id == b.agent_id:
        return
    if a.epoch != b.epoch:
        return
    intersection = a.qc_signers & b.qc_signers
    if len(intersection) < f + 1:
        raise CommitmentSafetyError(
            f"double assignment on task {a.task_id}: QCs intersect in "
            f"{len(intersection)} < f+1={f + 1} validators"
        )
