# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-propagation-across-tool-call-boundaries-is-silently-laundering-untrusted-text-into-trusted-slo.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-propagation-across-tool-call-boundaries-is-silently-laundering-untrusted-text-into-trusted-slo.warrant.json
# Markdown SHA-256:   7c127904e37ce750d8bee944541a6f20807b591a59933d118c3e1e70a70aa3d2
# Code AST SHA-256:   8ab3df72487226f02ef624b846b1a7a2322ff5b280422ca323ff6550a5f79cf2
# Verified Classes:   TaintLaunderingError, SlotRole, Provenance, ToolArg, TrustedState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when untrusted-derived content reaches an executable tool slot."""


class SlotRole(Enum):
    INFORMATIONAL = "informational"   # note, summary, label — safe to populate from taint
    EXECUTABLE = "executable"         # path, command, url, recipient, query — must be confirmed


@dataclass(frozen=True)
class Provenance:
    source_class: str          # "trusted" | "untrusted_read" | "model_transform"
    turn: int
    parent: "Provenance | None" = None

    def is_tainted(self) -> bool:
        node: Provenance | None = self
        while node is not None:
            if node.source_class == "untrusted_read":
                return True
            node = node.parent
        return False


@dataclass
class ToolArg:
    name: str
    value: str
    role: SlotRole
    provenance: Provenance


@dataclass
class TrustedState:
    """Pre-taint planning artifacts. Only these may confirm an executable target."""
    confirmed_targets: set[str] = field(default_factory=set)

    def can_confirm(self, value: str) -> bool:
        return value in self.confirmed_targets


def validate_tool_call(args: Iterable[ToolArg], trusted: TrustedState) -> None:
    for arg in args:
        if arg.role is not SlotRole.EXECUTABLE:
            continue
        if not arg.provenance.is_tainted():
            continue
        # Tainted value in an executable slot: only allow if independently confirmable.
        if not trusted.can_confirm(arg.value):
            raise TaintLaunderingError(
                f"tainted value reached executable slot '{arg.name}' "
                f"(source={arg.provenance.source_class}, turn={arg.provenance.turn}) "
                f"with no pre-taint antecedent; blocking dispatch"
            )
        # confirmable: allow, but caller must emit an audit record
