# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-lossy-transcript-compaction-to-preserve-a-pending-commit-invariant-across-the-summarization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-lossy-transcript-compaction-to-preserve-a-pending-commit-invariant-across-the-summarization-boundary.warrant.json
# Markdown SHA-256:   aa0915124cc5fcad39fe1c000e71f832d6b922d953a48717172ce48c200b56f9
# Code AST SHA-256:   14e16a1f961e9c09a2be5ad897551a753ca52eb78127f1ce43d9001623e92ebc
# Verified Classes:   CompactionInvariantError, ObligationState, Obligation, ObligationLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class CompactionInvariantError(RuntimeError):
    """Raised when a compaction would erase an open obligation from the transcript."""
    pass


class ObligationState(Enum):
    OPEN = "open"
    RESOLVED = "resolved"
    ABANDONED = "abandoned"


@dataclass
class Obligation:
    kind: str                 # "staged_commit", "subagent_join", "armed_rollback"
    handle: str               # opaque continuation token, e.g. "tok_9f2a"
    opened_at: float
    deadline: float           # absolute epoch; expiry forces abandonment
    terminal_predicate: str
    state: ObligationState = ObligationState.OPEN

    def is_expired(self, now: Optional[float] = None) -> bool:
        return (now or time.time()) >= self.deadline


class ObligationLedger:
    def __init__(self) -> None:
        self._obligations: dict[str, Obligation] = {}

    def register(self, ob: Obligation) -> None:
        self._obligations[ob.handle] = ob

    def open_handles(self) -> list[str]:
        return [h for h, o in self._obligations.items() if o.state is ObligationState.OPEN]

    def resolve(self, handle: str) -> None:
        self._obligations[handle].state = ObligationState.RESOLVED

    def abandon(self, handle: str, reason: str) -> None:
        ob = self._obligations[handle]
        ob.state = ObligationState.ABANDONED
        ob.terminal_predicate = f"abandoned: {reason}"

    def expire_stale(self, now: Optional[float] = None) -> list[str]:
        expired = []
        for h in self.open_handles():
            if self._obligations[h].is_expired(now):
                self.abandon(h, "deadline exceeded")
                expired.append(h)
        return expired


def gate_compaction(ledger: ObligationLedger, span_start: int, span_end: int,
                    obligation_span: dict[str, tuple[int, int]],
                    reify: bool = False) -> str:
    """Decide whether a compaction over [span_start, span_end) is legal.

    obligation_span maps handle -> (opened_turn, terminal_turn_or_-1).
    A compaction is illegal if any OPEN obligation opens inside the span but
    terminates outside it, unless the caller reifies the ledger verbatim.
    """
    ledger.expire_stale()
    for handle in ledger.open_handles():
        opened, terminal = obligation_span.get(handle, (-1, -1))
        if span_start <= opened < span_end and not (span_start <= terminal < span_end):
            if reify:
                return f"reified:{handle}"
            raise CompactionInvariantError(
                f"Compaction over [{span_start},{span_end}) would erase open "
                f"obligation {handle} (opened at turn {opened}, terminal outside span). "
                f"Defer compaction, reify the ledger, or abandon with reason."
            )
    return "safe"
