# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-at-the-retrieval-boundary-when-provenance-labels-are-re-derived-rather-than-propagated.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-at-the-retrieval-boundary-when-provenance-labels-are-re-derived-rather-than-propagated.warrant.json
# Markdown SHA-256:   09a19f7a72e831a187113d6e9bce6cf3d6b08164ef1cd955bc3f4a38811a426e
# Code AST SHA-256:   cea1607bb29783e5b35754d156535ce4a8f9a60ee07bba53bd294a2d87507c61
# Verified Classes:   Taint, TaintLaunderingError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Optional


class Taint(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1
    # Lattice: UNTRUSTED dominates TRUSTED. Join = max.


class TaintLaunderingError(RuntimeError):
    """Raised when assembled-context taint is lower than ingestion taint
    with no recorded declassification."""


@dataclass
class Span:
    text: str
    taint: Taint
    origin: str
    declassified: bool = False


def join(a: Taint, b: Taint) -> Taint:
    return Taint(max(a, b))


def merge_spans(spans: list[Span]) -> Span:
    if not spans:
        raise TaintLaunderingError("cannot merge empty span list")
    taint = Taint.TRUSTED
    for s in spans:
        taint = join(taint, s.taint)  # untrusted dominates
    return Span(
        text="\n".join(s.text for s in spans),
        taint=taint,
        origin="merge:" + ",".join(s.origin for s in spans),
        declassified=all(s.declassified for s in spans),
    )


def gate_action(
    assembled: Span,
    ingestion_taint: Taint,
    declassification_log: list[str],
) -> bool:
    # Guardrail: taint may not drop without an explicit declassification record.
    if assembled.taint < ingestion_taint and not declassification_log:
        raise TaintLaunderingError(
            f"taint dropped {ingestion_taint.name}->{assembled.taint.name} "
            f"at origin={assembled.origin} with no declassification record"
        )
    if assembled.taint == Taint.UNTRUSTED:
        return False  # escalate; do not execute side effect
    return True


def run_pipeline(email_body: str, retrieved: list[Span]) -> bool:
    ingested = Span(text=email_body, taint=Taint.UNTRUSTED, origin="email")
    # BUG: a re-deriving retriever would stamp `retrieved` spans TRUSTED.
    # Correct behavior: retrieved spans must carry ingestion taint forward.
    for r in retrieved:
        if r.taint < ingested.taint and not r.declassified:
            raise TaintLaunderingError(
                f"retrieval span from {r.origin} lost ingestion taint"
            )
    assembled = merge_spans(retrieved)
    return gate_action(assembled, ingested.taint, declassification_log=[])
