# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-poisoned-memory-from-being-laundered-through-episodic-to-semantic-consolidation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-poisoned-memory-from-being-laundered-through-episodic-to-semantic-consolidation.warrant.json
# Markdown SHA-256:   b8dcb2c4f12a00e9704bbe62af5fe958b8d743270dc2fdd43e66cdeddf709b66
# Code AST SHA-256:   eb646a3defc6169a34f753b1361dc9ccd488bfe1661f1435fff159b187b62c0e
# Verified Classes:   TrustLaunderingError, EpisodicRecord, SemanticRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal

Trust = Literal["untrusted", "derived", "trusted"]
_TRUST_RANK = {"untrusted": 0, "derived": 1, "trusted": 2}


class TrustLaunderingError(RuntimeError):
    """Raised when consolidation would escalate trust above its weakest input."""


@dataclass(frozen=True)
class EpisodicRecord:
    text: str
    trust: Trust


@dataclass(frozen=True)
class SemanticRecord:
    fact: str
    trust: Trust
    confidence: float


def consolidate(cluster: list[EpisodicRecord], raw_agreement: float) -> SemanticRecord:
    if not cluster:
        raise TrustLaunderingError("cannot consolidate an empty cluster")

    # Invariant: output trust is the argmin of input trust. Never escalate.
    min_trust: Trust = min((r.trust for r in cluster), key=lambda t: _TRUST_RANK[t])

    # Confidence is bounded by the fraction of support mass that is trusted.
    trusted_mass = sum(1 for r in cluster if r.trust == "trusted")
    support_fraction = trusted_mass / len(cluster)
    confidence = raw_agreement * support_fraction

    # Guardrail: if the cluster is entirely untrusted, the record must stay
    # untrusted AND its confidence must not exceed the untrusted ceiling.
    if min_trust == "untrusted" and confidence > 0.0:
        # raw_agreement on untrusted-only clusters must not buy confidence.
        confidence = 0.0

    record = SemanticRecord(
        fact=_summarize(cluster),
        trust=min_trust,
        confidence=confidence,
    )

    # Hard assertion at the store boundary: a semantic write may never
    # exceed the trust of its weakest supporting episodic record.
    if _TRUST_RANK[record.trust] > _TRUST_RANK[min_trust]:
        raise TrustLaunderingError(
            f"semantic trust {record.trust!r} exceeds min input trust "
            f"{min_trust!r}; laundering channel open"
        )
    return record


def _summarize(cluster: list[EpisodicRecord]) -> str:
    # Placeholder for the distiller's actual generalization step.
    return max(cluster, key=lambda r: len(r.text)).text


def safe_write(store: list[SemanticRecord], cluster: list[EpisodicRecord], agreement: float) -> None:
    record = consolidate(cluster, agreement)
    if record.trust == "untrusted" and record.confidence > 0.0:
        raise TrustLaunderingError(
            "untrusted-only cluster produced nonzero confidence; "
            "agreement was mistaken for corroboration"
        )
    store.append(record)
