# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-delegated-capability-token-when-a-tool-s-declared-schema-mutates-mid-chain-and-why-silent-token-reu.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-delegated-capability-token-when-a-tool-s-declared-schema-mutates-mid-chain-and-why-silent-token-reu.warrant.json
# Markdown SHA-256:   1d09f9c8cc5c8ee873299dcab6d71db09c43fc2e675f959b8aaa660b11997adb
# Code AST SHA-256:   ac7f52d436d9cc25946bf2013bfb1306d1ce14e9122cb6f6efd1af1766103e08
# Verified Classes:   SchemaDriftError, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaDriftError(RuntimeError):
    """Raised when a presented capability token is bound to a descriptor hash
    that no longer matches the live tool schema. Re-derivation is required;
    reuse would silently over-authorize."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    subject: str
    tool_id: str
    schema_hash: str
    scope_predicate: str
    expires_at: float
    signature: str


def canonical_descriptor_hash(descriptor: dict) -> str:
    # Canonicalize: sorted keys, explicit field types, enum closures, required flags.
    canon = json.dumps(descriptor, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canon.encode()).hexdigest()


def verify_and_gate(
    token: CapabilityToken,
    live_descriptor: dict,
    now: float,
    verify_signature,
) -> None:
    # 1. Cryptographic and temporal checks (the ones everyone runs).
    if not verify_signature(token):
        raise SchemaDriftError("signature invalid")
    if now >= token.expires_at:
        raise SchemaDriftError("token expired")
    if token.tool_id != live_descriptor.get("tool_id"):
        raise SchemaDriftError("tool_id mismatch")

    # 2. The invariant most runtimes skip: presentation-time hash gate.
    live_hash = canonical_descriptor_hash(live_descriptor)
    if live_hash != token.schema_hash:
        raise SchemaDriftError(
            f"schema drift on {token.tool_id}: token bound to "
            f"{token.schema_hash[:12]} but live descriptor is {live_hash[:12]}; "
            f"re-derive capability token before dispatch"
        )

    # 3. Predicate must be re-evaluated against presented args downstream,
    #    never against caller-claimed args. Gate returns only if all hold.


def dispatch_with_token(token: CapabilityToken, live_descriptor: dict, now: float, verify_signature, args: dict) -> dict:
    verify_and_gate(token, live_descriptor, now, verify_signature)
    # Re-evaluate scope predicate over *presented* args, not claimed args.
    if "override_limit" in args and "override_limit" not in token.scope_predicate:
        raise SchemaDriftError(
            "argument 'override_limit' not covered by scope_predicate; "
            "token was minted before this field existed"
        )
    return {"status": "dispatched", "args": args}
