# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-signed-skill-manifest-whose-payload-hash-still-validates-after-the-skill-s-tool-surface-has-been-mutated.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-signed-skill-manifest-whose-payload-hash-still-validates-after-the-skill-s-tool-surface-has-been-mutated.warrant.json
# Markdown SHA-256:   4a24dbadfe75aa18623c6b0fdee1ca007c53ec410a41bd6d82f7efa45dbd3afc
# Code AST SHA-256:   a369087350c631a62322a64e5ccb0a7efeb53a39d2d9b3364ed1b650c36df1d5
# Verified Classes:   UnattestableSurfaceError, Manifest, Binding, ProvenanceRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnattestableSurfaceError(RuntimeError):
    """Raised when a manifest verifies but the resolved callable cannot be bound to it."""
    pass


@dataclass(frozen=True)
class Manifest:
    manifest_id: str
    payload_digest: str          # sha256 over the signed artifact blob
    declared_tools: frozenset    # exact set of tool names this manifest may expose
    grants: frozenset            # e.g. {"network:none"}


@dataclass
class Binding:
    manifest_id: str
    tool_name: str
    callable_digest: str         # content address of the resolved implementation


class ProvenanceRegistry:
    """Name resolution keyed by (manifest_id, tool_name); never by bare name."""

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

    def register(self, manifest: Manifest, tool_name: str, impl_digest: str) -> None:
        if tool_name not in manifest.declared_tools:
            # Undeclared tools must be rejected, not merged into the namespace.
            raise UnattestableSurfaceError(
                f"tool {tool_name!r} not declared by manifest {manifest.manifest_id}"
            )
        key = (manifest.manifest_id, tool_name)
        if key in self._bindings:
            # Shadowing a signed binding is the substitution vector; refuse it.
            raise UnattestableSurfaceError(
                f"binding {key} already registered; shadowing rejected"
            )
        self._bindings[key] = Binding(manifest.manifest_id, tool_name, impl_digest)

    def resolve(self, manifest: Manifest, tool_name: str, live_impl_digest: str) -> Binding:
        key = (manifest.manifest_id, tool_name)
        binding = self._bindings.get(key)
        if binding is None:
            raise UnattestableSurfaceError(f"no signed binding for {key}")
        # Attest the callable actually about to run, not just the artifact at rest.
        if binding.callable_digest != live_impl_digest:
            raise UnattestableSurfaceError(
                f"callable drift for {key}: signed {binding.callable_digest} "
                f"!= live {live_impl_digest}"
            )
        return binding


def attest_and_invoke(
    manifest: Manifest,
    blob: bytes,
    registry: ProvenanceRegistry,
    tool_name: str,
    live_impl_digest: str,
    signature_ok: bool,
) -> Binding:
    # Gate 1: descriptor integrity (necessary, not sufficient).
    payload_digest = "sha256:" + hashlib.sha256(blob).hexdigest()
    if not signature_ok or payload_digest != manifest.payload_digest:
        raise UnattestableSurfaceError("manifest signature or payload digest failed")

    # Gate 2: surface integrity — bind the resolved callable to the signed manifest.
    binding = registry.resolve(manifest, tool_name, live_impl_digest)
    if binding.manifest_id != manifest.manifest_id:
        raise UnattestableSurfaceError("resolved binding provenance mismatch")
    return binding
