# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-orphaned-a-tool-call-boundary-before-checkpoint-recovery.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-orphaned-a-tool-call-boundary-before-checkpoint-recovery.warrant.json
# Markdown SHA-256:   85588992e1c53fbbde17102d8ba29bfcdf8d8a09afc0a57af18fdafcb42e2e45
# Code AST SHA-256:   3657b270d102cdb0d083fbfd5dece528569b0c48f32e79177a64e8b2604a82b4
# Verified Classes:   OrphanedToolBoundaryError, GenerationMismatchError, MessagePair, Checkpoint, Transcript
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class OrphanedToolBoundaryError(RuntimeError):
    """Raised when a checkpoint resume would cross a structurally broken tool-pair seam."""
    pass


class GenerationMismatchError(RuntimeError):
    """Raised when checkpoint generation does not match transcript generation."""
    pass


@dataclass(frozen=True)
class MessagePair:
    message_id: str          # stable content hash of the canonical pair
    tool_use: dict
    tool_result: dict

    @staticmethod
    def canonical_id(tool_use: dict, tool_result: dict) -> str:
        h = hashlib.sha256()
        h.update(repr(sorted(tool_use.items())).encode())
        h.update(repr(sorted(tool_result.items())).encode())
        return h.hexdigest()[:16]


@dataclass
class Checkpoint:
    last_message_id: str
    generation: int


@dataclass
class Transcript:
    pairs: list[MessagePair]
    generation: int

    def index_of(self, message_id: str) -> Optional[int]:
        for i, p in enumerate(self.pairs):
            if p.message_id == message_id:
                return i
        return None


def resume_from_checkpoint(cp: Checkpoint, transcript: Transcript) -> int:
    """
    Returns the index from which to resume execution.
    Raises if the resume would cross an orphaned or mismatched boundary.
    """
    if cp.generation != transcript.generation:
        raise GenerationMismatchError(
            f"checkpoint generation {cp.generation} != transcript generation "
            f"{transcript.generation}; compaction invalidated positional state"
        )

    idx = transcript.index_of(cp.last_message_id)
    if idx is None:
        raise OrphanedToolBoundaryError(
            f"checkpoint message_id {cp.last_message_id!r} absent from transcript; "
            f"cannot resume by position without risking silent divergence"
        )

    pair = transcript.pairs[idx]
    # Pair-atomicity check: both halves must be present and non-empty.
    if not pair.tool_use or not pair.tool_result:
        raise OrphanedToolBoundaryError(
            f"turn {idx} ({pair.message_id}) is a half-pair: "
            f"tool_use={bool(pair.tool_use)} tool_result={bool(pair.tool_result)}"
        )

    # Verify predecessor chain is intact (no gap before resume point).
    if idx > 0 and transcript.pairs[idx - 1].message_id == pair.message_id:
        raise OrphanedToolBoundaryError(
            f"duplicate message_id {pair.message_id!r} at {idx-1} and {idx}; "
            f"compaction seam produced ambiguous addressing"
        )

    return idx + 1
