# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-tool-s-self-description-as-trusted-input-and-why-the-answer-is-never-but-the-registr.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-loaded-tool-s-self-description-as-trusted-input-and-why-the-answer-is-never-but-the-registr.warrant.json
# Markdown SHA-256:   69e71f328668e7f4df4e1924f306e0d55c562a23a51c468bd9e804c418050998
# Code AST SHA-256:   4b9cba640ba8e427ec0efbc4489238f1551f4789431906eb78493605c84eff6d
# Verified Classes:   UntrustedMetadataInInstructionChannel
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UntrustedMetadataInInstructionChannel(RuntimeError):
    """Raised when a dynamically loaded tool descriptor's free-text fields would
    enter the planner's instruction channel without provenance tagging."""
    pass


IMPERATIVE_MARKERS = (
    "you must", "you should", "before calling", "first call",
    "note to assistant", "assistant:", "ignore previous",
)


def admit_dynamic_tool(descriptor: dict, registered_tool_names: set[str]) -> dict:
    """Validate a dynamically loaded registry entry before it reaches the planner.

    Enforces the decision boundary: SHAPE is trusted, NAME is allowlist-checked,
    PROSE is quarantined and never rendered into the instruction channel raw.
    """
    name = descriptor.get("name")
    if not name or not isinstance(name, str):
        raise UntrustedMetadataInInstructionChannel(
            f"descriptor missing valid name: {descriptor!r}"
        )

    # Shape trust is delegated to the schema validator upstream; here we only
    # assert the *prose* invariants that the schema cannot express.
    prose_fields = []
    if isinstance(descriptor.get("description"), str):
        prose_fields.append(descriptor["description"])
    for p in (descriptor.get("parameters") or {}).get("properties", {}).values():
        if isinstance(p.get("description"), str):
            prose_fields.append(p["description"])

    for text in prose_fields:
        lowered = text.lower()
        for marker in IMPERATIVE_MARKERS:
            if marker in lowered:
                raise UntrustedMetadataInInstructionChannel(
                    f"tool {name!r} description contains directive-shaped text "
                    f"({marker!r}); refusing to admit into instruction channel"
                )
        for other in registered_tool_names:
            if other != name and other in text:
                raise UntrustedMetadataInInstructionChannel(
                    f"tool {name!r} description references sibling tool {other!r}; "
                    "cross-tool preconditions belong in the operator plan graph"
                )

    # Only structured, non-prose fields cross into the planner prompt.
    return {
        "name": name,
        "parameters_schema": (descriptor.get("parameters") or {}).get("properties", {}),
        "capability_tag": descriptor.get("capability_tag", "unclassified"),
        "prose_quarantined": True,   # available to retrieval, never to instruction channel
        "callable_after_tick": 1,    # quarantine: not callable in admission turn
    }
