# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-dynamically-loaded-tool-manifest-before-schema-reconciliation-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-dynamically-loaded-tool-manifest-before-schema-reconciliation-completes.warrant.json
# Markdown SHA-256:   f8791147115d1fc9884f4534b0e9d151ca25016b96ec2f257e785a64d8a88bb6
# Code AST SHA-256:   965bcf9fdcc27e7d91de0a7b777dd144e946df0c2feb1ee5af88cf80c3bb18f4
# Verified Classes:   ManifestAttestationError, Attestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestAttestationError(RuntimeError):
    """Raised when a dynamically loaded manifest's instruction surface
    diverges from its pinned attestation before reconciliation completes."""


INSTRUCTION_FIELDS = ("description", "examples", "usage_hint")


def instruction_surface_hash(manifest: dict) -> str:
    surface = {k: manifest.get(k) for k in INSTRUCTION_FIELDS}
    for param in manifest.get("parameters", {}).get("properties", {}).values():
        surface.setdefault("param_descriptions", {})[param.get("name", "")] = param.get("description")
    blob = json.dumps(surface, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


@dataclass
class Attestation:
    tool_name: str
    surface_hash: str


def gate_manifest(manifest: dict, pinned: dict[str, Attestation], reconciled: set[str]) -> dict:
    name = manifest["name"]
    incoming = instruction_surface_hash(manifest)

    prior = pinned.get(name)
    if prior is None:
        # First-seen tool: do not auto-bind untrusted instruction surface.
        if name not in reconciled:
            raise ManifestAttestationError(
                f"tool {name!r} has no pinned attestation; instruction surface "
                f"{incoming[:12]} requires operator reconciliation before binding"
            )
    elif prior.surface_hash != incoming:
        if name not in reconciled:
            raise ManifestAttestationError(
                f"instruction-surface drift on {name!r}: pinned {prior.surface_hash[:12]} "
                f"!= incoming {incoming[:12]}; manifest quarantined pending re-attestation"
            )
    return manifest


def resolve_tools(manifests: list[dict], pinned: dict[str, Attestation], reconciled: set[str]) -> list[dict]:
    resolved = []
    for m in manifests:
        resolved.append(gate_manifest(m, pinned, reconciled))
    return resolved
