# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-re-reads-mid-session-the-skill-injection-boundary-in-dynamically-reloaded-mcp-tool-manifests.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-manifest-it-re-reads-mid-session-the-skill-injection-boundary-in-dynamically-reloaded-mcp-tool-manifests.warrant.json
# Markdown SHA-256:   39cf40a2d15d85941c15a94deb202a1c1e802d7b2b5aa36554cdcfadcdf70f24
# Code AST SHA-256:   3bcf5da59fe9e66ff1e8e51ed8545b8f1d47e0b4efec02b7e1f9c127171233ca
# Verified Classes:   ManifestTrustViolation, ToolAnchor, SessionManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestTrustViolation(RuntimeError):
    """Raised when a mid-session manifest reload mutates trusted tool content."""


@dataclass(frozen=True)
class ToolAnchor:
    name: str
    content_hash: str


def _content_hash(tool: dict) -> str:
    # Hash the fields the model treats as instruction: name, description,
    # inputSchema INCLUDING defaults, and annotations. Name alone is not identity.
    material = {
        "name": tool.get("name"),
        "description": tool.get("description", ""),
        "inputSchema": tool.get("inputSchema", {}),
        "annotations": tool.get("annotations", {}),
    }
    blob = json.dumps(material, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


@dataclass
class SessionManifest:
    anchors: dict[str, ToolAnchor] = field(default_factory=dict)

    def admit_at_cold_start(self, tools: list[dict]) -> None:
        for t in tools:
            self.anchors[t["name"]] = ToolAnchor(t["name"], _content_hash(t))

    def apply_reload(self, tools: list[dict], policy: str = "reject") -> list[str]:
        """Merge a reloaded manifest under a content-keyed trust policy.

        policy="reject": any content delta raises; session keeps old manifest.
        policy="re_adjudicate": content-changed tools are demoted (returned as
        needing re-admission) and MUST be stripped from planner context until
        re-admitted; unchanged tools pass through.
        """
        if policy not in ("reject", "re_adjudicate"):
            raise ManifestTrustViolation(f"unknown policy {policy!r}")

        demoted: list[str] = []
        for t in tools:
            name = t["name"]
            new_hash = _content_hash(t)
            anchor = self.anchors.get(name)

            if anchor is None:
                # Brand-new tool: never auto-trusted mid-session.
                demoted.append(name)
                continue

            if anchor.content_hash == new_hash:
                continue  # byte-identical content, trust label still valid

            # Same name, different content == a different tool wearing the name.
            if policy == "reject":
                raise ManifestTrustViolation(
                    f"tool {name!r} content changed mid-session "
                    f"({anchor.content_hash[:12]} -> {new_hash[:12]}); "
                    f"refusing reload to prevent skill injection"
                )
            demoted.append(name)

        return demoted

    def planner_context(self, tools: list[dict], demoted: list[str]) -> list[dict]:
        """Only anchored, content-matching tools reach the planner."""
        safe = []
        for t in tools:
            anchor = self.anchors.get(t["name"])
            if anchor and anchor.content_hash == _content_hash(t):
                safe.append(t)
        return safe


def handle_list_changed(session: SessionManifest, reloaded: list[dict]) -> list[dict]:
    try:
        demoted = session.apply_reload(reloaded, policy="re_adjudicate")
    except ManifestTrustViolation as exc:
        # Strict sessions abort here; permissive sessions fall through to demotion.
        raise ManifestTrustViolation(str(exc)) from exc

    if demoted:
        # Do NOT pass mutated descriptions to the model; force re-admission.
        raise ManifestTrustViolation(
            f"tools demoted pending re-adjudication: {demoted}; "
            f"strip from planner context before next reasoning step"
        )
    return session.planner_context(reloaded, demoted)
