# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-when-a-tool-result-provenance-edge-is-laundered-through-a-summarization-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-when-a-tool-result-provenance-edge-is-laundered-through-a-summarization-hop.warrant.json
# Markdown SHA-256:   cf8bb268a3f75743e562df7838a7660de9a1f1b8bcaf6c18aad6aa6f76f34329
# Code AST SHA-256:   1c4e3a3007cba5349d1cd106ab1b89a3a4acfcf86413ec16857b07d086b025be
# Verified Classes:   TaintError, Label, Node, ProvenanceGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum


class TaintError(RuntimeError):
    """Raised when a provenance edge would launder taint without declassification."""


class Label(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"


@dataclass
class Node:
    node_id: str
    label: Label
    origin: str
    ancestors: set[str] = field(default_factory=set)


class ProvenanceGraph:
    def __init__(self) -> None:
        self._nodes: dict[str, Node] = {}
        self._edges: list[tuple[str, str, str]] = []  # (src, dst, kind)

    def ingest_tool_result(self, node_id: str, origin: str) -> Node:
        node = Node(node_id, Label.UNTRUSTED, origin, ancestors={node_id})
        self._nodes[node_id] = node
        return node

    def derive(self, src_id: str, dst_id: str, kind: str, *, model_generated: bool,
               context_contains_src: bool, declassified: bool = False) -> Node:
        src = self._nodes[src_id]
        # A model-generated hop that saw the source inherits taint by derivation,
        # regardless of whether the byte string still matches the payload.
        if model_generated and context_contains_src:
            inherited = src.label
            anc = set(src.ancestors) | {dst_id}
        elif not model_generated:
            inherited = src.label
            anc = set(src.ancestors) | {dst_id}
        else:
            # Model hop with proven-disjoint context: only then may it be clean.
            inherited = Label.TRUSTED
            anc = {dst_id}

        if src.label is Label.UNTRUSTED and inherited is Label.TRUSTED and not declassified:
            raise TaintError(
                f"edge {src_id}->{dst_id} ({kind}) would drop UNTRUSTED taint "
                f"without an explicit declassification record"
            )
        node = Node(dst_id, inherited, f"derived:{kind}", ancestors=anc)
        self._nodes[dst_id] = node
        self._edges.append((src_id, dst_id, kind))
        return node

    def gate_side_effect(self, arg_node_id: str, tool: str) -> None:
        node = self._nodes[arg_node_id]
        if node.label is Label.UNTRUSTED:
            raise TaintError(
                f"blocked side-effecting call {tool!r}: argument {arg_node_id} "
                f"is tainted via ancestors {sorted(node.ancestors)}"
            )


# Reproduction of the observed laundering trace.
g = ProvenanceGraph()
g.ingest_tool_result("R1", "tool:fetch_url")                      # UNTRUSTED
# Summarizer hop: model-generated, context contained R1 -> must inherit taint.
g.derive("R1", "S1", "summarize", model_generated=True, context_contains_src=True)
# Attempting to treat the summary as clean would now raise:
try:
    g.derive("S1", "S2", "reformat", model_generated=True,
             context_contains_src=True, declassified=False)
    # S2 stays UNTRUSTED; the outbound gate below is what actually fires.
    g.gate_side_effect("S2", "send_email")
except TaintError as exc:
    print("GUARDRAIL:", exc)
