# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-across-a-tool-boundary-when-the-tool-itself-returns-a-laundered-copy-of-injected-content.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-taint-labels-across-a-tool-boundary-when-the-tool-itself-returns-a-laundered-copy-of-injected-content.warrant.json
# Markdown SHA-256:   9570312eddb8adcd92a9459c9e41d6ddf478273cfca4ea532aa5f538bbba56e2
# Code AST SHA-256:   eef535ba5fe544b53b042812731ed448d1475bc58af7c38c80271a42c74a03a5
# Verified Classes:   TaintLaunderingError, Provenance, Tagged
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a tool output drops or weakens the taint of its inputs."""


@dataclass(frozen=True)
class Provenance:
    labels: frozenset[str] = field(default_factory=frozenset)

    def join(self, other: "Provenance") -> "Provenance":
        return Provenance(self.labels | other.labels)

    def is_clean(self) -> bool:
        return len(self.labels) == 0


@dataclass
class Tagged:
    value: Any
    prov: Provenance


def invoke_tool(tool_fn, inputs: list[Tagged], declares_derivation: bool) -> Tagged:
    """Invoke a tool, conservatively joining input taint into output taint.

    If the tool does not declare derivation, every output is tainted with the
    union of all input taints. This is the guardrail against laundering.
    """
    joined = Provenance()
    for i in inputs:
        joined = joined.join(i.prov)

    raw_output = tool_fn([i.value for i in inputs])
    output_prov = Provenance(frozenset({f"tool:{tool_fn.__name__}"}))

    if not declares_derivation:
        # Conservative join: output inherits all input taint.
        output_prov = output_prov.join(joined)
        return Tagged(raw_output, output_prov)

    # Tool declares derivation but must still not drop input taint.
    declared = Provenance(frozenset(getattr(tool_fn, "declared_taint", set())))
    if not joined.labels.issubset(output_prov.join(declared).labels):
        raise TaintLaunderingError(
            f"tool {tool_fn.__name__} dropped taint labels "
            f"{sorted(joined.labels - output_prov.labels)} from its output"
        )
    return Tagged(raw_output, output_prov.join(declared))


def guarded_side_effect(instruction: Tagged, action_fn) -> None:
    """Refuse to execute a side effect whose instruction slot is tainted."""
    if not instruction.prov.is_clean():
        raise TaintLaunderingError(
            f"refusing side effect: instruction carries taint "
            f"{sorted(instruction.prov.labels)}"
        )
    action_fn(instruction.value)
