# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-brokered-trust-warrant-when-the-negotiation-transcript-hash-diverges-from-the-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-brokered-trust-warrant-when-the-negotiation-transcript-hash-diverges-from-the-capability.warrant.json
# Markdown SHA-256:   84a8309a29309732c02304cec75e324273a96f0ba88b2ee3773f3ee233d3354e
# Code AST SHA-256:   33d24cafbff7706d9e9ec5554cd6b01786423ac7230928d0694e2a5ca53a5f21
# Verified Classes:   WarrantConstraintDivergence, SignedWarrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class WarrantConstraintDivergence(RuntimeError):
    """Raised when the executor's enforcement-path transcript does not bind to the signed warrant."""
    pass


@dataclass(frozen=True)
class SignedWarrant:
    issuer: str
    transcript_digest: str
    signature_valid: bool


def canonicalize(transcript: dict[str, Any]) -> bytes:
    # Pinned canonical form: sorted keys, explicit nulls preserved, ints not floats.
    return json.dumps(transcript, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")


def enforce_federated_task(
    warrant: SignedWarrant,
    received_transcript: dict[str, Any],
    side_channel_constraints: dict[str, Any] | None,
) -> dict[str, Any]:
    if not warrant.signature_valid:
        raise WarrantConstraintDivergence(f"warrant from {warrant.issuer} failed signature check")

    enforcement_digest = hashlib.sha256(canonicalize(received_transcript)).hexdigest()
    if enforcement_digest != warrant.transcript_digest:
        # Fail closed. A mismatch means serializer drift; benignness is not verifiable here.
        raise WarrantConstraintDivergence(
            f"enforcement-path digest {enforcement_digest[:12]} != signed "
            f"{warrant.transcript_digest[:12]} for issuer {warrant.issuer}"
        )

    if side_channel_constraints is not None:
        # Even with a matching digest, constraints sourced outside the transcript are unbound.
        raise WarrantConstraintDivergence(
            "constraint set derived from side channel, not from verified transcript"
        )

    # Enforce directly from the parsed transcript object — no second serialization exists.
    return received_transcript
