# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-context-snapshot-has-silently-diverged-from-its-parent-at-resume-time.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-context-snapshot-has-silently-diverged-from-its-parent-at-resume-time.warrant.json
# Markdown SHA-256:   4f51fad4dd32e2dbaae61671af455c086ab5808ed9da8ef6c1f35efc3dea6217
# Code AST SHA-256:   27db060291e2d6b36e29545a69d0000d19d6ce1b0aca8b33b6303f7771eadbc5
# Verified Classes:   ContextDivergenceError, OpKind, Mutation, Snapshot
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class ContextDivergenceError(RuntimeError):
    """Raised when a resumed delegate's snapshot may be semantically stale."""


class OpKind(Enum):
    ADD = "add"
    REVISE = "revise"
    INVALIDATE = "invalidate"


@dataclass(frozen=True)
class Mutation:
    kind: OpKind
    entity_id: str


@dataclass
class Snapshot:
    base_checkpoint_id: str
    diff_base_epoch: int
    referenced_entity_ids: frozenset[str] = field(default_factory=frozenset)


def assert_resume_safe(
    snapshot: Snapshot,
    parent_head_checkpoint_id: str,
    parent_epoch: int,
    mutation_log: Iterable[Mutation] | None,
) -> str:
    """Decide whether a suspended delegate may resume against a mutated parent.

    Returns a resume verdict: 'in_place', 'correct_then_resume', or 'restart'.
    Raises ContextDivergenceError when the mutation history is uncomputable.
    """
    if mutation_log is None:
        # Parent history pruned or base checkpoint unresolvable: fail closed.
        raise ContextDivergenceError(
            f"cannot compute mutations from {snapshot.base_checkpoint_id} "
            f"to {parent_head_checkpoint_id}; history unavailable"
        )

    if snapshot.base_checkpoint_id == parent_head_checkpoint_id:
        return "in_place"

    if parent_epoch < snapshot.diff_base_epoch:
        raise ContextDivergenceError(
            f"epoch regression: snapshot epoch {snapshot.diff_base_epoch} "
            f"> parent epoch {parent_epoch}"
        )

    overlapping: list[Mutation] = []
    for mut in mutation_log:
        if mut.kind is OpKind.ADD:
            continue
        if mut.entity_id in snapshot.referenced_entity_ids:
            overlapping.append(mut)

    if not overlapping:
        return "in_place"  # stale-but-sound: append-only, disjoint

    if all(m.kind is OpKind.REVISE for m in overlapping):
        return "correct_then_resume"  # targeted diff can repair

    # Any INVALIDATE on a referenced entity, or mixed ops: full restart.
    return "restart"


def resume_delegate(
    snapshot: Snapshot,
    parent_head_checkpoint_id: str,
    parent_epoch: int,
    mutation_log: Iterable[Mutation] | None,
) -> None:
    verdict = assert_resume_safe(
        snapshot, parent_head_checkpoint_id, parent_epoch, mutation_log
    )
    if verdict == "restart":
        raise ContextDivergenceError(
            f"snapshot at {snapshot.base_checkpoint_id} references invalidated "
            f"entities; cannot resume in place, restart required"
        )
    # ... dispatch resume / correction-diff injection ...
