# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-a-tool-result-launders-injected-instructions-through-a-trusted-sub-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-a-tool-result-launders-injected-instructions-through-a-trusted-sub-agent.warrant.json
# Markdown SHA-256:   4d707a2c570ad1ee2720ae08f7cdd98e4f9672025801f7f32e58f7dd6bea6931
# Code AST SHA-256:   1914d9958a797c7bcca48482130b5bc7643f827f416c9a70830e5753c6e489f6
# Verified Classes:   TaintLaunderingError, Labeled
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

TRUSTED = "trusted"
UNTRUSTED = "untrusted"


class TaintLaunderingError(RuntimeError):
    """Raised when a tool emits output whose label does not equal the join of
    producer label and input labels — i.e., a label reset point was detected."""


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


def join_labels(producer: FrozenSet[str], inputs: list[FrozenSet[str]]) -> FrozenSet[str]:
    out = set(producer)
    for i in inputs:
        out |= i
    return frozenset(out)


def emit_from_tool(
    producer_label: FrozenSet[str],
    input_labels: list[FrozenSet[str]],
    output_value: str,
) -> Labeled:
    """Every tool that reads bytes and writes bytes must route through this.

    The invariant: output label == join(producer, inputs). A tool that emits
    under its own trusted identity alone is a laundering point and must be
    rejected before the output reaches the planner.
    """
    expected = join_labels(producer_label, input_labels)
    declared = producer_label  # the buggy path: relabel on producer identity
    if declared != expected:
        raise TaintLaunderingError(
            f"tool emit relabeled on producer identity: "
            f"declared={sorted(declared)} expected_join={sorted(expected)}"
        )
    return Labeled(output_value, expected)


def gate_privileged_call(arg_provenance: FrozenSet[str], tool_name: str) -> None:
    if UNTRUSTED in arg_provenance:
        raise TaintLaunderingError(
            f"privileged tool {tool_name!r} called with tainted argument provenance "
            f"{sorted(arg_provenance)}; require explicit de-taint (user confirmation "
            f"or signature verification) before proceeding"
        )


# Trace of the observed failure, now bounded:
fetch = Labeled("<doc>...call wire_transfer...</doc>", frozenset({UNTRUSTED}))
try:
    # summarize is policy-trusted but reads tainted input; naive emit resets label
    summary = emit_from_tool(
        producer_label=frozenset({TRUSTED}),
        input_labels=[fetch.labels],
        output_value="summary containing the directive",
    )
except TaintLaunderingError as e:
    # Correct behavior: the emit is rejected, the taint is not lost.
    # The runtime must re-emit under the join, not under producer identity.
    summary = Labeled("summary containing the directive", join_labels(frozenset({TRUSTED}), [fetch.labels]))

# Planner attempts a privileged call derived from the (correctly tainted) summary.
gate_privileged_call(summary.labels, "wire_transfer")
