# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-via-re-summarization-in-a-taint-aware-tool-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-via-re-summarization-in-a-taint-aware-tool-sandbox.warrant.json
# Markdown SHA-256:   c8a1ba06042ebf98cefecb42e377ab965ef04a9112a2e3e4d8be9504bb93920c
# Code AST SHA-256:   e4903d62a2416fd413bfd90a3da0c8f23dc2ba4e226f1c6151a17096f7417e7f
# Verified Classes:   Taint, TaintLaunderingError, Artifact, Node
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import IntEnum
from typing import Iterable


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

    @staticmethod
    def join(levels: Iterable["Taint"]) -> "Taint":
        return max(levels, default=Taint.TRUSTED)


class TaintLaunderingError(RuntimeError):
    """Raised when a transformation node lowers taint below the join of its inputs."""


@dataclass(frozen=True)
class Artifact:
    payload: str
    taint: Taint


@dataclass(frozen=True)
class Node:
    name: str
    # declared output taint if the node ignores input taint (the bug pattern)
    declared_out: Taint

    def apply(self, inputs: list[Artifact]) -> Artifact:
        joined = Taint.join(a.taint for a in inputs)
        out = Artifact(payload="<transformed>", taint=self.declared_out)
        if out.taint < joined:
            raise TaintLaunderingError(
                f"node={self.name!r} lowered taint: in_join={joined.name} "
                f"out={out.taint.name}; artifact must remain quarantined"
            )
        return out


def guarded_apply(node: Node, inputs: list[Artifact]) -> Artifact:
    """Enforce taint closure on every edge of the transformation graph."""
    return node.apply(inputs)


# Reproduces the incident: a TRUSTED-class summarizer fed an UNTRUSTED body.
if __name__ == "__main__":
    body = Artifact(payload="external page", taint=Taint.UNTRUSTED)
    summarizer = Node(name="summarize", declared_out=Taint.TRUSTED)
    try:
        guarded_apply(summarizer, [body])
    except TaintLaunderingError as exc:
        print(f"FAULT: {exc}")
        # Correct behavior: keep artifact quarantined, do not persist, do not dispatch.
