# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-the-semantic-store-has-already-laundered-the-poisoned-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-the-semantic-store-has-already-laundered-the-poisoned-episode.warrant.json
# Markdown SHA-256:   e98f0e7539d3c5217cdc87b2791a7d43e0ba6a62e4ddf3074ff336fa043c638f
# Code AST SHA-256:   f9d149eb0c1ffd513ee96fcc3e7f4e63ceaecf686a4565c63a41f418bcc78774
# Verified Classes:   ProvenanceLaunderingError, Episode, SemanticFact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a semantic fact's support set collapses to a single causal root
    yet is presented as corroborated by cross-store agreement."""
    pass


@dataclass
class Episode:
    episode_id: str
    source: str                 # e.g. "tool:fetch_url", "self:reasoning"
    trust_tier: str             # "untrusted_external", "internal", ...
    derived_from: Optional[str] = None   # episode_id this restates, if known


@dataclass
class SemanticFact:
    fact_id: str
    value: str
    supporting_episode_ids: list[str] = field(default_factory=list)
    confidence: float = 0.0


def external_root(ep: Episode, episodes: dict[str, Episode]) -> str:
    """Walk derived_from edges to the causal origin of an episode."""
    seen: set[str] = set()
    cur = ep
    while cur.derived_from is not None:
        if cur.episode_id in seen:
            raise ProvenanceLaunderingError(
                f"cycle in provenance graph at {cur.episode_id}"
            )
        seen.add(cur.episode_id)
        nxt = episodes.get(cur.derived_from)
        if nxt is None:
            raise ProvenanceLaunderingError(
                f"dangling derived_from {cur.derived_from} for {cur.episode_id}"
            )
        cur = nxt
    return cur.episode_id


def causal_fan_in(fact: SemanticFact, episodes: dict[str, Episode]) -> int:
    roots: set[str] = set()
    for eid in fact.supporting_episode_ids:
        ep = episodes.get(eid)
        if ep is None:
            raise ProvenanceLaunderingError(
                f"fact {fact.fact_id} cites missing episode {eid}"
            )
        roots.add(external_root(ep, episodes))
    return len(roots)


def verify_fact(fact: SemanticFact, episodes: dict[str, Episode]) -> str:
    """Cross-store consistency check hardened by provenance closure.

    Returns TRUSTED only when the fact agrees with its episodes AND those
    episodes trace to >= 2 independent external roots.
    """
    for eid in fact.supporting_episode_ids:
        ep = episodes[eid]
        if ep.trust_tier == "untrusted_external":
            # agreement with an untrusted episode is not corroboration
            pass
    fan_in = causal_fan_in(fact, episodes)
    if fan_in == 0:
        raise ProvenanceLaunderingError(
            f"fact {fact.fact_id} has no external root"
        )
    if fan_in == 1:
        # The exact laundering signature: many support entries, one origin.
        return "CONSISTENT_BUT_UNWITNESSED"
    return "TRUSTED"


def promote_fact(fact: SemanticFact, episodes: dict[str, Episode]) -> None:
    verdict = verify_fact(fact, episodes)
    if verdict != "TRUSTED":
        raise ProvenanceLaunderingError(
            f"refusing to promote {fact.fact_id}: verdict={verdict}, "
            f"support={fact.supporting_episode_ids}, "
            f"declared_confidence={fact.confidence}"
        )
