# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-weighted-retrieval-trust-scores-from-laundering-poisoned-memory-during-episodic-to-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-weighted-retrieval-trust-scores-from-laundering-poisoned-memory-during-episodic-to-semantic-distillation.warrant.json
# Markdown SHA-256:   b69b30d1ac200f93c69d853116d20ea74d99b40948cb67cff9111320ef8bad55
# Code AST SHA-256:   b1b84cf7e6c21ec07c1a30a3d644bbf8e75811cbf33b5a05387dadce58bf1e88
# Verified Classes:   TrustLaunderingError, MemoryRecord, SemanticStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TrustLaunderingError(RuntimeError):
    """Raised when a distilled memory record would exceed its antecedent trust ceiling."""


@dataclass(frozen=True)
class MemoryRecord:
    record_id: str
    trust: float
    root_ids: FrozenSet[str]          # transitive set of original (non-distilled) antecedents
    timestamp: float                  # for root-anchored decay: oldest root time


@dataclass
class SemanticStore:
    floor: float = 0.5
    records: dict = field(default_factory=dict)

    def admit_distilled(
        self,
        record_id: str,
        antecedents: list,
        claimed_trust: float,
        corroboration_roots: FrozenSet[str] = frozenset(),
    ) -> MemoryRecord:
        if not antecedents:
            # A summary that cites nothing is unverifiable; quarantine, do not rank.
            raise TrustLaunderingError(
                f"{record_id}: distilled record has empty antecedent set; cannot propagate trust"
            )

        ceiling = min(a.trust for a in antecedents)

        # Corroboration only lifts the ceiling if its roots are disjoint from every antecedent.
        antecedent_roots = frozenset().union(*(a.root_ids for a in antecedents))
        if corroboration_roots and corroboration_roots.isdisjoint(antecedent_roots):
            ceiling = max(ceiling, min(claimed_trust, 1.0))

        if claimed_trust > ceiling + 1e-9:
            raise TrustLaunderingError(
                f"{record_id}: claimed trust {claimed_trust:.3f} exceeds antecedent ceiling "
                f"{ceiling:.3f}; trust cannot increase across a distillation hop"
            )

        roots = antecedent_roots | corroboration_roots
        oldest = min(a.timestamp for a in antecedents)
        rec = MemoryRecord(record_id, claimed_trust, roots, oldest)
        self.records[record_id] = rec
        return rec

    def retrieve(self, candidates: list) -> list:
        # Hard gate: below-floor records are excluded, never merely down-ranked.
        return [c for c in candidates if c.trust >= self.floor]
