# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distinguish-a-forgotten-memory-from-a-never-stored-one-the-tombstone-collapse-boundary-in-forgetting-curve-garbage-collection.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distinguish-a-forgotten-memory-from-a-never-stored-one-the-tombstone-collapse-boundary-in-forgetting-curve-garbage-collection.warrant.json
# Markdown SHA-256:   2bebf36c4faede7f98661e4bd1a575414d085937b95ded9fac47694c73d49d4e
# Code AST SHA-256:   1c31f189646e6a29b87aedb72329c6a34d7bae68b21b692160f7a8b8b39cc781
# Verified Classes:   MemoryState, TombstoneCollapseError, Recall, DecayStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class MemoryState(Enum):
    PRESENT = "present"
    FORGOTTEN = "forgotten"
    ABSENT = "absent"


class TombstoneCollapseError(RuntimeError):
    """Raised when a retrieval collapses FORGOTTEN and ABSENT into one result,
    destroying the agent's ability to distinguish amnesia from ignorance."""


@dataclass
class Recall:
    state: MemoryState
    key: str
    payload: Optional[str] = None
    evicted_at: Optional[float] = None


class DecayStore:
    def __init__(self, half_life: float, evict_eps: float, reconcile_window: float):
        self.tau = half_life
        self.eps = evict_eps
        self.window = reconcile_window
        self.live: dict[str, tuple[str, float]] = {}      # key -> (payload, stored_at)
        self.tombstones: dict[str, float] = {}            # key -> evicted_at

    def store(self, key: str, payload: str, now: float) -> None:
        self.live[key] = (payload, now)
        self.tombstones.pop(key, None)

    def _retention(self, stored_at: float, now: float) -> float:
        import math
        return math.exp(-(now - stored_at) / self.tau)

    def retrieve(self, key: str, now: float) -> Recall:
        if key in self.live:
            payload, stored_at = self.live[key]
            if self._retention(stored_at, now) >= self.eps:
                return Recall(MemoryState.PRESENT, key, payload)
            # decayed: evict to tombstone, do NOT drop to ABSENT
            del self.live[key]
            self.tombstones[key] = now

        if key in self.tombstones:
            evicted_at = self.tombstones[key]
            if now - evicted_at <= self.window:
                return Recall(MemoryState.FORGOTTEN, key, evicted_at=evicted_at)
            del self.tombstones[key]  # reconcile window elapsed -> now truly ABSENT

        return Recall(MemoryState.ABSENT, key)

    def policy_branch(self, recall: Recall) -> str:
        if recall.state is MemoryState.FORGOTTEN:
            raise TombstoneCollapseError(
                f"key {recall.key!r} was evicted at {recall.evicted_at} but is being "
                f"treated as never-stored; re-derivation would silently overwrite "
                f"a decayed load-bearing memory"
            )
        if recall.state is MemoryState.ABSENT:
            return "acquire"
        return "use"
