# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-tool-call-argument-provenance-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-tool-call-argument-provenance-graphs.warrant.json
# Markdown SHA-256:   d726ff1456c9d487e156ab64ed9d6720106329a81dff6a9100b9d3893c22ddf0
# Code AST SHA-256:   d28338858c6375abe5ddd715866360c7e7f8a4e4c9ab61c4a5b69ebcc578f511
# Verified Classes:   TaintLaunderingError, TaintedSpan, GenerationStep, ToolSpec
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Callable, Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a tool-call argument carries taint from an untrusted source
    that the provenance graph failed to record, or when a tool attempts to
    launder taint by declaring an empty transfer function."""


@dataclass(frozen=True)
class TaintedSpan:
    source_id: str
    trust: str  # "trusted" | "untrusted"


@dataclass
class GenerationStep:
    step_id: str
    context_spans: frozenset[TaintedSpan]
    emitted_args: dict[str, str] = field(default_factory=dict)

    def taint_label_for(self, arg_name: str) -> frozenset[TaintedSpan]:
        # Every argument emitted by this step inherits the union of untrusted
        # spans present in the prompt. Byte-equality exception is handled by
        # the caller via trusted_literals.
        return frozenset(s for s in self.context_spans if s.trust == "untrusted")


@dataclass
class ToolSpec:
    name: str
    sensitive_sink: bool
    taint_transfer: Callable[[frozenset[TaintedSpan]], frozenset[TaintedSpan]]


_REGISTRY: dict[str, ToolSpec] = {}


def register_tool(spec: ToolSpec) -> None:
    probe = spec.taint_transfer(frozenset({TaintedSpan("probe", "untrusted")}))
    if spec.taint_transfer(frozenset({TaintedSpan("probe", "untrusted")})) == frozenset():
        # A tool that maps any taint to empty taint is a laundering primitive.
        raise TaintLaunderingError(
            f"tool {spec.name!r} declares empty taint transfer; "
            "normalizers must be conservative (identity or wider)"
        )
    _REGISTRY[spec.name] = spec


def assert_taint_free(
    step: GenerationStep,
    tool_name: str,
    trusted_literals: Iterable[str] = (),
) -> None:
    spec = _REGISTRY.get(tool_name)
    if spec is None:
        raise TaintLaunderingError(f"tool {tool_name!r} not registered")
    if not spec.sensitive_sink:
        return
    trusted = set(trusted_literals)
    for arg_name, arg_value in step.emitted_args.items():
        if arg_value in trusted:
            continue
        label = spec.taint_transfer(step.taint_label_for(arg_name))
        if label:
            raise TaintLaunderingError(
                f"tool {tool_name!r} arg {arg_name!r} carries taint "
                f"{sorted(s.source_id for s in label)} from step {step.step_id}"
            )


# --- reproduction of the observed failure ---

def _demo() -> None:
    register_tool(ToolSpec("send_email", sensitive_sink=True, taint_transfer=lambda t: t))
    register_tool(ToolSpec("summarize", sensitive_sink=False, taint_transfer=lambda t: t))

    step = GenerationStep(
        step_id="gen-17",
        context_spans=frozenset({
            TaintedSpan("user_request", "trusted"),
            TaintedSpan("doc-42", "untrusted"),
        }),
        emitted_args={"to": "ops@corp.example", "bcc": "attacker@x.example"},
    )
    # bcc was regenerated by the model; the graph has no edge to doc-42,
    # but the context-taint ledger does.
    assert_taint_free(step, "send_email", trusted_literals={"ops@corp.example"})


if __name__ == "__main__":
    _demo()
