# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-distilled-memory-provenance-anchored-forget-policies-and-the-silent-laundering-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-distilled-memory-provenance-anchored-forget-policies-and-the-silent-laundering-boundary.warrant.json
# Markdown SHA-256:   f4aaba772723bfa4ac74641b42ee71f26cac9f086ddc0a6e939eb2586377d6e3
# Code AST SHA-256:   5856469fd196b5800f67996459bc31f429bde2baf121658d98435bd6c59560ce
# Verified Classes:   OrphaningForgetError, TrustLaunderingError, EpisodicTrace, SemanticFact, ProvenanceAnchoredStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphaningForgetError(RuntimeError):
    """Raised when a forget would orphan a live semantic fact's sole provenance."""
    pass


class TrustLaunderingError(RuntimeError):
    """Raised when a distilled fact claims more trust than its provenance allows."""
    pass


TRUST_ORDER = {"untrusted_external": 0, "internal_unverified": 1, "internal_verified": 2}


@dataclass
class EpisodicTrace:
    ep_id: str
    trust: str
    raw_available: bool = True


@dataclass
class SemanticFact:
    fact_id: str
    trust: str
    derived_from: set = field(default_factory=set)


class ProvenanceAnchoredStore:
    def __init__(self):
        self.episodes: dict[str, EpisodicTrace] = {}
        self.facts: dict[str, SemanticFact] = {}

    def dependents(self, ep_id: str) -> list[SemanticFact]:
        return [f for f in self.facts.values() if f.derived_from == {ep_id}]

    def forget_episode(self, ep_id: str) -> None:
        ep = self.episodes.get(ep_id)
        if ep is None:
            return
        deps = self.dependents(ep_id)
        for fact in deps:
            if TRUST_ORDER[fact.trust] > TRUST_ORDER[ep.trust]:
                # Laundering detected: demote before any deletion.
                fact.trust = ep.trust
                raise TrustLaunderingError(
                    f"fact {fact.fact_id} claimed {fact.trust!r} but sole provenance "
                    f"{ep_id} is {ep.trust!r}; demoted and blocked from citation"
                )
        if deps:
            # Cannot collect: facts are load-bearing on this episode.
            raise OrphaningForgetError(
                f"refusing to forget {ep_id}: sole provenance of "
                f"{[f.fact_id for f in deps]}; re-ground or invalidate first"
            )
        del self.episodes[ep_id]

    def revoke_fact(self, fact_id: str) -> None:
        fact = self.facts.get(fact_id)
        if fact is None:
            return
        unresolved = [e for e in fact.derived_from if e not in self.episodes]
        if unresolved:
            raise OrphaningForgetError(
                f"cannot revoke {fact_id}: provenance {unresolved} already collected; "
                f"fact is unresolvable and must be quarantined, not served"
            )
        del self.facts[fact_id]


def nightly_consolidation_gc(store: ProvenanceAnchoredStore, ttl_expired: list[str]) -> None:
    for ep_id in ttl_expired:
        store.forget_episode(ep_id)  # raises rather than silently orphaning
