# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-content-through-a-trusted-summarizer-before-a-sink-check.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-content-through-a-trusted-summarizer-before-a-sink-check.warrant.json
# Markdown SHA-256:   d18ea3d1a23cd3a11980c2c4bfb96aa8b0dd6f803b41c516697cc7b0333c7877
# Code AST SHA-256:   b79e2054059a5ac9551deb277aba4e7a873c3eeb54ccf83e6bbf299c3329fdb9
# Verified Classes:   TaintLaunderingError, Taint, ToolSpec
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TaintLaunderingError(RuntimeError):
    """Raised when a trusted tool narrows taint it did not destroy."""


@dataclass(frozen=True)
class Taint:
    sources: frozenset[str] = field(default_factory=frozenset)

    def union(self, other: "Taint") -> "Taint":
        return Taint(self.sources | other.sources)

    @property
    def is_trusted(self) -> bool:
        return not self.sources


UNTRUSTED = Taint(frozenset({"untrusted"}))


@dataclass
class ToolSpec:
    name: str
    amplifying: bool  # True if the tool can emit arbitrary substrings of input


def invoke_tool(spec: ToolSpec, arg: Taint, declassified: bool = False) -> Taint:
    """Compute output taint under lineage closure.

    A trusted tool may only narrow taint if it is non-amplifying AND an
    explicit declassification has been recorded for this call.
    """
    if spec.amplifying and not declassified:
        # Output taint must be a superset of input taint.
        return arg
    if spec.amplifying and declassified:
        # Declassification of an amplifying tool is the defect we are guarding.
        raise TaintLaunderingError(
            f"tool {spec.name!r} is amplifying; it cannot be used as a "
            f"declassifier. Input taint {sorted(arg.sources)} would be "
            f"laundered into 'trusted' output."
        )
    # Non-amplifying tool: may narrow to trusted only if explicitly cleared.
    return UNTRUSTED if not declassified else Taint(frozenset())


def enforce_sink(spec: ToolSpec, arg_taint: Taint) -> None:
    if not arg_taint.is_trusted:
        raise TaintLaunderingError(
            f"sink {spec.name!r} refused: argument carries taint "
            f"{sorted(arg_taint.sources)}"
        )


def run_chain() -> None:
    summarizer = ToolSpec(name="summarize", amplifying=True)  # LLM in the loop
    post = ToolSpec(name="http_post", amplifying=False)

    page = UNTRUSTED
    # Naive runtime would do: summary = Taint()  -> laundering.
    summary = invoke_tool(summarizer, page)  # closure keeps it tainted
    enforce_sink(post, summary)  # correctly refuses


if __name__ == "__main__":
    run_chain()
