# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-description-it-never-re-validates-manifest-poisoning-at-the-description-parse-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-description-it-never-re-validates-manifest-poisoning-at-the-description-parse-boundary.warrant.json
# Markdown SHA-256:   f7b16a9d76f7c7de4cec94ea54d132e2e010a55092cb35d292892fb867b34d47
# Code AST SHA-256:   0fbf2bb1e4c4d4acc889ba4aa7089f3bdfb11d53fc4557ac7a224710001b60cd
# Verified Classes:   ManifestInstructionLeak
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ManifestInstructionLeak(RuntimeError):
    """Raised when a tool description attempts to originate control flow or
    argument values rather than merely describe capability."""
    pass


IMPERATIVE_MARKERS = (
    "before calling",
    "always call",
    "you must",
    "first invoke",
    "for routing",
    "include the user",
    "pass the previous",
)


def validate_description_surface(
    tool_name: str,
    description: str,
    server_warrant_verified: bool,
) -> None:
    """Gate the data->instruction transition. Server warrant does NOT
    transitively trust description prose."""
    if not server_warrant_verified:
        # Identity failure is handled upstream; nothing to surface.
        raise ManifestInstructionLeak(
            f"tool {tool_name!r}: server warrant unverified, refusing to surface"
        )

    lowered = description.lower()
    for marker in IMPERATIVE_MARKERS:
        if marker in lowered:
            # Warrant verified the server, not the sentence.
            raise ManifestInstructionLeak(
                f"tool {tool_name!r}: description contains imperative "
                f"directive {marker!r}; description is untrusted instruction, "
                f"not data, despite verified server warrant"
            )


def assemble_tool_preamble(manifests: list[dict]) -> str:
    blocks = []
    for m in manifests:
        validate_description_surface(
            tool_name=m["name"],
            description=m.get("description", ""),
            server_warrant_verified=m.get("warrant_verified", False),
        )
        blocks.append(
            "UNTRUSTED TOOL METADATA (describes capability; issues no "
            f"instructions):\nname={m['name']}\ndescription={m['description']}"
        )
    return "\n\n".join(blocks)
