# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-manifest-level-skill-injection-drift-when-a-dynamically-loaded-tool-s-declared-capability-diverges-from-its.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-manifest-level-skill-injection-drift-when-a-dynamically-loaded-tool-s-declared-capability-diverges-from-its.warrant.json
# Markdown SHA-256:   4d164078728b880abd1ecbbd6e95af6260466aa69bd99ed5102d76bf077c8b96
# Code AST SHA-256:   e40c1475ef7d1437d2beb81dbc445959611076f77a2ff0307851dc69338f28ed
# Verified Classes:   CapabilityBindingError, ManifestPin
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityBindingError(RuntimeError):
    """Raised when a tool's live manifest diverges from the plan-time pin."""
    pass


@dataclass(frozen=True)
class ManifestPin:
    name: str
    version: str
    manifest_sha256: str
    declared_capabilities: frozenset[str]


def _hash_manifest(manifest: dict) -> str:
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def pin_manifest(manifest: dict) -> ManifestPin:
    return ManifestPin(
        name=manifest["name"],
        version=manifest["version"],
        manifest_sha256=_hash_manifest(manifest),
        declared_capabilities=frozenset(manifest.get("capabilities", [])),
    )


def dispatch(pin: ManifestPin, live_manifest: dict, args: dict) -> dict:
    """Resolve and invoke a tool only if its live manifest matches the pin."""
    if live_manifest.get("name") != pin.name:
        raise CapabilityBindingError(
            f"name mismatch: pinned {pin.name!r}, live {live_manifest.get('name')!r}"
        )

    live_hash = _hash_manifest(live_manifest)
    if live_hash != pin.manifest_sha256:
        raise CapabilityBindingError(
            f"manifest drift for {pin.name}: pinned {pin.manifest_sha256[:12]} "
            f"({pin.version}), live {live_hash[:12]} ({live_manifest.get('version')})"
        )

    live_caps = frozenset(live_manifest.get("capabilities", []))
    widened = live_caps - pin.declared_capabilities
    if widened:
        raise CapabilityBindingError(
            f"undeclared capabilities on {pin.name}: {sorted(widened)}"
        )

    # Only now is it safe to hand args to the executable.
    return _invoke(live_manifest, args)


def _invoke(live_manifest: dict, args: dict) -> dict:
    # Placeholder for the actual tool call; kept out of the binding path.
    return {"tool": live_manifest["name"], "args": args, "status": "ok"}
