# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-that-a-memory-forget-operation-is-irreversible-before-acknowledging-deletion-under-covert-re-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-that-a-memory-forget-operation-is-irreversible-before-acknowledging-deletion-under-covert-re-injection.warrant.json
# Markdown SHA-256:   e3e5e81c5504624b1a0287d74b58ced77ea04801acd831291d2417b8a9c27244
# Code AST SHA-256:   3eb2d2d946526a62ba88028a246402797a41d7995725efc77bcd8e1c0708ee3a
# Verified Classes:   ResurrectionRisk, ForgetDirective, MemoryStore, PeerMesh
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Protocol


class ResurrectionRisk(RuntimeError):
    """Raised when a forget operation cannot prove non-retrievability."""


@dataclass
class ForgetDirective:
    content_hash: str
    sensitive: bool
    reachable_peers: list[str] = field(default_factory=list)


class MemoryStore(Protocol):
    def delete_by_semantic_hash(self, h: str) -> int: ...
    def probe_retrievable(self, h: str) -> bool: ...
    def flush_context_window(self) -> None: ...


class PeerMesh(Protocol):
    def send_tombstone(self, peer: str, h: str) -> None: ...
    def await_tombstone_ack(self, peer: str, h: str, timeout_s: float) -> bool: ...


def forget_and_ack(
    directive: ForgetDirective,
    store: MemoryStore,
    mesh: PeerMesh,
    peer_timeout_s: float = 2.0,
) -> str:
    # Phase 1: delete every derived artifact by content identity, not by ID.
    store.delete_by_semantic_hash(directive.content_hash)

    # Phase 2: flush any in-flight context carrying pre-delete content.
    store.flush_context_window()

    # Phase 3: propagate tombstones to every peer that could re-inject.
    unconfirmed: list[str] = []
    for peer in directive.reachable_peers:
        mesh.send_tombstone(peer, directive.content_hash)
        if not mesh.await_tombstone_ack(peer, directive.content_hash, peer_timeout_s):
            unconfirmed.append(peer)

    # Phase 4: the only direct test of the retrievability claim.
    still_retrievable = store.probe_retrievable(directive.content_hash)

    if directive.sensitive and (unconfirmed or still_retrievable):
        # Withhold the ack: optimistic success here is a correctness bug,
        # because downstream agents will stop guarding against the content.
        raise ResurrectionRisk(
            f"forget unverifiable for {directive.content_hash[:12]}: "
            f"retrievable={still_retrievable} unconfirmed_peers={unconfirmed}"
        )

    return "forgot" if not unconfirmed and not still_retrievable else "forget_pending"
