# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-the-divergence-between-a-model-authored-context-rewrite-and-the-checkpoint-it-claims-to-roll-back-to.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-the-divergence-between-a-model-authored-context-rewrite-and-the-checkpoint-it-claims-to-roll-back-to.warrant.json
# Markdown SHA-256:   058ced17604302b7d54a82cab022aa3013f24a7280ffdc248b3259dd9f7c2c33
# Code AST SHA-256:   2ad093a699ef1cabfc87d511b361d04ebba2023c0449c53ac2ebb03d2143a6df
# Verified Classes:   CheckpointRollbackError, Checkpoint, SideEffectLedger, RewriteIntent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class CheckpointRollbackError(RuntimeError):
    """Raised when a model-authored rollback names a checkpoint that cannot be safely restored."""
    pass


def _digest(obj) -> str:
    return hashlib.sha256(json.dumps(obj, sort_keys=True).encode()).hexdigest()


@dataclass
class Checkpoint:
    ckpt_id: str
    context_digest: str
    step_index: int


@dataclass
class SideEffectLedger:
    # maps step_index -> list of non-idempotent tool call ids
    entries: dict = field(default_factory=dict)

    def non_idempotent_between(self, lo: int, hi: int) -> list:
        out = []
        for step, calls in self.entries.items():
            if lo < step <= hi:
                out.extend(calls)
        return out


@dataclass
class RewriteIntent:
    kind: str                 # "discard_rewrite" | "rollback_to_checkpoint"
    base_digest: str          # digest of context the model actually read
    target_ckpt_id: Optional[str] = None


def apply_rewrite(
    intent: RewriteIntent,
    live_context_digest: str,
    live_step_index: int,
    checkpoints: dict,
    ledger: SideEffectLedger,
) -> str:
    # Gate 1: the model must have reasoned over the live context, not a stale view.
    if intent.base_digest != live_context_digest:
        raise CheckpointRollbackError(
            f"stale base: rewrite computed against {intent.base_digest[:12]} "
            f"but live context is {live_context_digest[:12]}"
        )

    if intent.kind == "discard_rewrite":
        # Pre-rewrite context is, by construction, the live context at apply time.
        return live_context_digest

    if intent.kind != "rollback_to_checkpoint":
        raise CheckpointRollbackError(f"unknown rewrite kind {intent.kind!r}")

    ckpt = checkpoints.get(intent.target_ckpt_id)
    if ckpt is None:
        raise CheckpointRollbackError(f"unknown checkpoint {intent.target_ckpt_id!r}")

    # Gate 2: intervening non-idempotent side effects make the rollback a splice.
    effects = ledger.non_idempotent_between(ckpt.step_index, live_step_index)
    if effects:
        raise CheckpointRollbackError(
            f"rollback to {ckpt.ckpt_id} crosses {len(effects)} non-idempotent "
            f"side effects ({effects}); refusing to orphan them"
        )

    return ckpt.context_digest
