# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-byzantine-equivocation-when-llm-agents-sign-divergent-reasoning-traces-under-identical-quorum-warrants.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-byzantine-equivocation-when-llm-agents-sign-divergent-reasoning-traces-under-identical-quorum-warrants.warrant.json
# Markdown SHA-256:   eec27afadfd8325782c9a66744c04c3da42fed116ef2aef535226ab31b60bfc6
# Code AST SHA-256:   befd28229abb00584447ebaa310ed20cf0e60754a51a05fb152fcfcd7684a983
# Verified Classes:   EquivocationDetected, UncommittedBundleRejected, CommitmentSlot
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when an agent writes a second commitment to a write-once slot."""
    pass


class UncommittedBundleRejected(RuntimeError):
    """Raised when a vote bundle lacks a quorum-acked commitment."""
    pass


@dataclass
class CommitmentSlot:
    # key: (agent_id, round, view) -> commitment digest, write-once
    slots: Dict[Tuple[str, int, int], str] = field(default_factory=dict)
    acked: Dict[Tuple[str, int, int], int] = field(default_factory=dict)
    quorum: int = 5

    def commit(self, agent_id: str, round_no: int, view: int, bundle_bytes: bytes) -> str:
        key = (agent_id, round_no, view)
        digest = hashlib.sha256(bundle_bytes).hexdigest()
        if key in self.slots:
            if self.slots[key] != digest:
                # Second, different commitment to same slot: attributable equivocation.
                # Trace stochasticity is irrelevant; the slot is write-once.
                raise EquivocationDetected(
                    f"agent {agent_id} committed divergent digests for "
                    f"round={round_no} view={view}: "
                    f"{self.slots[key][:12]} vs {digest[:12]}"
                )
            # Idempotent re-commit of identical bundle is allowed.
            return digest
        self.slots[key] = digest
        self.acked[key] = 0
        return digest

    def ack(self, agent_id: str, round_no: int, view: int) -> None:
        key = (agent_id, round_no, view)
        if key not in self.slots:
            raise UncommittedBundleRejected(
                f"ack for uncommitted slot {key}"
            )
        self.acked[key] += 1

    def admit_vote(self, agent_id: str, round_no: int, view: int, bundle_bytes: bytes) -> bool:
        key = (agent_id, round_no, view)
        digest = hashlib.sha256(bundle_bytes).hexdigest()
        if key not in self.slots:
            raise UncommittedBundleRejected(
                f"vote from {agent_id} round={round_no} view={view} "
                f"has no commitment slot"
            )
        if self.slots[key] != digest:
            raise EquivocationDetected(
                f"vote body digest {digest[:12]} does not match committed "
                f"{self.slots[key][:12]} for {key}"
            )
        if self.acked[key] < self.quorum:
            raise UncommittedBundleRejected(
                f"commitment for {key} has only {self.acked[key]}/{self.quorum} acks"
            )
        return True
