# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-reloaded-mid-session-skill-injection-via-manifest-drift-and-the-schema-freeze-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-reloaded-mid-session-skill-injection-via-manifest-drift-and-the-schema-freeze-invariant.warrant.json
# Markdown SHA-256:   8a6317b3c2dbe8c98a050b1dc36f01440be832b2b1ba5c2896ad1d0e42a97450
# Code AST SHA-256:   3bc0b3288123e7b600be75f852d70900a9784fc25534083f0cf66b6d1123d3a0
# Verified Classes:   ManifestDriftError, SchemaFreezeViolation, PinnedToolSet
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ManifestDriftError(RuntimeError):
    """Raised when a live tool manifest diverges from the pinned snapshot."""
    pass


class SchemaFreezeViolation(RuntimeError):
    """Raised when a tool call uses a parameter absent from the pinned schema."""
    pass


def _content_hash(manifest: dict[str, Any]) -> str:
    # Hash the full body, not just $id/version — version strings are attacker-controlled.
    body = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(body.encode("utf-8")).hexdigest()


@dataclass
class PinnedToolSet:
    tools: dict[str, dict[str, Any]]
    hashes: dict[str, str] = field(default_factory=dict)
    frozen: bool = True

    def __post_init__(self) -> None:
        for name, spec in self.tools.items():
            self.hashes[name] = _content_hash(spec)

    def reload(self, live_manifest: dict[str, Any]) -> None:
        """Attempt to adopt a re-fetched manifest for a single tool."""
        name = live_manifest.get("name")
        if name not in self.tools:
            raise ManifestDriftError(
                f"reload introduced unknown tool {name!r}; requires re-plan, not adoption"
            )
        live_hash = _content_hash(live_manifest)
        if live_hash != self.hashes[name]:
            delta = self._describe_delta(self.tools[name], live_manifest)
            # Identity fields matching does NOT authorize adoption.
            raise ManifestDriftError(
                f"tool {name!r} body changed under identical identity fields; "
                f"delta={delta}; freeze requires re-plan at task boundary"
            )
        # Byte-identical: safe no-op, do not re-emit into context.
        return

    @staticmethod
    def _describe_delta(old: dict[str, Any], new: dict[str, Any]) -> dict[str, Any]:
        out: dict[str, Any] = {}
        for key in ("description", "inputSchema"):
            if old.get(key) != new.get(key):
                out[key] = "changed"
        return out

    def validate_call(self, tool_name: str, arguments: dict[str, Any]) -> None:
        """Dispatch-time enforcement against the PINNED schema."""
        if tool_name not in self.tools:
            raise SchemaFreezeViolation(f"tool {tool_name!r} not in pinned set")
        schema = self.tools[tool_name].get("inputSchema", {})
        allowed = set(schema.get("properties", {}).keys())
        novel = set(arguments.keys()) - allowed
        if novel:
            # e.g. an injected 'auth' parameter first seen only in the live manifest
            raise SchemaFreezeViolation(
                f"tool {tool_name!r} called with parameters absent from pinned schema: "
                f"{sorted(novel)}"
            )


def handle_reload(pinned: PinnedToolSet, live_manifest: dict[str, Any]) -> None:
    try:
        pinned.reload(live_manifest)
    except ManifestDriftError:
        # Surface to planner/operator; do NOT silently adopt mid-task.
        raise
