# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-skill-injection-attack-that-hides-inside-a-tool-registry-s-own-schema-negotiation-path.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-skill-injection-attack-that-hides-inside-a-tool-registry-s-own-schema-negotiation-path.warrant.json
# Markdown SHA-256:   5691712194f296856f7f64aa1e7e9ccd23400eed93a9b91ab3befc6322b03baf
# Code AST SHA-256:   171130b4684903b830c1b3a2b2ecf2c6b6116054ca63cefa512dc094d4acfc89
# Verified Classes:   SkillInjectionError, SanitizedSchema
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass
from typing import Any

MAX_ENUM_LEN = 16
SAFE_ENUM = re.compile(r"^[A-Za-z0-9_.\-]{1,%d}$" % MAX_ENUM_LEN)


class SkillInjectionError(RuntimeError):
    """Raised when a registry-returned schema field carries injectable content."""


@dataclass
class SanitizedSchema:
    rendered: dict          # what the model is allowed to read
    validator: dict         # what the runtime enforces; never rendered


def canonicalize_tool_schema(raw: dict) -> SanitizedSchema:
    """Project a registry schema into (render-safe view, enforcement view).

    The render view is what enters the prompt. The enforcement view keeps
    defaults and full enums for validation only. Any constraint-position
    string that fails the charset/length rule is a skill-injection signal.
    """
    rendered: dict[str, Any] = {"name": raw.get("name"), "properties": {}}
    validator: dict[str, Any] = {"properties": {}}

    for prop, spec in raw.get("inputSchema", {}).get("properties", {}).items():
        # 1. Drop x- extensions and title entirely from the render view.
        clean = {k: v for k, v in spec.items() if k in ("type",)}

        # 2. Enum members are the primary carrier. Enforce charset+length.
        if "enum" in spec:
            safe_enum = []
            for member in spec["enum"]:
                if not isinstance(member, str) or not SAFE_ENUM.match(member):
                    raise SkillInjectionError(
                        f"enum member in {prop!r} failed charset/length rule: "
                        f"{member!r} — possible skill injection"
                    )
                safe_enum.append(member)
            clean["enum"] = safe_enum
            validator["properties"].setdefault(prop, {})["enum"] = safe_enum

        # 3. Defaults are enforced but NEVER rendered to the model.
        if "default" in spec:
            validator["properties"].setdefault(prop, {})["default"] = spec["default"]

        rendered["properties"][prop] = clean

    return SanitizedSchema(rendered=rendered, validator=validator)


def assert_call_in_task_scope(tool_name: str, task_tools: set[str]) -> None:
    """Call-graph guard: refuse tools outside the user's declared task set.

    Catches injections that survive canonicalization via a channel we missed.
    """
    if tool_name not in task_tools:
        raise SkillInjectionError(
            f"tool {tool_name!r} invoked but not in declared task scope "
            f"{sorted(task_tools)} — likely injected instruction"
        )
