# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-checkpoint-divergence-between-a-hierarchical-summary-and-its-source-spans-before-resuming-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-checkpoint-divergence-between-a-hierarchical-summary-and-its-source-spans-before-resuming-execution.warrant.json
# Markdown SHA-256:   e9eafdec014ece0ce5eb7d1a546651e222837b5186501fed853f7f9ed7c6ff9d
# Code AST SHA-256:   18c7a68008e7a173b2a3777d29d85ef121968b8870f526d51fcebe800422a0e4
# Verified Classes:   CheckpointDivergenceError, Entailment, SourceSpan, SummaryNode
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class CheckpointDivergenceError(RuntimeError):
    """Raised when a summary-derived claim cannot be entailment-verified
    against its source spans before the agent resumes execution."""


class Entailment(Enum):
    ENTAILED = "entailed"
    NOT_ENTAILED = "not_entailed"
    CONTRADICTED = "contradicted"


@dataclass
class SourceSpan:
    span_id: str
    content: str

    def content_hash(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()


@dataclass
class SummaryNode:
    node_id: str
    level: str  # "span" | "segment" | "chapter" | "root"
    text: str
    source_span_ids: list[str] = field(default_factory=list)
    tagged_claims: list[str] = field(default_factory=list)


def verify_entailment(claim: str, spans: list[SourceSpan]) -> Entailment:
    """Stub for an entailment/contradiction model. In production this is a
    judge model instructed to return ENTAILED / NOT_ENTAILED / CONTRADICTED.
    Similarity is explicitly NOT sufficient: 'applied to staging' and
    'applied to production' are near-identical embeddings but contradict."""
    joined = " ".join(s.content.lower() for s in spans)
    claim_l = claim.lower()
    if "production" in claim_l and "production" not in joined and "staging" in joined:
        return Entailment.CONTRADICTED
    if "verified" in claim_l and "error" in joined and "verified" not in joined:
        return Entailment.NOT_ENTAILED
    return Entailment.ENTAILED


def resume_from_checkpoint(
    root: SummaryNode,
    span_store: dict[str, SourceSpan],
    remaining_token_budget: int,
) -> None:
    if not root.source_span_ids:
        raise CheckpointDivergenceError(
            f"root node {root.node_id} carries no span pointers; "
            "it is an unverifiable semantic checkpoint and cannot gate execution"
        )

    for claim in root.tagged_claims:
        spans = [span_store[sid] for sid in root.source_span_ids if sid in span_store]
        if not spans:
            raise CheckpointDivergenceError(
                f"tagged claim {claim!r} has no re-fetchable source spans; "
                "refusing to resume on ungrounded state"
            )
        verdict = verify_entailment(claim, spans)
        if verdict is Entailment.CONTRADICTED:
            raise CheckpointDivergenceError(
                f"tagged claim {claim!r} is CONTRADICTED by source spans "
                f"{[s.span_id for s in spans]}; summary inversion detected, "
                "re-derive from spans before acting"
            )
        if verdict is Entailment.NOT_ENTAILED:
            raise CheckpointDivergenceError(
                f"tagged claim {claim!r} is NOT_ENTAILED by source spans "
                f"{[s.span_id for s in spans]}; possible fabrication, "
                "re-derive from spans before acting"
            )
        if remaining_token_budget <= 0:
            raise CheckpointDivergenceError(
                "token budget exhausted mid-verification; a tagged claim "
                "cannot be confirmed, hard-stop rather than resume on trust"
            )
    # Only reachable when every tagged claim is ENTAILED and budget held.
    return None
