# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-hierarchical-checkpoint-compaction-against-lossy-recall-recovery-when-the-summarizer-and-the-resumer-disagree-about-w.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-hierarchical-checkpoint-compaction-against-lossy-recall-recovery-when-the-summarizer-and-the-resumer-disagree-about-w.warrant.json
# Markdown SHA-256:   570519e9c4ed64dfcc67d26f71258979304e7fe53f522c183b6063adfc4ee4d4
# Code AST SHA-256:   1dd6533365a7816e61cc36e3356283ad117367fca89f71f6e9f9080025f6d5fb
# Verified Classes:   ObligationConflict, CompactionAborted, Status, Obligation, Checkpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ObligationConflict(RuntimeError):
    """Raised when a resumed instance attempts an action forbidden by an open obligation."""


class CompactionAborted(RuntimeError):
    """Raised when a segment cannot be safely summarized because obligations were not extracted."""


class Status(Enum):
    OPEN = "open"
    SATISFIED = "satisfied"
    WAIVED = "waived"


@dataclass(frozen=True)
class Obligation:
    oid: str
    scope: str            # e.g. "db/migrations/", "test_login_flow"
    kind: str             # "prohibition" | "precondition" | "promise"
    origin_turn: int
    status: Status = Status.OPEN
    justification: str | None = None


@dataclass
class Checkpoint:
    synopsis: str                       # lossy, allowed to drift
    leaf_summaries: list[str]           # lossy, allowed to drift
    obligations: list[Obligation]       # monotone, must not drift
    evidence_refs: dict[str, str] = field(default_factory=dict)

    def open_obligations(self) -> Iterable[Obligation]:
        return (o for o in self.obligations if o.status is Status.OPEN)


def compact_segment(turns: list[dict], extractor) -> Checkpoint:
    """
    Compact a segment. Every turn that introduces an obligation must have that
    obligation extracted BEFORE the turn is allowed to be summarized away.
    """
    obligations: list[Obligation] = []
    for t in turns:
        found = extractor(t)
        if t.get("suspected_obligation") and not found:
            # extractor missed a suspected obligation -> refuse to summarize this turn
            raise CompactionAborted(
                f"turn {t['idx']} suspected obligation but extractor returned none; "
                f"compaction of segment aborted to preserve ledger integrity"
            )
        obligations.extend(found)

    return Checkpoint(
        synopsis=summarize(turns),
        leaf_summaries=[summarize(chunk) for chunk in chunk_turns(turns)],
        obligations=obligations,
    )


def resume_and_gate(checkpoint: Checkpoint, plan) -> None:
    """
    Resume path. Synopsis drives planning; ledger gates irreversible actions.
    """
    for action in plan.irreversible_actions():
        for ob in checkpoint.open_obligations():
            if action.touches(ob.scope):
                if ob.kind == "prohibition":
                    raise ObligationConflict(
                        f"action {action.name!r} touches {ob.scope!r} which is "
                        f"forbidden by obligation {ob.oid!r} (origin turn {ob.origin_turn})"
                    )
                if ob.kind == "precondition" and not action.satisfies(ob):
                    raise ObligationConflict(
                        f"action {action.name!r} requires precondition {ob.oid!r} "
                        f"({ob.scope!r}) which is not satisfied"
                    )
