# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-resurrection-of-erased-episodic-memory-across-agent-checkpoint-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-resurrection-of-erased-episodic-memory-across-agent-checkpoint-replay.warrant.json
# Markdown SHA-256:   a6877e611710faea8c187cb6c650618feaf4cf138ace6f38c7953570968cdbdf
# Code AST SHA-256:   c9ffc3a5e238c0656839c0069b08b23fa675dde92f173db5716bced3ed88a027
# Verified Classes:   ErasureResurrectionError, DerivedArtifact, ErasureGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ErasureResurrectionError(RuntimeError):
    """Raised when a write or replay would re-materialize tombstoned content."""
    pass


@dataclass
class DerivedArtifact:
    artifact_id: str
    provenance: frozenset[str]  # source episode IDs feeding this artifact


class ErasureGuard:
    """Tombstone set + provenance gate enforcing cascade erasure."""

    def __init__(self) -> None:
        self._tombstones: set[str] = set()

    def tombstone(self, episode_ids: Iterable[str]) -> None:
        self._tombstones.update(episode_ids)

    def _closure_hits(self, provenance: frozenset[str]) -> frozenset[str]:
        return provenance & self._tombstones

    def admit_write(self, artifact: DerivedArtifact) -> None:
        # Gate evaluated at WRITE time, not request time.
        hits = self._closure_hits(artifact.provenance)
        if hits:
            raise ErasureResurrectionError(
                f"artifact {artifact.artifact_id} would resurrect tombstoned "
                f"episodes {sorted(hits)}; drop or re-derive without them"
            )

    def admit_replay(self, checkpoint: DerivedArtifact,
                     live_tombstones: frozenset[str]) -> None:
        # Replay uses LIVE tombstones, never the checkpoint's stale set.
        hits = checkpoint.provenance & live_tombstones
        if hits:
            raise ErasureResurrectionError(
                f"checkpoint {checkpoint.artifact_id} replays tombstoned "
                f"episodes {sorted(hits)}; resume must scrub provenance first"
            )


def consolidate(guard: ErasureGuard, buffer: list[str],
                distilled: DerivedArtifact) -> None:
    # Consolidation read the buffer before erasure; the write gate is the
    # only thing standing between success and silent resurrection.
    guard.admit_write(distilled)
    # ... persist distilled fact ...
