# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-derived-label-after-a-tool-boundary-taint-label-laundering-through-tool-returned-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-derived-label-after-a-tool-boundary-taint-label-laundering-through-tool-returned-provenance.warrant.json
# Markdown SHA-256:   3ecc406b7a88cf264a2763a169af81baf6091107cf6d042f281a258370ce3082
# Code AST SHA-256:   8f9a2b5c7f648ac8dac5808882f65c445629083814bfd638a6818f89a4f7d8f8
# Verified Classes:   TaintLaunderingError, LabeledValue, ToolManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

TRUSTED = "TRUSTED"
UNTRUSTED = "UNTRUSTED"

# Trust lattice: taint dominates under join.
_JOIN = {
    (TRUSTED, TRUSTED): TRUSTED,
    (TRUSTED, UNTRUSTED): UNTRUSTED,
    (UNTRUSTED, TRUSTED): UNTRUSTED,
    (UNTRUSTED, UNTRUSTED): UNTRUSTED,
}

def join(a: str, b: str) -> str:
    return _JOIN[(a, b)]


class TaintLaunderingError(RuntimeError):
    """Raised when a tool return's label is less tainted than the join of its inputs,
    or when a sink is asked to act on a value whose lineage is not fully trusted."""


@dataclass(frozen=True)
class LabeledValue:
    value: str
    label: str
    lineage: FrozenSet[str] = field(default_factory=frozenset)  # ancestor value ids


@dataclass(frozen=True)
class ToolManifest:
    name: str
    domain_label: str          # label the tool's own domain confers
    taint_passthrough: bool    # MUST be True for lossy/transform tools


def invoke_tool(manifest: ToolManifest, inputs: list[LabeledValue], raw_output: str,
                output_id: str) -> LabeledValue:
    """Enforce the monotonicity invariant at the tool boundary.

    out_label must equal domain_label(tool) JOIN (join of all input labels).
    A tool that emits its domain label while consuming tainted input is laundering.
    """
    if not inputs:
        return LabeledValue(raw_output, manifest.domain_label, frozenset({output_id}))

    input_join = inputs[0].label
    for v in inputs[1:]:
        input_join = join(input_join, v.label)
    expected = join(manifest.domain_label, input_join)

    if manifest.taint_passthrough and expected != manifest.domain_label:
        # Transform tool saw taint but claims a clean domain label -> laundering.
        raise TaintLaunderingError(
            f"tool '{manifest.name}' returned label {manifest.domain_label!r} "
            f"but input join is {input_join!r}; expected {expected!r}. "
            f"Output must be quarantined, not relabeled."
        )

    lineage = frozenset({output_id}).union(*(v.lineage for v in inputs))
    return LabeledValue(raw_output, expected, lineage)


def sink_write(manifest: ToolManifest, value: LabeledValue,
               trusted_lineage: FrozenSet[str]) -> None:
    """A sink may act only if the value AND its full lineage are TRUSTED."""
    if value.label != TRUSTED:
        raise TaintLaunderingError(
            f"sink '{manifest.name}' refused: value label {value.label!r} is not TRUSTED."
        )
    untrusted_ancestors = value.lineage - trusted_lineage
    if untrusted_ancestors:
        raise TaintLaunderingError(
            f"sink '{manifest.name}' refused: lineage contains untrusted ancestors "
            f"{sorted(untrusted_ancestors)!r} despite TRUSTED surface label."
        )
