# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-launders-through-a-lossy-summarizer-before-reaching-a-privileged-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-prompt-injection-taint-that-launders-through-a-lossy-summarizer-before-reaching-a-privileged-tool-call.warrant.json
# Markdown SHA-256:   6c8594d0edfa4135945944c31d880ae1012afaad37fa26aa9fbf0d55e195a37c
# Code AST SHA-256:   c56b480f6d5646fa80cdf0a55a587647b6b9947654bd3458c886dce1f7394f0d
# Verified Classes:   TaintLaunderingError, Span, Generated
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

PRIVILEGED_SOURCES = frozenset({"webhook", "user_upload", "external_email"})


class TaintLaunderingError(RuntimeError):
    """Raised when a generation edge shrinks taint, violating monotonicity."""
    pass


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


@dataclass(frozen=True)
class Generated:
    text: str
    taint: FrozenSet[str]


def generate(context: list[Span], output_text: str) -> Generated:
    """Model an LLM call as a data-flow edge: output taint = union of context taint."""
    inherited = frozenset().union(*(s.taint for s in context)) if context else frozenset()
    return Generated(text=output_text, taint=inherited)


def assert_monotonic(inputs: list[Span], out: Generated) -> None:
    expected = frozenset().union(*(s.taint for s in inputs)) if inputs else frozenset()
    if not expected.issubset(out.taint):
        raise TaintLaunderingError(
            f"generation edge shrank taint: inputs={sorted(expected)} "
            f"output={sorted(out.taint)}; summarizer is a laundering oracle"
        )


def check_sink(call_taint: FrozenSet[str], sink: str) -> None:
    if call_taint & PRIVILEGED_SOURCES:
        raise TaintLaunderingError(
            f"sink {sink} reached with privileged taint {sorted(call_taint & PRIVILEGED_SOURCES)}"
        )


def run(ticket_text: str, summary_text: str) -> str:
    ticket = Span(text=ticket_text, taint=frozenset({"webhook"}))
    summary = generate([ticket], summary_text)
    assert_monotonic([ticket], summary)          # blocks the laundering edge
    check_sink(summary.taint, "issue_refund")    # defense in depth at the sink
    return summary.text
