# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-lossless-summarization-checkpoint-as-a-recovery-point-rather-than-a-lossy-projection.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-lossless-summarization-checkpoint-as-a-recovery-point-rather-than-a-lossy-projection.warrant.json
# Markdown SHA-256:   c9c56f5edc4c15d86eb3330b1c65947a82a1314f98681a331681b76c72ca3270
# Code AST SHA-256:   a987ef1b79156fd0780e1d0fbddcafb4f521e6c7d45d26409590a23f7ceb2933
# Verified Classes:   CompactionProvenanceError, Span, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionProvenanceError(RuntimeError):
    """Raised when a rehydrated checkpoint cannot authorize an irreversible action."""
    pass


@dataclass
class Span:
    handle: str          # stable "turn:byte_start:byte_end"
    verbatim: str
    is_gating: bool      # prohibition / sign-off / non-idempotence / authz boundary


@dataclass
class Checkpoint:
    assertions: list[tuple[str, Optional[str]]]  # (text, span_handle or None)
    raw_store_live: bool
    gating_spans: list[Span] = field(default_factory=list)


IRREVERSIBLE_ACTIONS = {"schema_migrate", "deploy", "delete", "external_write"}


def authorize_resume(checkpoint: Checkpoint, pending_action: str) -> None:
    if pending_action not in IRREVERSIBLE_ACTIONS:
        return  # reversible work may proceed on a projection

    # 1. Every gating span must survive verbatim, not paraphrased.
    for span in checkpoint.gating_spans:
        if not any(span.handle == h for _, h in checkpoint.assertions):
            raise CompactionProvenanceError(
                f"gating span {span.handle} has no back-reference in checkpoint; "
                f"prohibition may have been paraphrased away"
            )

    # 2. Unsourced assertions bearing on an irreversible action block resume.
    unsourced = [text for text, handle in checkpoint.assertions if handle is None]
    if unsourced:
        raise CompactionProvenanceError(
            f"irreversible action '{pending_action}' rests on {len(unsourced)} "
            f"UNSOURCED assertion(s): {unsourced[:3]!r}"
        )

    # 3. Degraded recovery: raw store evicted -> escalate, do not proceed silently.
    if not checkpoint.raw_store_live:
        raise CompactionProvenanceError(
            f"raw transcript evicted; checkpoint is a degraded projection and "
            f"cannot authorize '{pending_action}' without re-derivation"
        )


def resume_task(checkpoint: Checkpoint, next_action: str) -> str:
    authorize_resume(checkpoint, next_action)
    return f"resumed; authorized {next_action} against live spans"
