# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-memory-provenance-when-a-taint-tagged-episode-is-distilled-into-a-semantic-fact-that-outlives-the-taint-label.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-memory-provenance-when-a-taint-tagged-episode-is-distilled-into-a-semantic-fact-that-outlives-the-taint-label.warrant.json
# Markdown SHA-256:   2f2a6ee8216cb019f134e20905c80614c196f77aee911d78fdf58d82cb985b19
# Code AST SHA-256:   f4c10f771ffa76db5f03a5e014ed5ed1468ac9111c4df1193392046d54e27c43
# Verified Classes:   Taint, ProvenanceLaunderingError, EpisodicRecord, SemanticFact
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class Taint(str, Enum):
    UNTRUSTED_TOOL_OUTPUT = "untrusted_tool_output"
    PEER_SUPPLIED = "peer_supplied"
    USER_INJECTED = "user_injected"


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a distilled fact would be committed without inherited taint."""


@dataclass
class EpisodicRecord:
    id: int
    content: str
    taint: Optional[Taint] = None


@dataclass
class SemanticFact:
    id: int
    content: str
    source_episode_ids: list[int]
    inherited_taint: list[Taint] = field(default_factory=list)


def consolidate(
    fact_id: int,
    content: str,
    source_episode_ids: list[int],
    episodic_store: dict[int, EpisodicRecord],
) -> SemanticFact:
    """Distill episodes into a semantic fact, propagating taint by lineage join.

    The model produces `content` and `source_episode_ids`. It is NOT trusted to
    produce `inherited_taint`; that is resolved here by deterministic join so a
    probabilistic summarizer cannot drop it.
    """
    if not source_episode_ids:
        raise ProvenanceLaunderingError(
            f"fact {fact_id}: no source lineage; refusing to write unattributed fact"
        )

    missing = [eid for eid in source_episode_ids if eid not in episodic_store]
    if missing:
        raise ProvenanceLaunderingError(
            f"fact {fact_id}: lineage references unknown episodes {missing}; "
            "cannot resolve taint, failing closed"
        )

    # Taint is monotone: union over all sources. One tainted source taints the fact.
    inherited: set[Taint] = set()
    for eid in source_episode_ids:
        tag = episodic_store[eid].taint
        if tag is not None:
            inherited.add(tag)

    return SemanticFact(
        id=fact_id,
        content=content,
        source_episode_ids=list(source_episode_ids),
        inherited_taint=sorted(inherited, key=lambda t: t.value),
    )


def retrieve(fact: SemanticFact) -> str:
    """Taint-aware retrieval gate. Fails closed on unknown provenance."""
    if fact.inherited_taint:
        raise ProvenanceLaunderingError(
            f"fact {fact.id}: blocked, inherited taint {fact.inherited_taint}"
        )
    if fact.source_episode_ids is None:
        # provenance: null is unknown, not clean
        raise ProvenanceLaunderingError(
            f"fact {fact.id}: provenance unknown; failing closed"
        )
    return fact.content
