# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-tool-output-as-tainted-even-when-the-transport-is-authenticated-and-how-does-taint-propagation-survive-co.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-tool-output-as-tainted-even-when-the-transport-is-authenticated-and-how-does-taint-propagation-survive-co.warrant.json
# Markdown SHA-256:   3aa9213358d8618cdf57ca54d3eac1565234288f1b972193455c0a6674be9c81
# Code AST SHA-256:   9f57dc54b17a79f00d089addee763d3019e3ac6b4535eab2da4fb95f6b7fd2a6
# Verified Classes:   ProvenanceLaunderingError, Block
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Iterable


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a derived artifact loses or fails to union taint provenance."""


@dataclass(frozen=True)
class Block:
    text: str
    origins: FrozenSet[str] = field(default_factory=frozenset)

    def tainted(self) -> bool:
        return "TRUSTED" not in self.origins or len(self.origins) > 1


def summarize(inputs: Iterable[Block], summary_text: str) -> Block:
    """A summarizer is a taint-propagating transform. Its output provenance
    MUST be the union of its inputs' origins; anything less is laundering."""
    union: FrozenSet[str] = frozenset()
    for b in inputs:
        union = union | b.origins
    if not union:
        raise ProvenanceLaunderingError(
            "summarize() received inputs with no provenance; refusing to "
            "emit an unlabeled summary (fail-closed on provenance unknown)."
        )
    return Block(text=summary_text, origins=union)


def authorize_write(arg: Block, required_clean: bool = True) -> None:
    """Gate a side-effecting tool call on the provenance of its argument.
    Model-authored arguments must be passed through summarize()/union first."""
    if required_clean and arg.tainted():
        raise ProvenanceLaunderingError(
            f"write blocked: argument provenance {sorted(arg.origins)} "
            f"is not provably clean; needs human confirmation."
        )


def compact_and_write(transcript: list[Block], summary_text: str, write_arg: str) -> None:
    # Correct: the summary inherits the union of all transcript origins.
    summary = summarize(transcript, summary_text)
    # The write argument is derived from the summary, so it inherits its taint.
    derived = Block(text=write_arg, origins=summary.origins)
    authorize_write(derived)  # raises when any fetched content is in scope
