# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-composed-skill-chains-in-a-taint-aware-tool-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-composed-skill-chains-in-a-taint-aware-tool-sandbox.warrant.json
# Markdown SHA-256:   91f3af8b76275d6960e6b23aeb782dd79d798ca16f3b67ddbd5c37a107040680
# Code AST SHA-256:   880eda6145f0d5059c6064cf80e28a98292905eafb8a7e52e7ca71fa73f6b4a2
# Verified Classes:   TaintLaunderingError, ProvenanceNode, ProvenanceLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a trusted sink value has a tainted ancestor reachable
    only through an unrecorded reconstructor edge."""


@dataclass
class ProvenanceNode:
    value_id: str
    label: str  # "trusted" | "untrusted"
    parents: list[str] = field(default_factory=list)
    operator_class: str = "constant"  # constant | passthrough | transformer | reconstructor


class ProvenanceLedger:
    def __init__(self) -> None:
        self.nodes: dict[str, ProvenanceNode] = {}

    def record(self, node: ProvenanceNode) -> None:
        self.nodes[node.value_id] = node

    def tainted_ancestors(self, value_id: str, seen: set[str] | None = None) -> list[str]:
        seen = seen or set()
        if value_id in seen:
            return []
        seen.add(value_id)
        node = self.nodes.get(value_id)
        if node is None:
            return []
        hits = [value_id] if node.label == "untrusted" else []
        for parent in node.parents:
            hits.extend(self.tainted_ancestors(parent, seen))
        return hits


def probe_operator_class(tool, tainted_arg: Any, canary_perturbation: Any) -> str:
    """Empirically classify a tool as constant vs. non-constant in its argument.

    A tool that returns identical output for a perturbed tainted argument is
    provably constant in that argument and may emit a trusted label. Any other
    result means the operator is a transformer or reconstructor and the label
    MUST propagate.
    """
    baseline = tool(tainted_arg)
    perturbed = tool(canary_perturbation)
    if baseline == perturbed:
        return "constant"
    return "reconstructor"


def enforce_sink(ledger: ProvenanceLedger, sink_value_id: str) -> None:
    """Refuse to emit a value whose provenance graph contains a tainted ancestor.

    This is the taint-continuity invariant: the sink does not care whether the
    immediate label is trusted; it cares whether any causal ancestor is tainted.
    """
    node = ledger.nodes.get(sink_value_id)
    if node is None:
        raise TaintLaunderingError(
            f"sink value {sink_value_id!r} has no provenance record; "
            "unrecorded values cannot be emitted"
        )
    tainted = ledger.tainted_ancestors(sink_value_id)
    if tainted:
        raise TaintLaunderingError(
            f"sink value {sink_value_id!r} labeled {node.label!r} has tainted "
            f"ancestors {tainted!r} reachable through operator_class="
            f"{node.operator_class!r}; refusing emission"
        )


def run_chain(ledger: ProvenanceLedger, tool, tainted_arg: Any, canary: Any) -> None:
    op_class = probe_operator_class(tool, tainted_arg, canary)
    out_id = f"out:{id(tool)}:{hash(str(tool(tainted_arg)))}"
    ledger.record(
        ProvenanceNode(
            value_id=out_id,
            label="trusted" if op_class == "constant" else "untrusted",
            parents=[f"in:{hash(str(tainted_arg))}"],
            operator_class=op_class,
        )
    )
    # A sink that trusts the declared label but not the provenance graph
    # would pass here; the invariant check below is what catches laundering.
    enforce_sink(ledger, out_id)
