# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-it-is-still-reasoning-over-tombstone-shadowing-and-retrieval-invalidation-races-in-read-write-forget-me.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-deletes-a-memory-it-is-still-reasoning-over-tombstone-shadowing-and-retrieval-invalidation-races-in-read-write-forget-me.warrant.json
# Markdown SHA-256:   7b829ba72e21c6719d8f43b1a505227adc74928856e3929f015d41cd9dee78ba
# Code AST SHA-256:   4dc6486330c514fa8edae442e4ba9b46f529f2b1f35d1110c43bd3cc555e91e1
# Verified Classes:   TombstoneShadowingError, MemoryToolAPI
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TombstoneShadowingError(RuntimeError):
    """Raised when an agent reasons over or re-persists a forgotten memory
    whose content is still resident in the live context window."""
    pass


def _hash(text: str) -> str:
    return "sha256:" + hashlib.sha256(text.encode("utf-8")).hexdigest()


@dataclass
class MemoryToolAPI:
    store: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)   # id -> content hash
    context_hashes: set = field(default_factory=set) # hashes still in prompt

    def read(self, key: str):
        if key in self.tombstones:
            return {"status": "not_found", "tombstone": True}
        return self.store.get(key, {"status": "not_found"})

    def write(self, key: str, text: str):
        h = _hash(text)
        # Guardrail (b): refuse to launder a tombstoned fact back in.
        if h in self.tombstones.values():
            raise TombstoneShadowingError(
                f"write of {key!r} matches tombstoned content {h}; "
                "fact resurrection via laundering blocked"
            )
        self.store[key] = {"text": text, "hash": h}
        return {"status": "ok", "hash": h}

    def forget(self, key: str):
        rec = self.store.pop(key, None)
        if rec is None:
            return {"status": "not_found"}
        h = rec["hash"]
        self.tombstones[key] = h
        # The forgotten text is STILL in context until a rebuild.
        self.context_hashes.add(h)
        return {"status": "deleted", "content_hash": h, "redact_from_context": True}

    def assert_context_clean(self, key: str):
        """Must be called before any reasoning step that references `key`
        after a forget. Enforces the store-authoritative discipline."""
        h = self.tombstones.get(key)
        if h is not None and h in self.context_hashes:
            raise TombstoneShadowingError(
                f"memory {key!r} was forgotten but its content ({h}) is still "
                "in the context window; rebuild context before reasoning over it"
            )

    def rebuild_context(self, dropped_hashes: set = None):
        self.context_hashes -= (dropped_hashes or set(self.context_hashes))


# --- failure trace ---
mem = MemoryToolAPI()
mem.write("m_4471", "Apollo ships 2024-03-15")
mem.write("m_5102", "Apollo ships 2024-04-01")

mem.forget("m_4471")                      # store deleted; context still holds it
mem.assert_context_clean("m_4471")        # raises: tombstone shadowing detected
