# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-hierarchical-auto-compaction-as-a-lossy-transform-and-refuse-to-resume-without-pointer-re-resolution.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-hierarchical-auto-compaction-as-a-lossy-transform-and-refuse-to-resume-without-pointer-re-resolution.warrant.json
# Markdown SHA-256:   656bff429aa6b2282444b230e093d94eda480602b61b0dc55dcfc9631d09005a
# Code AST SHA-256:   dbbb85d10e3332e807eded157665d4af008119d01d3c3003fe8b9a9230ac5fe3
# Verified Classes:   CompactionResumeError, PointerState, PointerClaim, Resolution
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class CompactionResumeError(RuntimeError):
    """Raised when a resumed agent cannot safely rely on a pointer claim."""
    pass


class PointerState(Enum):
    RESOLVED_MATCH = "resolved_match"       # exact bytes, version pinned, matches summary claim
    RESOLVED_MISMATCH = "resolved_mismatch" # resolved, but to a different version/content
    UNRESOLVABLE = "unresolvable"           # expired, deleted, or never existed
    CHAIN_TO_SUMMARY = "chain_to_summary"   # pointer terminates in another lossy summary


@dataclass(frozen=True)
class PointerClaim:
    pointer: str
    claimed_version: str
    summary_node_id: str


@dataclass(frozen=True)
class Resolution:
    state: PointerState
    resolved_version: Optional[str]
    is_verbatim_leaf: bool


# Resolver must implement resolve-or-fail semantics: no fuzzy fallback.
Resolver = Callable[[str], Resolution]


def assert_safe_to_resume(
    claims: list[PointerClaim],
    resolve: Resolver,
    require_verbatim_leaf: bool = True,
) -> None:
    """
    Enforce the resume invariant: every relied-upon pointer must re-resolve
    in the current session to a version-matched, verbatim leaf.

    Raises CompactionResumeError on the first unsafe claim. Callers must NOT
    catch-and-continue; the correct response is to halt the dependent
    sub-task and re-derive or escalate.
    """
    for claim in claims:
        res = resolve(claim.pointer)

        if res.state is PointerState.UNRESOLVABLE:
            raise CompactionResumeError(
                f"Pointer {claim.pointer!r} from summary node "
                f"{claim.summary_node_id!r} is unresolvable. The summary's "
                f"claim about this content is now an unverified assertion; "
                f"refusing to resume on it."
            )

        if res.state is PointerState.RESOLVED_MISMATCH:
            raise CompactionResumeError(
                f"Pointer {claim.pointer!r} resolved to version "
                f"{res.resolved_version!r} but summary {claim.summary_node_id!r} "
                f"was written against {claim.claimed_version!r}. Scope drift: "
                f"the summary's claim is invalid against current content."
            )

        if res.state is PointerState.CHAIN_TO_SUMMARY:
            raise CompactionResumeError(
                f"Pointer {claim.pointer!r} terminates in another summary node, "
                f"not a verbatim leaf. Fidelity is bounded by compounded loss; "
                f"re-derive before relying."
            )

        if require_verbatim_leaf and not res.is_verbatim_leaf:
            raise CompactionResumeError(
                f"Pointer {claim.pointer!r} resolved but target is not a "
                f"verbatim leaf (is_verbatim_leaf=False). Recall claim cannot "
                f"be honored at full fidelity."
            )

        # RESOLVED_MATCH + verbatim leaf: safe to rely on this claim.
