# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-the-recovery-path-when-auto-compaction-summarizes-the-checkpoint-that-was-meant-to-restore-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-the-recovery-path-when-auto-compaction-summarizes-the-checkpoint-that-was-meant-to-restore-it.warrant.json
# Markdown SHA-256:   36028b1755995bea5883c23ec95d7b76ae67b0363b86dad5d897636768b7d7e5
# Code AST SHA-256:   faca358dc2999b8bd7935447a6e9f65d6858c8d3836cef73cbe13fcf472043bf
# Verified Classes:   CompactionInvariantError, SegmentClass, Segment, Checkpoint, CompactionResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CompactionInvariantError(RuntimeError):
    """Raised when a compaction would destroy unrecoverable procedural state."""
    pass


class SegmentClass(Enum):
    NARRATIVE = "narrative"
    PROCEDURAL = "procedural"


@dataclass
class Segment:
    index: int
    text: str
    cls: SegmentClass


@dataclass
class Checkpoint:
    goal: str
    last_tool_invocation: str
    open_preconditions: list[str]
    invalidation_conditions: list[str]

    def is_complete(self) -> bool:
        return bool(
            self.goal
            and self.last_tool_invocation
            and self.invalidation_conditions
        )


@dataclass
class CompactionResult:
    surviving_narrative_summary: str
    checkpoints: list[Checkpoint] = field(default_factory=list)


def compact(segments: list[Segment], token_budget: int) -> CompactionResult:
    checkpoints: list[Checkpoint] = []
    narrative: list[str] = []

    for seg in segments:
        if seg.cls is SegmentClass.PROCEDURAL:
            # A procedural segment must yield a complete typed checkpoint.
            ckpt = extract_checkpoint(seg)
            if not ckpt.is_complete():
                raise CompactionInvariantError(
                    f"segment {seg.index} is PROCEDURAL but checkpoint is "
                    f"incomplete; refusing lossy summary of recovery path"
                )
            checkpoints.append(ckpt)
        else:
            narrative.append(seg.text)

    summary = summarize(narrative, token_budget)
    return CompactionResult(summary, checkpoints)


def extract_checkpoint(seg: Segment) -> Checkpoint:
    # Placeholder for a structured extractor; must not be a prose summarizer.
    return Checkpoint(
        goal="",
        last_tool_invocation="",
        open_preconditions=[],
        invalidation_conditions=[],
    )


def summarize(narrative: list[str], token_budget: int) -> str:
    return " ".join(narrative)[: token_budget * 4]


def continuity_probe(result: CompactionResult, expected_invocation: str) -> None:
    """Gate resumption: the compacted context must still contain the recovery path."""
    for ckpt in result.checkpoints:
        if ckpt.last_tool_invocation == expected_invocation:
            return
    raise CompactionInvariantError(
        f"post-compaction continuity probe failed: expected invocation "
        f"{expected_invocation!r} not present in surviving checkpoints"
    )
