# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-retention-scope-resurrection-during-right-to-be-forgotten-erasure-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-retention-scope-resurrection-during-right-to-be-forgotten-erasure-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   10c94f96085033121a46507de8045ae8ab664df20035a9b3ae363686c521e238
# Code AST SHA-256:   8125a0759e7855515916c4bfa110a762c7a86619b97f26fbb068efeb341e2524
# Verified Classes:   ErasureResurrectionError, TombstonedWriteError, Record, ScopedMemory
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ErasureResurrectionError(RuntimeError):
    """Raised when a read would emit a record whose lineage contains a tombstone."""


class TombstonedWriteError(RuntimeError):
    """Raised when a write's content fingerprint collides with an erased record."""


@dataclass
class Record:
    record_id: str
    scope: str
    payload: str
    parents: list[str] = field(default_factory=list)

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


class ScopedMemory:
    def __init__(self) -> None:
        self._records: dict[str, Record] = {}
        self._tombstoned_ids: set[str] = set()
        self._tombstoned_fingerprints: set[str] = set()

    def write(self, rec: Record) -> None:
        if rec.fingerprint() in self._tombstoned_fingerprints:
            raise TombstonedWriteError(
                f"write of {rec.record_id} collides with erased fingerprint"
            )
        self._records[rec.record_id] = rec

    def forget(self, record_id: str) -> None:
        rec = self._records.get(record_id)
        if rec is None:
            return
        self._tombstoned_ids.add(record_id)
        self._tombstoned_fingerprints.add(rec.fingerprint())

    def _ancestors(self, record_id: str, seen: set[str]) -> set[str]:
        if record_id in seen:
            return set()
        seen.add(record_id)
        rec = self._records.get(record_id)
        if rec is None:
            return {record_id}
        out = set(rec.parents)
        for p in rec.parents:
            out |= self._ancestors(p, seen)
        return out

    def read(self, record_id: str, query_scope: str) -> Record:
        rec = self._records.get(record_id)
        if rec is None:
            raise ErasureResurrectionError(f"{record_id} not present")
        lineage = {record_id} | self._ancestors(record_id, set())
        if lineage & self._tombstoned_ids:
            raise ErasureResurrectionError(
                f"read of {record_id} blocked: tombstoned ancestor in lineage"
            )
        if rec.fingerprint() in self._tombstoned_fingerprints:
            raise ErasureResurrectionError(
                f"read of {record_id} blocked: fingerprint matches erased content"
            )
        if not self._scope_allows(query_scope, rec.scope):
            raise ErasureResurrectionError(
                f"scope {query_scope} cannot read {rec.scope}"
            )
        return rec

    @staticmethod
    def _scope_allows(query_scope: str, record_scope: str) -> bool:
        return query_scope == "longterm" or query_scope == record_scope


def distill(mem: ScopedMemory, parent_id: str, new_id: str, summary: str) -> None:
    # Distiller must carry lineage so erasure is transitive.
    parent = mem._records.get(parent_id)
    if parent is None:
        raise ErasureResurrectionError(f"cannot distill missing {parent_id}")
    mem.write(Record(new_id, "longterm", summary, parents=[parent_id]))
