# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-re-fetched-tool-manifest-as-untrusted-input-rather-than-a-trusted-capability-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-re-fetched-tool-manifest-as-untrusted-input-rather-than-a-trusted-capability-refresh.warrant.json
# Markdown SHA-256:   ced10e91d35e943661689d1e42c6b01bf00e9b8962400843756e0235644fd006
# Code AST SHA-256:   dfed00cdecc6dfda2be434c334c55202d0374295e89f0b8ccc639f7222c6341a
# Verified Classes:   ManifestTrustViolation, PinnedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestTrustViolation(RuntimeError):
    """Raised when a refreshed manifest diverges from the pinned, vetted content."""


@dataclass
class PinnedManifest:
    server_id: str
    content_hash: str
    raw: dict
    vetted_tool_names: frozenset = field(default_factory=frozenset)


def _hash_manifest(raw: dict) -> str:
    canonical = json.dumps(raw, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _natural_language_fields(tool: dict) -> dict:
    keys = ("description", "title", "examples", "annotations")
    return {k: tool.get(k) for k in keys if k in tool}


def ingest_refreshed_manifest(pinned: PinnedManifest, refreshed_raw: dict) -> PinnedManifest:
    """
    Accept a refreshed manifest only if its content hash matches the pinned hash.
    Any divergence — especially in natural-language fields — is a trust violation
    and must be quarantined for re-vetting, never injected into model context.
    """
    new_hash = _hash_manifest(refreshed_raw)

    if new_hash == pinned.content_hash:
        return pinned  # byte-identical refresh, safe to reuse

    # Hash diverged: classify the delta before deciding.
    old_tools = {t["name"]: t for t in pinned.raw.get("tools", [])}
    new_tools = {t["name"]: t for t in refreshed_raw.get("tools", [])}

    added = set(new_tools) - set(old_tools)
    removed = set(old_tools) - set(new_tools)
    nl_changed = {
        name for name in set(old_tools) & set(new_tools)
        if _natural_language_fields(old_tools[name]) != _natural_language_fields(new_tools[name])
    }

    if added or removed or nl_changed:
        raise ManifestTrustViolation(
            f"server {pinned.server_id!r} manifest content drifted: "
            f"added={sorted(added)} removed={sorted(removed)} "
            f"nl_fields_changed={sorted(nl_changed)} "
            f"old_hash={pinned.content_hash[:12]} new_hash={new_hash[:12]}. "
            f"Quarantine and re-vet before use; do not inject into model context."
        )

    # Non-NL, non-tool-set change (e.g. metadata only) still requires explicit
    # re-pin; refuse to silently adopt.
    raise ManifestTrustViolation(
        f"server {pinned.server_id!r} hash changed without NL/tool-set delta; "
        f"refusing silent re-pin (old={pinned.content_hash[:12]} new={new_hash[:12]})"
    )


def authorize_tool_call(pinned: PinnedManifest, tool_name: str) -> None:
    """Only tools present in the last vetted manifest may be invoked."""
    if tool_name not in pinned.vetted_tool_names:
        raise ManifestTrustViolation(
            f"tool {tool_name!r} not in vetted set for server {pinned.server_id!r}; "
            f"refusing invocation of un-vetted capability"
        )
