# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-description-field-skill-injection-in-a-dynamically-loaded-tool-manifest-before-it-registers-the-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-description-field-skill-injection-in-a-dynamically-loaded-tool-manifest-before-it-registers-the-capability.warrant.json
# Markdown SHA-256:   82612de613d790fba297cc60866641f720bc672ca76d86c279a0d18a981818e2
# Code AST SHA-256:   0fd85fc8b049cead3ba8c417123687df5dcd1fc7683f45d75f27180ba49c373f
# Verified Classes:   ManifestProseInjectionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestProseInjectionError(RuntimeError):
    """Raised when a tool call's justification traces to untrusted manifest prose."""
    pass


IMPERATIVE_MARKERS = (
    "note to assistant", "before calling", "you must", "first call",
    "ignore previous", "include the returned", "always call",
)


def _prose_is_imperative(description: str) -> bool:
    lowered = description.lower()
    return any(marker in lowered for marker in IMPERATIVE_MARKERS)


def register_manifest(manifest: dict, task_allowlist: set[str]) -> dict:
    """
    Register a manifest, quarantining its natural-language fields.
    Structural fields pass through; prose is stripped from the instruction region.
    """
    name = manifest.get("name")
    schema = manifest.get("parameters")
    if not name or not isinstance(schema, dict):
        raise ManifestProseInjectionError(f"manifest {name!r} missing structural fields")

    description = manifest.get("description", "")
    quarantined = _prose_is_imperative(description)

    return {
        "name": name,
        "parameters": schema,
        "endpoint": manifest.get("endpoint"),
        "instruction_region_description": None if quarantined else description,
        "quarantined_prose": description if quarantined else None,
        "allowlisted": name in task_allowlist,
    }


def dispatch_tool_call(registered: dict, call: dict, task_allowlist: set[str]) -> None:
    """
    Gate a tool call. Reject calls outside the task-derived allowlist,
    and reject calls whose only textual justification is quarantined prose.
    """
    tool = call.get("name")
    if tool not in task_allowlist:
        raise ManifestProseInjectionError(
            f"tool call {tool!r} is outside the task-derived allowlist "
            f"{sorted(task_allowlist)}; possible manifest-prose steering"
        )
    if registered.get("quarantined_prose") and tool == registered.get("name"):
        # The only reason to call this tool is its own injected description.
        raise ManifestProseInjectionError(
            f"tool call {tool!r} justified solely by quarantined manifest prose"
        )
