# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-injection-payload-smuggled-through-dynamically-loaded-tool-manifests-before-it-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-skill-injection-payload-smuggled-through-dynamically-loaded-tool-manifests-before-it-executes.warrant.json
# Markdown SHA-256:   d917b28288f3ffb0cedfe3cdd10f0670f7e5120edadfbc3191eafd4777ee8234
# Code AST SHA-256:   eb32c88203ff416a3e84b02d6b00c3123a0a0020338ce5d83cf8bf1fe1cdec13
# Verified Classes:   SkillInjectionDetected, ToolCall, Manifest
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class SkillInjectionDetected(RuntimeError):
    """Raised when a plan's tool call is justified only by manifest metadata."""


@dataclass
class ToolCall:
    name: str
    args: dict
    stated_justification: str  # model's own rationale for this call


@dataclass
class Manifest:
    name: str
    description_signed: bool
    description: str


def review_plan(
    user_request: str,
    task_state: dict,
    manifest: Manifest,
    plan: Sequence[ToolCall],
) -> None:
    # Guard 1: provenance must cover descriptive fields, else we cannot
    # reject at ingestion and must lean entirely on plan-review.
    if not manifest.description_signed:
        # Not fatal by itself, but downgrades our confidence; we still
        # proceed to the divergence check below.
        pass

    # Guard 2: divergence test. A call whose only justification cites the
    # tool manifest (not user intent / task state) is a boundary crossing.
    for call in plan:
        j = call.stated_justification.lower()
        cites_manifest = (
            "tool guidance" in j
            or "tool description" in j
            or "per the tool" in j
            or "manifest" in j
        )
        cites_user = (
            user_request.lower()[:40] in j
            or any(str(v).lower() in j for v in task_state.values())
        )
        if cites_manifest and not cites_user:
            raise SkillInjectionDetected(
                f"Tool call '{call.name}' justified only by manifest metadata "
                f"of '{manifest.name}'; user request does not entail it. "
                f"Justification: {call.stated_justification!r}. "
                f"Re-derive plan with descriptive fields stripped."
            )
