# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-tool-call-fan-in-under-dynamic-ifc-labeling.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-through-tool-call-fan-in-under-dynamic-ifc-labeling.warrant.json
# Markdown SHA-256:   130f3c48d1e81c88035cb46289143235a3268fa821cc2f44f905ffa0506a0dbf
# Code AST SHA-256:   c6cc516d5f20e15b6a9e8bdc7484819e30ecbc0bdbdb2d04d831aa2b4966e02a
# Verified Classes:   Integrity, Confidentiality, Label, TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum


class Integrity(IntEnum):
    UNTRUSTED = 0
    TRUSTED = 1


class Confidentiality(IntEnum):
    PUBLIC = 0
    SECRET = 1


@dataclass(frozen=True)
class Label:
    integrity: Integrity
    confidentiality: Confidentiality


class TaintLaunderingError(RuntimeError):
    """Raised when a join or sink would erase provenance under a misordered lattice."""


def join(a: Label, b: Label) -> Label:
    # Componentwise join: integrity takes the MINIMUM (untrusted is bottom),
    # confidentiality takes the MAXIMUM. A single-scalar join is the bug.
    return Label(
        integrity=Integrity(min(a.integrity, b.integrity)),
        confidentiality=Confidentiality(max(a.confidentiality, b.confidentiality)),
    )


def assert_sink_accepts(sink_requires: Label, arg_label: Label, sink_name: str) -> None:
    if arg_label.integrity < sink_requires.integrity:
        raise TaintLaunderingError(
            f"sink {sink_name!r} requires integrity {sink_requires.integrity.name} "
            f"but argument carries {arg_label.integrity.name}; "
            f"derivation touched untrusted tool output — declassify explicitly."
        )
    if arg_label.confidentiality > sink_requires.confidentiality:
        raise TaintLaunderingError(
            f"sink {sink_name!r} would leak confidentiality {arg_label.confidentiality.name}."
        )


def reduce_tool_results(results: list[Label], sink_requires: Label, sink_name: str) -> Label:
    if not results:
        raise TaintLaunderingError("join over empty tool-result set is undefined.")
    acc = results[0]
    for r in results[1:]:
        acc = join(acc, r)
    # The critical check: the JOINED label, not the last result, gates the sink.
    assert_sink_accepts(sink_requires, acc, sink_name)
    return acc


# Reproduction of the observed bug: email (untrusted) + calendar (trusted) -> send_message.
email = Label(Integrity.UNTRUSTED, Confidentiality.SECRET)
calendar = Label(Integrity.TRUSTED, Confidentiality.PUBLIC)
send_requires = Label(Integrity.TRUSTED, Confidentiality.PUBLIC)

reduce_tool_results([email, calendar], send_requires, "send_message")
