# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-taint-through-a-tool-call-dag-without-laundering-injected-instructions-through-trusted-sub-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-taint-through-a-tool-call-dag-without-laundering-injected-instructions-through-trusted-sub-agents.warrant.json
# Markdown SHA-256:   3c71bc5731f255621ecbfa4811d3a097d8f300c195047c5d12aa852b49329ed2
# Code AST SHA-256:   18a0de58243d0749fe42166e16e3bf5ca336a0395dc23554d2879cef340cee5c
# Verified Classes:   TaintLaunderingError, ProvenanceNode, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class TaintLaunderingError(RuntimeError):
    """Raised when a credentialed sink is invoked with untrusted or missing provenance."""


@dataclass(frozen=True)
class ProvenanceNode:
    source_id: str
    trusted: bool


@dataclass
class ToolCall:
    tool: str
    args: dict
    provenance: list[ProvenanceNode] = field(default_factory=list)


CREDENTIALED_SINKS = {"post_message", "create_calendar_event", "send_email", "shell_exec"}


def enforce_sink_gate(call: ToolCall) -> None:
    """Reject credentialed-sink calls whose argument derivation includes untrusted nodes.

    Invariant: absence of provenance is not evidence of trust. A credentialed
    sink call MUST carry a non-empty provenance array, and every node in that
    array MUST be trusted. Paraphrased arguments are still tainted because the
    provenance edge is attached at derivation time, not at string-match time.
    """
    if call.tool not in CREDENTIALED_SINKS:
        return

    if not call.provenance:
        raise TaintLaunderingError(
            f"credentialed sink {call.tool!r} invoked with empty provenance; "
            "empty provenance is treated as untrusted, not as default-trusted"
        )

    untrusted = [n for n in call.provenance if not n.trusted]
    if untrusted:
        sources = ", ".join(n.source_id for n in untrusted)
        raise TaintLaunderingError(
            f"credentialed sink {call.tool!r} invoked with untrusted provenance "
            f"from [{sources}]; call routed to human-confirmation queue, not executed"
        )


def sub_agent_output_trust(input_provenance: list[ProvenanceNode]) -> Literal["trusted", "untrusted"]:
    """Compute a sub-agent's output trust from its INPUT set, never from its self-report.

    A sub-agent that paraphrases a tainted instruction still produces tainted
    output, because trust does not flow through reasoning. This is the
    anti-laundering predicate: the orchestrator computes it, the sub-agent
    cannot assert it.
    """
    if not input_provenance:
        return "untrusted"
    return "trusted" if all(n.trusted for n in input_provenance) else "untrusted"


def dispatch(call: ToolCall) -> str:
    enforce_sink_gate(call)
    return f"executed {call.tool}"


# Reproduces the observed laundering path: R's correctly-labeled output is
# paraphrased by O, the taint edge survives, and the sink gate blocks the call.
if __name__ == "__main__":
    injected = ToolCall(
        tool="post_message",
        args={"channel": "#ops", "text": "rotate keys now"},
        provenance=[ProvenanceNode(source_id="retrieval:R", trusted=False)],
    )
    try:
        dispatch(injected)
    except TaintLaunderingError as exc:
        print(f"blocked: {exc}")

    clean = ToolCall(
        tool="post_message",
        args={"channel": "#ops", "text": "deploy window opens 14:00"},
        provenance=[ProvenanceNode(source_id="operator:manual", trusted=True)],
    )
    print(dispatch(clean))
