# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-compaction-checkpoints-from-silently-destroying-resumable-task-state.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-compaction-checkpoints-from-silently-destroying-resumable-task-state.warrant.json
# Markdown SHA-256:   b97ba17c693a908b3e17811d99627a81ed8df7d26fd11338d7404d3df93d7496
# Code AST SHA-256:   87e17c675701d1c4716b02af65d414f78866f7ed0413d6f21d16106984ce8017
# Verified Classes:   CompactionInvariantError, DecisionLedger, Checkpoint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionInvariantError(RuntimeError):
    """Raised when a lossy checkpoint would discard uncommitted commitments."""


@dataclass
class DecisionLedger:
    task_id: str
    entries: list = field(default_factory=list)  # append-only, monotonic ids

    @property
    def head(self) -> int:
        return len(self.entries)  # 0-based next id == high-water mark

    def commit(self, decision: str) -> int:
        self.entries.append(decision)
        return self.head


@dataclass
class Checkpoint:
    summary: str
    ledger_high_water: int


def compact(
    ledger: DecisionLedger,
    in_context_decisions: list,
    summarize,
) -> Checkpoint:
    # Condition 1 & 4: every in-context decision must be flushed to the
    # out-of-band ledger BEFORE the context that produced it is discarded.
    for decision in in_context_decisions:
        ledger.commit(decision)

    summary = summarize()  # lossy: may drop narrative, never the ledger
    return Checkpoint(summary=summary, ledger_high_water=ledger.head)


def resume_and_act(
    checkpoint: Checkpoint,
    ledger: DecisionLedger,
    action_is_mutating: bool,
    ledger_loaded: bool,
) -> None:
    # Condition 2: high-water mark must match the authoritative ledger head.
    if checkpoint.ledger_high_water != ledger.head:
        raise CompactionInvariantError(
            f"checkpoint hwm={checkpoint.ledger_high_water} != "
            f"ledger head={ledger.head}; lost write or stale replay"
        )
    # Condition 3: no mutating action before the ledger is replayed.
    if action_is_mutating and not ledger_loaded:
        raise CompactionInvariantError(
            "mutating action attempted after resume without ledger replay; "
            "agent would violate prior commitments it can no longer recall"
        )
