# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-never-re-validates-capability-spoofing-and-the-manifest-drift-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-it-never-re-validates-capability-spoofing-and-the-manifest-drift-invariant.warrant.json
# Markdown SHA-256:   8821e13777f8b906973f248fe1bab981c6e0260ae60d0c05bdfc2980aabb0354
# Code AST SHA-256:   09026d4eb628282a9e048228ca64b436a0a8e796d54f25a4adf72fdce950e65b
# Verified Classes:   ManifestIntegrityError, CapabilitySpoofError, PinnedManifest, ManifestGuard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ManifestIntegrityError(RuntimeError):
    """Raised when a tool manifest diverges from its pinned discovery-time hash,
    or when a tool call is routed by name to a server that did not originate it."""


class CapabilitySpoofError(RuntimeError):
    """Raised when a tool call's resolved (server_id, tool_name) does not match
    the pinned origin for that tool, indicating capability spoofing."""


def canonical_hash(tools_list: list[dict[str, Any]]) -> str:
    # Canonicalize: sort keys, drop volatile fields the server may reorder.
    canonical = json.dumps(tools_list, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class PinnedManifest:
    server_id: str
    manifest_hash: str
    tools: dict[str, dict[str, Any]] = field(default_factory=dict)  # name -> schema


class ManifestGuard:
    def __init__(self) -> None:
        self._pins: dict[str, PinnedManifest] = {}
        self._origin: dict[str, str] = {}  # tool_name -> server_id that first claimed it

    def pin_at_discovery(self, server_id: str, tools_list: list[dict[str, Any]]) -> None:
        h = canonical_hash(tools_list)
        tools = {t["name"]: t for t in tools_list}
        for name in tools:
            if name in self._origin and self._origin[name] != server_id:
                raise CapabilitySpoofError(
                    f"tool '{name}' already pinned to server '{self._origin[name]}', "
                    f"server '{server_id}' attempted to claim it"
                )
            self._origin[name] = server_id
        self._pins[server_id] = PinnedManifest(server_id, h, tools)

    def verify_before_call(
        self,
        server_id: str,
        tool_name: str,
        current_tools_list: list[dict[str, Any]],
    ) -> dict[str, Any]:
        pin = self._pins.get(server_id)
        if pin is None:
            raise ManifestIntegrityError(f"server '{server_id}' was never pinned at discovery")

        current_hash = canonical_hash(current_tools_list)
        if current_hash != pin.manifest_hash:
            raise ManifestIntegrityError(
                f"manifest drift on server '{server_id}': "
                f"pinned={pin.manifest_hash[:12]} current={current_hash[:12]}"
            )

        if self._origin.get(tool_name) != server_id:
            raise CapabilitySpoofError(
                f"tool '{tool_name}' is pinned to '{self._origin.get(tool_name)}', "
                f"not '{server_id}'"
            )

        schema = pin.tools.get(tool_name)
        if schema is None:
            raise ManifestIntegrityError(
                f"tool '{tool_name}' absent from pinned manifest of '{server_id}'"
            )
        return schema
