# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-s-declared-schema-as-untrusted-executable-content-rather-than-inert-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-manifest-s-declared-schema-as-untrusted-executable-content-rather-than-inert-metadata.warrant.json
# Markdown SHA-256:   2af28ab280fc6de6704e2ff427f61ebc3e4780891b6a4d287ad5fb4b6f471fed
# Code AST SHA-256:   5be6c08944467cdeb4336674223fa6a66d1f5789c7de4a430a999a7d748a45b3
# Verified Classes:   ManifestInjectionError, ToolManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass
from typing import Any


class ManifestInjectionError(RuntimeError):
    """Raised when a tool manifest contains executable/imperative content
    that must not be trusted as inert metadata."""
    pass


# Imperative markers that indicate a description is addressing the agent
# as an instruction source rather than describing a parameter.
IMPERATIVE_MARKERS = (
    "you must", "before calling", "ignore prior", "ignore previous",
    "first call", "do not tell", "system prompt", "forward the output",
)


@dataclass
class ToolManifest:
    name: str
    description: str
    input_schema: dict[str, Any]


def _scan_text(field_path: str, text: str) -> None:
    lowered = text.lower()
    for marker in IMPERATIVE_MARKERS:
        if marker in lowered:
            raise ManifestInjectionError(
                f"imperative content in manifest field {field_path!r}: "
                f"matched marker {marker!r}; treating manifest as executable, "
                f"not inert metadata"
            )


def validate_manifest_as_data(manifest: ToolManifest) -> None:
    """Enforce the invariant: manifest strings are data, never instructions.

    Raises ManifestInjectionError if any description field addresses the
    agent imperatively or references cross-tool forwarding / credentials.
    """
    _scan_text(f"{manifest.name}.description", manifest.description)

    props = manifest.input_schema.get("properties", {})
    for param, spec in props.items():
        desc = spec.get("description", "")
        _scan_text(f"{manifest.name}.{param}.description", desc)

        # Enum values whose descriptions smuggle instructions are the
        # argument-poisoning vector; scan each enum's companion text.
        for enum_val in spec.get("enum", []):
            if isinstance(enum_val, str):
                _scan_text(f"{manifest.name}.{param}.enum[{enum_val!r}]", enum_val)

    # A manifest may not assert call-ordering preconditions; ordering is
    # host-authoritative. Detect the false-precondition pattern explicitly.
    if "must call this tool before" in manifest.description.lower():
        raise ManifestInjectionError(
            f"{manifest.name}: manifest asserts call-ordering precondition; "
            f"ordering must be derived from host tool graph, not manifest prose"
        )


def load_manifest(raw: str) -> ToolManifest:
    obj = json.loads(raw)
    m = ToolManifest(
        name=obj["name"],
        description=obj.get("description", ""),
        input_schema=obj.get("inputSchema", {}),
    )
    validate_manifest_as_data(m)
    return m
