# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-store-consistency-checks-from-ratifying-poisoned-episodic-memory-into-semantic-recall.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-store-consistency-checks-from-ratifying-poisoned-episodic-memory-into-semantic-recall.warrant.json
# Markdown SHA-256:   3a6b491da9513efb2f6eb7c306200412e66a0cb57cf4f9f3d2165d2a60efc3d3
# Code AST SHA-256:   3c601ea55779a2cd68eb4e3c4473ea028867e01e6fa3b64fe899b3cc152d573c
# Verified Classes:   CorroborationCollapse, Episode, Fact
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CorroborationCollapse(RuntimeError):
    """Raised when a consistency check would promote a fact whose support
    episodes are not provenance-independent (co-derived or self-reinforcing)."""
    pass


@dataclass
class Episode:
    turn_id: int
    source_uri: str
    context_fact_ids: frozenset[str] = frozenset()


@dataclass
class Fact:
    fact_id: str
    text: str
    support_episode_ids: list[int] = field(default_factory=list)
    trust_score: float = 0.0


PROMOTE_THRESHOLD = 0.85
INTERNAL_NS = "internal://"


def _is_context_dependent(ep: Episode, fact: Fact, derived: dict[str, set[int]]) -> bool:
    # Direct: fact was in the episode's context window.
    if fact.fact_id in ep.context_fact_ids:
        return True
    # Transitive: episode's context held a fact derived from this fact.
    for other_id in ep.context_fact_ids:
        if ep.turn_id in derived.get(other_id, set()) and fact.fact_id in derived:
            return True
    return False


def independent_source_count(fact: Fact, episodes: dict[int, Episode],
                             derived: dict[str, set[int]]) -> int:
    sources: set[str] = set()
    for eid in fact.support_episode_ids:
        ep = episodes[eid]
        if ep.source_uri.startswith(INTERNAL_NS):
            continue  # agent's own trace: never independent
        if _is_context_dependent(ep, fact, derived):
            continue  # self-reinforcement loop
        sources.add(ep.source_uri)
    return len(sources)


def check_and_promote(fact: Fact, episodes: dict[int, Episode],
                      derived: dict[str, set[int]],
                      proposed_trust: float) -> Fact:
    indep = independent_source_count(fact, episodes, derived)
    if proposed_trust < PROMOTE_THRESHOLD:
        fact.trust_score = proposed_trust
        return fact
    if indep < 2:
        raise CorroborationCollapse(
            f"fact {fact.fact_id!r} has support cardinality "
            f"{len(fact.support_episode_ids)} but only {indep} independent "
            f"source(s); restatements are not corroboration. Quarantining."
        )
    fact.trust_score = proposed_trust
    return fact
