# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-mcp-tool-manifest-when-tool-descriptions-are-lazily-re-fetched-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-poisoned-mcp-tool-manifest-when-tool-descriptions-are-lazily-re-fetched-mid-session.warrant.json
# Markdown SHA-256:   ce13f312a26babe6fae17c1ae31dd66307d1649c2e5733af0af4221fe5c85079
# Code AST SHA-256:   562c793b20b15c43d829da10ad8ebda361ca238f82dd1761dfc73e08f506de5d
# Verified Classes:   ManifestContinuityError, ToolRecord, ManifestGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestContinuityError(RuntimeError):
    """Raised when a tool record changes after approval without re-gating."""


@dataclass(frozen=True)
class ToolRecord:
    name: str
    description: str
    input_schema: dict
    annotations: dict

    def content_hash(self) -> str:
        payload = json.dumps(
            {
                "name": self.name,
                "description": self.description,
                "inputSchema": self.input_schema,
                "annotations": self.annotations,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(payload).hexdigest()


class ManifestGate:
    def __init__(self) -> None:
        # name -> (content_hash, approved_record)
        self._approved: dict[str, tuple[str, ToolRecord]] = {}

    def approve(self, record: ToolRecord) -> None:
        self._approved[record.name] = (record.content_hash(), record)

    def reconcile(self, incoming: list[ToolRecord]) -> list[str]:
        """Return names that must be re-approved. Never silently adopt
        a content change under an existing name."""
        must_reapprove: list[str] = []
        for rec in incoming:
            prior = self._approved.get(rec.name)
            if prior is None:
                must_reapprove.append(rec.name)
                continue
            prior_hash, _ = prior
            if rec.content_hash() != prior_hash:
                # Name stable, content changed: authority may have increased.
                must_reapprove.append(rec.name)
                # Demote: drop the stale approval so execution is blocked.
                del self._approved[rec.name]
        return must_reapprove

    def assert_executable(self, record: ToolRecord, plan_hash: str) -> None:
        """Guard called immediately before every tool invocation."""
        prior = self._approved.get(record.name)
        if prior is None:
            raise ManifestContinuityError(
                f"tool {record.name!r} is not currently approved"
            )
        approved_hash, approved_record = prior
        if record.content_hash() != approved_hash:
            raise ManifestContinuityError(
                f"tool {record.name!r} content changed since approval "
                f"(approved={approved_hash[:12]}, now={record.content_hash()[:12]})"
            )
        if approved_record.content_hash() != plan_hash:
            raise ManifestContinuityError(
                f"plan was built against manifest {plan_hash[:12]} but tool "
                f"{record.name!r} is now {approved_record.content_hash()[:12]}; "
                "re-plan before executing"
            )


def handle_tools_list_changed(gate: ManifestGate, incoming: list[ToolRecord], plan_hash: str) -> None:
    flagged = gate.reconcile(incoming)
    if flagged:
        raise ManifestContinuityError(
            "manifest re-list changed approved tool content; re-approval required "
            f"before execution: {sorted(flagged)}"
        )
    for rec in incoming:
        gate.assert_executable(rec, plan_hash)
