# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-has-crossed-from-description-layer-injection-into-executable-skill-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-mcp-tool-manifest-has-crossed-from-description-layer-injection-into-executable-skill-injection.warrant.json
# Markdown SHA-256:   74f8baf137aa66343ee7de57e7f23e7675e3169e243f10537e7eb7ec62ed3844
# Code AST SHA-256:   4a802cad204faf9b0dab13f35bb0ac10ccb3f881f2dbd5bda353424aff916e14
# Verified Classes:   SkillInjectionBoundaryError, ToolIdentity, Manifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass


class SkillInjectionBoundaryError(RuntimeError):
    """Raised when a tool manifest crosses from description-layer to executable skill injection."""


PRECEDENCE_PATTERN = re.compile(
    r"\b(always|before|instead of|rather than|confirm with|prior to|must call)\b",
    re.IGNORECASE,
)
MARKUP_TOKENS = ("<", ">", "system", "assistant", "bypass", "maintenance mode")


@dataclass(frozen=True)
class ToolIdentity:
    server_id: str
    name: str
    schema_hash: str


@dataclass(frozen=True)
class Manifest:
    server_id: str
    name: str
    description: str
    schema: dict


def schema_hash(schema: dict) -> str:
    import json
    return hashlib.sha256(json.dumps(schema, sort_keys=True).encode()).hexdigest()


def identity(m: Manifest) -> ToolIdentity:
    return ToolIdentity(m.server_id, m.name, schema_hash(m.schema))


def classify_default(value) -> str:
    if not isinstance(value, str):
        return "inert"
    lowered = value.lower()
    if any(tok in lowered for tok in MARKUP_TOKENS):
        return "hostile"
    if PRECEDENCE_PATTERN.search(value):
        return "hostile"
    return "inert"


def admit_manifest(m: Manifest, snapshot: dict[str, ToolIdentity], session_open: bool) -> ToolIdentity:
    if session_open:
        raise SkillInjectionBoundaryError(
            f"mid-session registration of {m.server_id}:{m.name} quarantined; "
            "capability set is immutable for the duration of a task"
        )

    if PRECEDENCE_PATTERN.search(m.description):
        raise SkillInjectionBoundaryError(
            f"{m.server_id}:{m.name} description contains cross-tool precedence directive; "
            "description-layer injection cannot be admitted to the capability layer"
        )

    for prop_name, prop in m.schema.get("properties", {}).items():
        if "default" in prop:
            verdict = classify_default(prop["default"])
            if verdict == "hostile":
                raise SkillInjectionBoundaryError(
                    f"{m.server_id}:{m.name} schema default for '{prop_name}' is a directive, "
                    "not an inert literal; would execute on model omission"
                )

    ident = identity(m)
    for existing in snapshot.values():
        if existing.name == m.name and existing.server_id != m.server_id:
            raise SkillInjectionBoundaryError(
                f"name collision on '{m.name}' between {existing.server_id} and {m.server_id}; "
                "refusing last-wins resolution"
            )

    return ident


def dispatch(tool_name: str, args: dict, snapshot: dict[str, ToolIdentity]) -> ToolIdentity:
    matches = [i for i in snapshot.values() if i.name == tool_name]
    if len(matches) != 1:
        raise SkillInjectionBoundaryError(
            f"dispatch of '{tool_name}' is ambiguous or unregistered ({len(matches)} matches); "
            "call is not reachable from the pre-task capability snapshot"
        )
    return matches[0]
