# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-summary-collapse-before-compaction-destroys-unrecoverable-trajectory-state.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-summary-collapse-before-compaction-destroys-unrecoverable-trajectory-state.warrant.json
# Markdown SHA-256:   3ac29809b98f4330c9d0faf3d89ecb3a47207af42611f19e44b65b9a29655119
# Code AST SHA-256:   dc26c51fc3e9ad1fb8779dba1802e92bb3b27f4dfe42c2388fad5fc162b69966
# Verified Classes:   SummaryCollapseError, Commitment, CompactionResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class SummaryCollapseError(RuntimeError):
    """Raised when a post-compaction summary has lost or fabricated commitment state."""


@dataclass(frozen=True)
class Commitment:
    kind: str          # "PROHIBIT" | "REQUIRE" | "IN_FLIGHT"
    text: str


@dataclass
class CompactionResult:
    summary: str
    raw_window_retained: bool
    synthesized_claims: list[str] = field(default_factory=list)


def _normalize(s: str) -> str:
    return " ".join(s.lower().split())


def verify_compaction(
    ledger: Iterable[Commitment],
    result: CompactionResult,
    *,
    allow_paraphrase: bool = False,
) -> None:
    """
    Enforce the compaction invariant: every ledger commitment must survive
    verbatim, or be explicitly tombstoned. Fabricated continuity always halts.
    """
    summary_norm = _normalize(result.summary)

    if result.synthesized_claims:
        # Confabulated continuity: summary asserts steps the window never took.
        raise SummaryCollapseError(
            f"summary contains {len(result.synthesized_claims)} synthesized "
            f"claim(s) with no supporting step; summary is not a faithful "
            f"projection. First: {result.synthesized_claims[0]!r}"
        )

    missing: list[Commitment] = []
    for c in ledger:
        needle = _normalize(c.text)
        if needle in summary_norm:
            continue
        if allow_paraphrase and _normalize(c.kind) in summary_norm:
            # Paraphrase present: recoverable by re-compaction, not a halt.
            continue
        missing.append(c)

    if missing:
        if result.raw_window_retained:
            # Recoverable: re-summarize with verbatim-carry directive.
            raise SummaryCollapseError(
                f"{len(missing)} commitment(s) dropped but raw window retained; "
                f"re-compact with verbatim carry. First: {missing[0]!r}"
            )
        # Unrecoverable: fail closed, do not re-compact a collapsed summary.
        raise SummaryCollapseError(
            f"{len(missing)} commitment(s) lost with no retained window; "
            f"halt and surface to durable state. First: {missing[0]!r}"
        )


def compact_and_verify(
    ledger: list[Commitment],
    summarize,  # callable(window) -> CompactionResult
    window: str,
) -> str:
    result = summarize(window)
    verify_compaction(ledger, result)
    return result.summary
