# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-retrieved-document-after-it-has-already-been-summarized-into-working-memory-the-taint-laundering-bound.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-retrieved-document-after-it-has-already-been-summarized-into-working-memory-the-taint-laundering-bound.warrant.json
# Markdown SHA-256:   8b0f048ec18f1b212cf2fc6bd0e1bb4607a04d9f7d5329f91c122f0585e81b67
# Code AST SHA-256:   3d90d993b222c934dc95f780a1e81f5cc7d51d08759bc0aafd02675ddcaae36a
# Verified Classes:   TaintLaunderingError, Node, ProvenanceDAG
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Trust = Literal["untrusted:web", "trusted:user", "trusted:internal_db", "trusted:self"]
_TRUST_ORDER = ["untrusted:web", "trusted:user", "trusted:internal_db", "trusted:self"]


class TaintLaunderingError(RuntimeError):
    """Raised when an action consumes a fact whose inherited provenance is
    below the action's required integrity level, i.e. taint was laundered
    through a model-mediated derivation (summarization) step."""


def min_trust(a: Trust, b: Trust) -> Trust:
    return _TRUST_ORDER[min(_TRUST_ORDER.index(a), _TRUST_ORDER.index(b))]


@dataclass
class Node:
    node_id: str
    trust: Trust
    inputs: list[str] = field(default_factory=list)


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

    def add_source(self, node_id: str, trust: Trust) -> None:
        self._nodes[node_id] = Node(node_id, trust)

    def add_derived(self, node_id: str, inputs: list[str]) -> None:
        # Provenance is computed by the runtime as the min-trust join over
        # inputs. The model's self-reported "source" string is ignored.
        if not inputs:
            raise TaintLaunderingError(
                f"derived node {node_id!r} has no recorded inputs; "
                "provenance cannot be computed and defaults are unsafe"
            )
        inherited = _TRUST_ORDER[-1]
        for i in inputs:
            if i not in self._nodes:
                raise TaintLaunderingError(
                    f"input {i!r} of {node_id!r} missing from DAG; "
                    "checkpoint may have dropped a derivation edge"
                )
            inherited = min_trust(inherited, self._nodes[i].trust)
        self._nodes[node_id] = Node(node_id, inherited, inputs)

    def provenance(self, node_id: str) -> Trust:
        if node_id not in self._nodes:
            raise TaintLaunderingError(
                f"no provenance record for {node_id!r}; refusing to assume trusted"
            )
        return self._nodes[node_id].trust

    def gate_action(self, action: str, consumed: list[str], required: Trust) -> None:
        for f in consumed:
            prov = self.provenance(f)
            if _TRUST_ORDER.index(prov) < _TRUST_ORDER.index(required):
                raise TaintLaunderingError(
                    f"action {action!r} requires {required!r} but fact {f!r} "
                    f"inherits {prov!r} via derivation; taint laundered through "
                    "summarization—re-retrieve from a trusted source or downgrade "
                    "to a human-confirmed proposal"
                )


# Reproduction of the observed failure and its guardrail.
dag = ProvenanceDAG()
dag.add_source("web_doc_1", "untrusted:web")
dag.add_derived("summary_1", ["web_doc_1"])          # summarize sub-call
dag.add_derived("summary_2", ["summary_1", "user_tier"])  # multi-hop; user_tier added below
dag.add_source("user_tier", "trusted:user")

print(dag.provenance("summary_1"))  # untrusted:web — laundering caught
dag.gate_action("issue_refund", ["summary_1"], "trusted:user")  # raises
