# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-task-critical-state-when-auto-compaction-summarizes-a-checkpoint-it-will-later-need-to-resume-from.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-task-critical-state-when-auto-compaction-summarizes-a-checkpoint-it-will-later-need-to-resume-from.warrant.json
# Markdown SHA-256:   7f7ae2fc4f479378d4d3f2d33df65e50de517a9d0b7d28cc54b07f6b4689f9a2
# Code AST SHA-256:   64648a0d0988bdcb7a3f1549f55917eaedcdb9e2b9505295e283390c4da10888
# Verified Classes:   UnsafeCompactionCheckpoint, Span, ResumeSpine
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field

# Identifier-shaped tokens that, if minted in a summarized span and later
# referenced, must be hoisted verbatim into the resume spine.
_IDENT_RE = re.compile(r"\b(?:0x[0-9a-fA-F]+|[A-Za-z_]+_off=\d+|[A-Za-z_]+_(?:id|key|cursor|lock|nonce)=\S+)\b")
# Imperative negations / discovered limits that must survive verbatim.
_NEGATION_RE = re.compile(r"\b(do not|don't|avoid|never|failed because|must not|without .*? timeout)\b", re.IGNORECASE)


class UnsafeCompactionCheckpoint(RuntimeError):
    """Raised when a checkpoint would make a lossy digest the sole carrier of
    resume-critical state (minted IDs or negative constraints)."""
    pass


@dataclass
class Span:
    messages: list[str]
    retrievable_id: str


@dataclass
class ResumeSpine:
    identifiers: set[str] = field(default_factory=set)
    constraints: list[str] = field(default_factory=list)


def build_checkpoint(span: Span, later_tool_args: list[str], digest: str) -> tuple[str, ResumeSpine]:
    """Partition a to-be-summarized span into a lossy digest + verbatim spine.

    Refuses to emit a resumable checkpoint if resume-critical state would be
    left only inside the digest.
    """
    joined = "\n".join(span.messages)
    later = "\n".join(later_tool_args)

    minted = {m.group(0) for m in _IDENT_RE.finditer(joined)}
    # Only identifiers that a LATER step actually references are load-bearing.
    referenced = {tok for tok in minted if tok in later}

    constraints = [line.strip() for line in span.messages if _NEGATION_RE.search(line)]

    spine = ResumeSpine(identifiers=referenced, constraints=constraints)

    if referenced and not spine.identifiers:
        # Defensive: referenced IDs exist but were not captured (e.g. regex miss).
        raise UnsafeCompactionCheckpoint(
            f"span {span.retrievable_id}: {len(referenced)} referenced identifiers "
            f"would be lost to digest-only state"
        )
    if constraints and not spine.constraints:
        raise UnsafeCompactionCheckpoint(
            f"span {span.retrievable_id}: negative constraints present but not hoisted"
        )
    if not span.retrievable_id:
        raise UnsafeCompactionCheckpoint(
            f"span {span.retrievable_id}: digest has no retrievable source pointer"
        )

    # Digest is stamped as derivative so the resumed instance must re-verify.
    tagged = f"[DIGEST span={span.retrievable_id} derivative=true]\n{digest}"
    return tagged, spine


def load_checkpoint(digest: str, spine: ResumeSpine, probe) -> ResumeSpine:
    """Cold-start loader: verify paraphrase-derived premises before acting."""
    if "derivative=true" not in digest:
        raise UnsafeCompactionCheckpoint("digest missing provenance tag; refusing resume")
    for ident in spine.identifiers:
        if not probe(ident):
            raise UnsafeCompactionCheckpoint(
                f"resume premise unverified against primary record: {ident}"
            )
    return spine
