# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-scoped-retention-memory-write-whose-ttl-boundary-lands-mid-reasoning-the-tombstone-before-readback-hazard.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-scoped-retention-memory-write-whose-ttl-boundary-lands-mid-reasoning-the-tombstone-before-readback-hazard.warrant.json
# Markdown SHA-256:   74fe2e66796a1e81ee7638d3cbf5ed3ec00085aa15dc2e3488ac6a40db412e15
# Code AST SHA-256:   58c0f21e0648220332414b052161247cc45a7813a7afcca0df932f5f2b5a5c10
# Verified Classes:   RetentionBoundaryError, HandleState, Handle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum


class RetentionBoundaryError(RuntimeError):
    """Raised when an agent attempts to act across a retention boundary it cannot observe."""


class HandleState(Enum):
    LIVE = "live"
    RETIRED = "retired"
    NEVER_WRITTEN = "never_written"


@dataclass(frozen=True)
class Handle:
    key: str
    state: HandleState
    expires_at: float


def resolve_absence(handle: Handle | None, now: float, reassert_requested: bool) -> str:
    """
    Decide what a NotFound read means for a key the agent previously wrote.

    The invariant: absence is only re-assertable when the handle proves the key
    was never written. A retired handle means the value was intentionally
    expired; re-writing it resurrects data the retention policy retired.
    """
    if not reassert_requested:
        return "no_action"

    if handle is None:
        # No handle held: absence is a genuine write failure. Re-assert is safe.
        return "reassert_write"

    if handle.state is HandleState.NEVER_WRITTEN:
        return "reassert_write"

    if handle.state is HandleState.RETIRED:
        # The retention boundary fired. Re-writing would defeat it.
        raise RetentionBoundaryError(
            f"key={handle.key!r} was retired at t={handle.expires_at:.3f} "
            f"(now={now:.3f}); refusing to resurrect from agent context. "
            f"Re-derive under a fresh scope instead of re-asserting."
        )

    if handle.state is HandleState.LIVE:
        # Live handle but read returned NotFound: store inconsistency, not retention.
        raise RetentionBoundaryError(
            f"key={handle.key!r} has a LIVE handle (expires_at={handle.expires_at:.3f}) "
            f"but read returned NotFound at t={now:.3f}; store state is inconsistent."
        )

    raise RetentionBoundaryError(f"unhandled handle state: {handle.state!r}")


def guarded_rewrite_after_miss(
    handle: Handle | None,
    now: float,
    payload_in_context: bool,
) -> str:
    """
    Gate the agent's idempotency retry behind the retention check.

    Only call this when the agent's recovery heuristic wants to re-write after
    a NotFound. If the payload is reconstructible from context AND the handle
    is retired, the hazard is live and we must refuse.
    """
    if handle is not None and handle.state is HandleState.RETIRED and payload_in_context:
        raise RetentionBoundaryError(
            f"resurrection hazard: handle for {handle.key!r} is RETIRED and the "
            f"payload is still in agent context; a re-write would extend retention "
            f"past its scoped TTL. Surface RetentionElapsed to the reasoning loop."
        )
    return resolve_absence(handle, now, reassert_requested=True)
