# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-as-executable-authority-rather-than-untrusted-data.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-as-executable-authority-rather-than-untrusted-data.warrant.json
# Markdown SHA-256:   16c40adc2a42ecdd45e8526b2a60940107a34be2d7dcea4e5505d7b7d04ad17b
# Code AST SHA-256:   54f1a372efd015147f9385f138a4590afde0427e8ed7ecbea327f75a517fb538
# Verified Classes:   ManifestAuthorityViolation, ToolDescriptor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestAuthorityViolation(RuntimeError):
    """Raised when a discovered descriptor is about to be granted executable authority."""


@dataclass
class ToolDescriptor:
    name: str
    description: str
    schema: dict
    source: str  # "pinned" | "discovered"
    raw: dict = field(default_factory=dict)

    def fingerprint(self) -> str:
        canonical = json.dumps(self.raw, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()


def register_tool(
    desc: ToolDescriptor,
    emittable_whitelist: frozenset[str],
    pinned_hashes: dict[str, str],
) -> str:
    """
    Promote a descriptor to the emittable tool set, or refuse.

    Invariant: a tool becomes emittable only if it was in the pre-discovery
    whitelist AND (if discovered) its fingerprint matches a pinned hash.
    Free-text fields are never inspected here for 'intent' — they are never
    granted authority by their content.
    """
    if desc.name not in emittable_whitelist:
        raise ManifestAuthorityViolation(
            f"tool {desc.name!r} from {desc.source} source is not in the "
            f"pre-discovery whitelist; discovered tools are candidates, not grants"
        )

    if desc.source == "discovered":
        expected = pinned_hashes.get(desc.name)
        if expected is None:
            raise ManifestAuthorityViolation(
                f"tool {desc.name!r} discovered at runtime has no pinned hash"
            )
        if desc.fingerprint() != expected:
            raise ManifestAuthorityViolation(
                f"tool {desc.name!r} fingerprint {desc.fingerprint()[:12]} "
                f"does not match pinned {expected[:12]}; manifest mutated post-pin"
            )

    # Description is rendered as data, never as instruction. Return the
    # sanitized rendering, not the raw string.
    return f"<tool_metadata name={desc.name!r} provenance={desc.source!r}>" \
           f"{json.dumps({'description': desc.description})}</tool_metadata>"


def handle_tools_list(
    response: dict,
    emittable_whitelist: frozenset[str],
    pinned_hashes: dict[str, str],
) -> list[str]:
    rendered = []
    for entry in response.get("tools", []):
        desc = ToolDescriptor(
            name=entry["name"],
            description=entry.get("description", ""),
            schema=entry.get("inputSchema", {}),
            source="discovered",
            raw=entry,
        )
        try:
            rendered.append(register_tool(desc, emittable_whitelist, pinned_hashes))
        except ManifestAuthorityViolation:
            # Quarantine: log fingerprint, do not surface description text.
            rendered.append(
                f"<tool_metadata name={desc.name!r} status='quarantined' "
                f"fingerprint={desc.fingerprint()[:12]!r}/>"
            )
    return rendered
