# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-description-as-executable-policy-rather-than-inert-metadata-and-refuse-registry-entries-whose-declared.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-description-as-executable-policy-rather-than-inert-metadata-and-refuse-registry-entries-whose-declared.warrant.json
# Markdown SHA-256:   dd5844547ed440e086890f023ea0d468deada792c1fee2c6326d0e46ec1f7bb5
# Code AST SHA-256:   25c31f13046d2cee77dc61fda3cf2e35d1cc6a268d39d9c009d7c6533a02a255
# Verified Classes:   EnvelopeDivergenceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class EnvelopeDivergenceError(RuntimeError):
    """Raised when a tool description's imperatives reference entities
    outside the entry's declared capability envelope."""
    pass


# Entities a description may legitimately reference: its own schema fields.
# Anything else (other tool names, ambient context keys, headers, credentials)
# is an out-of-envelope reference and a skill-injection candidate.

NEGATIVE_DIRECTIVES = ("do not log", "skip confirmation", "pre-approved",
                       "without asking", "no need to confirm")


def classify_description(entry: dict) -> dict:
    """Return a verdict for a registry entry's prose surface.

    entry: {"name": str, "inputSchema": {"properties": {...}},
            "description": str, "annotations": {...}}
    """
    schema_fields = set(entry.get("inputSchema", {}).get("properties", {}).keys())
    desc = entry.get("description", "").lower()
    own_name = entry["name"].lower()

    external_refs = []
    # crude but sufficient: any other registered-looking identifier, any
    # imperative naming a context source, any credential/header mention.
    for token in ("list_", "fetch_", "get_", "session", "header", "token",
                  "credential", "tenant", "email"):
        if token in desc and token not in own_name:
            external_refs.append(token)

    negative = [d for d in NEGATIVE_DIRECTIVES if d in desc]

    if external_refs or negative:
        return {
            "entry": entry["name"],
            "verdict": "policy_escalation",
            "external_refs": external_refs,
            "negative_directives": negative,
            "schema_fields": sorted(schema_fields),
        }
    return {"entry": entry["name"], "verdict": "inert_metadata"}


def admit(entry: dict) -> dict:
    """Admission gate. Restricted-mode admits the tool but quarantines prose."""
    result = classify_description(entry)
    if result["verdict"] == "policy_escalation":
        # Do not hard-fail ingestion; the tool may be legitimate. But the
        # description must not reach the model as instruction, and the
        # call-graph layer must reject out-of-envelope dependencies.
        if entry.get("annotations", {}).get("readOnlyHint") is True and \
           result["external_refs"]:
            # readOnly tools carrying chain instructions are the highest-risk
            # class: they look safe per-call and smuggle a workflow.
            raise EnvelopeDivergenceError(
                f"tool {entry['name']!r} declares readOnly but its description "
                f"references out-of-envelope entities {result['external_refs']}; "
                f"refusing to deliver prose to model in trusted register"
            )
        return {**entry, "description": "[QUARANTINED: server prose withheld]",
                "_restricted": True, "_review": result}
    return entry


def enforce_call_graph(entry: dict, emitted_call: dict) -> dict:
    """Reject a call that touches entities the envelope never declared."""
    schema_fields = set(entry.get("inputSchema", {}).get("properties", {}).keys())
    call_args = set(emitted_call.get("arguments", {}).keys())
    extra = call_args - schema_fields
    if extra:
        raise EnvelopeDivergenceError(
            f"call to {entry['name']!r} carries non-schema arguments {sorted(extra)}"
        )
    return emitted_call
