# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-quarantines-a-poisoned-tool-result-but-the-taint-label-fails-to-propagate-across-a-summarization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-quarantines-a-poisoned-tool-result-but-the-taint-label-fails-to-propagate-across-a-summarization-boundary.warrant.json
# Markdown SHA-256:   116a184e8421bf8926137e66058cddebe14581b75af6e88d249fded24382ad15
# Code AST SHA-256:   e57308112f34a8b70151f8901542c77794b0c8eb782092af38c143ae8e891b10
# Verified Classes:   Taint, TaintLaunderingError, Artifact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Any, Callable


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

    @classmethod
    def join(cls, *labels: "Taint") -> "Taint":
        return cls(max(labels)) if labels else cls.TRUSTED


class TaintLaunderingError(RuntimeError):
    """Raised when a transform emits under its own producer identity
    instead of inheriting the join of its input taints."""


@dataclass
class Artifact:
    value: Any
    taint: Taint
    lineage: tuple[str, ...] = field(default_factory=tuple)


def transform(
    fn: Callable[[Any], Any],
    inputs: list[Artifact],
    producer_id: str,
    *,
    declassify: bool = False,
    declassify_reason: str | None = None,
) -> Artifact:
    joined = Taint.join(*(a.taint for a in inputs))
    raw = fn(*(a.value for a in inputs))

    if declassify:
        if not declassify_reason:
            raise TaintLaunderingError(
                f"transform {producer_id!r} attempted declassification without reason"
            )
        out_taint = Taint.TRUSTED
    else:
        out_taint = joined

    # The invariant: a trusted producer does not sanitize untrusted input.
    # If inputs were untrusted and the output claims TRUSTED without an
    # explicit declassification, the label was laundered.
    if joined is Taint.UNTRUSTED and out_taint is Taint.TRUSTED and not declassify:
        raise TaintLaunderingError(
            f"transform {producer_id!r} emitted TRUSTED from UNTRUSTED input "
            f"without declassification; taint laundering detected"
        )

    lineage = tuple(f"{a.lineage[-1] if a.lineage else 'root'}" for a in inputs)
    return Artifact(value=raw, taint=out_taint, lineage=lineage + (producer_id,))


def privileged_action(art: Artifact, action: Callable[[Any], None]) -> None:
    if art.taint is Taint.UNTRUSTED:
        raise TaintLaunderingError(
            f"refusing privileged action on UNTRUSTED artifact from {art.lineage}"
        )
    action(art.value)


# --- Failure trace reproduced ---
raw = Artifact(value="<html>...ACTION: rotate_api_key...</html>", taint=Taint.UNTRUSTED, lineage=("fetch",))

# Naive sandbox: summarizer is a trusted tool, so output defaults to TRUSTED.
# This is the bug. The correct call joins input taint:
summary = transform(lambda s: "ACTION: rotate_api_key", [raw], producer_id="summarize")
assert summary.taint is Taint.UNTRUSTED, "summarizer must carry input taint"

# Downstream privileged action now correctly refuses:
try:
    privileged_action(summary, lambda v: print("executing", v))
except TaintLaunderingError as e:
    print("blocked:", e)

# The only legitimate path to TRUSTED is an audited declassification
# whose validator rejects arbitrary content:
def strict_allowlist(s: str) -> str:
    if s not in {"safe_value"}:
        raise TaintLaunderingError(f"declassification validator rejected {s!r}")
    return s

try:
    transform(strict_allowlist, [raw], producer_id="extract_field",
              declassify=True, declassify_reason="strict allowlist, value re-derived")
except TaintLaunderingError as e:
    print("declassification rejected:", e)
