# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-forget-tool-compliance-is-unverifiable-the-tombstones-vs-absence-ambiguity-in-agent-memory-privacy-auditing.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-forget-tool-compliance-is-unverifiable-the-tombstones-vs-absence-ambiguity-in-agent-memory-privacy-auditing.warrant.json
# Markdown SHA-256:   48e37bf8b0f132c4ccdba644bd568952c60075acfd6b50461d337dc94f016e34
# Code AST SHA-256:   a0695a70c000bfa2f8388a7ac7e4c2a10f777688188e66fc4dc51b50440f9d26
# Verified Classes:   ForgetComplianceError, MemoryRecord, MemoryStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ForgetComplianceError(RuntimeError):
    """Raised when a forget operation's erase cannot be verified as complete."""


@dataclass
class MemoryRecord:
    key: str
    value: str
    source_episode: Optional[str] = None
    tombstoned: bool = False


@dataclass
class MemoryStore:
    records: dict = field(default_factory=dict)
    deleted_episodes: set = field(default_factory=set)

    def add(self, rec: MemoryRecord) -> None:
        self.records[rec.key] = rec

    def recall(self, query: str) -> list:
        # Naive retrieval: substring match over live (non-tombstoned) keys/values.
        hits = []
        for rec in self.records.values():
            if rec.tombstoned:
                continue
            if query.lower() in rec.key.lower() or query.lower() in rec.value.lower():
                hits.append(rec)
        return hits

    def forget(self, subject: str) -> None:
        # Soft delete: only keys literally containing the subject are tombstoned.
        for rec in self.records.values():
            if subject.lower() in rec.key.lower():
                rec.tombstoned = True
                if rec.source_episode:
                    self.deleted_episodes.add(rec.source_episode)


def audit_forget(store: MemoryStore, subject: str, reconstruction_probes: list) -> None:
    """Fail closed if any reconstruction probe resolves state whose provenance
    terminates in a deleted episode, or resolves the subject without naming it."""
    store.forget(subject)

    for probe in reconstruction_probes:
        for rec in store.recall(probe):
            if rec.source_episode and rec.source_episode in store.deleted_episodes:
                raise ForgetComplianceError(
                    f"Reconstruction probe {probe!r} resolved record {rec.key!r} "
                    f"whose source episode {rec.source_episode!r} is deleted; "
                    f"erase is unverifiable (derived artifact outlived source)."
                )
            if subject.lower() not in probe.lower() and subject.lower() in rec.value.lower():
                raise ForgetComplianceError(
                    f"Reconstruction probe {probe!r} reached subject {subject!r} "
                    f"via derived key {rec.key!r}; named-subject suppression bypassed."
                )


if __name__ == "__main__":
    store = MemoryStore()
    store.add(MemoryRecord("person:alice_chen", "Alice Chen", source_episode="ep1"))
    store.add(
        MemoryRecord(
            "office_berlin_manager",
            "alice.chen@example.com",
            source_episode="ep1",  # distilled from the same episode
        )
    )
    try:
        audit_forget(
            store,
            "Alice Chen",
            reconstruction_probes=["manages the Berlin office", "who manages Berlin"],
        )
    except ForgetComplianceError as exc:
        print(f"AUDIT FAILED: {exc}")
