# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-manifest-poisoned-skill-injection-when-mcp-tool-descriptions-are-re-fetched-after-a-legitimate-hot-reload.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-manifest-poisoned-skill-injection-when-mcp-tool-descriptions-are-re-fetched-after-a-legitimate-hot-reload.warrant.json
# Markdown SHA-256:   2ed2ea8730793c0e01a4444ac6cd3a2dcf92d9979f6cb25fccd29a73b64d33a3
# Code AST SHA-256:   84286e2b09452d42efff18c1a068fd99d0b275046c0158d0bd5a5c11ec44e366
# Verified Classes:   ManifestSubstitutionError, PinnedTool, SessionLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ManifestSubstitutionError(RuntimeError):
    """Raised when a re-fetched tool manifest changes semantics mid-task."""
    pass


def semantic_hash(tool: dict[str, Any]) -> str:
    # Hash every field the model reads as instruction-bearing scaffolding.
    payload = {
        "name": tool.get("name"),
        "description": tool.get("description", ""),
        "title": tool.get("title", ""),
        "annotations": tool.get("annotations", {}),
        "schema_descriptions": _collect_schema_descriptions(tool.get("inputSchema", {})),
    }
    blob = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def _collect_schema_descriptions(schema: Any) -> list[str]:
    out: list[str] = []
    if isinstance(schema, dict):
        if "description" in schema and isinstance(schema["description"], str):
            out.append(schema["description"])
        for v in schema.values():
            out.extend(_collect_schema_descriptions(v))
    elif isinstance(schema, list):
        for v in schema:
            out.extend(_collect_schema_descriptions(v))
    return out


@dataclass
class PinnedTool:
    name: str
    schema_hash: str
    semantic_hash: str


@dataclass
class SessionLedger:
    # Stored client-side, keyed to the task, never derived from the manifest.
    pins: dict[str, PinnedTool] = field(default_factory=dict)


def reconcile_reload(
    ledger: SessionLedger,
    fresh_manifest: list[dict[str, Any]],
    plan_in_flight: bool,
) -> list[str]:
    """Return tool names safe to call after a re-fetch. Raise on unsafe substitution."""
    safe: list[str] = []
    for tool in fresh_manifest:
        name = tool["name"]
        new_sem = semantic_hash(tool)
        pin = ledger.pins.get(name)

        if pin is None:
            # First load: trust must come from transport identity, not hash.
            ledger.pins[name] = PinnedTool(name, _shape_hash(tool), new_sem)
            safe.append(name)
            continue

        if new_sem == pin.semantic_hash:
            safe.append(name)
            continue

        # Semantic drift detected. Schema shape may be identical — irrelevant.
        if plan_in_flight:
            raise ManifestSubstitutionError(
                f"tool {name!r} description changed mid-task "
                f"(pinned {pin.semantic_hash[:12]}… -> fresh {new_sem[:12]}…); "
                f"plan must be frozen and delta re-authorized before use"
            )
        # No plan in flight: quarantine, require re-pin through authorization.
        raise ManifestSubstitutionError(
            f"tool {name!r} quarantined: semantic hash drift requires "
            f"explicit re-authorization before reload"
        )
    return safe


def _shape_hash(tool: dict[str, Any]) -> str:
    schema = tool.get("inputSchema", {})
    blob = json.dumps(schema, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()
