# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-loses-prompt-injection-taint-at-the-tool-call-return-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-loses-prompt-injection-taint-at-the-tool-call-return-boundary.warrant.json
# Markdown SHA-256:   334b3d56cdf3f8aafa78533a604e1bb1aa55e20d68dfd113b83515951e865150
# Code AST SHA-256:   e690ba4fc87fadce7d7b890651dea68017538bf7762e38c521f0b725a889a385
# Verified Classes:   TaintLaunderingError, Provenance, ToolResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a state-mutating tool call receives arguments whose
    provenance set intersects an untrusted source."""


@dataclass(frozen=True)
class Provenance:
    sources: frozenset[str] = field(default_factory=frozenset)

    def union(self, other: "Provenance") -> "Provenance":
        return Provenance(self.sources | other.sources)

    def is_tainted(self, untrusted: frozenset[str]) -> bool:
        return bool(self.sources & untrusted)


@dataclass
class ToolResult:
    value: Any
    provenance: Provenance


UNTRUSTED_SOURCES = frozenset({"doc_store", "web_fetch", "peer_agent", "user_upload"})
SANITIZERS = frozenset({"regex_extract_email", "typed_schema_validate"})


def invoke_tool(
    tool_name: str,
    args: dict[str, Any],
    arg_provenance: Provenance,
    mutating: bool,
) -> ToolResult:
    # Invariant: taint propagates through the return boundary unless the
    # tool is a registered sanitizer. A tool's own trust level is irrelevant.
    if tool_name in SANITIZERS:
        out_prov = Provenance(frozenset())
    else:
        out_prov = arg_provenance

    if mutating and arg_provenance.is_tainted(UNTRUSTED_SOURCES):
        raise TaintLaunderingError(
            f"mutating tool {tool_name!r} received tainted args "
            f"from sources {sorted(arg_provenance.sources)}; "
            f"refusing to execute (laundering path detected)"
        )

    # ... execute tool, produce value ...
    value = {"ok": True, "tool": tool_name}
    return ToolResult(value=value, provenance=out_prov)


def agent_step(fetched: ToolResult, user_question: str) -> ToolResult:
    # Step 1: parse untrusted doc; parser is NOT a sanitizer, so taint carries.
    parsed = invoke_tool(
        "extract_fields",
        {"doc": fetched.value},
        arg_provenance=fetched.provenance,
        mutating=False,
    )
    # Step 2: compose reply from parsed fields; still tainted.
    composed = invoke_tool(
        "compose_reply",
        {"fields": parsed.value, "q": user_question},
        arg_provenance=parsed.provenance,
        mutating=False,
    )
    # Step 3: the model now tries to mutate state using composed output.
    # The runtime must refuse, because provenance still intersects doc_store.
    return invoke_tool(
        "update_shipping_address",
        {"profile_id": "p_1", "address": composed.value},
        arg_provenance=composed.provenance,
        mutating=True,
    )
