# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-memory-tool-forget-acknowledgment-as-a-proof-of-erasure-rather-than-a-hint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-memory-tool-forget-acknowledgment-as-a-proof-of-erasure-rather-than-a-hint.warrant.json
# Markdown SHA-256:   d8ea676c8634f4e1a1a81b5ed229c41191de0264923b5aa71c61f5387c337404
# Code AST SHA-256:   841df335927cb78d1deaf195f38916432bb7f3208a8bf359f9fdbfb90abb30d8
# Verified Classes:   UnverifiedErasureError, ErasureLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnverifiedErasureError(RuntimeError):
    """Raised when an agent attempts to assert non-observability of a memory
    that has only been acknowledged-forgotten, not probe-verified across all
    scopes and read paths."""
    pass


class ErasureLedger:
    """Tracks forget attempts and their verification state. A memory is only
    'erased' when a post-probe is clean across every probed scope."""

    def __init__(self, memory_tool, probe_scopes, max_attempts=3):
        self.tool = memory_tool
        self.probe_scopes = probe_scopes  # namespaces incl. derived/provenance
        self.max_attempts = max_attempts
        self.verified = set()

    def _probe(self, value, scope):
        # Probe for exact, substring, and semantic-neighbor forms.
        hits = self.tool.recall(scope=scope, query=value, k=10)
        return [h for h in hits if value in repr(h)]

    def forget_and_verify(self, value, primary_scope):
        for attempt in range(self.max_attempts):
            ack = self.tool.forget(scope=primary_scope, value=value)
            if not ack.get("deleted"):
                raise UnverifiedErasureError(
                    f"forget of {value!r} in {primary_scope} not acknowledged: {ack}"
                )
            residual = {}
            for scope in self.probe_scopes:
                hits = self._probe(value, scope)
                if hits:
                    residual[scope] = hits
            if not residual:
                self.verified.add((value, primary_scope))
                return True
            # Expand scope: re-forget in the scopes that still leak.
            primary_scope = list(residual.keys())[0]
        raise UnverifiedErasureError(
            f"erasure of {value!r} unverified after {self.max_attempts} attempts; "
            f"residual observability in {residual}. Do not assert non-observability."
        )

    def assert_forgotten(self, value, scope):
        if (value, scope) not in self.verified:
            raise UnverifiedErasureError(
                f"refusing to assert {value!r} forgotten in {scope}: "
                f"no clean post-probe on record."
            )
        return True
