# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-masked-resurrection-hazard-in-tiered-agent-memory-deletion-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-tombstone-masked-resurrection-hazard-in-tiered-agent-memory-deletion-apis.warrant.json
# Markdown SHA-256:   a969b2f85b444cffc4d5786bbc3ca415f7d4f562d50b7f59af4b2da654566930
# Code AST SHA-256:   4d03b487d28b932c58a72da7fa9babfd908cc3c16e49251cbba1a5c6f3b03de0
# Verified Classes:   ResurrectionHazard, TombstoneLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ResurrectionHazard(RuntimeError):
    """Raised when a recall hit traces to a tombstoned source via a derived tier."""


@dataclass
class TombstoneLedger:
    _hashes: set = field(default_factory=set)
    _source_ids: set = field(default_factory=set)

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

    def forget(self, content: str, source_record_id: str) -> None:
        self._hashes.add(self._h(content))
        self._source_ids.add(source_record_id)

    def is_tombstoned(self, content: str, source_record_id: str | None) -> bool:
        if self._h(content) in self._hashes:
            return True
        if source_record_id and source_record_id in self._source_ids:
            return True
        return False


def verified_recall(memory_api, query: str, ledger: TombstoneLedger) -> list:
    """Recall that refuses resurrection. Rejects any hit whose content hash
    or source_record_id is tombstoned, regardless of the store's claim."""
    hits = memory_api.recall(query)
    clean = []
    for hit in hits:
        content = hit.get("content", "")
        src = hit.get("source_record_id")
        if ledger.is_tombstoned(content, src):
            # The store returned something we explicitly forgot. Do not
            # silently drop it: surface the hazard so the caller can decide.
            raise ResurrectionHazard(
                f"recall({query!r}) returned tombstoned content via "
                f"source={hit.get('source')!r} src_id={src!r}; "
                f"deletion was tier-local, not total."
            )
        if hit.get("source") in ("semantic_index", "summary_cache") and src is None:
            raise ResurrectionHazard(
                f"derived hit from {hit.get('source')!r} carries no indexed "
                f"source_record_id; cascade invalidation is unverifiable."
            )
        clean.append(hit)
    return clean


def forget_with_verification(memory_api, content: str, source_record_id: str,
                             ledger: TombstoneLedger, probes: list[str]) -> dict:
    """Forget, then adversarially probe. If any probe resurrects, escalate."""
    resp = memory_api.forget(source_record_id)
    ledger.forget(content, source_record_id)
    if resp.get("pending_invalidation"):
        return {"status": "deferred", "token": resp["pending_invalidation"]}
    for probe in probes:
        try:
            verified_recall(memory_api, probe, ledger)
        except ResurrectionHazard as e:
            return {"status": "resurrection_detected", "probe": probe, "detail": str(e)}
    return {"status": "verified_total_deletion"}
