# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-sandboxed-tool-re-enters-the-planner-through-a-summarized-observation-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-sandboxed-tool-re-enters-the-planner-through-a-summarized-observation-channel.warrant.json
# Markdown SHA-256:   c8c99fd2ec8908fb6a0282331868141b3bfc474f4c7b4d2d6351cfe326256a45
# Code AST SHA-256:   767742c76c5265a525d78d12bdd2891e5c258a762517def3fc6ef221a454744e
# Verified Classes:   TaintLaunderingError, Taint, Observation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class TaintLaunderingError(RuntimeError):
    """Raised when a privileged tool argument derives from a taint-clearing
    transformation whose inputs were tainted. The gate cannot prove the
    argument is untainted, so it must refuse."""

@dataclass(frozen=True)
class Taint:
    labels: frozenset[str] = frozenset()
    def join(self, other: "Taint") -> "Taint":
        return Taint(self.labels | other.labels)

@dataclass
class Observation:
    content: str
    taint: Taint
    parent: "Observation | None" = None
    transform: str | None = None  # name of transformation that produced this

# Registry of transformations. True = taint-preserving (must carry join).
TAINT_PRESERVING: dict[str, bool] = {
    "summarize": True,
    "truncate": True,
    "reformat_json": True,
    "drop_field": False,   # cannot carry content forward
    "hash": False,
}

def apply_transform(name: str, parent: Observation, new_content: str) -> Observation:
    if name not in TAINT_PRESERVING:
        raise TaintLaunderingError(f"unregistered transformation: {name}")
    if TAINT_PRESERVING[name]:
        taint = parent.taint  # monotone: output inherits parent's join
    else:
        # taint-clearing: output is untainted BUT we must record that a
        # tainted input was cleared, so downstream gates can refuse.
        taint = Taint(frozenset({f"CLEARED_FROM:{parent.taint.labels}"}))
    return Observation(new_content, taint, parent=parent, transform=name)

def assert_privileged_args_safe(args: Iterable[Observation]) -> None:
    """Gate for privileged tools. Walks the full provenance chain of each
    argument. Refuses if any chain contains a taint-clearing step whose
    input was tainted, OR if any terminal label is external."""
    for arg in args:
        node: Observation | None = arg
        while node is not None:
            if any(lbl.startswith("CLEARED_FROM:") for lbl in node.taint.labels):
                raise TaintLaunderingError(
                    f"argument provenance contains taint-clearing transform "
                    f"'{node.transform}' applied to tainted input; cannot "
                    f"prove argument is untainted"
                )
            if "TAINTED:external" in node.taint.labels:
                raise TaintLaunderingError(
                    f"privileged argument derives from external taint at "
                    f"transform '{node.transform}'"
                )
            node = node.parent
