# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-forget-as-a-tombstone-rather-than-a-deletion-and-when-does-downstream-re-derivation-silentl.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-memory-tool-forget-as-a-tombstone-rather-than-a-deletion-and-when-does-downstream-re-derivation-silentl.warrant.json
# Markdown SHA-256:   6a84ce71b219f0498c769c01de2d1e1c39ab8eee2fdb57f239007586241f2c2d
# Code AST SHA-256:   1b20462490cf7715960c6869b687fb2d63fbdfb6895b663e751d9bf33f9baa4f
# Verified Classes:   ResurrectionError, Tombstone, MemoryStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ResurrectionError(RuntimeError):
    """Raised when a write would re-derive a tombstoned fact into a live key."""
    pass


@dataclass
class Tombstone:
    key: str
    fingerprint: str          # normalized-content hash of the forgotten record
    derived_ids: set[str] = field(default_factory=set)
    rederive_forbidden: bool = True


def fingerprint(text: str) -> str:
    norm = " ".join(text.lower().split())
    return hashlib.sha256(norm.encode()).hexdigest()


class MemoryStore:
    def __init__(self):
        self.live: dict[str, str] = {}
        self.tombstones: dict[str, Tombstone] = {}  # fingerprint -> tombstone

    def forget(self, key: str, content: str) -> Tombstone:
        fp = fingerprint(content)
        ts = Tombstone(key=key, fingerprint=fp)
        self.tombstones[fp] = ts
        self.live.pop(key, None)
        return ts

    def write_derived(self, new_key: str, content: str, source_fingerprints: list[str]) -> None:
        # Guardrail: refuse to mint a live key from tombstoned lineage.
        for src_fp in source_fingerprints:
            ts = self.tombstones.get(src_fp)
            if ts is not None and ts.rederive_forbidden:
                raise ResurrectionError(
                    f"write '{new_key}' derives from tombstoned fingerprint "
                    f"{src_fp[:12]} (forgotten key '{ts.key}'); "
                    f"resurrection blocked — re-assert tombstone or drop content"
                )
        self.live[new_key] = content

    def retrieve(self, query_fp: str) -> str | None:
        # Tombstone-aware retrieval: suppress exact and neighbor hits.
        if query_fp in self.tombstones:
            return None
        return self.live.get(query_fp)


def consolidate_session_digest(store: MemoryStore, digest_line: str, digest_source_fp: str) -> None:
    """A routine consolidation pass — the exact place resurrection happens."""
    store.write_derived(
        new_key=f"semantic:{fingerprint(digest_line)[:8]}",
        content=digest_line,
        source_fingerprints=[digest_source_fp],
    )
