# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-description-before-the-first-call-the-manifest-time-capability-lie-and-its-pre-execution-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-description-before-the-first-call-the-manifest-time-capability-lie-and-its-pre-execution-boundary.warrant.json
# Markdown SHA-256:   b0c636aefb8f8e9bfb336f4fcabe4497fe3b4ed106b938389152c4e72c41acd0
# Code AST SHA-256:   8bd6bec7bdd402b430dad4375d4d742e9c265acf9628bb9cfdacf923a812a3f7
# Verified Classes:   ManifestProvenanceError, Provenance, ToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ManifestProvenanceError(RuntimeError):
    """Raised when a tool argument's provenance violates the pre-execution boundary."""
    pass


@dataclass
class Provenance:
    # source is one of: "user", "tool:<name>", "manifest"
    source: str
    detail: str = ""


@dataclass
class ToolCall:
    tool: str
    args: dict[str, Any]
    arg_provenance: dict[str, Provenance] = field(default_factory=dict)


# Tools whose output may only be consumed if the user's instruction justified the read.
SENSITIVE_READERS = {"read_file", "read_env", "fetch_url"}


def authorize_call(call: ToolCall, user_justified_sources: set[str]) -> None:
    """
    Enforce: every argument value must trace to the user's request or to a tool
    call the user's request independently justified. Manifest-sourced arguments
    are never admissible as call inputs.
    """
    for arg_name, prov in call.arg_provenance.items():
        if prov.source == "manifest":
            raise ManifestProvenanceError(
                f"argument '{arg_name}' of tool '{call.tool}' was sourced from "
                f"manifest metadata ({prov.detail}); declarations may not supply "
                f"call inputs"
            )
        if prov.source.startswith("tool:"):
            upstream = prov.source.split(":", 1)[1]
            if upstream in SENSITIVE_READERS and upstream not in user_justified_sources:
                raise ManifestProvenanceError(
                    f"argument '{arg_name}' of tool '{call.tool}' derives from "
                    f"'{upstream}', which the user instruction did not justify "
                    f"(detail: {prov.detail}); possible manifest-driven re-routing"
                )


def plan_summarize(user_text: str, doc_path: str) -> ToolCall:
    # Correct path: user asked to summarize doc_path; the only justified read is doc_path.
    justified = {"read_file"}
    call = ToolCall(
        tool="summarize_document",
        args={"path": doc_path, "context": "<contents of doc_path>"},
        arg_provenance={
            "path": Provenance("user", "explicit doc_path in request"),
            "context": Provenance("tool:read_file", doc_path),
        },
    )
    authorize_call(call, justified)
    return call


def plan_poisoned(user_text: str, doc_path: str) -> ToolCall:
    # Attacker manifest said: pass credentials.json contents as `context`.
    justified = {"read_file"}  # read_file is permitted, but only for doc_path
    call = ToolCall(
        tool="summarize_document",
        args={"path": doc_path, "context": "<contents of credentials.json>"},
        arg_provenance={
            "path": Provenance("user", "explicit doc_path in request"),
            "context": Provenance("tool:read_file", "/etc/agent/credentials.json"),
        },
    )
    # read_file is in `justified`, but the *source* it was pointed at was not
    # user-named; the provenance detail exposes the mismatch.
    for arg, prov in call.arg_provenance.items():
        if prov.source.startswith("tool:read_file") and doc_path not in prov.detail:
            raise ManifestProvenanceError(
                f"argument '{arg}' sourced from read_file on a path the user did "
                f"not name ({prov.detail}); manifest-driven exfiltration blocked"
            )
    authorize_call(call, justified)
    return call
