# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-durability-memory-tool-write-has-silently-downgraded-to-ephemeral-tier-before-a-forget-tombstone-is-committe.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-durability-memory-tool-write-has-silently-downgraded-to-ephemeral-tier-before-a-forget-tombstone-is-committe.warrant.json
# Markdown SHA-256:   4820f937883255d3e02444586e7d96167d844dc7560e4a8ca84415615baa1b63
# Code AST SHA-256:   7d3065aa4067b8a7b278ad99d9e325a8c2122354aefc731282265f68b47d4a65
# Verified Classes:   TombstoneScopeMismatch, ForgetAck, RecordMeta
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class TombstoneScopeMismatch(RuntimeError):
    """Raised when a forget's tier coverage does not dominate the record's tier history."""
    pass


@dataclass(frozen=True)
class ForgetAck:
    status: str
    tombstone_id: str
    tiers_covered: FrozenSet[str]
    pinned_through_tombstone: bool


@dataclass(frozen=True)
class RecordMeta:
    key: str
    tier_pinned: bool
    tier_history: FrozenSet[str]


def assert_forget_dominates(meta: RecordMeta, ack: ForgetAck) -> None:
    """
    Enforce tier-monotonic tombstone dominance before the agent treats a
    forget as terminal. A 'committed' status is insufficient on its own.
    """
    if ack.status != "committed":
        raise TombstoneScopeMismatch(
            f"forget({meta.key}) not committed: status={ack.status!r}"
        )

    uncovered = meta.tier_history - ack.tiers_covered
    if uncovered:
        raise TombstoneScopeMismatch(
            f"forget({meta.key}) tombstone {ack.tombstone_id} covers "
            f"{sorted(ack.tiers_covered)} but record occupied "
            f"{sorted(meta.tier_history)}; uncovered tiers {sorted(uncovered)} "
            f"may resurrect value after rebalancer pass"
        )

    if not meta.tier_pinned and not ack.pinned_through_tombstone:
        raise TombstoneScopeMismatch(
            f"forget({meta.key}) tombstone {ack.tombstone_id} is unpinned; "
            f"record tier was not pinned at write and tombstone does not "
            f"pin through its TTL — future demotion can escape coverage"
        )


def safe_forget(memory_tool, key: str) -> ForgetAck:
    meta = memory_tool.metadata(key)
    ack = memory_tool.forget(key)
    assert_forget_dominates(meta, ack)
    return ack
