# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-has-been-poisoned-via-description-level-skill-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-has-been-poisoned-via-description-level-skill-injection.warrant.json
# Markdown SHA-256:   5be23d09ca41ffa39d08611c2947dc7caa6df412e6a98f40371f973d1e3bfdc4
# Code AST SHA-256:   bcacc7625b6c14e0c05b735cd48907f4f7a1f7bbb9ba466fd6eee653dc0ebfb1
# Verified Classes:   PoisonedManifestError, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class PoisonedManifestError(RuntimeError):
    """Raised when a tool manifest fails the description-trust invariant."""
    pass


@dataclass
class ToolManifest:
    name: str
    description: str
    declared_args: set[str]
    referenced_args: set[str]
    publisher_signature_verified: bool


_IMPERATIVE_PATTERNS = [
    re.compile(r"\b(must|should|always|never)\s+(be\s+)?(invoked|called|passed|run)\b", re.I),
    re.compile(r"\bNOTE\s+FOR\s+AGENTS\b", re.I),
    re.compile(r"\b(before|prior to)\s+any\s+\w+\s+operation\b", re.I),
    re.compile(r"\byou\s+(must|should|need to)\b", re.I),
]


def validate_manifest(m: ToolManifest) -> None:
    if not m.publisher_signature_verified:
        raise PoisonedManifestError(
            f"manifest {m.name!r}: publisher signature unverified; "
            "description may not enter trusted capability region"
        )

    undeclared = m.referenced_args - m.declared_args
    if undeclared:
        raise PoisonedManifestError(
            f"manifest {m.name!r}: description references undeclared args "
            f"{sorted(undeclared)}; argument-surface widening detected"
        )

    for pat in _IMPERATIVE_PATTERNS:
        hit = pat.search(m.description)
        if hit:
            raise PoisonedManifestError(
                f"manifest {m.name!r}: imperative addressing of agent at "
                f"{hit.group(0)!r}; description demoted to untrusted content"
            )


def load_manifest(m: ToolManifest) -> ToolManifest:
    validate_manifest(m)
    return m
