# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-quorum-authorization-when-the-voting-set-s-action-commitment-hash-diverges-from-the-execution-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-quorum-authorization-when-the-voting-set-s-action-commitment-hash-diverges-from-the-execution-manifest.warrant.json
# Markdown SHA-256:   3637a2fe1f149fe056c77aae86736b23aed17afa47f7c39ab2ed7c39dc3c379a
# Code AST SHA-256:   55cab701cd96bc4cd5bcac10e202c770c52c3b2f652945ef9f35ee1c65882b43
# Verified Classes:   CommitmentDivergence, CanonicalizerUnavailable, AuthorizationToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CommitmentDivergence(RuntimeError):
    """Raised when an execution manifest does not re-hash to the quorum-signed commitment."""
    pass


class CanonicalizerUnavailable(RuntimeError):
    """Raised when the canonicalization version pinned by the token is not available."""
    pass


CANONICALIZERS = {
    "v3": lambda d: json.dumps(d, sort_keys=True, separators=(",", ":")).encode("utf-8"),
}


@dataclass(frozen=True)
class AuthorizationToken:
    commitment: str
    canon_version: str
    quorum_signatures: int


def authorize_execution(token: AuthorizationToken, manifest: dict) -> str:
    """Return the canonical commitment iff the manifest re-derives to the signed commitment.

    Fail-closed: any inability to prove the match is treated as a refusal.
    """
    canon = CANONICALIZERS.get(token.canon_version)
    if canon is None:
        raise CanonicalizerUnavailable(
            f"token pins canonicalization {token.canon_version!r}; "
            f"executor has {sorted(CANONICALIZERS)}"
        )

    derived = hashlib.sha256(canon(manifest)).hexdigest()
    if derived != token.commitment:
        raise CommitmentDivergence(
            f"manifest hash {derived[:12]} != signed commitment "
            f"{token.commitment[:12]} (canon={token.canon_version}); "
            f"refusing side effect — do not retry with a rebuilt manifest"
        )
    return derived


def dispatch(token: AuthorizationToken, manifest: dict, tool) -> object:
    """Gate a side-effecting tool call behind commitment re-derivation."""
    authorize_execution(token, manifest)  # raises before any side effect
    return tool(manifest)
