# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-signs-a-task-commitment-it-cannot-re-derive-quorum-forgery-via-divergent-canonicalization-in-llm-agent-bft-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-signs-a-task-commitment-it-cannot-re-derive-quorum-forgery-via-divergent-canonicalization-in-llm-agent-bft-consensus.warrant.json
# Markdown SHA-256:   3c5fba05d8dcfe23cb4fb07dde9ba82b59f331c634a3bbacc32295e02c024465
# Code AST SHA-256:   1f92959484f5c550f3b5905fdb743598dfcbe145e854c4eba92f35d7a69a4e08
# Verified Classes:   UnreproducibleCommitmentError, SignedEnvelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Mapping


class UnreproducibleCommitmentError(RuntimeError):
    """Raised when a sealed commitment cannot be re-derived byte-identically
    by a recovery agent, meaning the quorum certificate is unsound."""


@dataclass(frozen=True)
class SignedEnvelope:
    canonical_bytes: bytes
    canonicalizer_id: str
    digest: str
    signatures: Mapping[str, str]  # agent_id -> signature over digest


def canonicalize(payload: Mapping, canonicalizer_id: str) -> bytes:
    """Pinned, versioned canonicalizer. MUST be identical across all agents.
    Any LLM-driven 'normalization' here is the bug this record documents."""
    if canonicalizer_id != "cf-canon-v1":
        raise UnreproducibleCommitmentError(
            f"unknown canonicalizer {canonicalizer_id!r}; cannot reproduce digest"
        )
    return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()


def seal_commitment(
    payload: Mapping,
    canonicalizer_id: str,
    signatures: Mapping[str, str],
    quorum_size: int,
) -> SignedEnvelope:
    if len(signatures) < quorum_size:
        raise UnreproducibleCommitmentError(
            f"insufficient signatures: {len(signatures)} < {quorum_size}"
        )
    canon = canonicalize(payload, canonicalizer_id)
    digest = hashlib.sha256(canon).hexdigest()
    return SignedEnvelope(canon, canonicalizer_id, digest, dict(signatures))


def resume_commitment(envelope: SignedEnvelope, quorum_size: int) -> Mapping:
    """Recovery agent replays bytes, never semantics. If this cannot reproduce
    the digest from the stored bytes, the commitment is dead."""
    recomputed = hashlib.sha256(envelope.canonical_bytes).hexdigest()
    if recomputed != envelope.digest:
        raise UnreproducibleCommitmentError(
            f"digest mismatch on replay: sealed={envelope.digest} "
            f"recomputed={recomputed}"
        )
    if len(envelope.signatures) < quorum_size:
        raise UnreproducibleCommitmentError(
            "sealed envelope lost quorum during storage"
        )
    return json.loads(envelope.canonical_bytes)


def verify_signer_is_byte_bound(
    envelope: SignedEnvelope, signer_canonicalizer_id: str
) -> None:
    """The guardrail: reject any signer whose canonicalizer differs from the
    one bound into the envelope. A signature over a re-derived projection is
    not a signature over the commitment."""
    if signer_canonicalizer_id != envelope.canonicalizer_id:
        raise UnreproducibleCommitmentError(
            f"signer canonicalizer {signer_canonicalizer_id!r} != "
            f"envelope canonicalizer {envelope.canonicalizer_id!r}; "
            "signature attests to a projection, not the commitment"
        )
