# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-provenance-trust-at-write-time-to-survive-memory-poisoning-that-only-manifests-after-episodic-to-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-provenance-trust-at-write-time-to-survive-memory-poisoning-that-only-manifests-after-episodic-to-semantic-distillation.warrant.json
# Markdown SHA-256:   25d65a3057c2f70106dd00ecb4b3638bc77a25427853cae0695520e4d6455f6d
# Code AST SHA-256:   c31d7aa3b695c415395b9ae67a0db6cd68c8b5932c72888244aa1f8942d35afe
# Verified Classes:   ProvenanceTrustViolation, Episode, SemanticEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceTrustViolation(RuntimeError):
    """Raised when a semantic memory entry is retrieved with trust exceeding
    the minimum trust of its contributing episodes (distillation laundering)."""
    pass


@dataclass(frozen=True)
class Episode:
    id: str
    trust: float          # assigned by ingestion channel, NOT by content
    text: str


@dataclass(frozen=True)
class SemanticEntry:
    fact: tuple
    derived_from: FrozenSet[str]
    trust: float          # MUST equal min(trust_in) over derived_from


def distill(cluster: list[Episode], fact: tuple) -> SemanticEntry:
    if not cluster:
        raise ProvenanceTrustViolation("cannot distill empty cluster")
    trusts = {e.trust for e in cluster}
    if max(trusts) - min(trusts) > 0.4:
        # Force conflict to surface; do not launder a mixed-trust cluster
        # into a single confident semantic claim.
        raise ProvenanceTrustViolation(
            f"mixed-trust cluster (spread={max(trusts)-min(trusts):.2f}); "
            f"route to human review instead of distilling"
        )
    return SemanticEntry(
        fact=fact,
        derived_from=frozenset(e.id for e in cluster),
        trust=min(trusts),          # min-join: one bad premise taints conclusion
    )


def retrieve(entry: SemanticEntry, episodes: dict[str, Episode],
             trust_floor: float = 0.5) -> SemanticEntry:
    # Recompute join from live episode trust; never trust the stored value blindly.
    if not entry.derived_from:
        raise ProvenanceTrustViolation(
            f"semantic entry {entry.fact} has no provenance; refusing retrieval"
        )
    live_join = min(episodes[eid].trust for eid in entry.derived_from)
    if entry.trust > live_join + 1e-9:
        raise ProvenanceTrustViolation(
            f"entry {entry.fact} claims trust={entry.trust:.2f} but "
            f"provenance join={live_join:.2f}; distillation laundering detected"
        )
    if entry.trust < trust_floor:
        raise ProvenanceTrustViolation(
            f"entry {entry.fact} trust={entry.trust:.2f} below floor "
            f"{trust_floor:.2f}; planner must corroborate via episodic tier"
        )
    return entry
