# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-retained-memory-resurrection-after-a-scoped-forget-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-retained-memory-resurrection-after-a-scoped-forget-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   c3fcf94b1409335f92e33879bded43fd3c83f0dc0c7cba261fdd492f3f545e21
# Code AST SHA-256:   d982f311daae98ee9708914a13e304a5d912326c98e0ef2d4b83b7aa856db494
# Verified Classes:   ResurrectedMemoryError, UnenforceableForgetError, Tombstone, DerivedArtifact, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResurrectedMemoryError(RuntimeError):
    """Raised when recall surfaces content whose source was erased."""
    pass


class UnenforceableForgetError(RuntimeError):
    """Raised when a forget is requested for a scope whose derived
    artifacts cannot be traced back to source keys."""
    pass


@dataclass
class Tombstone:
    key: str
    epoch: int


@dataclass
class DerivedArtifact:
    content: str
    derived_from: list[str] = field(default_factory=list)  # provenance closure
    epoch: int = 0


class MemoryStore:
    def __init__(self) -> None:
        self._tombstones: dict[str, int] = {}
        self._artifacts: list[DerivedArtifact] = []
        self._epoch = 0

    def remember(self, key: str, content: str) -> None:
        self._epoch += 1
        self._artifacts.append(
            DerivedArtifact(content=content, derived_from=[key], epoch=self._epoch)
        )

    def forget(self, key: str) -> int:
        # Refuse forgets we cannot enforce: any artifact lacking provenance
        # that might carry this key makes scoped erasure unprovable.
        for art in self._artifacts:
            if key in art.content and not art.derived_from:
                raise UnenforceableForgetError(
                    f"cannot erase {key!r}: artifact {art.content!r} has no provenance"
                )
        self._epoch += 1
        self._tombstones[key] = self._epoch
        return self._epoch  # pending_erasure handle

    def recall(self, query: str, *, require_epoch: Optional[int] = None) -> list[str]:
        hits = [a for a in self._artifacts if query in a.content]
        for art in hits:
            erased = [k for k in art.derived_from if k in self._tombstones]
            if erased:
                # Read-path suppression: a resurrected derived claim whose
                # source is tombstoned must never be returned as evidence.
                if require_epoch is not None and art.epoch <= self._tombstones[erased[0]]:
                    raise ResurrectedMemoryError(
                        f"recall hit {art.content!r} derives from erased key(s) {erased}"
                    )
                continue
        return [a.content for a in hits if not any(k in self._tombstones for k in a.derived_from)]
