# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-poisoned-episodic-write-from-being-laundered-into-attested-semantic-memory-by-the-distillation-step.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-poisoned-episodic-write-from-being-laundered-into-attested-semantic-memory-by-the-distillation-step.warrant.json
# Markdown SHA-256:   9c5d5b7370372e88b1a71dd663cf848e38408416f4b2615ad29e59c6ec990d5e
# Code AST SHA-256:   94bf5c23f82c96e849ac3561f5f31c9f730f902339008fe206993378daeeb86d
# Verified Classes:   MemoryLaunderingError, EpisodicRecord, SemanticRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class MemoryLaunderingError(RuntimeError):
    """Raised when a distillation attempt would re-attest low-trust episodic
    content at a higher trust level than its inputs permit."""


@dataclass(frozen=True)
class EpisodicRecord:
    record_id: str
    trust: float
    taint_flags: frozenset[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class SemanticRecord:
    summary: str
    attestation: float
    contributors: tuple[tuple[str, float], ...]
    taint_flags: frozenset[str]


def distill(
    cluster: Sequence[EpisodicRecord],
    summarize,  # callable: list[EpisodicRecord] -> str
    max_cross_class_span: float = 0.4,
) -> list[SemanticRecord]:
    if not cluster:
        raise MemoryLaunderingError("empty cluster: nothing to distill")

    trusts = [r.trust for r in cluster]
    if max(trusts) - min(trusts) > max_cross_class_span:
        # Mixed trust classes: partition before the summarizer sees them.
        # Summarizing across this boundary is the laundering channel.
        partitions: dict[int, list[EpisodicRecord]] = {}
        for r in cluster:
            partitions.setdefault(int(r.trust * 10), []).append(r)
        out: list[SemanticRecord] = []
        for group in partitions.values():
            out.extend(distill(group, summarize, max_cross_class_span))
        return out

    # Homogeneous class: attestation is the MINIMUM of inputs, never the
    # distiller's own identity or an independent confidence score.
    attestation = min(trusts)
    contributors = tuple((r.record_id, r.trust) for r in cluster)
    taint = frozenset().union(*(r.taint_flags for r in cluster))

    summary = summarize(list(cluster))

    # Guard: a derived record may never be attested above its weakest input.
    if attestation > min(trusts) + 1e-9:
        raise MemoryLaunderingError(
            f"attestation {attestation} exceeds minimum input trust {min(trusts)}"
        )
    if taint and attestation > 0.5:
        raise MemoryLaunderingError(
            f"tainted contributors {sorted(taint)} promoted to attestation {attestation}"
        )

    return [
        SemanticRecord(
            summary=summary,
            attestation=attestation,
            contributors=contributors,
            taint_flags=taint,
        )
    ]
