# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scoped-retention-memory-tools-from-resurrecting-forgotten-records-through-derived-summaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scoped-retention-memory-tools-from-resurrecting-forgotten-records-through-derived-summaries.warrant.json
# Markdown SHA-256:   c80ef8e16c016eb4bbaa038c3cb266a704c3df2244125ac4d4a2d583b37434ee
# Code AST SHA-256:   f19d54b6fdd9774f369449602177cfe83e910147aafdd301c9bc981283c275cf
# Verified Classes:   ErasureInvariantError, RetentionEvent, Artifact, MemoryStore
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Set


class ErasureInvariantError(RuntimeError):
    """Raised when a forget() call leaves a live descendant of an erased source."""


class RetentionEvent(Enum):
    EXPIRE = "expire"   # stale, not prohibited: descendants remain valid
    FORGET = "forget"   # prohibited: descendants must be invalidated


@dataclass
class Artifact:
    artifact_id: str
    scope: str
    subject: str
    content: str
    derived_from: List[str] = field(default_factory=list)  # ancestor artifact_ids


class MemoryStore:
    def __init__(self) -> None:
        self._artifacts: Dict[str, Artifact] = {}
        self._tombstones: Set[str] = set()
        self._provenance_complete: bool = True  # set False if any derived_from is partial

    def write(self, art: Artifact) -> None:
        self._artifacts[art.artifact_id] = art

    def _descendants(self, root_id: str) -> Set[str]:
        out: Set[str] = set()
        frontier = [root_id]
        while frontier:
            cur = frontier.pop()
            for aid, art in self._artifacts.items():
                if cur in art.derived_from and aid not in out:
                    out.add(aid)
                    frontier.append(aid)
        return out

    def forget(self, scope: str, subject: str, *, conservative_ok: bool = True) -> Dict[str, object]:
        roots = [
            a.artifact_id
            for a in self._artifacts.values()
            if a.scope == scope and a.subject == subject
        ]
        if not roots:
            return {"erased": 0, "conservative": False, "scopes": [scope]}

        if self._provenance_complete:
            to_erase: Set[str] = set(roots)
            for r in roots:
                to_erase |= self._descendants(r)
            conservative = False
        else:
            if not conservative_ok:
                raise ErasureInvariantError(
                    "incomplete provenance: exact transitive erasure impossible; "
                    "refusing predicate-only deletion on RTBF request"
                )
            to_erase = {a.artifact_id for a in self._artifacts.values() if a.scope == scope}
            conservative = True

        for aid in to_erase:
            self._artifacts.pop(aid, None)
            self._tombstones.add(aid)

        # Post-condition: no live artifact may have an erased ancestor.
        for art in self._artifacts.values():
            if any(anc in self._tombstones for anc in art.derived_from):
                raise ErasureInvariantError(
                    f"artifact {art.artifact_id} still reachable from erased source; "
                    f"tombstone set incomplete"
                )

        return {"erased": len(to_erase), "conservative": conservative, "scopes": [scope]}

    def read(self, artifact_id: str) -> str:
        if artifact_id in self._tombstones:
            raise ErasureInvariantError(
                f"read of erased artifact {artifact_id} blocked by tombstone"
            )
        art = self._artifacts.get(artifact_id)
        if art is None:
            raise ErasureInvariantError(f"artifact {artifact_id} not present")
        if any(anc in self._tombstones for anc in art.derived_from):
            raise ErasureInvariantError(
                f"artifact {artifact_id} has erased ancestor; read blocked"
            )
        return art.content


def run_erasure_scenario() -> None:
    store = MemoryStore()
    store.write(Artifact("e1", "episodic", "alice", "alice prefers async standups"))
    store.write(Artifact("s1", "semantic", "alice", "alice prefers async",
                         derived_from=["e1"]))
    # Context-derived artifact: subject is NOT alice, but ancestry is e1.
    store.write(Artifact("s2", "semantic", "team-lead", "team lead schedules morning syncs",
                         derived_from=["e1"]))

    result = store.forget("episodic", "alice")
    assert result["conservative"] is False
    # s2 must be gone too, because it is a descendant of e1.
    try:
        store.read("s2")
    except ErasureInvariantError:
        pass
    else:
        raise ErasureInvariantError("resurrection: s2 survived erasure of its ancestor e1")


if __name__ == "__main__":
    run_erasure_scenario()
