# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-when-episodic-and-semantic-stores-disagree-under-consistency-audit.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-when-episodic-and-semantic-stores-disagree-under-consistency-audit.warrant.json
# Markdown SHA-256:   97b4fa9feb13de5fd3afc02413527b93b010d6fa4eb0157ce2da55256919e6e2
# Code AST SHA-256:   dacbee7027fae174c1a6bd8d94811e9fc3c7b9c06dfeaee2fd4ffdca1c2663ad
# Verified Classes:   MemoryPoisoningError, Modality, EpisodicRecord, SemanticBelief
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import IntEnum


class MemoryPoisoningError(RuntimeError):
    """Raised when a semantic belief escalates claim strength while
    suppressing the episodic evidence that contradicts it."""
    pass


class Modality(IntEnum):
    HYPOTHETICAL = 0
    REPORTED = 1
    INFERRED = 2
    ASSERTED = 3


@dataclass
class EpisodicRecord:
    rec_id: str
    content: str
    superseded_by: str | None = None

    def digest(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()


@dataclass
class SemanticBelief:
    belief_id: str
    claim: str
    modality: Modality
    derived_from: list[str] = field(default_factory=list)


def audit_belief(
    belief: SemanticBelief,
    episodic: dict[str, EpisodicRecord],
    rederived_modality: Modality,
) -> None:
    # 1. Provenance must resolve to surviving, content-addressed records.
    missing = [r for r in belief.derived_from if r not in episodic]
    if missing:
        raise MemoryPoisoningError(
            f"belief {belief.belief_id} cites nonexistent episodic records {missing}"
        )

    # 2. Modality escalation: stored belief asserts more than evidence licenses.
    escalated = belief.modality > rederived_modality

    # 3. Provenance cut: supporting evidence suppressed by a belief that
    #    itself lacks independent grounding (self-referential suppression).
    suppressed = [
        r for r in belief.derived_from
        if episodic[r].superseded_by is not None
        and episodic[r].superseded_by in belief.derived_from
    ]

    if escalated and suppressed:
        raise MemoryPoisoningError(
            f"belief {belief.belief_id} escalated "
            f"{rederived_modality.name}->{belief.modality.name} while "
            f"self-referentially suppressing {suppressed}"
        )
    # Escalation alone = drift (log only); suppression alone = retention policy.
