# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-tool-result-before-it-re-enters-the-reasoning-loop-label-laundering-across-the-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-tool-result-before-it-re-enters-the-reasoning-loop-label-laundering-across-the-tool-boundary.warrant.json
# Markdown SHA-256:   ef5a3610f89400ea088a357bf8aa57c394d109e10a410f6c21d731923889f22b
# Code AST SHA-256:   f846fbd99ae3c1ab47edbbe1acccb18784eed4ffad936a0fc71e6ec550197bf6
# Verified Classes:   TaintLabel, EffectClass, TaintLaunderingError, ContextItem, ToolResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class TaintLabel(str, Enum):
    TRUSTED_INTERNAL = "TRUSTED:internal"
    UNTRUSTED_WEB = "UNTRUSTED:web"
    UNTRUSTED_DERIVED = "UNTRUSTED:derived"


class EffectClass(str, Enum):
    READ_ONLY = "read_only"
    MUTATING = "mutating"
    EXFILTRATING = "exfiltrating"


class TaintLaunderingError(RuntimeError):
    """Raised when a tool result's taint set omits an inherited untrusted label,
    or when a tainted result is routed into a mutating/exfiltrating sink."""


@dataclass(frozen=True)
class ContextItem:
    label: FrozenSet[TaintLabel]
    content: str


@dataclass
class ToolResult:
    content: str
    declared_trust: TaintLabel
    inherited_taint: FrozenSet[TaintLabel] = field(default_factory=frozenset)

    @property
    def effective_taint(self) -> FrozenSet[TaintLabel]:
        return self.inherited_taint | {self.declared_trust}


def propagate_taint(context_items: list[ContextItem],
                    declared_trust: TaintLabel) -> FrozenSet[TaintLabel]:
    """Union rule: a tool result inherits the taint of every context item
    present at the reasoning step that emitted the call. No span matching."""
    inherited: set[TaintLabel] = set()
    for item in context_items:
        inherited |= item.label
    return frozenset(inherited) | {declared_trust}


def admit_tool_result(result: ToolResult,
                      sink_effect: EffectClass,
                      clearing_edge_available: bool) -> TaintLabel:
    taint = result.effective_taint
    untrusted = {l for l in taint if l.value.startswith("UNTRUSTED")}

    if not untrusted:
        return TaintLabel.TRUSTED_INTERNAL

    if sink_effect in (EffectClass.MUTATING, EffectClass.EXFILTRATING):
        if not clearing_edge_available:
            raise TaintLaunderingError(
                f"quarantine required: taint={sorted(l.value for l in untrusted)} "
                f"sink={sink_effect.value} and no out-of-band clearing edge exists"
            )
        return TaintLabel.TRUSTED_INTERNAL

    # Read-only sink: downgrade, do not quarantine.
    return TaintLabel.UNTRUSTED_DERIVED


def run_step(context: list[ContextItem], tool_trust: TaintLabel,
             sink_effect: EffectClass, clearing_edge: bool) -> TaintLabel:
    result = ToolResult(
        content="<tool output>",
        declared_trust=tool_trust,
        inherited_taint=propagate_taint(context, tool_trust) - {tool_trust},
    )
    return admit_tool_result(result, sink_effect, clearing_edge)


# The observed failure, replayed under the union rule:
web_read = ContextItem(label=frozenset({TaintLabel.UNTRUSTED_WEB}),
                       content="...injected instruction...")
# Model paraphrased the injected instruction; argument string is clean.
# Span matching would see no taint; the union rule still sees the web read.
try:
    run_step(
        context=[web_read],
        tool_trust=TaintLabel.TRUSTED_INTERNAL,   # lookup_contact's static class
        sink_effect=EffectClass.EXFILTRATING,     # send_email
        clearing_edge=False,
    )
except TaintLaunderingError as e:
    print("blocked:", e)
