# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-on-the-second-tool-hop-and-why-does-provenance-graph-depth-hide-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-on-the-second-tool-hop-and-why-does-provenance-graph-depth-hide-it.warrant.json
# Markdown SHA-256:   3631f5314836f544009974076ca6647bb2ad8e81a71c35a30fc4f29966c31f6c
# Code AST SHA-256:   b5055701863315c15e441e20ee2ce4ee72aa2b608504bd069c1b914634a4caae
# Verified Classes:   Taint, TaintLaunderingError, ProvenanceNode, ToolOutput, ProvenanceResolver
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class Taint(Enum):
    CLEAN = 0
    UNTRUSTED = 1


class TaintLaunderingError(RuntimeError):
    """Raised when a side-effecting sink receives data whose taint label
    was lost across an intermediate re-serialization hop."""


@dataclass
class ProvenanceNode:
    node_id: str
    tool: str
    taint_union: Taint
    parents: list[str] = field(default_factory=list)


@dataclass
class ToolOutput:
    payload: dict
    taint: Optional[Taint]  # None means "label absent after re-serialization"


SIDE_EFFECTING_SINKS = {"write_file", "exec", "http_post", "send_email"}


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

    def record(self, node: ProvenanceNode) -> None:
        self.nodes[node.node_id] = node

    def resolve(self, node_id: str) -> Taint:
        node = self.nodes.get(node_id)
        if node is None:
            raise TaintLaunderingError(
                f"provenance node {node_id!r} missing from graph; "
                f"cannot establish taint lineage"
            )
        return node.taint_union

    def enforce_sink(self, node_id: str, sink_tool: str) -> Taint:
        if sink_tool not in SIDE_EFFECTING_SINKS:
            return self.resolve(node_id)

        node = self.nodes[node_id]
        # Fail closed: absent label on a side-effecting sink is treated as
        # a laundering boundary, not as clean.
        if node.taint_union is None:
            raise TaintLaunderingError(
                f"side-effecting sink {sink_tool!r} reached via node {node_id!r} "
                f"with absent taint label; intermediate hop laundered provenance"
            )
        # Monotonicity check: every parent must be present and its taint
        # must be a subset of this node's taint_union.
        for parent_id in node.parents:
            parent = self.nodes.get(parent_id)
            if parent is None:
                raise TaintLaunderingError(
                    f"node {node_id!r} references missing parent {parent_id!r}; "
                    f"provenance graph is discontinuous"
                )
            if parent.taint_union == Taint.UNTRUSTED and node.taint_union != Taint.UNTRUSTED:
                raise TaintLaunderingError(
                    f"taint non-monotonicity: parent {parent_id!r} is UNTRUSTED "
                    f"but child {node_id!r} is {node.taint_union.name}; "
                    f"label dropped across re-serialization"
                )
        return node.taint_union

    def emit_intermediate(
        self, node_id: str, tool: str, parents: list[str], raw: ToolOutput
    ) -> ProvenanceNode:
        # Re-attach inherited taint on every intermediate emission. The
        # serializer must not be allowed to drop this field.
        inherited = Taint.CLEAN
        for parent_id in parents:
            parent = self.nodes.get(parent_id)
            if parent is None:
                raise TaintLaunderingError(
                    f"cannot emit {node_id!r}: parent {parent_id!r} not in graph"
                )
            if parent.taint_union == Taint.UNTRUSTED:
                inherited = Taint.UNTRUSTED
        node = ProvenanceNode(
            node_id=node_id, tool=tool, taint_union=inherited, parents=list(parents)
        )
        self.record(node)
        return node


def run_three_hop_chain() -> None:
    r = ProvenanceResolver()
    r.record(ProvenanceNode("h1", "fetch_url", Taint.UNTRUSTED, parents=[]))

    # Intermediate summarizer emits without taint field (the laundering hop).
    r.emit_intermediate(
        "h2", "summarize", parents=["h1"],
        raw=ToolOutput(payload={"summary": "SSH key management overview."}, taint=None),
    )

    # Downstream side-effecting sink. Must fail closed.
    r.enforce_sink("h2", "write_file")


if __name__ == "__main__":
    try:
        run_three_hop_chain()
    except TaintLaunderingError as exc:
        print(f"blocked: {exc}")
