# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-tool-call-boundaries-when-a-trusted-tool-re-emits-injected-content.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-tool-call-boundaries-when-a-trusted-tool-re-emits-injected-content.warrant.json
# Markdown SHA-256:   2cc6b708bae75bd574d11a58a9e9b231c2e6e897a281f4c2bfdcb1bc30d543b3
# Code AST SHA-256:   69ef0548fe2573f7872c76ee377ec2c9fd9596c612e541abd201ebe93bd99fc4
# Verified Classes:   TaintLaunderingError, Label
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TaintLaunderingError(RuntimeError):
    """Raised when a derivative tool output is about to be labeled as trusted,
    violating the monotonic-label invariant across a tool boundary."""


@dataclass
class Label:
    contains_untrusted: bool = False
    sources: frozenset = field(default_factory=frozenset)

    def join(self, other: "Label") -> "Label":
        return Label(
            contains_untrusted=self.contains_untrusted or other.contains_untrusted,
            sources=self.sources | other.sources,
        )


TRUSTED = Label(contains_untrusted=False, sources=frozenset())


def label_tool_output(tool_schema: dict, input_labels: list[Label],
                      tool_trust: Label) -> Label:
    transform = tool_schema.get("transform", "derivative")  # conservative default

    if transform == "independent":
        # Output is not a function of input; label by the tool's own trust.
        return tool_trust

    if transform == "derivative":
        if not input_labels:
            raise TaintLaunderingError(
                f"tool {tool_schema.get('name')!r} declared derivative but "
                f"received no input labels; cannot compute join"
            )
        joined = TRUSTED
        for lbl in input_labels:
            joined = joined.join(lbl)
        # Guard: a derivative output must never be less tainted than its inputs.
        if joined.contains_untrusted and not tool_trust.contains_untrusted:
            # Returning tool_trust here would launder the taint. Refuse.
            if tool_trust.contains_untrusted is False and joined.contains_untrusted:
                return joined  # carry, do not reset — but flag for audit
        return joined.join(tool_trust)

    raise TaintLaunderingError(
        f"unknown transform class {transform!r} for tool "
        f"{tool_schema.get('name')!r}"
    )


def compact_context(raw_outputs: list[tuple[bytes, Label]],
                    summarizer_schema: dict) -> Label:
    """Compaction is a derivative tool; it must carry the join of evicted labels."""
    if not raw_outputs:
        raise TaintLaunderingError("compaction invoked with empty context")
    labels = [lbl for _, lbl in raw_outputs]
    out = label_tool_output(summarizer_schema, labels, TRUSTED)
    if out.contains_untrusted:
        # Taint survived compaction; downstream gates must see it.
        return out
    return out
