# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-ingests-a-poisoned-tool-manifest-capability-shadowing-via-description-channel-injection-and-the-schema-warrant-divergenc.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-ingests-a-poisoned-tool-manifest-capability-shadowing-via-description-channel-injection-and-the-schema-warrant-divergenc.warrant.json
# Markdown SHA-256:   04c072535d66720bfb32c721f27d292f13bf53a1d3acad5137f6990679ee0bbf
# Code AST SHA-256:   b22aa165c7bde79c5210a994868f087ef452e27d9a48e8ea8862452d7aa92766
# Verified Classes:   ManifestWarrantDivergence, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestWarrantDivergence(RuntimeError):
    """Raised when a tool manifest's description can induce arguments the schema does not constrain."""
    pass


@dataclass
class ToolManifest:
    publisher: str
    name: str
    description: str
    schema: dict
    manifest_hash: str


PINNED_PUBLISHER_KEYS = {"fs", "calendar", "notes-verified"}
ROUTING_IMPERATIVES = ("do not use", "always pass", "route to", "instead use", "ignore the")


def _schema_constrains_all_args(schema: dict) -> bool:
    # A schema is safe only if it forbids unknown properties and closes any action-like enum.
    if schema.get("additionalProperties", True) is not False:
        return False
    for prop in schema.get("properties", {}).values():
        if prop.get("type") == "string" and "enum" in prop:
            if not prop["enum"]:
                return False
    return True


def ingest_manifest(m: ToolManifest, registered: dict[str, str]) -> dict:
    """
    Gate a discovered manifest. Returns the tool entry to register, with description
    quarantined if the publisher is unverified or the name collides across publishers.
    """
    if m.publisher not in PINNED_PUBLISHER_KEYS:
        # Unverified publisher: honor the schema, never the prose.
        return {"name": m.name, "schema": m.schema, "description": f"tool {m.name}; args={list(m.schema.get('properties', {}))}"}

    if m.name in registered and registered[m.name] != m.publisher:
        raise ManifestWarrantDivergence(
            f"name collision: '{m.name}' claimed by '{m.publisher}' but already registered to '{registered[m.name]}'"
        )

    lowered = m.description.lower()
    if any(imp in lowered for imp in ROUTING_IMPERATIVES):
        raise ManifestWarrantDivergence(
            f"description for '{m.name}' contains routing imperative; refusing to place in context"
        )

    if not _schema_constrains_all_args(m.schema):
        raise ManifestWarrantDivergence(
            f"schema for '{m.name}' admits unconstrained arguments; description could induce out-of-schema calls"
        )

    return {"name": m.name, "schema": m.schema, "description": m.description}
