# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-it-was-told-to-retain-tombstone-shadowing-and-the-deletion-retention-deadlock-in-agent-memory-tool-apis.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-it-was-told-to-retain-tombstone-shadowing-and-the-deletion-retention-deadlock-in-agent-memory-tool-apis.warrant.json
# Markdown SHA-256:   95bcec62a02f1c4c296600149d78e9c1ce4ae768c0f90c69770ae7a0452b701b
# Code AST SHA-256:   123981ed114c6e95813be23e2c00e94a9f74ef2316289146cd1c0c818113df30
# Verified Classes:   MemoryState, ShadowedWriteError, UnreconciledStateError, ReadResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class MemoryState(Enum):
    PRESENT = "present"
    DELETED = "deleted"
    QUARANTINED = "quarantined"
    SHADOWED = "shadowed"
    NEVER_EXISTED = "never_existed"


class ShadowedWriteError(RuntimeError):
    """Raised when a write is silently converted to a no-op by a defense tombstone."""
    pass


class UnreconciledStateError(RuntimeError):
    """Raised when the store returns an ambiguous empty read that the agent cannot classify."""
    pass


@dataclass
class ReadResult:
    state: MemoryState
    memory_id: Optional[str] = None
    shadowed_by: Optional[str] = None
    poison_score: Optional[float] = None


def commit_and_verify(write_fn, read_fn, content: str, namespace: str,
                      max_attempts: int = 1) -> ReadResult:
    """
    Enforce the write-read atomicity contract. A write is provisional until a
    committed read returns MemoryState.PRESENT for the returned id.
    """
    provisional_id = write_fn(content=content, namespace=namespace)

    result = read_fn(provisional_id)

    if result.state is MemoryState.PRESENT:
        return result

    if result.state is MemoryState.SHADOWED:
        # Do NOT paraphrase and retry to evade the denylist. Escalate.
        raise ShadowedWriteError(
            f"write to {namespace} returned id {provisional_id} but read is "
            f"shadowed by {result.shadowed_by}; refusing to retry with "
            f"paraphrased content (denylist evasion). Escalate for purge or audit."
        )

    if result.state in (MemoryState.DELETED, MemoryState.QUARANTINED):
        raise ShadowedWriteError(
            f"write to {namespace} collided with terminal state {result.state.value} "
            f"on id {provisional_id}; content lineage must be purged or re-verified."
        )

    if result.state is MemoryState.NEVER_EXISTED:
        raise UnreconciledStateError(
            f"write returned id {provisional_id} but read says never_existed; "
            f"store is not projecting a reconciled state at the API boundary."
        )

    raise UnreconciledStateError(f"unhandled state {result.state}")
