# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-s-declared-schema-after-re-injection-without-re-validating-the-capability-hash.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-s-declared-schema-after-re-injection-without-re-validating-the-capability-hash.warrant.json
# Markdown SHA-256:   955412d73b234b013de0a93e7766f69a1849c255fc0596ff90f5409f7e55e154
# Code AST SHA-256:   2ef3b6832161e2b1eae2fff29d10666005995dfc5b1c70084390083ec12cb587
# Verified Classes:   ManifestIntegrityError, TrustStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class ManifestIntegrityError(RuntimeError):
    """Raised when a re-loaded manifest's content hash diverges from the pinned trust binding."""


def canonical_hash(manifest: dict[str, Any]) -> str:
    # Bind every field the model can read as instruction, not just inputSchema.
    payload = json.dumps(manifest, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


class TrustStore:
    def __init__(self) -> None:
        # Trust is keyed by name but *bound* to the exact canonical hash it was granted to.
        self._pinned: dict[str, str] = {}

    def approve(self, manifest: dict[str, Any]) -> None:
        self._pinned[manifest["name"]] = canonical_hash(manifest)

    def load(self, manifest: dict[str, Any]) -> dict[str, Any]:
        name = manifest["name"]
        current = canonical_hash(manifest)
        pinned = self._pinned.get(name)

        if pinned is None:
            raise ManifestIntegrityError(
                f"tool {name!r} has no pinned trust binding; refusing to expose unvetted manifest"
            )
        if pinned != current:
            # Re-injection detected: schema may be valid, but content changed under a trusted name.
            raise ManifestIntegrityError(
                f"tool {name!r} manifest hash changed ({pinned[:12]} -> {current[:12]}); "
                f"quarantine description and require re-approval before model exposure"
            )
        return manifest


def refresh_manifest(store: TrustStore, incoming: dict[str, Any]) -> dict[str, Any]:
    manifest = store.load(incoming)
    # Only reachable when hash matches; safe to hand description to the model.
    return manifest
