# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-memory-deletion-as-a-tombstone-rather-than-a-hard-erasure-and-how-does-resurrection-through-re-deriv.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-memory-deletion-as-a-tombstone-rather-than-a-hard-erasure-and-how-does-resurrection-through-re-deriv.warrant.json
# Markdown SHA-256:   3925142a39d58698bc32f06f27ecd4f1286bd79926c2bdcdc3fd2b7054bda43a
# Code AST SHA-256:   8f34ea3fa15a00df8ebed5938b36aa16c8006659a5c57598e8a543b91632d877
# Verified Classes:   ResurrectionViolation, Provenance, Tombstone, ScopedMemoryStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class ResurrectionViolation(RuntimeError):
    """Raised when a write would re-materialize a tombstoned key without consent."""


class Provenance(Enum):
    USER_CONSENT = "user_consent"
    TOOL_OUTPUT = "tool_output"
    AGENT_INFERENCE = "agent_inference"


@dataclass
class Tombstone:
    scope: str
    key: str
    derivation_barrier: bool
    invalidated_checkpoints: list[str] = field(default_factory=list)


class ScopedMemoryStore:
    def __init__(self) -> None:
        self._values: dict[tuple[str, str], str] = {}
        self._tombstones: dict[tuple[str, str], Tombstone] = {}
        self._checkpoint_scopes: dict[str, set[str]] = {}

    def remember(
        self,
        scope: str,
        key: str,
        value: str,
        provenance: Provenance,
        derivation_lineage: str,
    ) -> None:
        tomb = self._tombstones.get((scope, key))
        if tomb is not None and tomb.derivation_barrier:
            if provenance is not Provenance.USER_CONSENT:
                raise ResurrectionViolation(
                    f"write to tombstoned ({scope!r}, {key!r}) via {provenance.value} "
                    f"lineage={derivation_lineage}; only user re-consent may clear the tombstone"
                )
            # Legitimate re-consent clears the tombstone.
            del self._tombstones[(scope, key)]
        self._values[(scope, key)] = value

    def forget(
        self,
        scope: str,
        key: str,
        checkpoints_touching_scope: list[str],
    ) -> Tombstone:
        self._values.pop((scope, key), None)
        tomb = Tombstone(
            scope=scope,
            key=key,
            derivation_barrier=True,
            invalidated_checkpoints=list(checkpoints_touching_scope),
        )
        self._tombstones[(scope, key)] = tomb
        return tomb

    def assert_no_resurrection(
        self,
        scope: str,
        key: str,
        checkpoint_context: dict[str, str],
        derivation_lineage: str,
    ) -> None:
        """Fail closed if a checkpoint still carries a tombstoned payload."""
        tomb = self._tombstones.get((scope, key))
        if tomb is None:
            return
        if key in checkpoint_context:
            raise ResurrectionViolation(
                f"checkpoint for scope {scope!r} still carries tombstoned key {key!r}; "
                f"lineage={derivation_lineage}; deletion is not durable"
            )
        if not tomb.derivation_barrier:
            raise ResurrectionViolation(
                f"tombstone for ({scope!r}, {key!r}) is storage-layer only; "
                f"derivation barrier required before reporting 'deleted'"
            )
