# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-byzantine-equivocation-and-benign-staleness-in-agent-task-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-byzantine-equivocation-and-benign-staleness-in-agent-task-commitment.warrant.json
# Markdown SHA-256:   49c88466ab564eb33321ccefd2cd2966655aeb4a9914a6ccc74e25154c07c81c
# Code AST SHA-256:   5de5acda94a85f05440145fa2730290c31a003842e86a9e50adda8a49b7b6c7e
# Verified Classes:   ByzantineCommitmentError, CommitmentRecord
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ByzantineCommitmentError(RuntimeError):
    """Raised when a commitment record violates the view-scoped quorum invariant."""
    pass


@dataclass(frozen=True)
class CommitmentRecord:
    origin: str
    task_id: str
    assignee: str
    view: int
    signature: bytes  # sign(origin, task_id, assignee, view)


def verify_sig(rec: CommitmentRecord) -> bool:
    expected = hashlib.sha256(
        f"{rec.origin}|{rec.task_id}|{rec.assignee}|{rec.view}".encode()
    ).digest()
    return expected == rec.signature


def classify_disagreement(
    local: CommitmentRecord,
    incoming: CommitmentRecord,
    quorum_current_view: int,
) -> str:
    """
    Classify an incoming record against local state under the view-scoped
    quorum invariant. Returns one of: 'equivocation', 'stale', 'self_stale',
    'forgery', 'consistent'.
    """
    if not (verify_sig(local) and verify_sig(incoming)):
        raise ByzantineCommitmentError(
            f"signature verification failed: local={local.origin}@{local.view} "
            f"incoming={incoming.origin}@{incoming.view}"
        )

    if incoming.origin != local.origin:
        # Cross-origin comparison is not a disagreement; it is a distinct
        # proposal and must be handled by the commit protocol, not here.
        return "consistent"

    if incoming.task_id != local.task_id:
        return "consistent"

    if incoming.view == local.view:
        if incoming.assignee != local.assignee:
            # Same origin, same view, same task, different assignee:
            # unforgeable equivocation proof.
            return "equivocation"
        if incoming.signature != local.signature:
            return "forgery"
        return "consistent"

    if incoming.view < local.view:
        # Stale peer. Must NOT be ejected. Its vote does not count toward
        # quorum_current_view.
        if incoming.view < quorum_current_view:
            return "stale"
        return "stale"

    if incoming.view > local.view:
        return "self_stale"

    raise ByzantineCommitmentError(
        f"unreachable classification state for {incoming.origin}"
    )


def admit_vote(
    record: CommitmentRecord,
    quorum_current_view: int,
    known_equivocation_proofs: dict,
) -> bool:
    """
    Admit a vote into the current-view quorum tally. Raises on any record
    that would violate the view-scoped invariant.
    """
    if not verify_sig(record):
        raise ByzantineCommitmentError(
            f"unverifiable vote from {record.origin}@{record.view}"
        )

    if record.origin in known_equivocation_proofs:
        raise ByzantineCommitmentError(
            f"vote from ejected equivocator {record.origin}"
        )

    if record.view != quorum_current_view:
        # Stale or future vote: excluded from tally, but NOT an error and
        # NOT grounds for ejection. Caller must trigger view-sync.
        return False

    return True


def reconcile(
    local: CommitmentRecord,
    incoming: CommitmentRecord,
    quorum_current_view: int,
    proofs: dict,
) -> Optional[str]:
    verdict = classify_disagreement(local, incoming, quorum_current_view)

    if verdict == "equivocation":
        proof_key = f"{incoming.origin}:{incoming.task_id}:{incoming.view}"
        proofs[proof_key] = (local, incoming)
        raise ByzantineCommitmentError(
            f"equivocation proof recorded for {incoming.origin} at view "
            f"{incoming.view}; eject and propagate proof"
        )

    if verdict == "forgery":
        raise ByzantineCommitmentError(
            f"forged record from {incoming.origin} at view {incoming.view}"
        )

    if verdict == "stale":
        # Do not eject. Request view-sync; vote is provisional.
        return "request_view_sync"

    if verdict == "self_stale":
        # Halt local commit until caught up.
        return "halt_and_sync"

    return None
