# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-taint-labels-across-a-tool-call-boundary-and-when-does-label-laundering-silently-defeat-the-guardrail.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-taint-labels-across-a-tool-call-boundary-and-when-does-label-laundering-silently-defeat-the-guardrail.warrant.json
# Markdown SHA-256:   6547f797763f1821f5ab00a1359afdb38b180d06d79057a6a4a0399c4901448d
# Code AST SHA-256:   09794afecb9c1787dea35f85c3f7297ada917f83842a68ca7073ce325184bdab
# Verified Classes:   TaintLaunderingError, Label, Value
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a value reaches a sink with a label that under-reports its derivation."""
    pass


@dataclass(frozen=True)
class Label:
    sources: FrozenSet[str] = frozenset()

    def join(self, other: "Label") -> "Label":
        return Label(self.sources | other.sources)

    @property
    def clean(self) -> bool:
        return not self.sources


@dataclass
class Value:
    payload: str
    label: Label


# A model call is a derivation node: it consumes the full context label
# and emits that label on every output. It is never a declassifier.
def model_transform(context: list[Value], instruction: str) -> Value:
    context_label = Label()
    for v in context:
        context_label = context_label.join(v.label)
    # The model may paraphrase, extract, or re-emit -- surface form is irrelevant.
    derived = f"<transformed:{instruction[:24]}>"
    return Value(payload=derived, label=context_label)


def sink_send_email(to: str, body: Value, require_clean: bool = True) -> None:
    if require_clean and not body.label.clean:
        raise TaintLaunderingError(
            f"send_email blocked: body derived from {sorted(body.label.sources)}. "
            f"Declassification must be explicit and logged, not implicit in a transform."
        )
    # ... actual send ...


def run_agent_turn(web_text: str, injected_instruction: str) -> None:
    web = Value(payload=web_text, label=Label(frozenset({"T_web"})))
    config = Value(payload="SECRET=...", label=Label(frozenset({"T_local"})))

    # Model reads both the tainted web text and the local config, then summarizes.
    summary = model_transform([web, config], instruction=injected_instruction)

    # Envelope tracking would have labeled `summary` clean because `summarize`
    # is a "trusted" tool. Derivation closure carries T_web | T_local forward.
    if summary.label.clean:
        raise TaintLaunderingError(
            "invariant violated: model transform emitted a clean label from tainted context"
        )

    sink_send_email("ops@corp", body=summary)  # raises TaintLaunderingError
