# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-valid-aaif-attestation-chain-when-the-warrant-s-scope-digest-no-longer-binds-to-the-live-capability-manifest.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-valid-aaif-attestation-chain-when-the-warrant-s-scope-digest-no-longer-binds-to-the-live-capability-manifest.warrant.json
# Markdown SHA-256:   887ba638c9b96c2153b0437b9138387a78340a0d981b66b972fcb5a8006a6cf4
# Code AST SHA-256:   5e1d1c6549a546ae4d97b8192a518b4e48815c3cf4c59e4e4abf1a51ba83eee4
# Verified Classes:   ScopeBindingError, Warrant, LiveTool
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Iterable


class ScopeBindingError(RuntimeError):
    """Raised when a valid AAIF chain fails to bind to the live capability manifest."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope_digest: str
    scope_canon: str | None      # e.g. "jcs-rfc8785/v1"; None => advisory only
    allowed_tools: frozenset[str]
    allowed_effects: frozenset[str]
    manifest_pinned: bool        # runtime warrants manifest immutability until expiry


@dataclass(frozen=True)
class LiveTool:
    name: str
    effect_class: str
    is_recursive_variant: bool = False


def canonicalize(manifest: Iterable[LiveTool], canon: str) -> bytes:
    if canon != "jcs-rfc8785/v1":
        raise ScopeBindingError(f"unsupported canonicalization: {canon!r}")
    payload = sorted(
        ({"name": t.name, "effect": t.effect_class, "recursive": t.is_recursive_variant}
         for t in manifest),
        key=lambda d: d["name"],
    )
    return json.dumps(payload, separators=(",", ":"), sort_keys=True).encode()


def authorize_call(warrant: Warrant, live_manifest: list[LiveTool], tool_name: str) -> None:
    tool = next((t for t in live_manifest if t.name == tool_name), None)
    if tool is None:
        raise ScopeBindingError(f"tool {tool_name!r} absent from live manifest")

    # Axis 2: attempt scope binding.
    if warrant.scope_canon is None or not warrant.manifest_pinned:
        # Indeterminate: downgrade to transport-only authority.
        if tool.name not in warrant.allowed_tools:
            raise ScopeBindingError(f"{tool_name!r} outside verbatim allow-list")
        if tool.effect_class not in warrant.allowed_effects:
            raise ScopeBindingError(f"effect {tool.effect_class!r} outside allowed_effects")
        if tool.is_recursive_variant:
            raise ScopeBindingError(f"{tool_name!r} is a recursive variant; forbidden under unbound warrant")
        return

    live_digest = hashlib.sha256(canonicalize(live_manifest, warrant.scope_canon)).hexdigest()
    if live_digest != warrant.scope_digest:
        raise ScopeBindingError(
            f"scope digest mismatch: warranted {warrant.scope_digest[:12]} "
            f"!= live {live_digest[:12]} under {warrant.scope_canon}"
        )
