# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-byzantine-commit-equivocation-before-shared-state-reconciliation-in-multi-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-byzantine-commit-equivocation-before-shared-state-reconciliation-in-multi-agent-consensus.warrant.json
# Markdown SHA-256:   aa270d2c04d80a9fe291b917b24eada5f540bca7b9baaf8cff6b6c3d47bcb5e2
# Code AST SHA-256:   49adb8d2ce7439f79421dc3a9e58589a88db74e2a052195db2d2be7c71cc6e61
# Verified Classes:   PayloadEquivocationError, CommitCertificate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class PayloadEquivocationError(RuntimeError):
    """Raised when a reconciled payload's canonical hash does not match the
    propose-time hash pinned in the commit certificate. Signals a semantic
    fork attempt (post-vote paraphrase, non-canonical serialization, or
    payload substitution) that the vote layer cannot detect."""
    pass


def canonical_hash(payload: dict) -> str:
    # Canonical serialization: sorted keys, no whitespace, UTF-8, no floats.
    # LLM agents must normalize paraphrase BEFORE propose; this function
    # is the single source of truth for H*.
    canon = json.dumps(payload, sort_keys=True, separators=(",", ":"),
                       ensure_ascii=False)
    return hashlib.sha256(canon.encode("utf-8")).hexdigest()


@dataclass
class CommitCertificate:
    round: int
    tx: str
    pinned_hash: str          # H* fixed at PROPOSE time
    votes: dict               # agent_id -> signed vote over (round, tx, H*)


def reconcile(cert: CommitCertificate, delivered_payload: dict,
              delivered_hash: str) -> dict:
    """Reconciliation entry point. Fails closed on hash mismatch."""
    recomputed = canonical_hash(delivered_payload)
    if delivered_hash != cert.pinned_hash:
        raise PayloadEquivocationError(
            f"tx={cert.tx} round={cert.round}: delivered_hash "
            f"{delivered_hash[:12]} != pinned {cert.pinned_hash[:12]}; "
            f"agent attempted post-propose payload substitution"
        )
    if recomputed != cert.pinned_hash:
        raise PayloadEquivocationError(
            f"tx={cert.tx} round={cert.round}: recomputed canonical hash "
            f"{recomputed[:12]} != pinned {cert.pinned_hash[:12]}; "
            f"payload was paraphrased or non-canonically serialized"
        )
    return delivered_payload


# --- Failure trace from the observed swarm ---
# Agent-2 paraphrased after PROPOSE; its delivered_hash was computed over the
# paraphrase, so delivered_hash != pinned_hash. Under the old per-agent-hash
# certificate this passed and forked the store. Under the pinned-hash
# certificate it is rejected here, before any write.
_cert = CommitCertificate(round=7, tx="0x9af", pinned_hash="deadbeef" * 8,
                          votes={"a1": "COMMIT", "a2": "COMMIT"})
try:
    reconcile(_cert, {"fact": "paraphrased version"},
              delivered_hash=canonical_hash({"fact": "paraphrased version"}))
except PayloadEquivocationError as e:
    # Bounded rejection: tx treated as not-committed for state purposes.
    # Store does not fork; agent must re-propose.
    print(f"rejected: {e}")
