# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-instructions-across-a-tool-output-chain-and-the-taint-label-decays-at-the-second-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-instructions-across-a-tool-output-chain-and-the-taint-label-decays-at-the-second-hop.warrant.json
# Markdown SHA-256:   9ea0a8ea3f2d61769cc8ab31187ca002ff84fa6d399de16d8a2a1bca7d76beae
# Code AST SHA-256:   b3061d374ad2cf1527e50fdaddc595c98c2018e7d00ad799d565f8b3b6527814
# Verified Classes:   TaintLaunderingError, Value, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class TaintLaunderingError(RuntimeError):
    """Raised when a derived value re-enters context without inheriting source taint."""

# Tools whose output cannot carry free-form imperative text. Membership is a
# reviewed security decision with an output-schema argument, never a default.
SANITIZERS: frozenset[str] = frozenset({"hash_sha256", "count_tokens", "parse_json_enum"})

SINKS: frozenset[str] = frozenset({"send_email", "http_post", "write_file", "execute_sql"})

@dataclass(frozen=True)
class Value:
    text: str
    taint: frozenset[str] = field(default_factory=frozenset)  # provenance span ids

@dataclass
class ToolCall:
    tool: str
    args: dict[str, Value]

def propagate(call: ToolCall, output_text: str) -> Value:
    taint_in = frozenset().union(*(v.taint for v in call.args.values()))
    if call.tool in SANITIZERS:
        return Value(output_text, frozenset())          # proven sanitizer
    if taint_in and not output_text_taint_declared(call.tool):
        # Default: derived value inherits source taint. If a wrapper forgot to
        # declare propagation, refuse rather than silently launder.
        raise TaintLaunderingError(
            f"tool {call.tool!r} received tainted args {sorted(taint_in)} "
            f"but did not declare taint propagation on output"
        )
    return Value(output_text, taint_in)

def output_text_taint_declared(tool: str) -> bool:
    # Wrappers must opt in to propagation; absence is a hard error, not a pass.
    return tool in {"summarize", "extract_fields", "translate", "format_as_table"}

def guarded_sink(call: ToolCall, warrant: Iterable[str] | None = None) -> None:
    if call.tool not in SINKS:
        return
    taint_in = frozenset().union(*(v.taint for v in call.args.values()))
    if not taint_in:
        return
    approved = frozenset(warrant or ())
    if not taint_in <= approved:
        raise TaintLaunderingError(
            f"sink {call.tool!r} blocked: args carry taint {sorted(taint_in)} "
            f"not covered by approval warrant {sorted(approved)}"
        )
