# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-never-re-verifies-shadow-registry-drift-and-the-post-injection-capability-gap-in-dynamically-loaded-agen.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-never-re-verifies-shadow-registry-drift-and-the-post-injection-capability-gap-in-dynamically-loaded-agen.warrant.json
# Markdown SHA-256:   006333dafabc5f242451b99e99beda2aa6b9ba55e19dfb727197c93659bc2bd2
# Code AST SHA-256:   58adc562b8d657e7637f173d077acd123325012a2ae56fdf929c0e0bebdcf63b
# Verified Classes:   RegistryBodyDriftError, ToolManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class RegistryBodyDriftError(RuntimeError):
    """Raised when a tool body no longer matches the manifest the planner trusted."""
    pass


@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    body_sha256: str | None  # None means the manifest does not bind the body


def resolve_and_invoke(manifest: ToolManifest, body_bytes: bytes, args: dict, invoke):
    # Enforce the cross-binding invariant at invocation time, not registration time.
    if manifest.body_sha256 is None:
        raise RegistryBodyDriftError(
            f"tool {manifest.name!r} has no body hash in manifest; "
            f"execution authority cannot be granted (unbound body)"
        )

    actual = hashlib.sha256(body_bytes).hexdigest()
    if actual != manifest.body_sha256:
        raise RegistryBodyDriftError(
            f"tool {manifest.name!r} body hash mismatch: "
            f"manifest={manifest.body_sha256} actual={actual}; "
            f"registry mutated by unauthorized principal, quarantining for session"
        )

    # Only now does the body inherit the authority the planner granted the manifest.
    return invoke(body_bytes, args)
