# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-plan-commitments-when-byzantine-peers-sign-divergent-plan-digests-under-partial-synchrony.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-plan-commitments-when-byzantine-peers-sign-divergent-plan-digests-under-partial-synchrony.warrant.json
# Markdown SHA-256:   c5809a6c236859a65130345867091a41e43b9c30ee9a8a7b6079a9aeba27ff03
# Code AST SHA-256:   553dac7306231c898069dbfe1440b2a9b742cdccf2d7b6c9eccdcac7a33e255b
# Verified Classes:   PlanEquivocationError, CanonicalizationMismatch, SignedDigest, CommitmentLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class PlanEquivocationError(RuntimeError):
    """Raised when a peer signs two distinct plan digests for one (plan_id, epoch)."""
    pass


class CanonicalizationMismatch(RuntimeError):
    """Raised when a peer cannot reproduce the proposed digest from semantic content."""
    pass


@dataclass(frozen=True)
class SignedDigest:
    signer: str
    plan_id: str
    epoch: int
    digest: str
    signature: str


def canonical_plan_bytes(plan: dict) -> bytes:
    # Deterministic projection: sort tool calls by (name, args_repr); no dict order.
    steps = sorted(
        ((s["name"], repr(sorted(s.get("args", {}).items()))) for s in plan["steps"]),
        key=lambda t: (t[0], t[1]),
    )
    return repr(steps).encode("utf-8")


def digest_of(plan: dict) -> str:
    return hashlib.sha256(canonical_plan_bytes(plan)).hexdigest()


@dataclass
class CommitmentLedger:
    signed: Dict[Tuple[str, int], SignedDigest] = field(default_factory=dict)
    equivocation_proofs: Dict[str, Tuple[SignedDigest, SignedDigest]] = field(default_factory=dict)

    def sign(self, signer: str, plan_id: str, epoch: int, plan: dict, proposed_digest: str) -> SignedDigest:
        local = digest_of(plan)
        if local != proposed_digest:
            raise CanonicalizationMismatch(
                f"{signer}: proposed {proposed_digest[:12]} != local {local[:12]} for {plan_id}/{epoch}"
            )
        key = (plan_id, epoch)
        prior = self.signed.get(key)
        if prior is not None and prior.digest != local:
            proof = (prior, SignedDigest(signer, plan_id, epoch, local, sig="pending"))
            self.equivocation_proofs[signer] = proof
            raise PlanEquivocationError(
                f"{signer}: equivocation on {plan_id}/{epoch}: {prior.digest[:12]} vs {local[:12]}"
            )
        sd = SignedDigest(signer, plan_id, epoch, local, sig=f"sig:{signer}:{local[:8]}")
        self.signed[key] = sd
        return sd

    def commit(self, plan_id: str, epoch: int, quorum_size: int) -> str:
        key = (plan_id, epoch)
        if key not in self.signed:
            raise PlanEquivocationError(f"no commitment for {plan_id}/{epoch}")
        if self.signed[key].signer in self.equivocation_proofs:
            raise PlanEquivocationError(f"quorum for {plan_id}/{epoch} contains proven equivocator")
        return self.signed[key].digest


def run_epoch(ledger: CommitmentLedger, plan_id: str, epoch: int, plan_a: dict, plan_b: dict, quorum: int = 4) -> str:
    # Adversarial peer attempts split-signing across two semantically divergent plans.
    da, db = digest_of(plan_a), digest_of(plan_b)
    try:
        ledger.sign("planner", plan_id, epoch, plan_a, da)
        ledger.sign("executor_a", plan_id, epoch, plan_b, db)  # second distinct digest -> tripwire
    except PlanEquivocationError:
        raise
    return ledger.commit(plan_id, epoch, quorum)
