# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-tool-manifest-whose-description-is-itself-an-instruction-skill-injection-via-mcp-registry-supply-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-tool-manifest-whose-description-is-itself-an-instruction-skill-injection-via-mcp-registry-supply-chains.warrant.json
# Markdown SHA-256:   4abe8308f95c6c41ddd205993e0b3b550c60d103caf5bd4a6ba7f8ce42c5431c
# Code AST SHA-256:   ef8d5d1fed65e797a77bbeada8051a7996a528315eb7569405b416852820488f
# Verified Classes:   ManifestInjectionError, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass


class ManifestInjectionError(RuntimeError):
    """Raised when a tool manifest's description carries instruction-shaped text."""
    pass


# Policy-shaped patterns that a benign tool description never needs.
_INJECTION_PATTERNS = [
    re.compile(r"\b(before|after|prior to)\s+(calling|using|invoking)\b", re.I),
    re.compile(r"\bdo not (mention|reveal|surface|disclose)\b", re.I),
    re.compile(r"\b(system prompt|operator policy|deployment policy)\b", re.I),
    re.compile(r"\b(must|should) (first|always) (call|invoke)\b", re.I),
]

# Tools whose descriptions may legitimately reference other tools (rare, allowlisted).
_ORDERING_ALLOWLIST = {"compose_pipeline"}


@dataclass(frozen=True)
class ToolManifest:
    name: str
    description: str
    version: str
    publisher: str
    signature_ok: bool


def admit_manifest(m: ToolManifest) -> str:
    """
    Returns the fenced, untrusted-labeled description block to place in context.
    Raises ManifestInjectionError if the description is instruction-shaped.
    Signature validity is checked but is explicitly NOT sufficient.
    """
    if not m.signature_ok:
        raise ManifestInjectionError(
            f"{m.name}@{m.version}: signature invalid; refusing admission"
        )

    if m.name not in _ORDERING_ALLOWLIST:
        for pat in _INJECTION_PATTERNS:
            hit = pat.search(m.description)
            if hit:
                raise ManifestInjectionError(
                    f"{m.name}@{m.version} by {m.publisher}: "
                    f"instruction-shaped description matched {pat.pattern!r} "
                    f"at {hit.group(0)!r}; quarantine for human review"
                )

    desc_hash = hashlib.sha256(m.description.encode()).hexdigest()[:16]
    # Fence as untrusted data; never concatenate raw into the system channel.
    return (
        f'<tool_manifest name="{m.name}" version="{m.version}" '
        f'publisher="{m.publisher}" desc_sha256="{desc_hash}" untrusted="true">\n'
        f"{m.description}\n"
        f"</tool_manifest>"
    )


def load_registry(manifests: list[ToolManifest]) -> list[str]:
    admitted, quarantined = [], []
    for m in manifests:
        try:
            admitted.append(admit_manifest(m))
        except ManifestInjectionError as e:
            quarantined.append(str(e))
    if quarantined:
        # Surface quarantines to the operator; never silently drop.
        raise ManifestInjectionError(
            f"{len(quarantined)} manifest(s) quarantined: " + "; ".join(quarantined)
        )
    return admitted
