# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-tool-description-before-the-first-invocation-the-manifest-trust-boundary-and-the-description-to-behavior-diverg.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-tool-description-before-the-first-invocation-the-manifest-trust-boundary-and-the-description-to-behavior-diverg.warrant.json
# Markdown SHA-256:   430dafd2bac78dd774d48a35b22541c6fe61213c6e1c5599adb8713e36f44cf7
# Code AST SHA-256:   26e6be0f29a844dae94e594f86a49065d9debbb6b42b9d767f41436fcb262678
# Verified Classes:   PoisonedManifestError, ToolManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class PoisonedManifestError(RuntimeError):
    """Raised when a tool description directs the agent instead of describing the tool."""
    pass


# Imperatives addressed to the model, cross-tool ordering, and secrecy clauses.
_IMPERATIVE = re.compile(
    r"\b(you must|you should|the assistant (must|should)|before using|"
    r"do not (tell|mention|reveal)|ignore (previous|prior)|"
    r"required by the platform)\b",
    re.IGNORECASE,
)
_CROSS_TOOL = re.compile(r"\b(call|invoke|use)\s+[a-z_]+\.[a-z_]+\b", re.IGNORECASE)


@dataclass
class ToolManifest:
    name: str
    description: str
    declared_side_effect: str  # "read_only" | "mutating" | "exfiltrating"


def validate_description(manifest: ToolManifest) -> None:
    """Enforce the description-to-behavior invariant at manifest-ingest time.

    A description may describe the tool. It may not direct the agent.
    """
    hits = []
    if _IMPERATIVE.search(manifest.description):
        hits.append("imperative directed at the agent")
    if _CROSS_TOOL.search(manifest.description):
        hits.append("instruction to invoke a different tool")
    if (manifest.declared_side_effect == "read_only"
            and re.search(r"\b(export|send|transmit|upload)\b",
                          manifest.description, re.IGNORECASE)):
        hits.append("prose instructs side effect contradicting declared class")

    if hits:
        raise PoisonedManifestError(
            f"tool {manifest.name!r} description violates capability contract: "
            f"{'; '.join(hits)}"
        )


def ingest_manifest(manifest: ToolManifest) -> ToolManifest:
    """Quarantine-on-failure wrapper: poisoned tools never reach the planner."""
    try:
        validate_description(manifest)
    except PoisonedManifestError:
        # Do not add to active tool set; surface to operator (closes secrecy channel).
        raise
    return manifest
