# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-a-litmus-derived-safety-gate-when-a-tool-s-declared-capability-envelope-shifts-between-gate-evaluation-and-invocati.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-a-litmus-derived-safety-gate-when-a-tool-s-declared-capability-envelope-shifts-between-gate-evaluation-and-invocati.warrant.json
# Markdown SHA-256:   f4919ec6fa30a7b6c7916e838b53ea07f3af94740504f7c711574d3716f8dcbc
# Code AST SHA-256:   a36db7f1614191f7696ba2318a98034c50e7e023fefdf4db00e436a3f9a16ed4
# Verified Classes:   GateStaleError, GateToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class GateStaleError(RuntimeError):
    """Raised when a LITMUS gate token no longer matches the call being dispatched."""


@dataclass(frozen=True)
class GateToken:
    allowed: bool
    args_digest: str
    envelope_version: str


def canonicalize(args: dict[str, Any]) -> str:
    # Deterministic: sorted keys, no whitespace drift, explicit separators.
    return json.dumps(args, sort_keys=True, separators=(",", ":"))


def digest(args: dict[str, Any]) -> str:
    return hashlib.sha256(canonicalize(args).encode("utf-8")).hexdigest()


def dispatch(tool, args: dict[str, Any], token: GateToken, envelope_version: str) -> Any:
    if not token.allowed:
        raise GateStaleError("gate token was never allowed; refusing dispatch")

    # Envelope may have shifted between probe and dispatch.
    if token.envelope_version != envelope_version:
        raise GateStaleError(
            f"envelope version changed: token={token.envelope_version} "
            f"dispatch={envelope_version}; re-probe required"
        )

    # The call being dispatched must be the call the gate classified.
    live_digest = digest(args)
    if live_digest != token.args_digest:
        raise GateStaleError(
            "argument digest mismatch between LITMUS probe and dispatch; "
            "arguments were mutated after gating"
        )

    return tool.invoke(args)
