# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-survives-tool-call-graph-re-entry-but-not-label-preserving-transforms.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-survives-tool-call-graph-re-entry-but-not-label-preserving-transforms.warrant.json
# Markdown SHA-256:   2f62a752718fb0197a0dbf941f3538f43aba9095db1e6034d7a3124ea957e637
# Code AST SHA-256:   25d35e6f9e87bef2837e609cbb400679530c101a941f2136a1f80540a8598d36
# Verified Classes:   TaintLaunderingError, EdgeKind, Node, Edge
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Set


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink is reachable from a tainted ancestor
    only through model-mediated (generation) edges, so the sink's direct
    taint label is empty but the value is not provably clean."""


class EdgeKind(Enum):
    FORWARD = "forward"   # deterministic passthrough; label is preserved
    GENERATE = "generate" # model-mediated; label may be laundered


@dataclass
class Node:
    name: str
    tainted: bool = False          # direct label as computed by the engine
    ancestors_tainted: Set[str] = field(default_factory=set)


@dataclass
class Edge:
    src: str
    dst: str
    kind: EdgeKind


def compute_ancestor_taint(nodes: Dict[str, Node], edges: List[Edge]) -> None:
    """Propagate taint reachability across ALL edges (forward + generate),
    recording which tainted ancestors are reachable and via what edge kinds."""
    changed = True
    while changed:
        changed = False
        for e in edges:
            src, dst = nodes[e.src], nodes[e.dst]
            incoming = set(src.ancestors_tainted)
            if src.tainted:
                incoming.add(src.name)
            if not incoming.issubset(dst.ancestors_tainted):
                dst.ancestors_tainted |= incoming
                changed = True


def paths_are_forward_only(
    nodes: Dict[str, Node], edges: List[Edge], source: str, sink: str
) -> bool:
    """True iff every path from source to sink uses only FORWARD edges.
    Conservative: any GENERATE edge on any path makes it False."""
    adj: Dict[str, List[Edge]] = {}
    for e in edges:
        adj.setdefault(e.src, []).append(e)

    # DFS tracking whether we have crossed a generation edge.
    stack = [(source, False)]
    seen = set()
    while stack:
        cur, crossed_gen = stack.pop()
        if cur == sink:
            if crossed_gen:
                return False
            continue
        state = (cur, crossed_gen)
        if state in seen:
            continue
        seen.add(state)
        for e in adj.get(cur, []):
            stack.append((e.dst, crossed_gen or e.kind is EdgeKind.GENERATE))
    return True


def admit_privileged_action(
    nodes: Dict[str, Node], edges: List[Edge], sink: str
) -> None:
    """Gate a privileged sink. Direct clean label is NOT sufficient when a
    tainted ancestor is reachable only through generation edges."""
    compute_ancestor_taint(nodes, edges)
    sink_node = nodes[sink]

    if sink_node.tainted:
        raise TaintLaunderingError(
            f"sink {sink!r} carries a direct taint label; action blocked"
        )

    for anc in sink_node.ancestors_tainted:
        if not paths_are_forward_only(nodes, edges, anc, sink):
            raise TaintLaunderingError(
                f"sink {sink!r} has empty direct label but tainted ancestor "
                f"{anc!r} reachable only via a model-mediated edge; "
                f"value is unverified (laundering window open)"
            )
    # All tainted ancestors reach the sink via forwarding-only paths:
    # direct label is authoritative, admission is sound.
    return None
