# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-tool-call-boundary-in-taint-aware-agent-sandboxes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-tool-call-boundary-in-taint-aware-agent-sandboxes.warrant.json
# Markdown SHA-256:   21bc9f5660be5dafbd622008d425288f43c3b9aacefddceec666dab7faf3263b
# Code AST SHA-256:   5be8be568f5898f703e46ce06d41ef626660df5f7cf0f3461c4c72653c2e1c38
# Verified Classes:   TaintLaunderingError, ProvenanceNode, TaintGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class TaintLaunderingError(RuntimeError):
    """Raised when a sink receives an argument whose ancestor closure
    contains untrusted provenance despite a trusted direct tag."""
    pass

@dataclass
class ProvenanceNode:
    node_id: str
    tag: str                      # "trusted" | "untrusted:<source>"
    ancestors: set[str] = field(default_factory=set)

class TaintGraph:
    def __init__(self) -> None:
        self.nodes: dict[str, ProvenanceNode] = {}

    def add(self, node_id: str, tag: str, ancestors: set[str]) -> ProvenanceNode:
        # Monotonic join: output tag must be >= join of ancestor tags.
        joined = tag
        for a in ancestors:
            anc = self.nodes.get(a)
            if anc and anc.tag.startswith("untrusted"):
                joined = anc.tag
        node = ProvenanceNode(node_id, joined, set(ancestors))
        self.nodes[node_id] = node
        return node

    def ancestor_closure(self, node_id: str) -> set[str]:
        seen: set[str] = set()
        stack = [node_id]
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            n = self.nodes.get(cur)
            if n:
                stack.extend(n.ancestors)
        return seen

    def check_sink(self, node_id: str) -> None:
        node = self.nodes.get(node_id)
        if node is None:
            raise TaintLaunderingError(f"unknown provenance node {node_id!r}")
        closure = self.ancestor_closure(node_id)
        for anc_id in closure:
            anc = self.nodes[anc_id]
            if anc.tag.startswith("untrusted") and node.tag == "trusted":
                # Structural laundering signal: trusted output, untrusted ancestor.
                raise TaintLaunderingError(
                    f"taint laundering at {node_id!r}: direct tag=trusted "
                    f"but ancestor {anc_id!r} carries {anc.tag!r}"
                )

# Failure trace reproduction
g = TaintGraph()
g.add("fetch_1", "untrusted:web", set())
# summarize is an LLM transform; runtime incorrectly emits trusted.
g.add("summarize_1", "trusted", {"fetch_1"})
try:
    g.check_sink("summarize_1")   # must raise before write_file
except TaintLaunderingError as e:
    print("BLOCKED:", e)
