# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-decay-driven-semantic-promotion-from-resurrecting-forgotten-episodic-residue.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-decay-driven-semantic-promotion-from-resurrecting-forgotten-episodic-residue.warrant.json
# Markdown SHA-256:   6527a404d1573f99c905af0d396ba740b194077b640b556bdb665935768e0f12
# Code AST SHA-256:   cc92c6e1acf84e611e6dd7a956f9bea5e87d0691c084095101e9fdb07d7a3742
# Verified Classes:   ForgetInvariantViolation, Liveness, EpisodicRecord, SemanticFact, ScopedMemory
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ForgetInvariantViolation(RuntimeError):
    """Raised when a memory operation would resurrect or launder forgotten state."""


class Liveness(Enum):
    LIVE = "live"
    FORGOTTEN = "forgotten"
    EVICTED = "evicted"


@dataclass
class EpisodicRecord:
    id: str
    payload: str
    recency: float = 1.0
    liveness: Liveness = Liveness.LIVE


@dataclass
class SemanticFact:
    id: str
    text: str
    source_ids: list[str] = field(default_factory=list)
    liveness: Liveness = Liveness.LIVE


class ScopedMemory:
    def __init__(self, theta: float = 0.3):
        self.episodic: dict[str, EpisodicRecord] = {}
        self.semantic: dict[str, SemanticFact] = {}
        self.theta = theta

    def write_episodic(self, rec_id: str, payload: str) -> None:
        self.episodic[rec_id] = EpisodicRecord(id=rec_id, payload=payload)

    def forget(self, rec_id: str) -> None:
        rec = self.episodic.get(rec_id)
        if rec is None:
            raise ForgetInvariantViolation(f"forget on unknown record {rec_id}")
        # Terminal transition; recency pinned to floor, never raised again.
        rec.liveness = Liveness.FORGOTTEN
        rec.recency = 0.0

    def read(self, rec_id: str) -> EpisodicRecord:
        rec = self.episodic.get(rec_id)
        if rec is None:
            raise ForgetInvariantViolation(f"read on unknown record {rec_id}")
        if rec.liveness is Liveness.FORGOTTEN:
            # Tombstone: do NOT touch recency. Return an explicit marker.
            return EpisodicRecord(id=rec.id, payload="<forgotten>",
                                  recency=0.0, liveness=Liveness.FORGOTTEN)
        # Guarded recency refresh: only live records may be touched.
        if rec.liveness is Liveness.LIVE:
            rec.recency = 1.0
        return rec

    def distill(self) -> list[SemanticFact]:
        written = []
        for rec in self.episodic.values():
            if rec.liveness is not Liveness.LIVE:
                continue  # liveness predicate, not score-only
            if rec.recency < self.theta:
                continue
            fact = SemanticFact(
                id=f"sem_{rec.id}",
                text=f"derived from {rec.id}",
                source_ids=[rec.id],
            )
            self.semantic[fact.id] = fact
            written.append(fact)
        return written

    def refresh_semantic(self) -> None:
        # Cascade re-validation on every decay tick.
        for fact in self.semantic.values():
            if fact.liveness is not Liveness.LIVE:
                continue
            for sid in fact.source_ids:
                src = self.episodic.get(sid)
                if src is None or src.liveness is Liveness.FORGOTTEN:
                    fact.liveness = Liveness.FORGOTTEN
                    break

    def recall(self, fact_id: str) -> SemanticFact:
        fact = self.semantic.get(fact_id)
        if fact is None:
            raise ForgetInvariantViolation(f"recall on unknown fact {fact_id}")
        if fact.liveness is Liveness.FORGOTTEN:
            raise ForgetInvariantViolation(
                f"semantic fact {fact_id} laundered forgotten episodic source"
            )
        return fact


def demonstrate_resurrection_guard() -> None:
    mem = ScopedMemory(theta=0.3)
    mem.write_episodic("ep_4412", "user's previous address is 14 Rue ...")
    mem.forget("ep_4412")

    # A backfill/touch path attempts to read the forgotten record.
    tomb = mem.read("ep_4412")
    if tomb.liveness is not Liveness.FORGOTTEN:
        raise ForgetInvariantViolation("read resurrected a forgotten record")

    # Distillation must skip it entirely.
    if mem.distill():
        raise ForgetInvariantViolation("distillation promoted forgotten residue")

    # Pre-existing fact whose source is now forgotten must cascade on refresh.
    mem.semantic["sem_9001"] = SemanticFact(
        id="sem_9001", text="user's previous address is 14 Rue ...",
        source_ids=["ep_4412"],
    )
    mem.refresh_semantic()
    try:
        mem.recall("sem_9001")
    except ForgetInvariantViolation:
        return  # expected: cascade caught the launder
    raise ForgetInvariantViolation("cascade failed to forget derived fact")
