# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-that-mutates-between-static-scan-and-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-that-mutates-between-static-scan-and-first-invocation.warrant.json
# Markdown SHA-256:   2bc7f2a18c6c33ebb5f61ab425d333e44bbd843c53890d66a35ae976bed1e769
# Code AST SHA-256:   712a87b91a4fdc6bc73add7818b10a6d1c77f9ec5a1ef4b9694169ac0f6debbc
# Verified Classes:   ManifestDriftError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json


class ManifestDriftError(RuntimeError):
    """Raised when the manifest served at invocation does not match the approved digest."""
    pass


def canonical_manifest_digest(tools_list_payload: dict) -> str:
    # Canonicalize the parts of the manifest that carry semantic weight.
    tools = sorted(
        (
            {
                "name": t["name"],
                "description": t.get("description", ""),
                "inputSchema": t.get("inputSchema", {}),
            }
            for t in tools_list_payload.get("tools", [])
        ),
        key=lambda t: t["name"],
    )
    blob = json.dumps(tools, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return "sha256:" + hashlib.sha256(blob).hexdigest()


def load_tool_for_invocation(
    server_id: str,
    approved_digests: dict,
    served_manifest: dict,
) -> dict:
    approved = approved_digests.get(server_id)
    if approved is None:
        raise ManifestDriftError(
            f"server {server_id!r} has no approved manifest digest; refusing to load"
        )

    served = canonical_manifest_digest(served_manifest)
    if served != approved:
        # Do not attempt to diff or "reason about" the delta. Any description
        # change is a semantic change and must go back through static scan.
        raise ManifestDriftError(
            f"manifest drift on {server_id!r}: approved {approved}, served {served}; "
            f"re-scan required before invocation"
        )

    return served_manifest
