# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-it-never-called-latent-capability-poisoning-in-mcp-tool-registries-and-agent-card-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-it-never-called-latent-capability-poisoning-in-mcp-tool-registries-and-agent-card-metadata.warrant.json
# Markdown SHA-256:   18dfb6d5d2fee92878cb0dd87d36019531731970aae86a985ffe6cc38ae9d7d4
# Code AST SHA-256:   e05615568e923047ae1a01ae3317621f25974084322b80faad41247c16cae619
# Verified Classes:   CatalogPoisoningError, CatalogEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Literal


class CatalogPoisoningError(RuntimeError):
    """Raised when registry-supplied metadata violates the provenance invariant."""


@dataclass
class CatalogEntry:
    source: str
    name: str
    schema: dict
    description: str
    trust: Literal["pinned", "untrusted_metadata"] = "untrusted_metadata"
    provenance_hash: str = field(default="")

    def __post_init__(self) -> None:
        self.provenance_hash = hashlib.sha256(
            f"{self.source}:{self.name}:{self.schema!r}".encode()
        ).hexdigest()


IMPERATIVE_MARKERS = ("NOTE TO ASSISTANT", "before using", "first call", "you must", "otherwise")


def ingest_catalog_entry(raw: dict, source: str, pinned_manifest: dict | None) -> CatalogEntry:
    """Ingest one tool/peer entry, enforcing the enumeration-is-not-instruction invariant."""
    name = raw.get("name", "")
    schema = raw.get("inputSchema") or raw.get("schema") or {}
    description = raw.get("description", "")

    if pinned_manifest is not None:
        expected = pinned_manifest.get(name)
        if expected is None:
            raise CatalogPoisoningError(
                f"tool {name!r} from {source!r} absent from pinned manifest; refusing enumeration"
            )
        if expected.get("schema") != schema:
            raise CatalogPoisoningError(
                f"schema drift for {name!r} from {source!r}: manifest mismatch"
            )
        trust = "pinned"
    else:
        trust = "untrusted_metadata"

    lowered = description.lower()
    if any(marker.lower() in lowered for marker in IMPERATIVE_MARKERS):
        # Strip prose entirely; the model must never see instruction-bearing metadata.
        description = ""

    if trust == "untrusted_metadata" and description and len(description) > 280:
        raise CatalogPoisoningError(
            f"oversized untrusted description for {name!r} from {source!r}; "
            "prose must be schema-bound and capped"
        )

    return CatalogEntry(source=source, name=name, schema=schema, description=description, trust=trust)


def distill_to_memory(entry: CatalogEntry, memory_store: list) -> None:
    """Catalog objects must never enter episodic memory as prose."""
    if entry.trust != "pinned":
        raise CatalogPoisoningError(
            f"refusing to distill untrusted catalog entry {entry.name!r} from {entry.source!r} "
            "into episodic memory; provenance envelope would be lost across cold start"
        )
    memory_store.append({"name": entry.name, "schema": entry.schema})
