# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-its-episodic-and-semantic-stores-disagree-but-both-are-internally-consistent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-memory-poisoning-when-its-episodic-and-semantic-stores-disagree-but-both-are-internally-consistent.warrant.json
# Markdown SHA-256:   b51354a108852b2c974452edf02ee71487f6208f5c72f4ac7fa9d31fdc77cfe2
# Code AST SHA-256:   726a29fc3c36ed4dbb895de5ff4d19fef2004c85d95f17ad150d7e2ab0a595b5
# Verified Classes:   PoisoningAuditError, SourceClass, Episode, SemanticFact, ProvenanceAuditor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Set


class PoisoningAuditError(RuntimeError):
    """Raised when the derivation graph is structurally unsound (not merely lossy)."""


class SourceClass(Enum):
    USER_INPUT = "user_input"
    TOOL_OUTPUT = "tool_output"
    AGENT_ACTION = "agent_action"
    DISTILLATION_SUMMARY = "distillation_summary"


@dataclass(frozen=True)
class Episode:
    eid: str
    source: SourceClass
    cites_facts: Set[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class SemanticFact:
    fid: str
    derived_from: Set[str]  # episode ids
    content_hash: str


class ProvenanceAuditor:
    def __init__(self, episodes: Dict[str, Episode], facts: Dict[str, SemanticFact]):
        self.episodes = episodes
        self.facts = facts

    def _fact_closure(self, fid: str, seen: Set[str]) -> Set[str]:
        # Walk fact -> episodes -> facts-cited-by-those-episodes, detect back-edges.
        if fid in seen:
            raise PoisoningAuditError(
                f"Derivation cycle through episodic store at fact {fid!r}: "
                f"a semantic fact is corroborated only by its own output."
            )
        seen = seen | {fid}
        fact = self.facts[fid]
        if not fact.derived_from:
            raise PoisoningAuditError(f"Fact {fid!r} has no derivation (unsupported).")
        reached: Set[str] = set()
        for eid in fact.derived_from:
            ep = self.episodes.get(eid)
            if ep is None:
                raise PoisoningAuditError(f"Fact {fid!r} cites missing episode {eid!r}.")
            if ep.cites_facts:
                # This episode was generated while citing facts -> not independent evidence.
                for cited in ep.cites_facts:
                    reached |= self._fact_closure(cited, seen)
        return reached

    def audit(self) -> None:
        for fid in self.facts:
            self._fact_closure(fid, set())
            # Independence check: at least one non-agent_action supporter.
            supporters = [self.episodes[e].source for e in self.facts[fid].derived_from]
            if all(s == SourceClass.AGENT_ACTION for s in supporters):
                raise PoisoningAuditError(
                    f"Fact {fid!r} supported only by agent_action episodes "
                    f"(self-corroboration laundering)."
                )


def run_nightly_audit(episodes, facts) -> None:
    auditor = ProvenanceAuditor(episodes, facts)
    try:
        auditor.audit()
    except PoisoningAuditError:
        # Hard fail: evict and re-derive descendants; do NOT silently pass.
        raise
