# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-history-mid-task-the-summarization-commit-invariant-and-the-orphaned-antecedent-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-history-mid-task-the-summarization-commit-invariant-and-the-orphaned-antecedent-failure.warrant.json
# Markdown SHA-256:   7be80db59c186d388767e36e021ab5cbe6631d8c80d8ddcc1958a770f3c0af12
# Code AST SHA-256:   0318ea1a2f12515b8b7da372463ff5db01470b55091ff4cd6aed09d097d1e95d
# Verified Classes:   CompactionOrphanError, Obligation, ObligationLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionOrphanError(RuntimeError):
    """Raised when a compaction span would orphan a live antecedent or in-flight call."""
    pass


@dataclass
class Obligation:
    oid: str
    kind: str                 # "precondition" | "in_flight_call" | "open_constraint"
    established_turn: int
    resolved: bool = False


@dataclass
class ObligationLedger:
    obligations: dict[str, Obligation] = field(default_factory=dict)

    def live(self) -> list[Obligation]:
        return [o for o in self.obligations.values() if not o.resolved]

    def intersects(self, start_turn: int, end_turn: int) -> list[Obligation]:
        return [
            o for o in self.live()
            if start_turn <= o.established_turn <= end_turn
        ]


def compact_span(
    ledger: ObligationLedger,
    start_turn: int,
    end_turn: int,
    raw_span_retained: bool,
) -> str:
    # Condition 3: replayability — compaction must be a view, not a deletion.
    if not raw_span_retained:
        raise CompactionOrphanError(
            f"span [{start_turn},{end_turn}] not replayable; "
            "refusing to compact without raw-span retention"
        )

    # Conditions 1 & 2: closure + antecedent quiescence, via the ledger.
    live = ledger.intersects(start_turn, end_turn)
    if live:
        ids = ", ".join(f"{o.oid}({o.kind}@{o.established_turn})" for o in live)
        raise CompactionOrphanError(
            f"span [{start_turn},{end_turn}] contains live obligations: {ids}. "
            "Drain in-flight calls or externalize antecedents to the ledger, "
            "then compact the settled prefix only."
        )

    # Eligible: summarize narrative only; obligations never enter the summary.
    return _summarize(start_turn, end_turn)


def _summarize(start_turn: int, end_turn: int) -> str:
    # Placeholder for the lossy summarizer over the settled span.
    return f"<summary of settled turns {start_turn}..{end_turn}>"
