# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-tool-manifest-s-declared-schema-and-the-server-s-runtime-behavior-and-what-breaks-when-it-doe.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-tool-manifest-s-declared-schema-and-the-server-s-runtime-behavior-and-what-breaks-when-it-doe.warrant.json
# Markdown SHA-256:   7f60336262284ea2475e579c03dfebe4a981e127b1dd921afa77cff76f557ef8
# Code AST SHA-256:   c97510bdcb613706739f6350bffdaa234d1164048f16e8c3d52c5e84a5c5e665
# Verified Classes:   ManifestTrustError, CapabilityViolation, PinnedManifest, ToolBinding
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ManifestTrustError(RuntimeError):
    """Raised when a tool manifest cannot be bound to a verifiable handler."""
    pass


class CapabilityViolation(ManifestTrustError):
    """Raised when a tool call requests or produces capabilities beyond the pinned manifest."""
    pass


@dataclass(frozen=True)
class PinnedManifest:
    tool_name: str
    digest: str                      # sha256 of canonicalized tools/list entry
    declared_capabilities: frozenset[str]
    attested_capabilities: frozenset[str] | None   # None => un-attested, minimum only


@dataclass
class ToolBinding:
    manifest: PinnedManifest
    session_digest: str
    granted_capabilities: frozenset[str] = field(default_factory=frozenset)


MINIMUM_CAPABILITIES = frozenset({"respond"})


def canonical_digest(entry: dict[str, Any]) -> str:
    canonical = json.dumps(entry, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def bind_tool(entry: dict[str, Any], pinned_digest: str) -> ToolBinding:
    actual = canonical_digest(entry)
    if actual != pinned_digest:
        # Substitution window: tag repointed, cache stale, or registry mutated.
        raise ManifestTrustError(
            f"manifest digest mismatch for {entry.get('name')!r}: "
            f"pinned={pinned_digest} actual={actual}"
        )
    attested = entry.get("x-attested-capabilities")
    attested_set = frozenset(attested) if attested is not None else None
    declared = frozenset(entry.get("x-declared-capabilities", ["respond"]))
    granted = (attested_set & declared) if attested_set is not None else MINIMUM_CAPABILITIES
    return ToolBinding(
        manifest=PinnedManifest(
            tool_name=entry["name"],
            digest=actual,
            declared_capabilities=declared,
            attested_capabilities=attested_set,
        ),
        session_digest=actual,
        granted_capabilities=granted,
    )


def authorize_call(binding: ToolBinding, requested: frozenset[str]) -> None:
    if binding.session_digest != binding.manifest.digest:
        raise ManifestTrustError("binding digest drifted from session pin")
    over = requested - binding.granted_capabilities
    if over:
        raise CapabilityViolation(
            f"tool {binding.manifest.tool_name!r} requested {sorted(over)} "
            f"but only {sorted(binding.granted_capabilities)} are granted"
        )


def validate_response(binding: ToolBinding, response: dict[str, Any],
                      declared_output_fields: frozenset[str]) -> None:
    extra = frozenset(response.keys()) - declared_output_fields
    if extra:
        # Undeclared output field => handler is not the manifest-described handler.
        raise CapabilityViolation(
            f"tool {binding.manifest.tool_name!r} returned undeclared fields "
            f"{sorted(extra)}; handler diverges from manifest"
        )
