# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-tainted-memory-writes-rather-than-sanitize-them-in-place-the-taint-laundering-boundary-in-pro.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-provenance-tainted-memory-writes-rather-than-sanitize-them-in-place-the-taint-laundering-boundary-in-pro.warrant.json
# Markdown SHA-256:   176092166b1f0bb12fe6dafbe86a9ee5e7635e21e5ae987d3d70a5807c29b631
# Code AST SHA-256:   5ae080f9d8d9b64cd29162da322db829689fcbd83dac628220d235ba381e9fe6
# Verified Classes:   TaintLaunderingError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

TrustLabel = Literal["trusted:user", "trusted:reviewed", "untrusted:derived", "untrusted:web", "untrusted:tool"]

_TRUST_RANK = {
    "untrusted:web": 0,
    "untrusted:tool": 1,
    "untrusted:derived": 2,
    "trusted:reviewed": 3,
    "trusted:user": 4,
}


class TaintLaunderingError(RuntimeError):
    """Raised when a transformation attempts to raise a span's trust floor."""


@dataclass
class Span:
    span_id: str
    content: str
    label: TrustLabel
    derived_from: list[str] = field(default_factory=list)


def trust_floor(inputs: list[Span]) -> TrustLabel:
    if not inputs:
        raise TaintLaunderingError("cannot compute trust floor over empty input set")
    return min((s.label for s in inputs), key=lambda l: _TRUST_RANK[l])


def transform(inputs: list[Span], output_content: str, output_id: str,
              proposed_label: TrustLabel) -> Span:
    """Apply a lossy transformation while preserving the taint floor.

    The proposed label may only *demote* relative to the floor. Any attempt
    to promote (e.g. labeling summarizer output 'trusted:derived' when its
    inputs were 'untrusted:web') is rejected as laundering.
    """
    floor = trust_floor(inputs)
    if _TRUST_RANK[proposed_label] > _TRUST_RANK[floor]:
        raise TaintLaunderingError(
            f"span {output_id}: proposed label {proposed_label!r} exceeds "
            f"trust floor {floor!r} derived from {[s.span_id for s in inputs]}"
        )
    return Span(
        span_id=output_id,
        content=output_content,
        label=proposed_label,
        derived_from=[s.span_id for s in inputs],
    )


def write_memory(span: Span, tier: Literal["trusted", "quarantine"]) -> None:
    if tier == "trusted" and span.label.startswith("untrusted:"):
        raise TaintLaunderingError(
            f"span {span.span_id} ({span.label}) may not enter trusted tier; "
            f"route to quarantine or obtain a signed review event"
        )
    # persist span with lineage intact; retriever must check trust_floor at cold start
