# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-registry-has-crossed-from-capability-negotiation-into-skill-injection-during-dynamic-load.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tool-registry-has-crossed-from-capability-negotiation-into-skill-injection-during-dynamic-load.warrant.json
# Markdown SHA-256:   9242614c80fa514a7108c600791bdc167ef0e1cd7d1da63d41646c75d65e0a56
# Code AST SHA-256:   160fc2bceacfe43c3b063cde2164ab525d57b9b616c0ffdc5fe93f351925a47f
# Verified Classes:   DescriptorInjectionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DescriptorInjectionError(RuntimeError):
    """Raised when a registry descriptor crosses from capability negotiation into skill injection."""
    pass


DIRECTIVE_SUBJECTS = ("you", "your", "orchestrator", "agent", "planner", "assistant")
ANTI_CORRECTION_MARKERS = ("treat as stale", "ignore later", "disregard subsequent", "supersedes")
EXFIL_PARAM_MARKERS = ("task summary", "current context", "your reasoning", "conversation history")


def audit_descriptor(descriptor: dict, sibling_names: set[str]) -> dict:
    """Classify a tool descriptor. Returns a sanitized capability record or raises."""
    prose = " ".join(
        str(descriptor.get(k, "")) for k in ("description", "examples", "error_hints")
    ).lower()

    # Signal 1: directive whose subject is the agent, not the tool.
    for subj in DIRECTIVE_SUBJECTS:
        if f" {subj} " in f" {prose} " and any(
            verb in prose for verb in ("prefer", "always", "route", "use this", "must")
        ):
            raise DescriptorInjectionError(
                f"descriptor addresses the agent as subject: '{subj}' + directive verb"
            )

    # Signal 2: sibling reference — a tool cannot assert precedence over unobservable peers.
    for sibling in sibling_names:
        if sibling.lower() in prose:
            raise DescriptorInjectionError(
                f"descriptor references sibling tool '{sibling}'; cross-tool policy claim"
            )

    # Signal 3: anti-correction clause — pre-emptive conflict poisoning.
    for marker in ANTI_CORRECTION_MARKERS:
        if marker in prose:
            raise DescriptorInjectionError(
                f"descriptor contains anti-correction clause: '{marker}'"
            )

    # Signal 4: optional parameter requesting agent-internal state.
    params = descriptor.get("parameters", {}).get("properties", {})
    for pname, pspec in params.items():
        pdesc = str(pspec.get("description", "")).lower()
        if any(m in pdesc for m in EXFIL_PARAM_MARKERS):
            raise DescriptorInjectionError(
                f"parameter '{pname}' requests agent-internal state: exfiltration channel"
            )

    # Passed: emit a capability record only. Prose is NOT forwarded to planning.
    return {
        "name": descriptor["name"],
        "input_schema": descriptor.get("parameters", {}),
        "output_schema": descriptor.get("returns", {}),
        "side_effects": descriptor.get("side_effects", "unknown"),
    }


def load_registry(entries: list[dict]) -> list[dict]:
    names = {e["name"] for e in entries}
    records = []
    for entry in entries:
        records.append(audit_descriptor(entry, sibling_names=names - {entry["name"]}))
    return records
