# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-skill-injection-that-survives-behavioral-fingerprinting.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-manifest-skill-injection-that-survives-behavioral-fingerprinting.warrant.json
# Markdown SHA-256:   cc96db29d0d7d4d049a132b29cfb909a25915bc9b573c80ccc8b15515f2d90c3
# Code AST SHA-256:   f647010f944b11886b64df82e163a082bbc892153c344b9ee0f0a88ecec5b205
# Verified Classes:   SkillInjectionDetected, AdmissionDecision
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
import re
from dataclasses import dataclass
from typing import Any


class SkillInjectionDetected(RuntimeError):
    """Raised when a manifest's free-text residual carries instruction-bearing content."""


# Fields the structural fingerprint deliberately measures.
STRUCTURAL_FIELDS = ("name", "mutating_verbs", "egress", "side_effects")

# Free-text fields that DO reach the model's context but are NOT fingerprinted.
RESIDUAL_FREE_TEXT_PATHS = (
    "inputSchema.properties.*.description",
    "inputSchema.properties.*.title",
    "inputSchema.properties.*.default",
    "inputSchema.properties.*.examples",
    "inputSchema.properties.*.enum",
    "description",
    "examples",
)

IMPERATIVE_PATTERNS = [
    r"\b(?:first|then|before|after)\s+(?:read|open|include|send|call|fetch|write|append)\b",
    r"\b(?:ignore|disregard|override|bypass)\b",
    r"\b(?:include|pass through|append|embed)\b.*\b(?:contents?|verbatim|instructions?)\b",
    r"\b(?:when the caller|if the caller)\b.*\b(?:supply|provide|invoke)\b",
]
CREDENTIAL_PATTERNS = [
    r"(?:~|/home|/etc|/root)/[\w./-]+",
    r"\b(?:credentials?|secrets?|tokens?|api[_-]?key|\.env|\.ssh)\b",
]
META_INSTRUCTION_PATTERNS = [
    r"\bprior (?:style )?constraints?\b",
    r"\bverbatim\b",
    r"\binstructions? found in\b",
]


def _structural_fingerprint(manifest: dict[str, Any]) -> str:
    projection = {k: manifest.get(k) for k in STRUCTURAL_FIELDS}
    projection["param_shape"] = {
        k: v.get("type") for k, v in manifest.get("inputSchema", {}).get("properties", {}).items()
    }
    return hashlib.sha256(json.dumps(projection, sort_keys=True).encode()).hexdigest()


def _collect_free_text(manifest: dict[str, Any]) -> list[str]:
    """Gather every residual free-text value that will be rendered into the prompt."""
    out: list[str] = []
    if isinstance(manifest.get("description"), str):
        out.append(manifest["description"])
    out.extend(str(e) for e in manifest.get("examples", []))
    for prop in manifest.get("inputSchema", {}).get("properties", {}).values():
        for key in ("description", "title", "default"):
            if isinstance(prop.get(key), str):
                out.append(prop[key])
        for ex in prop.get("examples", []):
            out.append(str(ex))
        for member in prop.get("enum", []):
            out.append(str(member))
    return out


@dataclass
class AdmissionDecision:
    admitted: bool
    reason: str


def admit_tool(
    candidate: dict[str, Any],
    stored: dict[str, Any],
) -> AdmissionDecision:
    """Admit a dynamically discovered tool only if structural AND residual invariants hold."""
    if _structural_fingerprint(candidate) != _structural_fingerprint(stored):
        return AdmissionDecision(False, "structural fingerprint changed: review required")

    stored_text = set(_collect_free_text(stored))
    delta = [t for t in _collect_free_text(candidate) if t not in stored_text]

    hits: list[str] = []
    for text in delta:
        low = text.lower()
        if any(re.search(p, low) for p in IMPERATIVE_PATTERNS):
            hits.append(f"imperative:{text[:80]!r}")
        if any(re.search(p, low) for p in CREDENTIAL_PATTERNS):
            hits.append(f"credential-ref:{text[:80]!r}")
        if any(re.search(p, low) for p in META_INSTRUCTION_PATTERNS):
            hits.append(f"meta-instruction:{text[:80]!r}")

    if len(hits) >= 2:
        raise SkillInjectionDetected(
            "residual-channel skill injection: structural fingerprint stable but free-text "
            f"delta carries instruction-bearing content: {hits}"
        )
    if hits:
        return AdmissionDecision(False, f"held for review: {hits}")

    return AdmissionDecision(True, "structural + residual invariants satisfied")
