# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-orphaned-embedding-after-partial-forget-in-an-agent-vector-memory-tool.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-orphaned-embedding-after-partial-forget-in-an-agent-vector-memory-tool.warrant.json
# Markdown SHA-256:   f63b74b6b1d4b293842daedf014a98d4efd95036e6ca4de6b30e8c60cb790941
# Code AST SHA-256:   11a9d5a69754d6ec0d7a82b2381e9f91626c6cdadf91287fc7f55ce9e6e038d2
# Verified Classes:   ForgettingInvariantViolation, ErasureState, ForgetResult, WriteResult, ErasureLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ForgettingInvariantViolation(RuntimeError):
    """Raised when a forget's post-condition (content unreachable) is not met,
    or when a write resurrects a tombstoned memory via the dedup path."""
    pass


class ErasureState(Enum):
    PENDING_ERASE = "pending_erase"
    ERASED = "erased"


@dataclass
class ForgetResult:
    memory_id: str
    status: str
    compaction_pending: int
    reverse_map_tombstone_aware: bool


@dataclass
class WriteResult:
    status: str
    memory_id: str
    deduplicated: bool


@dataclass
class ErasureLedger:
    pending: dict = field(default_factory=dict)  # content_hash -> memory_id

    def _hash(self, content: str) -> str:
        return hashlib.sha256(content.encode()).hexdigest()

    def record_forget(self, content: str, result: ForgetResult) -> ErasureState:
        if result.status != "ok":
            raise ForgettingInvariantViolation(
                f"forget failed for {result.memory_id}: status={result.status}"
            )
        # Debt-free AND tombstone-aware => terminal erase.
        if result.compaction_pending == 0 and result.reverse_map_tombstone_aware:
            return ErasureState.ERASED
        # Otherwise the erase is provisional; quarantine the hash space.
        self.pending[self._hash(content)] = result.memory_id
        return ErasureState.PENDING_ERASE

    def guard_write(self, content: str, write: WriteResult) -> None:
        h = self._hash(content)
        if h in self.pending and write.deduplicated:
            raise ForgettingInvariantViolation(
                f"write deduplicated onto tombstoned memory {write.memory_id} "
                f"(pending erase {self.pending[h]}); resurrection of erased content"
            )

    def confirm_erased(self, content: str, probe_read_found: bool) -> ErasureState:
        h = self._hash(content)
        if h not in self.pending:
            raise ForgettingInvariantViolation(f"no pending erase for hash {h[:12]}")
        if probe_read_found:
            raise ForgettingInvariantViolation(
                f"post-compaction probe still reachable for {self.pending[h]}; "
                f"erasure invariant not established"
            )
        self.pending.pop(h)
        return ErasureState.ERASED
