# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-when-an-agent-s-memory-write-path-and-deletion-verification-path-race-across-a-retention-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tombstone-resurrection-when-an-agent-s-memory-write-path-and-deletion-verification-path-race-across-a-retention-boundary.warrant.json
# Markdown SHA-256:   96110a72bb21606d6f5053614eb8122abe37f888c936fbef0906c3ec6c3a7f56
# Code AST SHA-256:   87d225fd642a2e3c14385db209b5d0eaefebaf05252779fc5e5110cafa81fb55
# Verified Classes:   TombstoneResurrectionError, DeletionStatus, Tombstone
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from enum import Enum
from dataclasses import dataclass


class TombstoneResurrectionError(RuntimeError):
    """Raised when an agent attempts a write that would defeat a committed tombstone."""


class DeletionStatus(Enum):
    CONFIRMED = "confirmed"
    PENDING = "pending"
    SUPERSEDED = "superseded"
    HELD = "held"


@dataclass(frozen=True)
class Tombstone:
    tombstone_id: str
    key: str
    epoch: int


def safe_forget_and_verify(memory_tool, key: str, current_epoch: int) -> DeletionStatus:
    """
    Issue a forget, then verify via the dedicated verification path.
    Refuses to treat recall output as deletion evidence.
    """
    ack = memory_tool.forget(key)
    tombstone = Tombstone(
        tombstone_id=ack["tombstone_id"],
        key=key,
        epoch=current_epoch,
    )

    status = DeletionStatus(memory_tool.verify_deletion(tombstone.tombstone_id))

    if status is DeletionStatus.PENDING:
        # Do NOT recall, do NOT re-remember. Wait for the grace window.
        return status

    if status is DeletionStatus.SUPERSEDED:
        # A concurrent write with a newer epoch defeated the tombstone.
        # The agent must escalate, never re-issue the original value.
        raise TombstoneResurrectionError(
            f"tombstone {tombstone.tombstone_id} for key {key!r} was superseded "
            f"by a write with epoch > {tombstone.epoch}; agent must surface "
            f"conflict to user rather than reconcile state"
        )

    if status is DeletionStatus.HELD:
        # Legal hold: deletion is intentionally blocked; do not retry.
        return status

    return DeletionStatus.CONFIRMED


def guarded_remember(memory_tool, key: str, value: str, write_epoch: int, tombstones: list[Tombstone]) -> None:
    """
    Reject any write whose epoch is dominated by an existing tombstone for the same key.
    This is the invariant that prevents resurrection when writes race deletion.
    """
    for t in tombstones:
        if t.key == key and write_epoch <= t.epoch:
            raise TombstoneResurrectionError(
                f"write to {key!r} at epoch {write_epoch} is dominated by "
                f"tombstone {t.tombstone_id} at epoch {t.epoch}; refusing to resurrect"
            )
    memory_tool.remember(key, value, epoch=write_epoch)
