# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-during-scoped-retention-erasure-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-during-scoped-retention-erasure-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   c37420ea0d2bef061b29d03d7e45910110e94a4a01d3ff6815447ac7d5b16c88
# Code AST SHA-256:   d0ac4768431c8128f2fb3245aace17a518a24747eb1a80b71e7784b830048f90
# Verified Classes:   ErasureClosureViolation, MemoryRecord, ScopedMemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class ErasureClosureViolation(RuntimeError):
    """Raised when an erasure is reported complete while derived artifacts survive."""


@dataclass
class MemoryRecord:
    id: str
    content: str
    derived_from: list[str] = field(default_factory=list)


class ScopedMemoryStore:
    def __init__(self) -> None:
        self._records: dict[str, MemoryRecord] = {}
        self._tombstones: set[str] = set()
        # reverse index: parent id -> child ids, the derivation DAG edges
        self._children: dict[str, set[str]] = {}

    def write(self, rec: MemoryRecord, *, is_derivation: bool) -> None:
        # Invariant: derivation writes must carry provenance, else unclosable.
        if is_derivation and not rec.derived_from:
            raise ErasureClosureViolation(
                f"derivation write {rec.id!r} has no derived_from; "
                "record would be unclosable under erasure"
            )
        # Commit-time revalidation: refuse to materialize a child of a tombstone.
        for parent in rec.derived_from:
            if parent in self._tombstones:
                raise ErasureClosureViolation(
                    f"refusing to commit {rec.id!r}: parent {parent!r} is tombstoned "
                    "(resurrection window)"
                )
            self._children.setdefault(parent, set()).add(rec.id)
        self._records[rec.id] = rec

    def _closure(self, root: str) -> set[str]:
        seen: set[str] = set()
        stack = [root]
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            stack.extend(self._children.get(cur, ()))
        return seen

    def forget(self, root: str) -> list[str]:
        if root in self._tombstones:
            return [root]  # idempotent
        closure = self._closure(root)
        survivors = [cid for cid in closure if cid in self._records and cid not in self._tombstones
                     and not self._erasable(cid)]
        if survivors:
            # Partial erasure: never report success.
            raise ErasureClosureViolation(
                f"erasure of {root!r} incomplete; surviving closure members: {survivors}"
            )
        for cid in closure:
            self._records.pop(cid, None)
            self._tombstones.add(cid)
        return sorted(closure)

    def _erasable(self, cid: str) -> bool:
        # Immutable audit holds are the only permitted survivors; here we model none.
        return True
