# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-retention-memory-tool-has-silently-violated-its-ttl-erasure-invariant-during-agent-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-retention-memory-tool-has-silently-violated-its-ttl-erasure-invariant-during-agent-resume.warrant.json
# Markdown SHA-256:   22d3419aa46ab4522a2e266422461517fdcba98ca5551cbae9a3c42ea3e5d1de
# Code AST SHA-256:   d88c3f3bf49c971740a8c46748dc33389c51e162ff1f53b2cc1b7696abe69c10
# Verified Classes:   RetentionInvariantViolation, ReadEnvelope, ForgetResult
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass
from typing import Iterable


class RetentionInvariantViolation(RuntimeError):
    """Raised when a scoped-retention memory tool response cannot be trusted
    for erasure/TTL authorization on an agent resume path."""


@dataclass(frozen=True)
class ReadEnvelope:
    candidates: tuple[str, ...]
    hydrated: tuple[str, ...]
    dropped: tuple[str, ...]
    now_monotonic: float | None
    erasure_epoch: int | None
    scope: str


@dataclass(frozen=True)
class ForgetResult:
    ok: bool
    tombstoned: int
    compaction_pending: bool
    scope: str


def authorize_read(envelope: ReadEnvelope, *, expected_scope: str,
                   quarantined_scopes: set[str],
                   prior_dropped: Iterable[str]) -> None:
    """Gate agent behavior on a read envelope. Raises on any structural
    signal that the tool's retention view has diverged from the agent's."""
    if envelope.scope != expected_scope:
        raise RetentionInvariantViolation(
            f"scope mismatch: envelope={envelope.scope!r} expected={expected_scope!r}"
        )
    if envelope.scope in quarantined_scopes:
        raise RetentionInvariantViolation(
            f"read attempted on quarantined scope {envelope.scope!r}; "
            f"call verify_scope first"
        )
    if envelope.now_monotonic is None or envelope.erasure_epoch is None:
        raise RetentionInvariantViolation(
            f"envelope for {envelope.scope!r} missing now_monotonic/erasure_epoch; "
            f"cannot authorize TTL or erasure"
        )
    # Signal 1: candidate/hydration divergence on a scope we did not write to.
    if envelope.dropped and set(envelope.dropped) & set(prior_dropped):
        raise RetentionInvariantViolation(
            f"tombstoned IDs resurfaced as candidates on {envelope.scope!r}: "
            f"{sorted(set(envelope.dropped) & set(prior_dropped))}"
        )
    # Signal 2: recall not ledger-gated (candidates exceed hydrated+dropped).
    if len(envelope.candidates) != len(envelope.hydrated) + len(envelope.dropped):
        raise RetentionInvariantViolation(
            f"cardinality mismatch on {envelope.scope!r}: "
            f"candidates={len(envelope.candidates)} "
            f"hydrated={len(envelope.hydrated)} dropped={len(envelope.dropped)}"
        )


def authorize_forget(result: ForgetResult, *, quarantined_scopes: set[str]) -> None:
    """`forget` with compaction_pending is a conditional success, not a barrier."""
    if not result.ok:
        raise RetentionInvariantViolation(
            f"forget failed on {result.scope!r}; scope remains live"
        )
    if result.compaction_pending:
        quarantined_scopes.add(result.scope)
        raise RetentionInvariantViolation(
            f"forget on {result.scope!r} returned compaction_pending=true; "
            f"scope quarantined pending verify_scope"
        )


def check_ttl(expires_at: float, now_monotonic: float, scope: str) -> None:
    """TTL must be evaluated against the store's monotonic clock, never host time."""
    if expires_at <= now_monotonic:
        raise RetentionInvariantViolation(
            f"record in {scope!r} past TTL: expires_at={expires_at} "
            f"now_monotonic={now_monotonic} (host time {time.time()} is not authoritative)"
        )
