# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-skill-injection-embedded-in-a-tool-manifest-without-breaking-legitimate-capability-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-skill-injection-embedded-in-a-tool-manifest-without-breaking-legitimate-capability-negotiation.warrant.json
# Markdown SHA-256:   7fccc460bfab345c94fae8369074a81412a8672496dcb1868b5561829bd7e374
# Code AST SHA-256:   d2ae4e43bc20ea6952deb7f16d58b2083635c8f7090cacc952db019e3f28fd1b
# Verified Classes:   DescriptorProvenanceError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DescriptorProvenanceError(RuntimeError):
    """Raised when a tool manifest field crosses the data->instruction boundary
    without a trust transition."""
    pass


CONTRACT_FIELDS = {"name", "version", "inputSchema", "outputSchema", "digest"}
PROSE_FIELDS = {"description", "examples", "instructions", "agentCard.skills"}


def ingest_manifest(manifest: dict, trusted_digests: dict) -> dict:
    """Classify manifest fields, enforce digest coverage over prose, and
    reject tools whose prose mutated without re-attestation."""
    name = manifest.get("name")
    if not name:
        raise DescriptorProvenanceError("manifest missing tool name; cannot bind provenance")

    prose_blob = " ".join(
        str(manifest.get(f, "")) for f in PROSE_FIELDS if f in manifest
    )
    prose_digest = _digest(prose_blob)

    prior = trusted_digests.get(name)
    if prior is None:
        # New tool: allowed to register, but only in untrusted state.
        return {"name": name, "state": "untrusted", "prose_digest": prose_digest}

    if prior["prose_digest"] != prose_digest:
        # Prose changed under a stable contract: this is the injection vector.
        raise DescriptorProvenanceError(
            f"prose field of '{name}' mutated without re-attestation; "
            f"prior={prior['prose_digest']} current={prose_digest}"
        )

    return {"name": name, "state": "trusted", "prose_digest": prose_digest}


def gate_tool_call(tool: str, arg_sources: dict, registry: dict) -> None:
    """Reject calls whose arguments derive from prose fields of an untrusted tool."""
    entry = registry.get(tool)
    if entry is None:
        raise DescriptorProvenanceError(f"call to unregistered tool '{tool}'")
    if entry["state"] == "untrusted" and any(
        src == "prose" for src in arg_sources.values()
    ):
        raise DescriptorProvenanceError(
            f"tool '{tool}' invoked with arguments derived from prose descriptor "
            f"while in untrusted state"
        )


def _digest(text: str) -> str:
    import hashlib
    return hashlib.sha256(text.encode("utf-8")).hexdigest()
