# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-shadowing-in-dynamically-loaded-agent-tool-registries-the-trust-boundary-mismatch-between-registration-time-author.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-shadowing-in-dynamically-loaded-agent-tool-registries-the-trust-boundary-mismatch-between-registration-time-author.warrant.json
# Markdown SHA-256:   c6c7f0ed4f12da8faa31b945ecfe22c1a245d42af991dd31b3750d93634e6585
# Code AST SHA-256:   5e14f092d425db52a5423713ae0fb3882996d25cfc95c9abd96a8b7fca54db3a
# Verified Classes:   CapabilityShadowingError, Binding, SafeToolResolver
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Callable, Optional


class CapabilityShadowingError(RuntimeError):
    """Raised when a dispatch key would resolve to a binding that policy did not authorize."""


@dataclass(frozen=True)
class Binding:
    plugin_id: str
    tool_name: str
    version: str
    content_hash: str
    callable: Callable
    authorized_principal: str

    @property
    def dispatch_key(self) -> str:
        return self.tool_name

    def identity(self) -> tuple[str, str, str]:
        return (self.plugin_id, self.version, self.content_hash)


class SafeToolResolver:
    """Resolver that treats tool names as capabilities, not labels."""

    def __init__(self) -> None:
        self._bindings: dict[str, Binding] = {}

    def register(self, binding: Binding, *, replace: bool = False) -> None:
        existing = self._bindings.get(binding.dispatch_key)
        if existing is None:
            self._bindings[binding.dispatch_key] = binding
            return
        if existing.identity() == binding.identity():
            return
        # A different binding wants the same dispatch key.
        if not replace:
            raise CapabilityShadowingError(
                f"refusing to shadow {binding.dispatch_key!r}: "
                f"held by {existing.plugin_id}/{existing.version}, "
                f"attempted by {binding.plugin_id}/{binding.version}"
            )
        # Replacement is only legal if it re-runs authorization.
        raise CapabilityShadowingError(
            f"hot-reload cannot rebind {binding.dispatch_key!r} without fresh "
            f"authorization; re-register under a new principal-approved identity"
        )

    def resolve(self, tool_name: str, *, principal: str, approved_identity: tuple[str, str, str]) -> Callable:
        binding = self._bindings.get(tool_name)
        if binding is None:
            raise CapabilityShadowingError(f"no binding for {tool_name!r}")
        if binding.identity() != approved_identity:
            raise CapabilityShadowingError(
                f"binding identity mismatch for {tool_name!r}: "
                f"policy approved {approved_identity}, resolver holds {binding.identity()}"
            )
        if binding.authorized_principal != principal:
            raise CapabilityShadowingError(
                f"principal {principal!r} not authorized for {tool_name!r}"
            )
        return binding.callable


def hash_tool_source(source: bytes) -> str:
    return hashlib.sha256(source).hexdigest()
