# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-ttl-expiry-as-a-semantic-invalidation-rather-than-a-cache-miss-when-reading-from-a-typed-memory-store.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-ttl-expiry-as-a-semantic-invalidation-rather-than-a-cache-miss-when-reading-from-a-typed-memory-store.warrant.json
# Markdown SHA-256:   a81c9bcf80834c1649b3f7c77facdb7e4eb21426fa1003425e7007f9bd2a7677
# Code AST SHA-256:   bd5efdee31f3f8635b47d8248e527203ba3e5b74bac0deab9a7f1a71633be0b0
# Verified Classes:   MissReason, ResurrectionError, Miss, WriteIntent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class MissReason(str, Enum):
    ABSENT = "absent"
    EXPIRED = "expired"
    FORGOTTEN = "forgotten"


class ResurrectionError(RuntimeError):
    """Raised when a write-after-miss would launder a decayed or revoked record into a fresh one."""


@dataclass
class Miss:
    key: str
    reason: MissReason
    last_written_at: Optional[float]  # epoch seconds, None if never written
    last_written_by: Optional[str]    # provenance tag, None if never written


@dataclass
class WriteIntent:
    key: str
    value: str
    provenance: str          # "self" for context-carried, else a source id
    provenance_at: float     # epoch seconds the witness was observed
    target_class: str        # "semantic" | "procedural" | "scratchpad"


def guard_write_after_miss(miss: Miss, intent: WriteIntent) -> None:
    """Enforce monotonic-trust decay: an expired/forgotten record may not be healed
    from the agent's own prior context, and a forgotten record may not be healed at all."""

    if miss.reason is MissReason.FORGOTTEN:
        raise ResurrectionError(
            f"write to {intent.key!r} rejected: record was explicitly forgotten (tombstone), "
            f"not merely decayed; resurrection forbidden regardless of provenance"
        )

    if miss.reason is MissReason.ABSENT:
        return  # no prior to resurrect

    # miss.reason is EXPIRED from here on.
    if intent.provenance == "self":
        raise ResurrectionError(
            f"write to {intent.key!r} rejected: expired record would be resurrected from "
            f"agent's own context (provenance='self'); escalate or downgrade to scratchpad"
        )

    if miss.last_written_at is not None and intent.provenance_at <= miss.last_written_at:
        raise ResurrectionError(
            f"write to {intent.key!r} rejected: provenance timestamp "
            f"{intent.provenance_at} does not postdate expired record's last write "
            f"{miss.last_written_at}; witness is not newer than the decayed fact"
        )

    if intent.target_class in ("semantic", "procedural") and intent.provenance.startswith("scratchpad:"):
        raise ResurrectionError(
            f"write to {intent.key!r} rejected: cannot promote scratchpad-derived evidence "
            f"into durable class {intent.target_class!r} after a TTL expiry"
        )
