# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-quarantine-a-tainted-provenance-label-when-a-retrieved-document-launders-it-through-a-tool-call-round-trip.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-quarantine-a-tainted-provenance-label-when-a-retrieved-document-launders-it-through-a-tool-call-round-trip.warrant.json
# Markdown SHA-256:   1348f5c37f52e20ce2ac8fb53cb46c7b30d0b1ed0e648c12bfe84784d0dddf7d
# Code AST SHA-256:   13d5740ba3f643cc973eff061555375aeb4d9b7a7877e13647489834e51827f8
# Verified Classes:   TrustTier, Label, TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TrustTier(IntEnum):
    UNTRUSTED = 0
    TOOL_INTERNAL = 1
    PEER_AGENT = 2
    FIRST_PARTY = 3


@dataclass(frozen=True)
class Label:
    tier: TrustTier
    origin: str


class TaintLaunderingError(RuntimeError):
    """Raised when a derivation would raise trust above its inputs' meet."""


def meet(labels: Iterable[Label]) -> Label:
    """The sound label for derived content: no more trusted than any input."""
    labels = list(labels)
    if not labels:
        # No attributable inputs -> fail closed.
        return Label(TrustTier.UNTRUSTED, "unattributed")
    lowest = min(labels, key=lambda l: l.tier)
    origins = "+".join(sorted({l.origin for l in labels}))
    return Label(lowest.tier, f"derived[{origins}]")


def derive(
    inputs: list[Label],
    producer: Label,
    implicit_context_read: bool,
) -> Label:
    """Compute the label for content produced from `inputs` by `producer`."""
    if implicit_context_read:
        # Cannot enumerate the true input set; the meet is uncomputable.
        # Fail closed rather than inherit the producer's tier.
        return Label(TrustTier.UNTRUSTED, f"opaque[{producer.origin}]")

    joined = meet(inputs + [producer])

    # Invariant: derivation may lower trust, never raise it.
    if joined.tier > producer.tier:
        raise TaintLaunderingError(
            f"derivation from {producer.origin} produced tier "
            f"{joined.tier.name} above producer tier {producer.tier.name}"
        )
    return joined


def scratchpad_write(
    stored_inputs: list[Label],
    producer: Label,
    implicit_context_read: bool = False,
) -> Label:
    """A scratchpad slot's label is the running meet over all writes."""
    slot_label = derive(stored_inputs, producer, implicit_context_read)
    # Slot accumulates taint monotonically across turns; caller must persist
    # this and meet it with future writes, not overwrite it.
    return slot_label


def may_drive_tool_selection(label: Label) -> bool:
    return label.tier >= TrustTier.TOOL_INTERNAL


# Reproduction of the observed trace under the enforced meet.
web_doc = Label(TrustTier.UNTRUSTED, "web:idx-4471")
scratchpad = Label(TrustTier.TOOL_INTERNAL, "scratchpad:slot-9")

slot = scratchpad_write([web_doc], scratchpad)
assert slot.tier == TrustTier.UNTRUSTED  # taint survived the round-trip

if may_drive_tool_selection(slot):
    raise TaintLaunderingError("laundered taint reached tool selection")
# else: action item is routed to human approval with provenance attached.
