# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-taint-label-through-a-lossy-summarization-step-between-tool-output-and-context-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-taint-label-through-a-lossy-summarization-step-between-tool-output-and-context-injection.warrant.json
# Markdown SHA-256:   882625efa146a5a6f1f71b1ad09c979199a304689b553e98383628e6dc15bea0
# Code AST SHA-256:   5e15c05bea2a9fbb5e125f2f299c2106db3363b298c33ff7d8a0ea5ea7a2a357
# Verified Classes:   Taint, TaintLaunderingError, Provenance
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from enum import IntEnum

class Taint(IntEnum):
    TRUSTED = 0
    USER_DERIVED = 1
    UNTRUSTED = 2  # join is max; lattice is a total order here


class TaintLaunderingError(RuntimeError):
    """Raised when a free-text transform would emit output without a derivation edge."""
    pass


class Provenance:
    def __init__(self, label: Taint, source_ids: list[str]):
        self.label = label
        self.source_ids = source_ids


def join_labels(inputs: list[Provenance]) -> Provenance:
    # Lattice join: max over the total order. NEVER majority vote.
    if not inputs:
        raise TaintLaunderingError("transform with no declared inputs")
    label = max(p.label for p in inputs)
    ids = [sid for p in inputs for sid in p.source_ids]
    return Provenance(label, ids)


def apply_transform(
    tool_name: str,
    emits_free_text: bool,
    declared_provenance: str,
    inputs: list[Provenance],
) -> Provenance:
    if emits_free_text:
        if declared_provenance != "derived":
            # A free-text tool claiming 'tool' provenance is a laundering site.
            raise TaintLaunderingError(
                f"tool {tool_name!r} emits free text but declares "
                f"provenance={declared_provenance!r}; must be 'derived'"
            )
        return join_labels(inputs)
    # Structured/non-text output cannot carry an injection payload.
    return Provenance(Taint.TRUSTED, [f"{tool_name}:out"])


def gate_privileged_action(
    action: str, args_provenance: Provenance, max_allowed: Taint
) -> None:
    if args_provenance.label > max_allowed:
        raise TaintLaunderingError(
            f"blocked {action!r}: args tainted {args_provenance.label.name} "
            f"via {args_provenance.source_ids}"
        )


# Demonstration of the failure and the guard.
raw = Provenance(Taint.UNTRUSTED, ["fetch_url:chunk_7"])

# The broken schema: summarizer claims 'tool' provenance -> raises here.
try:
    summary = apply_transform(
        "summarize_chunk", emits_free_text=True,
        declared_provenance="tool", inputs=[raw],
    )
except TaintLaunderingError as e:
    print("caught laundering site:", e)

# The corrected schema: 'derived' -> label propagates, gate blocks.
summary = apply_transform(
    "summarize_chunk", emits_free_text=True,
    declared_provenance="derived", inputs=[raw],
)
gate_privileged_action("send_email", summary, max_allowed=Taint.USER_DERIVED)
