# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-after-lossy-context-compaction-when-the-summarizer-s-own-tokens-are-indistinguishable-from-the-source-it-su.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-after-lossy-context-compaction-when-the-summarizer-s-own-tokens-are-indistinguishable-from-the-source-it-su.warrant.json
# Markdown SHA-256:   f2381ef95f4bd1a9d543f44e270ae1550d33650a8c60d7719d3319b90a77665d
# Code AST SHA-256:   d2457808c0f05fde5a9c7dfd0745a2ecfb20bc62376df9b6b70820dcf3ef7512
# Verified Classes:   CompactionIntegrityError, Currency, Recoverability, SummaryClaim, CompactionResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class CompactionIntegrityError(RuntimeError):
    """Raised when a summary cannot be safely reasoned on after compaction."""


class Currency(Enum):
    CURRENT = "current"
    SUPERSEDED = "superseded"


class Recoverability(Enum):
    VERBATIM_IN_FILE = "verbatim-in-file"
    RE_DERIVABLE_BY_TOOL = "re-derivable-by-tool"
    EPHEMERAL = "ephemeral"  # existed only in discarded tokens


@dataclass(frozen=True)
class SummaryClaim:
    key: str
    value: str
    currency: Currency
    recoverability: Recoverability
    superseded_by: str | None = None


@dataclass
class CompactionResult:
    claims: list[SummaryClaim] = field(default_factory=list)
    corrections_seen: int = 0


def assert_safe_to_reason_on(
    result: CompactionResult,
    *,
    re_verifiable: Iterable[str] = (),
) -> None:
    """Refuse to resume reasoning on a summary that hides supersession.

    The invariant: every claim must be CURRENT, or SUPERSEDED with a
    resolvable supersession edge, or EPHEMERAL-and-current (nothing to
    re-fetch but nothing stale either). Any SUPERSEDED claim whose
    replacement is not present in the summary, or any EPHEMERAL claim
    that is superseded, is a correction-amnesia hazard.
    """
    re_verifiable_set = set(re_verifiable)
    present_keys = {c.key for c in result.claims}

    for claim in result.claims:
        if claim.currency is Currency.SUPERSEDED:
            if claim.superseded_by is None:
                raise CompactionIntegrityError(
                    f"claim {claim.key!r} is SUPERSEDED with no edge; "
                    "summary dropped the correction that obsoleted it"
                )
            if claim.superseded_by not in present_keys and (
                claim.superseded_by not in re_verifiable_set
            ):
                raise CompactionIntegrityError(
                    f"claim {claim.key!r} superseded by {claim.superseded_by!r}, "
                    "which is neither in the summary nor re-verifiable"
                )
        if (
            claim.recoverability is Recoverability.EPHEMERAL
            and claim.currency is Currency.SUPERSEDED
        ):
            raise CompactionIntegrityError(
                f"claim {claim.key!r} is ephemeral AND superseded: the current "
                "value existed only in discarded tokens and cannot be recovered"
            )

    if result.corrections_seen > 0 and not any(
        c.currency is Currency.SUPERSEDED for c in result.claims
    ):
        raise CompactionIntegrityError(
            f"compaction window contained {result.corrections_seen} correction(s) "
            "but the summary emitted no supersession edges — correction amnesia"
        )


def compact_and_resume(
    result: CompactionResult,
    *,
    re_verifiable: Iterable[str] = (),
) -> None:
    # Guardrail: fail closed. If the summary cannot prove currency,
    # do not reason on it — offload and retrieve instead.
    assert_safe_to_reason_on(result, re_verifiable=re_verifiable)
    # ... resume reasoning here, only on validated claims ...
