# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-when-a-byzantine-agent-commits-divergent-task-graphs-to-two-quorums.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocation-when-a-byzantine-agent-commits-divergent-task-graphs-to-two-quorums.warrant.json
# Markdown SHA-256:   8f1688bde74439061b5f8a5a60bd8d5fcda0a05a47724cd7a889ab305644e1ed
# Code AST SHA-256:   5079c94e674a2e2b17327c59d3d3832e0b3f040230691af88749d24030219821
# Verified Classes:   EquivocationDetected, CommitmentHashMismatch, SignedCommit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class EquivocationDetected(RuntimeError):
    """Raised when two signed commitments from one identity share an epoch
    but bind different canonical payloads."""
    pass


class CommitmentHashMismatch(RuntimeError):
    """Raised when a member is asked to sign an identifier that does not
    match the canonical hash of the payload it holds."""
    pass


def canonicalize(dag: dict[str, Any]) -> bytes:
    # Deterministic across replicas: sorted keys, sorted dependency sets,
    # no free-text in structural positions.
    def norm(node: dict[str, Any]) -> dict[str, Any]:
        out = dict(node)
        if "depends_on" in out:
            out["depends_on"] = sorted(out["depends_on"])
        return out

    normalized = {k: norm(v) for k, v in sorted(dag.items())}
    return json.dumps(normalized, sort_keys=True, separators=(",", ":")).encode()


def commitment_id(dag: dict[str, Any]) -> str:
    return hashlib.sha256(canonicalize(dag)).hexdigest()


@dataclass(frozen=True)
class SignedCommit:
    signer: str
    epoch: int
    identifier: str
    payload: dict[str, Any]


def sign_commit(signer: str, epoch: int, dag: dict[str, Any]) -> SignedCommit:
    expected = commitment_id(dag)
    # The signer must be able to reproduce the identifier from its own body.
    # If it cannot, it is about to equivocate against a peer.
    if expected != commitment_id(dag):
        raise CommitmentHashMismatch(
            f"{signer} cannot reproduce identifier for epoch {epoch}"
        )
    return SignedCommit(signer=signer, epoch=epoch, identifier=expected, payload=dag)


def check_equivocation(
    prior: list[SignedCommit], incoming: SignedCommit
) -> None:
    for p in prior:
        if p.signer == incoming.signer and p.epoch == incoming.epoch:
            if p.identifier != incoming.identifier:
                raise EquivocationDetected(
                    f"signer={incoming.signer} epoch={incoming.epoch} "
                    f"committed {p.identifier} and {incoming.identifier}"
                )
            # Same identifier must imply same canonical payload.
            if canonicalize(p.payload) != canonicalize(incoming.payload):
                raise EquivocationDetected(
                    f"signer={incoming.signer} epoch={incoming.epoch} "
                    f"identifier collision on divergent payloads"
                )
