# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-lossy-context-compaction-summary-has-silently-dropped-a-live-execution-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-lossy-context-compaction-summary-has-silently-dropped-a-live-execution-invariant.warrant.json
# Markdown SHA-256:   58e5ed9dd6fde2636bdc6d3275801fa7de483e80a84270af6adae4270f9765c8
# Code AST SHA-256:   0c77ad5cd0140a03d1082836708f37f30b48f7b7cc73d61227428eef98b0c3d3
# Verified Classes:   ObligationPreservationError, ObligationKind, Status, Obligation, ObligationRegister, CompactionDecision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ObligationPreservationError(RuntimeError):
    """Raised when a compaction boundary would drop a live execution obligation."""


class ObligationKind(Enum):
    LEASE = "lease"
    ORDERING = "ordering"
    TOKEN = "token"
    PRECONDITION = "precondition"
    OBLIGATION = "obligation"


class Status(Enum):
    LIVE = "live"
    DISCHARGED = "discharged"


@dataclass
class Obligation:
    kind: ObligationKind
    referent: str
    status: Status = Status.LIVE
    bound: Optional[str] = None
    recoverable_from_durable: bool = False


@dataclass
class ObligationRegister:
    entries: list[Obligation] = field(default_factory=list)

    def live_unrecoverable(self) -> list[Obligation]:
        return [
            e for e in self.entries
            if e.status is Status.LIVE and not e.recoverable_from_durable
        ]


class CompactionDecision(Enum):
    COMPACT_FREELY = "compact_freely"
    COMPACT_WITH_PINNED_REGISTER = "compact_with_pinned_register"
    CHECKPOINT_AND_RESTART = "checkpoint_and_restart"


def decide_compaction(
    register: ObligationRegister,
    summary_budget_tokens: int,
    register_tokens: int,
    compactor_is_constrainable: bool,
) -> CompactionDecision:
    """
    Decide how to cross a compaction boundary given the live obligation set.

    The decision is made on the register BEFORE compaction, never on the
    quality of the summary AFTER it. Gating on summary fidelity is the
    failure mode this guardrail exists to prevent.
    """
    live = register.live_unrecoverable()

    if not live:
        return CompactionDecision.COMPACT_FREELY

    # A live, unrecoverable obligation exists. It must survive the boundary.
    can_pin = compactor_is_constrainable and register_tokens <= summary_budget_tokens

    if can_pin:
        return CompactionDecision.COMPACT_WITH_PINNED_REGISTER

    # Cannot guarantee the register survives inside the summary.
    # A cold start with intact obligations beats a warm continuation
    # whose summary may have silently dropped them.
    if not compactor_is_constrainable:
        return CompactionDecision.CHECKPOINT_AND_RESTART

    raise ObligationPreservationError(
        f"Cannot cross compaction boundary: {len(live)} live obligation(s) "
        f"({[e.referent for e in live]}) exceed summary budget "
        f"({register_tokens} > {summary_budget_tokens} tokens) and cannot be "
        f"pinned. Refusing to summarize execution-binding state. "
        f"Checkpoint the register to durable state and cold-start instead."
    )


def reconcile_on_resume(register: ObligationRegister, world: dict) -> None:
    """
    After resume, verify each live obligation against the world before
    proceeding. The world may have moved during the compaction gap.
    """
    for entry in register.live_unrecoverable():
        observed = world.get(entry.referent)
        if observed is None:
            raise ObligationPreservationError(
                f"Live obligation {entry.kind.value}:{entry.referent} has no "
                f"referent in post-resume world state. The summary or the gap "
                f"dropped a binding invariant; the task is not safely resumable."
            )
        if entry.bound is not None and observed != entry.bound:
            raise ObligationPreservationError(
                f"Obligation {entry.referent} bound violated on resume: "
                f"expected {entry.bound!r}, world shows {observed!r}. "
                f"Re-verify before continuing."
            )
