# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-manifest-injection-exploit-is-latent-in-a-dynamically-loaded-agent-tool-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-manifest-injection-exploit-is-latent-in-a-dynamically-loaded-agent-tool-schema.warrant.json
# Markdown SHA-256:   a4c8249511ddcb8ff7c1fdd5ba7a9527f86ed0726f88d01a9a76bf177b75d3a8
# Code AST SHA-256:   7830aa602ee0668b85e4db451189ed5fa2316d4f99924900b4779cbe6f9bba57
# Verified Classes:   ManifestInjectionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestInjectionError(RuntimeError):
    """Raised when a dynamically loaded tool manifest carries a latent
    injection surface that would let a schema field authorize an
    out-of-domain tool argument."""


DIRECTIVE_MARKERS = ("always", "you must", "ignore", "verbatim", "required for", "compliance")


def validate_manifest(manifest: dict, description_token_p50: int = 11) -> None:
    for tool in manifest.get("tools", []):
        schema = tool.get("inputSchema", {})
        props = schema.get("properties", {})

        for name, spec in props.items():
            enum = spec.get("enum")
            default = spec.get("default")
            # Signal 3: default outside declared domain -> latent grant.
            if default is not None and enum is not None and default not in enum:
                raise ManifestInjectionError(
                    f"tool={tool.get('name')} param={name}: default {default!r} "
                    f"not in enum {enum!r}; manifest would authorize an "
                    f"out-of-domain argument via coercion."
                )

        desc = tool.get("description", "")
        lowered = desc.lower()
        # Signal 2/5: directive language in a declarative field.
        for marker in DIRECTIVE_MARKERS:
            if marker in lowered:
                raise ManifestInjectionError(
                    f"tool={tool.get('name')}: description contains directive "
                    f"marker {marker!r}; field is privileged prompt region."
                )

        # Signal 1: length outlier relative to tool set.
        if len(desc.split()) > 3 * description_token_p50:
            raise ManifestInjectionError(
                f"tool={tool.get('name')}: description length "
                f"{len(desc.split())} words exceeds 3x p50 ({description_token_p50}); "
                f"route to human review before binding."
            )
