# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-key-it-never-wrote-tombstone-resurrection-across-scoped-memory-ttls.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-key-it-never-wrote-tombstone-resurrection-across-scoped-memory-ttls.warrant.json
# Markdown SHA-256:   ca0be31f07958c92c39febe7ea66564d829c1c01b07491462eb78b54c69114c1
# Code AST SHA-256:   9b1d599426988b01578f25893828ed27f934b6355c9473f26d8a57fa4b9c5ca9
# Verified Classes:   ResurrectionAttempt, ReadStatus, ReadResult, ScopedMemory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ResurrectionAttempt(RuntimeError):
    """Raised when an agent tries to write a key that carries a hard tombstone."""
    pass


class ReadStatus(Enum):
    FOUND = "found"
    NEVER_WRITTEN = "never_written"
    EXPIRED = "expired"
    TOMBSTONED = "tombstoned"


@dataclass
class ReadResult:
    status: ReadStatus
    value: object = None
    forgotten_at: float = None
    guarantee: str = None


class ScopedMemory:
    def __init__(self):
        self._values = {}
        self._tombstones = {}  # (scope, key) -> (forgotten_at, guarantee)

    def read(self, scope, key):
        tomb = self._tombstones.get((scope, key))
        if tomb is not None:
            return ReadResult(ReadStatus.TOMBSTONED, forgotten_at=tomb[0], guarantee=tomb[1])
        if (scope, key) in self._values:
            return ReadResult(ReadStatus.FOUND, value=self._values[(scope, key)])
        return ReadResult(ReadStatus.NEVER_WRITTEN)

    def forget(self, scope, key, guarantee="hard", now=0.0):
        self._values.pop((scope, key), None)
        self._tombstones[(scope, key)] = (now, guarantee)

    def write(self, scope, key, value, now=0.0):
        tomb = self._tombstones.get((scope, key))
        if tomb is not None and tomb[1] == "hard":
            raise ResurrectionAttempt(
                f"refusing write to hard-tombstoned key {scope}/{key} "
                f"(forgotten_at={tomb[0]}); re-derivation is forbidden"
            )
        self._values[(scope, key)] = value


def safe_hydrate(memory, scope, key, hydrate_fn, now=0.0):
    """Only re-derive and write when the key was provably never written."""
    result = memory.read(scope, key)
    if result.status is ReadStatus.NEVER_WRITTEN:
        memory.write(scope, key, hydrate_fn(), now=now)
        return
    if result.status is ReadStatus.TOMBSTONED:
        # fail closed: do not call hydrate_fn, do not write
        raise ResurrectionAttempt(
            f"hydrate blocked: {scope}/{key} is tombstoned "
            f"(guarantee={result.guarantee}, forgotten_at={result.forgotten_at})"
        )
    # FOUND or EXPIRED: caller decides; do not silently overwrite
    return
