# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-forget-the-episodic-deletion-tombstone-divergence-in-auditable-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-forget-the-episodic-deletion-tombstone-divergence-in-auditable-agent-memory.warrant.json
# Markdown SHA-256:   cb9bc790edf488c41ad93549b395e040fbb70b673b8c72850789af4c51bf942d
# Code AST SHA-256:   97ca697ad1b1c47a8bc510dc5ca7b5dfdbb9d8a6626e0c213302c55b07c187a6
# Verified Classes:   ErasurePropagationError, Checkpoint, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ErasurePropagationError(RuntimeError):
    """Raised when an erasure cannot be proven to reach every serialized copy."""
    pass


@dataclass
class Checkpoint:
    step: int
    # Content-bearing buffer: may embed erasable payloads as rendered text.
    buffer: str
    # Manifest of every erasable span and the slot it was copied from.
    redaction_manifest: list[tuple[int, int, str]] = field(default_factory=list)
    sealed_hash: Optional[str] = None


@dataclass
class MemoryStore:
    slots: dict[str, Optional[str]]
    tombstones: dict[str, str] = field(default_factory=dict)

    def erase(self, slot_id: str) -> None:
        if slot_id not in self.slots:
            raise ErasurePropagationError(f"unknown slot {slot_id}")
        self.slots[slot_id] = None
        self.tombstones[slot_id] = "erased"


def propagate_erasure(store: MemoryStore, slot_id: str,
                      checkpoints: list[Checkpoint]) -> list[Checkpoint]:
    """Erase a slot and rewrite every checkpoint that embedded its payload.

    Invariant: after this returns, no checkpoint buffer contains the payload,
    and every affected checkpoint carries a tombstone marker at the span.
    """
    store.erase(slot_id)
    payload = store.tombstones.get(slot_id)
    if payload is None:
        raise ErasurePropagationError(f"no tombstone for {slot_id}")

    rewritten: list[Checkpoint] = []
    for cp in checkpoints:
        spans = [s for s in cp.redaction_manifest if s[2] == slot_id]
        if not spans:
            rewritten.append(cp)
            continue
        buf = cp.buffer
        # Rewrite from the end so earlier offsets stay valid.
        for start, end, _ in sorted(spans, key=lambda s: s[0], reverse=True):
            if buf[start:end] == "":
                raise ErasurePropagationError(
                    f"span {start}:{end} in step {cp.step} already empty; "
                    f"manifest drift detected"
                )
            buf = buf[:start] + "[ERASED]" + buf[end:]
        cp.buffer = buf
        cp.sealed_hash = None  # must be re-sealed after redaction
        rewritten.append(cp)

    # Completeness proof: the slot must no longer appear in any buffer.
    for cp in rewritten:
        if any(s[2] == slot_id and "[ERASED]" not in cp.buffer for s in cp.redaction_manifest):
            raise ErasurePropagationError(
                f"erasure incomplete: slot {slot_id} survives in step {cp.step}"
            )
    return rewritten
