# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-re-plan-itself-into-a-checkpoint-it-cannot-restore-from-after-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-re-plan-itself-into-a-checkpoint-it-cannot-restore-from-after-compaction.warrant.json
# Markdown SHA-256:   f36b17832e87429aa199e3abe16b964a742fac239b601cb9106d5dff0d8d64de
# Code AST SHA-256:   6910634e5db3abc7f3bb189c5f1158c9d76de81d789bcf924b3c3364a579cdba
# Verified Classes:   CheckpointRestoreError, Anchor, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import tokenize
from dataclasses import dataclass, field


class CheckpointRestoreError(RuntimeError):
    """Raised when a checkpoint cannot be restored against live context state."""
    pass


@dataclass
class Anchor:
    turn_id: int
    verbatim: bool


@dataclass
class Checkpoint:
    plan: list
    anchors: list
    budget_remaining_serialized: int
    digest_manifest: dict = field(default_factory=dict)


def restore_checkpoint(cp: Checkpoint, live_context_tokens: int, total_budget: int,
                       live_verbatim_turns: set) -> dict:
    # Invariant 1: budget is re-measured, never trusted from the checkpoint.
    true_remaining = total_budget - live_context_tokens
    if cp.budget_remaining_serialized - true_remaining > 0.15 * total_budget:
        raise CheckpointRestoreError(
            f"budget divergence {cp.budget_remaining_serialized - true_remaining} "
            f"exceeds 15% threshold; checkpoint ledger is stale"
        )

    # Invariant 2: every anchor must resolve verbatim at resume time.
    for a in cp.anchors:
        if a.turn_id not in live_verbatim_turns:
            raise CheckpointRestoreError(
                f"anchor turn {a.turn_id} was compacted away; "
                f"plan references content that no longer exists verbatim. "
                f"Re-plan with digest_manifest surcharge, do not resume."
            )

    return {"budget_remaining": true_remaining, "plan": cp.plan}
