# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-tombstone-resurrection-across-scoped-agent-memory-tools-with-ttl-and-deletion-audits.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-tombstone-resurrection-across-scoped-agent-memory-tools-with-ttl-and-deletion-audits.warrant.json
# Markdown SHA-256:   1e0991e10cfe9623337d05d162d6caca9d707b3f0ae69b40e2255dad26c95760
# Code AST SHA-256:   90444495a5097ded8026a1d69dfaa3b1c9d47e0909a64e2b62d5d8e286c67ffb
# Verified Classes:   TombstonedError, ScopeCanonicalizationError, Tombstone, MemoryStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class TombstonedError(RuntimeError):
    """Raised when a write targets a key whose tombstone generation is not exceeded."""

    def __init__(self, scope: str, key: str, tombstone_gen: int, observed_gen: int, reason: str):
        self.scope = scope
        self.key = key
        self.tombstone_gen = tombstone_gen
        self.observed_gen = observed_gen
        self.reason = reason
        super().__init__(
            f"write rejected: scope={scope!r} key={key!r} "
            f"tombstone_gen={tombstone_gen} observed_gen={observed_gen} reason={reason!r}"
        )


class ScopeCanonicalizationError(ValueError):
    """Raised when a scope string cannot be canonicalized before tombstone lookup."""


@dataclass
class Tombstone:
    scope: str
    key: str
    gen: int
    reason: str
    ts: float


@dataclass
class MemoryStore:
    live: dict = field(default_factory=dict)          # (scope, key) -> (value, ttl, gen)
    tombstones: dict = field(default_factory=dict)    # (scope, key) -> Tombstone
    ledger: list = field(default_factory=list)

    def _canon(self, scope: str) -> str:
        s = scope.rstrip("/").lower()
        if not s or "/" not in s:
            raise ScopeCanonicalizationError(f"non-canonical scope: {scope!r}")
        return s

    def write(self, scope: str, key: str, value, ttl: int, observed_gen: int) -> int:
        scope = self._canon(scope)
        tomb = self.tombstones.get((scope, key))
        if tomb is not None and observed_gen <= tomb.gen:
            # Reject BEFORE any mutation. Do not silently upgrade.
            self.ledger.append(
                {"op": "write_rejected", "scope": scope, "key": key,
                 "observed_gen": observed_gen, "tombstone_gen": tomb.gen, "ts": time.time()}
            )
            raise TombstonedError(scope, key, tomb.gen, observed_gen, tomb.reason)
        new_gen = (tomb.gen if tomb else 0) + 1
        self.live[(scope, key)] = (value, time.time() + ttl, new_gen)
        self.ledger.append(
            {"op": "write", "scope": scope, "key": key, "gen": new_gen,
             "tombstone_gen": tomb.gen if tomb else None, "ts": time.time()}
        )
        return new_gen

    def forget(self, scope: str, key: str, reason: str) -> None:
        scope = self._canon(scope)
        prior = self.tombstones.get((scope, key))
        gen = (prior.gen if prior else 0) + 1
        self.tombstones[(scope, key)] = Tombstone(scope, key, gen, reason, time.time())
        self.live.pop((scope, key), None)
        self.ledger.append(
            {"op": "delete", "scope": scope, "key": key, "gen": gen, "reason": reason, "ts": time.time()}
        )

    def expire(self, now: Optional[float] = None) -> None:
        now = now if now is not None else time.time()
        for (scope, key), (_, exp, gen) in list(self.live.items()):
            if exp <= now:
                del self.live[(scope, key)]
                # Expiry is a clock event, NOT a deletion constraint.
                self.ledger.append(
                    {"op": "expire", "scope": scope, "key": key, "gen": gen, "ts": now}
                )


# Reproduction of the observed failure: stale planner writes after sub-agent forget.
store = MemoryStore()
gen0 = store.write("tenant:acme/project:atlas", "db.primary.host", "10.4.2.11", ttl=86400, observed_gen=0)
store.forget("tenant:acme/project:atlas", "db.primary.host", reason="policy:secret-adjacent")

try:
    # Planner's context predates the forget; it still holds gen0.
    store.write("tenant:acme/project:atlas", "db.primary.host", "10.4.2.11", ttl=86400, observed_gen=gen0)
except TombstonedError as e:
    assert e.tombstone_gen == 1 and e.observed_gen == 1
    assert "secret-adjacent" in e.reason
else:
    raise AssertionError("tombstone invariant violated: stale write resurrected key")

# Trailing-slash scope must fail canonicalization rather than dodge the tombstone.
try:
    store.write("tenant:acme/project:atlas/", "db.primary.host", "10.4.2.11", ttl=86400, observed_gen=0)
except ScopeCanonicalizationError:
    pass
else:
    raise AssertionError("non-canonical scope bypassed tombstone lookup")
