# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-delete-a-memory-scope-and-still-answer-from-it-in-the-same-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-delete-a-memory-scope-and-still-answer-from-it-in-the-same-turn.warrant.json
# Markdown SHA-256:   b295a32dd531f54533e931dbf5ea2fed70033e89cf39eb66afb6f1d15ef8e195
# Code AST SHA-256:   3a636441d8d39e56c090b367e80c84544d8fcae0158ddb55d4c3f1281861597f
# Verified Classes:   GhostMemoryError, ScopeState, AgentMemoryView
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GhostMemoryError(RuntimeError):
    """Raised when an agent attempts to emit a value whose only provenance is a
    context-resident copy of a record the store would no longer return."""


@dataclass
class ScopeState:
    epoch: int = 0
    tombstoned: bool = False
    purge_after: Optional[str] = None


@dataclass
class AgentMemoryView:
    """Tracks what the agent *believes* it knows vs. what the store will return."""
    store: dict = field(default_factory=dict)          # scope -> {key: value}
    scopes: dict = field(default_factory=dict)         # scope -> ScopeState
    context_cache: dict = field(default_factory=dict)  # (scope, key) -> (value, epoch)

    def read(self, scope: str, key: str) -> Optional[str]:
        state = self.scopes.get(scope, ScopeState())
        if state.tombstoned or scope not in self.store:
            return None
        val = self.store[scope].get(key)
        if val is not None:
            self.context_cache[(scope, key)] = (val, state.epoch)
        return val

    def forget(self, scope: str, mode: str = "hard") -> dict:
        state = self.scopes.setdefault(scope, ScopeState())
        if mode == "hard":
            self.store.pop(scope, None)
            state.tombstoned = True
        elif mode == "soft":
            state.tombstoned = True
            state.purge_after = "2025-07-12"
        state.epoch += 1
        # NOTE: context_cache is deliberately NOT purged here. That is the bug.
        return {"status": "ok", "mode": mode, "epoch": state.epoch,
                "purge_after": state.purge_after}

    def emit(self, scope: str, key: str, claimed_value: str) -> str:
        """Gate every emitted value on a live store read + epoch match."""
        state = self.scopes.get(scope, ScopeState())
        live = self.read(scope, key)

        if state.tombstoned and claimed_value:
            raise GhostMemoryError(
                f"scope={scope!r} is tombstoned (mode=soft, purge_after="
                f"{state.purge_after!r}); refusing to emit claimed value "
                f"{claimed_value!r} sourced from context cache"
            )

        if live is None and claimed_value:
            cached = self.context_cache.get((scope, key))
            raise GhostMemoryError(
                f"ghost emission: scope={scope!r} key={key!r} returned empty "
                f"from store but agent holds cached copy "
                f"{cached[0]!r} from epoch {cached[1] if cached else 'unknown'}; "
                f"current epoch={state.epoch}"
            )

        if live is not None and live != claimed_value:
            cached = self.context_cache.get((scope, key))
            if cached and cached[1] != state.epoch:
                raise GhostMemoryError(
                    f"stale epoch: scope={scope!r} key={key!r} cached at epoch "
                    f"{cached[1]} but store is at epoch {state.epoch}; "
                    f"claimed={claimed_value!r} live={live!r}"
                )
        return live if live is not None else claimed_value


def run_turn(mem: AgentMemoryView, scope: str, key: str) -> str:
    # Agent reads, then forgets, then (bug) answers from the old read.
    mem.read(scope, key)
    mem.forget(scope, mode="hard")
    return mem.emit(scope, key, claimed_value="card_last4=4242")


if __name__ == "__main__":
    m = AgentMemoryView(store={"billing_prefs": {"card_last4": "4242"}})
    try:
        run_turn(m, "billing_prefs", "card_last4")
    except GhostMemoryError as e:
        print(f"BLOCKED: {e}")
