# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-scoped-forget-has-silently-orphaned-a-derived-memory-index-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-scoped-forget-has-silently-orphaned-a-derived-memory-index-entry.warrant.json
# Markdown SHA-256:   bc4a7b8299acd74aba4d1c46c006634f13d72d3ed184fb465d467b5a043477d0
# Code AST SHA-256:   e920dd4e0ee375eb8cdba761069a5556899c3e5a13dc544bf89d5e2f29cf4259
# Verified Classes:   RetentionViolation, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class RetentionViolation(RuntimeError):
    """Raised when a scoped forget() leaves causally-derived artifacts live."""


@dataclass
class MemoryStore:
    # canonical records: scope -> {record_id: text}
    records: dict[str, dict[str, str]] = field(default_factory=dict)
    # derived artifacts: namespace -> {artifact_id: {"source_scope": str, "cites": [ids]}}
    derived: dict[str, dict[str, dict]] = field(default_factory=dict)

    def write(self, scope: str, record_id: str, text: str) -> None:
        self.records.setdefault(scope, {})[record_id] = text

    def write_derived(self, namespace: str, artifact_id: str,
                      source_scope: str, cites: Iterable[str]) -> None:
        self.derived.setdefault(namespace, {})[artifact_id] = {
            "source_scope": source_scope,
            "cites": list(cites),
        }

    def forget(self, scope: str, *, require_clean_closure: bool = True) -> int:
        """Forget a scope. Refuses to report success if derivation closure is non-empty."""
        tombstones = len(self.records.pop(scope, {}))

        # Reverse-traverse the derivation closure. This is the invariant check.
        orphans: list[tuple[str, str]] = []
        for ns, artifacts in self.derived.items():
            for aid, meta in artifacts.items():
                if meta["source_scope"] == scope:
                    orphans.append((ns, aid))
                elif any(cid not in self.records.get(scope, {})
                         for cid in meta["cites"]
                         if meta["source_scope"] == scope):
                    orphans.append((ns, aid))

        if require_clean_closure and orphans:
            # Do NOT report success. The caller must scrub or re-derive.
            raise RetentionViolation(
                f"forget({scope!r}) tombstoned {tombstones} canonical records "
                f"but {len(orphans)} derived artifacts remain live: {orphans[:5]}"
                f"{'...' if len(orphans) > 5 else ''}. "
                f"Derivation closure is non-empty; retention invariant D(S) ∩ Live = ∅ violated."
            )
        return tombstones

    def probe_derived(self, scope: str) -> list[tuple[str, str]]:
        """Explicit probe for agents whose tool layer lacks closure enforcement."""
        return [(ns, aid) for ns, arts in self.derived.items()
                for aid, m in arts.items() if m["source_scope"] == scope]


def safe_forget(store: MemoryStore, scope: str) -> int:
    """Agent-side wrapper: probe before trusting, escalate on violation."""
    tombstones = store.forget(scope, require_clean_closure=False)
    leaks = store.probe_derived(scope)
    if leaks:
        raise RetentionViolation(
            f"scoped forget({scope!r}) returned {tombstones} tombstones but "
            f"probe found {len(leaks)} live derived artifacts: {leaks}. "
            f"Escalate to full derived-store scrub; do not proceed."
        )
    return tombstones
