# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-a-re-summarization-hop-in-tool-output-provenance-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-a-re-summarization-hop-in-tool-output-provenance-graphs.warrant.json
# Markdown SHA-256:   4111730fccb837f0a8f1cb5ec3e381a607f6c115b72eb396836ed225a477ac5e
# Code AST SHA-256:   664abb5934daf2a5167c2c4b44f4c0d4ee4f328b37821706e36587a0bf6b0caa
# Verified Classes:   Taint, TaintLaunderingError, Node, ProvenanceGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum


class Taint(IntEnum):
    TRUSTED = 0
    DERIVED = 1
    UNTRUSTED = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a sink argument's label is clean but its ancestry closure is not."""


@dataclass
class Node:
    node_id: str
    taint: Taint
    produced_by: str            # tool name or "model"
    context_nodes: list[str] = field(default_factory=list)
    tokens: set[str] = field(default_factory=set)


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

    def add(self, node: Node) -> None:
        # Monotone closure: a model-authored hop inherits the union of its
        # context taints and may never lower it.
        if node.produced_by == "model":
            inherited = max(
                (self.nodes[c].taint for c in node.context_nodes if c in self.nodes),
                default=Taint.TRUSTED,
            )
            node.taint = max(node.taint, inherited)
        self.nodes[node.node_id] = node

    def closure(self, node_id: str) -> Taint:
        seen: set[str] = set()
        stack = [node_id]
        worst = Taint.TRUSTED
        while stack:
            nid = stack.pop()
            if nid in seen or nid not in self.nodes:
                continue
            seen.add(nid)
            n = self.nodes[nid]
            worst = max(worst, n.taint)
            stack.extend(n.context_nodes)
        return worst

    def trusted_tokens(self) -> set[str]:
        out: set[str] = set()
        for n in self.nodes.values():
            if self.closure(n.node_id) == Taint.TRUSTED:
                out |= n.tokens
        return out


def enforce_sink(graph: ProvenanceGraph, arg_node_id: str, sink: str) -> None:
    declared = graph.nodes[arg_node_id].taint
    closure = graph.closure(arg_node_id)
    if declared < closure:
        raise TaintLaunderingError(
            f"sink={sink} arg={arg_node_id} declared={declared.name} "
            f"closure={closure.name}: label was lowered across a transform hop"
        )
    novel = graph.nodes[arg_node_id].tokens - graph.trusted_tokens()
    if closure >= Taint.UNTRUSTED and novel:
        raise TaintLaunderingError(
            f"sink={sink} arg={arg_node_id}: untrusted-ancestry tokens "
            f"novel to trusted lineage: {sorted(novel)[:5]}"
        )
