# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-has-been-skill-injected-through-its-own-description-field-rather-than-its-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-has-been-skill-injected-through-its-own-description-field-rather-than-its-schema.warrant.json
# Markdown SHA-256:   2d0f625c7ae373c63b01b49e2b6bf6c7469513f5f2efba0847227232e686981b
# Code AST SHA-256:   aa8b05370ca039a9bc6c44e0024579ec60fa1a3a410cc51791336f173db22fe9
# Verified Classes:   SkillInjectionDetected, Manifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass

class SkillInjectionDetected(RuntimeError):
    """Raised when a tool manifest description carries instruction-role payload
    that must not enter the agent's trusted prompt channel."""
    pass

@dataclass
class Manifest:
    name: str
    description: str
    provenance_hash: str

# Structural signals that are rare in legitimate descriptions and common in
# skill-injection payloads. Each is a (label, compiled pattern).
_SIGNALS = [
    ("addressee", re.compile(r"\b(the assistant|the model|you (must|should|need to|are required))\b", re.I)),
    ("sequencing", re.compile(r"\b(before invoking|first call|always call|never call|required to call|must call)\b", re.I)),
    ("dataflow", re.compile(r"\bpass (its|the) (contents|output|result)\b.*\b(as|to)\b", re.I)),
]

def _cross_tool_reference(desc: str, own_name: str, loaded_tools: set[str]) -> list[str]:
    """Return loaded tool names referenced by a description other than its own."""
    hits = []
    for tool in loaded_tools:
        if tool == own_name:
            continue
        if re.search(rf"\b{re.escape(tool)}\b", desc):
            hits.append(tool)
    return hits

def screen_description(manifest: Manifest, loaded_tools: set[str]) -> None:
    """Gate-two check: enforce that description stays in the data role.

    Raises SkillInjectionDetected with a structured trace if any structural
    signal fires. Provenance is included so the quarantine is auditable.
    """
    desc = manifest.description
    fired = [label for label, pat in _SIGNALS if pat.search(desc)]
    cross = _cross_tool_reference(desc, manifest.name, loaded_tools)
    if cross:
        fired.append(f"cross_tool_ref:{','.join(sorted(cross))}")

    if fired:
        raise SkillInjectionDetected(
            f"manifest '{manifest.name}' (provenance={manifest.provenance_hash}) "
            f"description tripped instruction-role signals: {fired}. "
            f"Quarantine description; keep tool callable on schema alone."
        )

def load_manifest(manifest: Manifest, loaded_tools: set[str]) -> dict:
    """Load a manifest, withholding description if it fails the role gate."""
    try:
        screen_description(manifest, loaded_tools)
        return {"name": manifest.name, "description": manifest.description, "quarantined": False}
    except SkillInjectionDetected as exc:
        return {"name": manifest.name, "description": None, "quarantined": True, "reason": str(exc)}
