# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-lossy-summarization-during-memory-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-lossy-summarization-during-memory-consolidation.warrant.json
# Markdown SHA-256:   de3584676c28f77de7d2ff3e0daed19849ee6e21aa5e05a6e6bc19bd80211e02
# Code AST SHA-256:   a526e473e0cf28612e3ef0011ff28eac798cfb531c7b39f6ce765dc9ea795424
# Verified Classes:   Taint, TaintLaunderingError, Episode, SemanticRecord, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class Taint(IntEnum):
    TRUSTED = 0
    UNKNOWN = 1
    UNTRUSTED = 2


def join(labels: Iterable[Taint]) -> Taint:
    """Lattice least-upper-bound: any tainted ancestor taints the descendant."""
    result = Taint.TRUSTED
    for label in labels:
        if label > result:
            result = label
    return result


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would lose or downgrade provenance taint."""


@dataclass
class Episode:
    content: str
    label: Taint


@dataclass
class SemanticRecord:
    content: str
    label: Taint
    derivation: list[str] = field(default_factory=list)


class MemoryStore:
    def __init__(self) -> None:
        self._records: dict[str, SemanticRecord] = {}

    def write(self, record_id: str, record: SemanticRecord) -> None:
        if not record.derivation:
            raise TaintLaunderingError(
                f"record {record_id!r} has no derivation edges; provenance "
                "cannot be reconstructed, treating as injection"
            )
        self._records[record_id] = record

    def read(self, record_id: str) -> SemanticRecord:
        rec = self._records[record_id]
        recomputed = join(
            self._records[ancestor].label
            for ancestor in rec.derivation
            if ancestor in self._records
        )
        if recomputed > rec.label:
            raise TaintLaunderingError(
                f"record {record_id!r} stored label {rec.label.name} is weaker "
                f"than provenance closure {recomputed.name}; label was laundered"
            )
        return rec


def consolidate(
    store: MemoryStore,
    record_id: str,
    episodes: list[Episode],
    summarize,
) -> SemanticRecord:
    """LLM-mediated consolidation with conservative taint propagation."""
    if any(ep.label is Taint.UNKNOWN for ep in episodes):
        out_label = Taint.UNKNOWN  # fail-closed
    else:
        out_label = join(ep.label for ep in episodes)

    summary = summarize([ep.content for ep in episodes])

    # The summarizer must echo the input label set; if it cannot, the
    # consolidation is untrusted by construction and must not be written.
    echoed = getattr(summary, "input_labels", None)
    if echoed is None:
        raise TaintLaunderingError(
            "summarizer did not round-trip input label set; refusing write"
        )
    if join(echoed) != out_label:
        raise TaintLaunderingError(
            f"summarizer echoed {join(echoed).name} but closure is "
            f"{out_label.name}; label set was dropped or downgraded"
        )

    record = SemanticRecord(
        content=summary.text,
        label=out_label,
        derivation=[f"episode:{i}" for i in range(len(episodes))],
    )
    store.write(record_id, record)
    return record
