# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-after-the-capability-digest-has-already-been-pinned.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-after-the-capability-digest-has-already-been-pinned.warrant.json
# Markdown SHA-256:   d1e5e482b6757cbc50778b09a9a733a457b15d99fffc2b4b7859a03c07fdb143
# Code AST SHA-256:   2cdf1c793a85a99b548cdb9ae4fcb7132428ebbfb78a4c465d9f1a3c32f9b836
# Verified Classes:   ManifestIntegrityViolation, PinnedCapability
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestIntegrityViolation(RuntimeError):
    """Raised when a re-fetched tool manifest diverges from the pinned
    capability tuple (schema + model-visible text + resolved entrypoint)."""
    pass


@dataclass(frozen=True)
class PinnedCapability:
    name: str
    digest: str          # covers schema, description, examples, resolved entrypoint
    resolved_entrypoint: str


def compute_capability_digest(manifest: dict, resolved_entrypoint: str) -> str:
    # Bind every field the model reads AND the executable binding.
    bound = {
        "name": manifest["name"],
        "description": manifest.get("description", ""),
        "inputSchema": manifest.get("inputSchema", {}),
        "examples": manifest.get("examples", []),
        "resolved_entrypoint": resolved_entrypoint,
    }
    canonical = json.dumps(bound, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def resolve_entrypoint(manifest: dict) -> str:
    # In production this resolves a mutable reference (registry tag, DNS, image
    # digest). The resolved artifact must be content-addressed, not the ref.
    ref = manifest.get("entrypoint")
    if not ref:
        raise ManifestIntegrityViolation(
            f"manifest {manifest.get('name')!r} has no entrypoint binding"
        )
    return f"content-addr:{ref}"


def enforce_pinned_capability(pinned: PinnedCapability, live_manifest: dict) -> None:
    live_entrypoint = resolve_entrypoint(live_manifest)
    live_digest = compute_capability_digest(live_manifest, live_entrypoint)

    if live_digest != pinned.digest:
        # Divergence in model-visible text OR entrypoint binding. Refuse.
        raise ManifestIntegrityViolation(
            f"capability {pinned.name!r} diverged from pinned digest "
            f"{pinned.digest[:12]}... -> {live_digest[:12]}...; "
            f"entrypoint {pinned.resolved_entrypoint!r} -> {live_entrypoint!r}. "
            f"Refusing invocation; re-authorization required."
        )
    if live_entrypoint != pinned.resolved_entrypoint:
        # Defensive: digest collision or partial binding must still fail closed.
        raise ManifestIntegrityViolation(
            f"entrypoint binding mismatch for {pinned.name!r} despite digest match"
        )


def invoke_tool(pinned: PinnedCapability, live_manifest: dict, args: dict) -> dict:
    enforce_pinned_capability(pinned, live_manifest)
    # Only now is it safe to hand the manifest text to the model and dispatch.
    return {"tool": pinned.name, "args": args, "entrypoint": pinned.resolved_entrypoint}
