# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-memory-tool-tombstone-gap-from-resurrecting-forgotten-state-across-a-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-memory-tool-tombstone-gap-from-resurrecting-forgotten-state-across-a-resume.warrant.json
# Markdown SHA-256:   1003375722d47441f264e5850b7f4b18c91e0055a3b34b0dd6fc2bb66c659208
# Code AST SHA-256:   f24a5f979ecd04d0bc492d5e627b6989a948257136c5502387de95dc02ab934d
# Verified Classes:   TombstoneGapError, Record, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List


class TombstoneGapError(RuntimeError):
    """Raised when a memory operation would resurrect or launder a tombstoned record."""


@dataclass
class Record:
    record_id: str
    content: str
    scope: str
    tombstone_version: int = 0
    derived_from: List[str] = field(default_factory=list)


@dataclass
class Checkpoint:
    records: Dict[str, Record]
    observed_tombstone: Dict[str, int]


def reconcile_on_resume(checkpoint: Checkpoint, store_tombstones: Dict[str, int]) -> Checkpoint:
    """Drop any snapshot record whose store tombstone version has advanced.

    Ledger-authoritative resume: the store's tombstone ledger wins over the
    checkpoint for every record under a revocable scope.
    """
    live: Dict[str, Record] = {}
    for rid, rec in checkpoint.records.items():
        store_ver = store_tombstones.get(rid, 0)
        if store_ver > checkpoint.observed_tombstone.get(rid, 0):
            # Tombstoned after the snapshot was taken; do not rehydrate.
            continue
        live[rid] = rec
    return Checkpoint(records=live, observed_tombstone=dict(checkpoint.observed_tombstone))


def write_derived(rec: Record, checkpoint: Checkpoint, store_tombstones: Dict[str, int]) -> Record:
    """Persist a derived record only if no ancestor is tombstoned past our ack."""
    for ancestor in rec.derived_from:
        store_ver = store_tombstones.get(ancestor, 0)
        acked = checkpoint.observed_tombstone.get(ancestor, 0)
        if store_ver > acked:
            raise TombstoneGapError(
                f"write of {rec.record_id} derives from {ancestor} "
                f"tombstoned at v{store_ver} but agent only acked v{acked}; "
                f"refusing to launder forgotten content"
            )
    if rec.record_id in checkpoint.records:
        raise TombstoneGapError(
            f"record {rec.record_id} already present in working map; "
            f"resume reconciliation was skipped"
        )
    return rec


def resume_and_write(checkpoint: Checkpoint, store_tombstones: Dict[str, int], pending: Record) -> Checkpoint:
    reconciled = reconcile_on_resume(checkpoint, store_tombstones)
    new_rec = write_derived(pending, reconciled, store_tombstones)
    reconciled.records[new_rec.record_id] = new_rec
    return reconciled
