# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-when-retrieved-context-and-tool-outputs-re-enter-the-prompt.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-when-retrieved-context-and-tool-outputs-re-enter-the-prompt.warrant.json
# Markdown SHA-256:   de347b09c512feea31d23573fb055fe03f9fa0a5bc1c79b4fef2b28af3f31066
# Code AST SHA-256:   e9b451c4e0c8a9fb5bff83e71ea808367753c2adfa6c3758adecc4b9344f5d55
# Verified Classes:   TaintLaunderingError, LabeledValue, ContextWindow
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a sink receives content whose taint was dropped by model re-encoding."""


@dataclass(frozen=True)
class LabeledValue:
    value: str
    taint: FrozenSet[str]


@dataclass
class ContextWindow:
    # Labels currently resident in the model's context. Taint is bounded by
    # residency, not by byte containment.
    resident: FrozenSet[str] = field(default_factory=frozenset)
    _history: list = field(default_factory=list)

    def ingest(self, chunk: LabeledValue) -> None:
        # Ingestion label: what MAY influence the model.
        self.resident = self.resident | chunk.taint
        self._history.append(chunk)

    def emit(self, generated: str) -> LabeledValue:
        # Emission label: every generation inherits the union of labels
        # resident during generation. This is the anti-laundering invariant.
        return LabeledValue(value=generated, taint=self.resident)

    def compact(self, summary: str) -> LabeledValue:
        # Summarization is an emission and MUST NOT drop taint.
        # Label-monotone: the summary inherits the full resident set.
        return self.emit(summary)


def privileged_sink(call_arg: LabeledValue, forbidden: FrozenSet[str]) -> None:
    leaked = call_arg.taint & forbidden
    if leaked:
        raise TaintLaunderingError(
            f"sink refused: argument carries {sorted(leaked)}; "
            f"content was re-encoded through a tainted context window"
        )


def run_agent_turn(window: ContextWindow, retrieved: LabeledValue, model_output: str) -> None:
    window.ingest(retrieved)
    # Model paraphrases the retrieved instruction into a new string.
    # Byte-containment no longer holds; residency-labeling must catch it.
    out = window.emit(model_output)
    privileged_sink(out, forbidden=frozenset({"UNTRUSTED_WEB"}))
