# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-deletion-memory-tools-from-resurrecting-erased-state-via-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-deletion-memory-tools-from-resurrecting-erased-state-via-distillation.warrant.json
# Markdown SHA-256:   50d295ddd73627ca1ce9df38ed27a21ace636c2b209ce09d13077c3300072616
# Code AST SHA-256:   1c641ee06f3d751089a34b918a88e58b1b172395bf9b430a6b6c52dac5450ce2
# Verified Classes:   ProvenanceClosureError, Record, MemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field

class ProvenanceClosureError(RuntimeError):
    """Raised when a forget() call cannot guarantee transitive erasure."""

@dataclass
class Record:
    record_id: str
    scope: str
    text: str
    derived_from: frozenset[str] = field(default_factory=frozenset)
    tombstoned: bool = False

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

    def write(self, rec: Record, require_provenance_for: str | None = None) -> None:
        # Guardrail: a derived write into a distillation-fed scope must declare sources.
        if require_provenance_for is not None and not rec.derived_from:
            raise ProvenanceClosureError(
                f"write {rec.record_id!r} into scope {rec.scope!r} has empty "
                f"derived_from; closure invariant is vacuous"
            )
        self._records[rec.record_id] = rec

    def _descendants(self, root: str) -> set[str]:
        out, frontier = {root}, [root]
        while frontier:
            cur = frontier.pop()
            for rid, rec in self._records.items():
                if cur in rec.derived_from and rid not in out:
                    out.add(rid)
                    frontier.append(rid)
        return out

    def forget(self, record_id: str, protected_scopes: set[str]) -> set[str]:
        if record_id not in self._records:
            raise ProvenanceClosureError(f"unknown record {record_id!r}")
        closure = self._descendants(record_id)
        # Conflict: a descendant sits in a scope we may not delete from.
        conflicts = {
            rid for rid in closure
            if self._records[rid].scope in protected_scopes and rid != record_id
        }
        if conflicts:
            raise ProvenanceClosureError(
                f"cannot erase {record_id!r}: live descendants in protected "
                f"scopes {sorted(conflicts)}"
            )
        for rid in closure:
            self._records[rid].tombstoned = True
        return closure

    def consolidation_input(self, scope: str) -> list[Record]:
        # Guardrail: tombstoned records never feed distillation, even if readable.
        return [
            r for r in self._records.values()
            if r.scope == scope and not r.tombstoned
        ]
