# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-manifest-skill-injection-from-surviving-registry-reload.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-manifest-skill-injection-from-surviving-registry-reload.warrant.json
# Markdown SHA-256:   d60322ca2883174dfeaead4bc6fb6fa3e95beb2461c7ee8800c366a2100a53df
# Code AST SHA-256:   0808b927d7ada705a9518171dbae3f0366e2ac975da02ec884b6ea58417477c8
# Verified Classes:   ManifestDriftError, UnscheduledCompositionError, VettedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestDriftError(RuntimeError):
    """Raised when a tool's manifest content diverges from its vetted hash."""
    pass


class UnscheduledCompositionError(RuntimeError):
    """Raised when manifest text attempts to schedule a tool chain not in the task."""
    pass


NATURAL_LANGUAGE_FIELDS = ("description", "usage_notes", "examples", "deprecation_message")


def content_hash(manifest: dict) -> str:
    payload = {k: manifest.get(k) for k in ("tool_id", "version", *NATURAL_LANGUAGE_FIELDS, "parameters")}
    return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()


@dataclass
class VettedTool:
    tool_id: str
    vetted_hash: str


def reload_and_verify(cached: dict[str, VettedTool], incoming: list[dict]) -> list[dict]:
    approved = []
    for manifest in incoming:
        tid = manifest["tool_id"]
        h = content_hash(manifest)
        prior = cached.get(tid)
        if prior is None:
            raise ManifestDriftError(f"tool {tid} not in vetted set; requires first-load vetting")
        if prior.vetted_hash != h:
            # Version class is deliberately ignored: patch bump does not grant trust.
            raise ManifestDriftError(
                f"tool {tid} content hash {h[:12]} != vetted {prior.vetted_hash[:12]}; "
                f"re-vet required before load"
            )
        approved.append(manifest)
    return approved


def frame_for_model(manifest: dict, task_composition: set[tuple[str, str]]) -> str:
    lines = [f"<tool id=\"{manifest['tool_id']}\" trust=\"untrusted\">"]
    for field in NATURAL_LANGUAGE_FIELDS:
        if field in manifest:
            lines.append(f"  <manifest_field name=\"{field}\">{manifest[field]}</manifest_field>")
    lines.append("</tool>")
    # Reject manifest text that schedules a chain absent from the operator task.
    text = " ".join(str(manifest.get(f, "")) for f in NATURAL_LANGUAGE_FIELDS).lower()
    if "first call" in text or "then call" in text:
        if not task_composition:
            raise UnscheduledCompositionError(
                f"tool {manifest['tool_id']} manifest schedules a call chain; task has none"
            )
    return "\n".join(lines)
