# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-lossless-summarization-checkpoint-whose-summary-is-itself-a-lossy-projection-of-a-saturated-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-lossless-summarization-checkpoint-whose-summary-is-itself-a-lossy-projection-of-a-saturated-context-window.warrant.json
# Markdown SHA-256:   923d111421ca10f996d9149e407087576b3de6c37b46ec42890e4d0c7871b0e4
# Code AST SHA-256:   190bd685b0c8aab804b9966cfaf0227a77088c3695116b01b9a25c431e2ded3d
# Verified Classes:   SupersessionLossError, ReplayDivergenceError, Fact, Checkpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SupersessionLossError(RuntimeError):
    """Raised when a checkpoint cannot prove it is closed under supersession."""
    pass


class ReplayDivergenceError(RuntimeError):
    """Raised when resuming from a checkpoint would change a recorded decision."""
    pass


@dataclass
class Fact:
    key: str
    value: str
    prior_value: Optional[str] = None
    changed_at: Optional[int] = None
    reason: Optional[str] = None


@dataclass
class Checkpoint:
    facts: dict[str, Fact] = field(default_factory=dict)
    raw_tail_steps: int = 0
    reconstruction_target: Optional[str] = None

    def assert_supersession_closed(self) -> None:
        for key, fact in self.facts.items():
            # A fact that was ever overridden MUST record the edge.
            if fact.prior_value is not None and (
                fact.changed_at is None or not fact.reason
            ):
                raise SupersessionLossError(
                    f"fact '{key}' was superseded (was {fact.prior_value!r}) "
                    f"but carries no changed_at/reason edge; checkpoint is "
                    f"lossy with respect to supersession."
                )
        if not self.reconstruction_target:
            raise SupersessionLossError(
                "checkpoint has no declared reconstruction target; projection "
                "error is unbounded and cannot be validated."
            )


def resume(checkpoint: Checkpoint, replay_decisions, recorded_decisions) -> None:
    """
    Gate resumption on (1) supersession closure and (2) replay agreement.
    Fails closed: a mismatch refuses resumption rather than resuming lossy.
    """
    checkpoint.assert_supersession_closed()

    if len(replay_decisions) != len(recorded_decisions):
        raise ReplayDivergenceError(
            f"replay produced {len(replay_decisions)} decisions, recorded "
            f"{len(recorded_decisions)}; checkpoint+tail is not a sufficient "
            f"statistic for the next decision."
        )

    for i, (replayed, recorded) in enumerate(
        zip(replay_decisions, recorded_decisions)
    ):
        if replayed != recorded:
            raise ReplayDivergenceError(
                f"decision divergence at replay step {i}: checkpoint would "
                f"drive {replayed!r} but full context drove {recorded!r}. "
                f"Refusing resumption; re-derive from full context."
            )
