# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-stale-signed-manifest-after-a-hot-reload-of-its-tool-registry.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-stale-signed-manifest-after-a-hot-reload-of-its-tool-registry.warrant.json
# Markdown SHA-256:   7ce8cd8a49e01cc1a5d50dd131f82e2c739ebf312e5a0649025757bb8ccfdc3f
# Code AST SHA-256:   98dcdf4854494e99e6ff3fd246566d9390ed926d4f5f9f5f2b96c8f419675e0a
# Verified Classes:   ManifestIntegrityError, SignedManifest, Binding, ToolRegistry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ManifestIntegrityError(RuntimeError):
    """Raised when a dispatch would invoke an implementation whose digest
    does not match the signed manifest bound to it, or when a mutable
    registry reload leaves a stale verification cache entry."""
    pass


@dataclass(frozen=True)
class SignedManifest:
    tool_name: str
    impl_digest: str          # hex digest of the signed implementation
    input_schema_hash: str
    issuer_sig: str           # signature over canonical(descriptor)
    generation: int


@dataclass(frozen=True)
class Binding:
    """Immutable record captured atomically at dispatch time."""
    impl: Callable[..., Any]
    impl_digest: str
    manifest: SignedManifest


def _digest(fn: Callable[..., Any]) -> str:
    # In production: hash the code object / module bytes, not the repr.
    return hashlib.sha256(fn.__qualname__.encode()).hexdigest()


def _verify_sig(manifest: SignedManifest) -> bool:
    # Placeholder for real Ed25519/RSA verification over the descriptor.
    return bool(manifest.issuer_sig)


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

    def register(self, manifest: SignedManifest, impl: Callable[..., Any]) -> None:
        if not _verify_sig(manifest):
            raise ManifestIntegrityError(
                f"signature invalid for {manifest.tool_name}"
            )
        actual = _digest(impl)
        if actual != manifest.impl_digest:
            # The signed descriptor does not describe this implementation.
            raise ManifestIntegrityError(
                f"impl_digest mismatch for {manifest.tool_name}: "
                f"signed={manifest.impl_digest} bound={actual}"
            )
        self._generation += 1
        # Copy-on-write swap: in-flight dispatches keep the old Binding.
        self._bindings[manifest.tool_name] = Binding(
            impl=impl, impl_digest=actual, manifest=manifest
        )

    def dispatch(self, tool_name: str, **kwargs: Any) -> Any:
        binding = self._bindings.get(tool_name)
        if binding is None:
            raise ManifestIntegrityError(f"unknown tool {tool_name}")
        # Re-assert the invariant at use time; never trust a name-keyed cache.
        if _digest(binding.impl) != binding.manifest.impl_digest:
            raise ManifestIntegrityError(
                f"runtime integrity violated for {tool_name}: "
                f"bound impl no longer matches signed manifest"
            )
        if not _verify_sig(binding.manifest):
            raise ManifestIntegrityError(
                f"manifest signature invalid at dispatch for {tool_name}"
            )
        return binding.impl(**kwargs)
