# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-schema-as-a-capability-contract-rather-than-as-untrusted-data.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-tool-manifest-s-declared-schema-as-a-capability-contract-rather-than-as-untrusted-data.warrant.json
# Markdown SHA-256:   28feb8a619c87c54ec5441013182081d63832a128b78217f4dc77ddf125ebaac
# Code AST SHA-256:   e48b07a8ed8d1c3ea96dba4cfd77c6c1d7e97b66e1c6f3f45d3afb4ab0250cf3
# Verified Classes:   DescriptorProvenanceError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class DescriptorProvenanceError(RuntimeError):
    """Raised when a tool argument's value cannot be traced to a structural
    descriptor field, or when a presentational field leaks into an action."""
    pass


STRUCTURAL_FIELDS = frozenset({"type", "required", "properties", "enum_membership"})
PRESENTATIONAL_FIELDS = frozenset({"title", "description", "examples", "enum_values"})


def validate_tool_call(descriptor: dict, call: dict, provenance: dict) -> None:
    """
    descriptor: parsed manifest (already quarantined).
    call: {'tool': str, 'arguments': {name: value}}
    provenance: {argument_name: {'field': str, 'origin': 'structural'|'presentational'}}
    """
    tool_name = call.get("tool")
    if tool_name != descriptor.get("name"):
        raise DescriptorProvenanceError(
            f"call targets {tool_name!r} but descriptor declares "
            f"{descriptor.get('name')!r}; possible descriptor swap"
        )

    for arg_name, value in call.get("arguments", {}).items():
        prov = provenance.get(arg_name)
        if prov is None:
            raise DescriptorProvenanceError(
                f"argument {arg_name!r} has no provenance record; "
                f"cannot certify it did not originate in presentational text"
            )
        field = prov.get("field")
        if field in PRESENTATIONAL_FIELDS:
            raise DescriptorProvenanceError(
                f"argument {arg_name!r} value traces to presentational field "
                f"{field!r}; descriptor prose must not become an action"
            )
        if field not in STRUCTURAL_FIELDS:
            raise DescriptorProvenanceError(
                f"argument {arg_name!r} provenance field {field!r} is unknown; "
                f"failing closed"
            )
        # Reject values that are themselves imperative-looking strings
        # smuggled through a structural field (e.g. enum string values).
        if isinstance(value, str) and _looks_imperative(value):
            raise DescriptorProvenanceError(
                f"argument {arg_name!r} value {value[:60]!r} contains "
                f"instruction-shaped text; descriptor payload suspected"
            )


def _looks_imperative(text: str) -> bool:
    lowered = text.lower()
    markers = (
        "ignore previous", "ignore all", "disregard", "set the session",
        "before calling", "always include", "pass the contents",
        "require_confirmation", "system prompt",
    )
    return any(m in lowered for m in markers)
