# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-through-lossy-summarization-at-the-episodic-to-semantic-memory-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-label-laundering-through-lossy-summarization-at-the-episodic-to-semantic-memory-boundary.warrant.json
# Markdown SHA-256:   8cc85603c176dd54ef4682379757d6f604c464ea5ea9d992360b4990a4d3d496
# Code AST SHA-256:   61e0ced0a82ae1a3ad718ecc2313fce23e4e36f54066af29e1e48c5bb285119f
# Verified Classes:   TaintLaunderingError, Labeled
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

TAINTED = "tainted"
CLEAN = "clean"

def join(labels: Iterable[str]) -> str:
    # Taint lattice: tainted dominates clean. Empty join is CLEAN.
    return TAINTED if any(l == TAINTED for l in labels) else CLEAN

class TaintLaunderingError(RuntimeError):
    """Raised when a generative transform or schema projection would drop a taint label."""

@dataclass
class Labeled:
    content: str
    label: str
    provenance: str = ""

def generative_transform(inputs: list[Labeled], output_text: str,
                        citations: list[str] | None = None) -> Labeled:
    # Invariant: output label = join of input labels, UNLESS every output span
    # carries a verifiable citation to a clean input. Absent citations => strict join.
    input_join = join(i.label for i in inputs)
    if citations is None:
        return Labeled(output_text, input_join, provenance="strict-join")
    # Citable path: only valid if citations are non-empty and all cited inputs are clean.
    if not citations:
        raise TaintLaunderingError(
            "generative transform returned empty citations; cannot verify provenance"
        )
    cited_labels = [i.label for i in inputs if i.provenance in citations]
    if len(cited_labels) != len(citations):
        raise TaintLaunderingError(
            "citations reference spans not present in inputs; provenance unverifiable"
        )
    return Labeled(output_text, join(cited_labels), provenance="span-cited")

def remember(store: list[Labeled], item: Labeled, schema_has_provenance: bool) -> None:
    # Invariant: tainted content may only enter an unlabeled schema slot via declassification.
    if item.label == TAINTED and not schema_has_provenance:
        raise TaintLaunderingError(
            "refusing to write tainted content into schema slot with no provenance field"
        )
    store.append(item)

def recall(store: list[Labeled], idx: int, schema_has_provenance: bool) -> Labeled:
    # Fail-closed: missing provenance reconstructs as TAINTED, never CLEAN.
    rec = store[idx]
    if not schema_has_provenance:
        return Labeled(rec.content, TAINTED, provenance="reconstructed-default-tainted")
    return rec
