# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-agent-is-equivocating-on-task-commitment-rather-than-merely-lagging.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-agent-is-equivocating-on-task-commitment-rather-than-merely-lagging.warrant.json
# Markdown SHA-256:   758bf210d5bdfc3ce45986b00c623e1160e8f02d42a511523d420f5b5ab93caf
# Code AST SHA-256:   0e6c576085397be9c11c462411ea0f258a8b1658d3aec434c16673c490da2d61
# Verified Classes:   EquivocationEvidenceDestroyed, EquivocationDetected, Commitment, CommitmentStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EquivocationEvidenceDestroyed(RuntimeError):
    """Raised when a commitment store cannot reconstruct the full multiset
    M(agent, round) because deduplication collapsed conflicting commitments."""
    pass


class EquivocationDetected(RuntimeError):
    """Raised when an agent has signed two conflicting commitments in the same round."""
    pass


@dataclass(frozen=True)
class Commitment:
    agent_id: str
    round: int
    task_id: str
    payload_root: str  # Merkle root of task payload; MUST be in preimage
    signature: bytes

    def commit_hash(self) -> str:
        # Identity includes payload_root; omitting it masks equivocation.
        preimage = f"{self.agent_id}|{self.round}|{self.task_id}|{self.payload_root}".encode()
        return hashlib.sha256(preimage).hexdigest()


class CommitmentStore:
    """Append-only store. Deduplicates ONLY by full digest, never by identity key."""

    def __init__(self) -> None:
        # key: (agent_id, round, task_id) -> list of distinct commitments
        self._by_identity: Dict[Tuple[str, int, str], List[Commitment]] = {}
        self._seen_digests: set = set()

    def ingest(self, c: Commitment) -> None:
        digest = c.commit_hash() + "|" + c.signature.hex()
        if digest in self._seen_digests:
            return  # true duplicate, safe to drop
        self._seen_digests.add(digest)
        key = (c.agent_id, c.round, c.task_id)
        self._by_identity.setdefault(key, []).append(c)

    def detect_equivocation(self, agent_id: str, round_no: int) -> None:
        # Collect all commitments from this agent in this round across tasks.
        roots_by_task: Dict[str, set] = {}
        for (aid, rnd, task), commits in self._by_identity.items():
            if aid != agent_id or rnd != round_no:
                continue
            roots_by_task.setdefault(task, set()).update(
                c.payload_root for c in commits
            )
        for task, roots in roots_by_task.items():
            if len(roots) > 1:
                raise EquivocationDetected(
                    f"agent={agent_id} round={round_no} task={task} "
                    f"signed conflicting payload_roots={sorted(roots)}"
                )

    def reconstruct_multiset(self, agent_id: str, round_no: int) -> List[Commitment]:
        out: List[Commitment] = []
        for (aid, rnd, _task), commits in self._by_identity.items():
            if aid == agent_id and rnd == round_no:
                out.extend(commits)
        if not out:
            raise EquivocationEvidenceDestroyed(
                f"no commitments retained for agent={agent_id} round={round_no}; "
                f"evidence may have been deduplicated by identity key"
            )
        return out


def reconcile_round(store: CommitmentStore, agents: List[str], round_no: int) -> None:
    """Decision boundary: equivocation -> exclude; absence -> lag (retry)."""
    for agent in agents:
        try:
            store.detect_equivocation(agent, round_no)
        except EquivocationDetected:
            # Byzantine: exclude from quorum, do NOT retry.
            raise
        # Absence is lag, handled by caller's retry loop — not a fault here.
