# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-erasure-tombstone-resurrection-across-agent-memory-tool-apis-with-retention-guarantees.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-erasure-tombstone-resurrection-across-agent-memory-tool-apis-with-retention-guarantees.warrant.json
# Markdown SHA-256:   bc3aa58d06faf45245ba0dcde50e34ed30b7cc96182be6a4edd58741935f9c47
# Code AST SHA-256:   bb7a0f376ed572930f96e1206b0e146313baa2527fe5ac90d8a0963759c03836
# Verified Classes:   ErasureResurrectionError, Tombstone, MemoryWrapper
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ErasureResurrectionError(RuntimeError):
    """Raised when a write would re-instantiate a tombstoned key or land before its barrier."""


@dataclass(frozen=True)
class Tombstone:
    key: str
    version: int
    barrier_seq: int
    session_id: str


class MemoryWrapper:
    def __init__(self, store, session_id: str):
        self.store = store
        self.session_id = session_id
        self._tombstones: dict[str, Tombstone] = {}

    def forget(self, key: str, reason: str) -> Tombstone:
        resp = self.store.forget(key, reason=reason)
        ts = Tombstone(key=key, version=resp["version"],
                       barrier_seq=resp["seq"], session_id=self.session_id)
        self._tombstones[key] = ts
        return ts

    def write(self, key: str, value: str, expected_version: int,
              resurrect: bool = False) -> dict:
        ts = self._tombstones.get(key)
        if ts is not None and not resurrect:
            # I1: expected_version matching the erased version is a resurrection primitive.
            if expected_version <= ts.version:
                raise ErasureResurrectionError(
                    f"write to {key} at expected_version={expected_version} "
                    f"would resurrect tombstone v{ts.version} (barrier_seq={ts.barrier_seq})"
                )
        resp = self.store.write(key, value, expected_version=expected_version)
        # I2: commit order must equal response order.
        if ts is not None and resp["commit_seq"] < ts.barrier_seq:
            raise ErasureResurrectionError(
                f"write to {key} committed at seq {resp['commit_seq']} "
                f"before forget barrier {ts.barrier_seq}; result is provisional"
            )
        return resp

    def read(self, key: str) -> Optional[str]:
        # I3: read-your-erasure within the session.
        if key in self._tombstones:
            return None
        return self.store.read(key)
