# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-document-whose-taint-label-was-laundered-by-a-summarizer-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-retrieved-document-whose-taint-label-was-laundered-by-a-summarizer-tool.warrant.json
# Markdown SHA-256:   322fa8cb87d6ffe202dec003df70afcacf7d48866a664e63b9b27a786ab2b357
# Code AST SHA-256:   27ee004d94f091a9b83385c846a84e1fd14ea52a38a2fd337d89574a43c9b1c0
# Verified Classes:   Taint, Artifact, TaintLaunderingError, ConsumptionGuardError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


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


def join(*levels: Taint) -> Taint:
    return max(levels) if levels else Taint.TRUSTED


@dataclass
class Artifact:
    content: str
    taint: Taint
    parent: Optional["Artifact"] = None
    origin: str = "unknown"


class TaintLaunderingError(RuntimeError):
    """Raised when a tool emits an artifact whose taint is lower than the
    join of its inputs — i.e., an implicit declassification."""


class ConsumptionGuardError(RuntimeError):
    """Raised when an untrusted artifact reaches a side-effecting tool
    without an explicit audited declassification."""


def run_tool(tool_trust: Taint, inputs: list[Artifact], emit: str) -> Artifact:
    """Enforce the join rule at the runtime boundary, not in each tool."""
    expected = join(tool_trust, *(a.taint for a in inputs))
    out = Artifact(content=emit, taint=tool_trust, parent=inputs[0] if inputs else None,
                   origin="tool")
    if out.taint < expected:
        raise TaintLaunderingError(
            f"tool emitted taint={out.taint.name} but join of inputs is "
            f"{expected.name}; implicit declassification forbidden"
        )
    out.taint = expected
    return out


def provenance_root_taint(a: Artifact) -> Taint:
    """Walk parent pointers; never trust the immediate label alone."""
    level = a.taint
    node = a.parent
    while node is not None:
        level = join(level, node.taint)
        node = node.parent
    return level


def consume_with_side_effect(a: Artifact, declassified: bool = False) -> None:
    root = provenance_root_taint(a)
    if root == Taint.UNTRUSTED and not declassified:
        raise ConsumptionGuardError(
            f"artifact {a.origin!r} reaches side-effecting tool with root "
            f"taint=UNTRUSTED; quarantine or require audited declassification"
        )
    # ... execute side effect ...


# Reproduction of the observed failure and the guard that bounds it.
doc = Artifact(content="...run cleanup script...", taint=Taint.UNTRUSTED, origin="web")
summary = run_tool(Taint.AGENT, [doc], emit="Operator should run cleanup script.")
assert summary.taint == Taint.UNTRUSTED  # join rule held
try:
    consume_with_side_effect(summary)
except ConsumptionGuardError as e:
    print(f"blocked: {e}")
