# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-writes-to-a-scoped-memory-namespace-whose-ttl-is-shorter-than-its-own-task-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-writes-to-a-scoped-memory-namespace-whose-ttl-is-shorter-than-its-own-task-horizon.warrant.json
# Markdown SHA-256:   d6dce9de51981616a236d5dbb623eda57c35d7930bc1c4b5095ce89f4b88819e
# Code AST SHA-256:   52f1e2599ce90d65b5c298e8b0d1fd2142149e84ab16adc9a23ecd013f7a00ea
# Verified Classes:   MemoryContinuityError, ReadStatus, ScopedMemory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Any


class MemoryContinuityError(RuntimeError):
    """Raised when a TTL-scoped memory operation would break task continuity."""
    pass


class ReadStatus(Enum):
    PRESENT = "present"
    EXPIRED = "expired"
    ABSENT = "absent"


@dataclass
class ScopedMemory:
    store: dict           # (namespace, key) -> (value, expires_at)
    horizon_deadline: float   # absolute ts the agent's plan must survive to

    def write(self, namespace: str, key: str, value: Any,
              ttl_seconds: float, now: float) -> None:
        remaining = self.horizon_deadline - now
        if ttl_seconds < remaining:
            raise MemoryContinuityError(
                f"write {namespace}/{key} ttl={ttl_seconds:.0f}s < "
                f"remaining horizon {remaining:.0f}s; entry would reap "
                f"mid-task and read would masquerade as cold start"
            )
        self.store[(namespace, key)] = (value, now + ttl_seconds)

    def read(self, namespace: str, key: str, now: float) -> tuple[ReadStatus, Any]:
        entry = self.store.get((namespace, key))
        if entry is None:
            return ReadStatus.ABSENT, None
        value, expires_at = entry
        if now >= expires_at:
            return ReadStatus.EXPIRED, None
        return ReadStatus.PRESENT, value

    def resolve_route(self, namespace: str, key: str, now: float,
                      derive) -> Any:
        status, value = self.read(namespace, key, now)
        if status is ReadStatus.PRESENT:
            return value
        if status is ReadStatus.EXPIRED:
            # Hard stop: never re-derive from a mutated world state.
            raise MemoryContinuityError(
                f"{namespace}/{key} expired mid-task; re-derivation would "
                f"diverge from the original. Re-plan from last checkpoint."
            )
        # ABSENT is the only case where cold-start derivation is sound.
        return derive()
