# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-context-diff-self-edits-from-corrupting-rollback-checkpoints.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-context-diff-self-edits-from-corrupting-rollback-checkpoints.warrant.json
# Markdown SHA-256:   70aafbdaa8f912b818de8600af9e1d176c7c59da1ecebc84e39d66b743726de3
# Code AST SHA-256:   da2723b88006e7942598afb41eb0c381caba46b90cd903cbdae1341bf51fe676
# Verified Classes:   ContextDiffInadmissible, CheckpointTainted, Checkpoint, ContextDiff, Lineage
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ContextDiffInadmissible(RuntimeError):
    """Raised when a model-authored diff's base hash does not match the
    checkpoint it is being applied or replayed against."""
    pass


class CheckpointTainted(RuntimeError):
    """Raised when a sealed checkpoint's bytes changed after sealing,
    invalidating all lineage entries that reference it."""
    pass


def _hash(state: str) -> str:
    return hashlib.sha256(state.encode("utf-8")).hexdigest()


@dataclass(frozen=True)
class Checkpoint:
    cp_id: str
    state: str
    restore_hash: str
    sealed: bool = True


@dataclass(frozen=True)
class ContextDiff:
    diff_id: str
    base_hash: str          # hash of the base the MODEL authored against
    delete_span: tuple[int, int]
    insert_text: str


@dataclass
class Lineage:
    entries: list[tuple[str, str]] = field(default_factory=list)  # (diff_id, applied_hash)


def seal_checkpoint(cp_id: str, state: str) -> Checkpoint:
    return Checkpoint(cp_id=cp_id, state=state, restore_hash=_hash(state))


def apply_diff(current_state: str, diff: ContextDiff) -> str:
    if _hash(current_state) != diff.base_hash:
        raise ContextDiffInadmissible(
            f"diff {diff.diff_id} authored against base {diff.base_hash[:12]} "
            f"but live base is {_hash(current_state)[:12]}; refusing fuzzy apply"
        )
    start, end = diff.delete_span
    return current_state[:start] + diff.insert_text + current_state[end:]


def verify_checkpoint(cp: Checkpoint) -> None:
    if _hash(cp.state) != cp.restore_hash:
        raise CheckpointTainted(
            f"checkpoint {cp.cp_id} bytes mutated after seal; "
            f"expected {cp.restore_hash[:12]}, found {_hash(cp.state)[:12]}"
        )


def replay_lineage(cp: Checkpoint, diffs: dict[str, ContextDiff],
                   lineage: Lineage) -> str:
    verify_checkpoint(cp)
    state = cp.state
    for diff_id, recorded_hash in lineage.entries:
        diff = diffs[diff_id]
        if _hash(state) != diff.base_hash:
            raise ContextDiffInadmissible(
                f"replay hop {diff_id}: base {diff.base_hash[:12]} != "
                f"current {_hash(state)[:12]}; lineage diverged, cold-start required"
            )
        state = apply_diff(state, diff)
        if _hash(state) != recorded_hash:
            raise ContextDiffInadmissible(
                f"replay hop {diff_id}: post-apply hash {_hash(state)[:12]} "
                f"!= recorded {recorded_hash[:12]}; non-deterministic replay"
            )
    return state
