# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-crossed-the-lossy-summarization-threshold-in-long-horizon-agent-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-crossed-the-lossy-summarization-threshold-in-long-horizon-agent-memory.warrant.json
# Markdown SHA-256:   4d3711289146dd4cae470d586eb0d2d1a0a10f9ef118729e9a1fb701337c7158
# Code AST SHA-256:   5fcc41307ba0869c070f3bcef06cdaf7d10f734d6ad180cb735131a1a2b86ad3
# Verified Classes:   CompactionLossError, EntryKind, LedgerEntry, CommitmentLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CompactionLossError(RuntimeError):
    """Raised when a compaction pass would drop a non-rederivable commitment."""
    pass


class EntryKind(Enum):
    CONSTRAINT = "constraint"          # user instruction binding future action
    OBLIGATION = "obligation"          # pending, awaits closure event
    NEGATIVE_RESULT = "negative_result"  # rejected approach / discovered precondition
    PRECONDITION = "precondition"      # guard for an irreversible operation


@dataclass
class LedgerEntry:
    kind: EntryKind
    text: str
    non_rederivable: bool          # True => must never be summarized away
    closed: bool = False
    closure_event: Optional[str] = None


@dataclass
class CommitmentLedger:
    entries: list[LedgerEntry] = field(default_factory=list)

    def open_non_rederivable(self) -> list[LedgerEntry]:
        return [e for e in self.entries if e.non_rederivable and not e.closed]

    def close(self, text: str, event: str) -> None:
        for e in self.entries:
            if e.text == text:
                e.closed = True
                e.closure_event = event
                return
        raise CompactionLossError(f"closure event {event!r} references unknown entry {text!r}")


def commit_compaction(ledger: CommitmentLedger, digest_covered_texts: set[str]) -> None:
    """
    Gate a compaction pass. The digest may only cover texts that are either
    (a) closed, or (b) re-derivable. Any open non-rederivable entry that the
    digest would cover is a lossy-threshold crossing -> reject the compaction.
    """
    survivors = {e.text for e in ledger.open_non_rederivable()}
    dropped = survivors & digest_covered_texts
    if dropped:
        raise CompactionLossError(
            "compaction crossed lossy-summarization threshold; "
            f"would drop open non-rederivable commitments: {sorted(dropped)}"
        )
    # Safe: digest covers only closed or re-derivable material.
    # Ledger itself is carried forward verbatim; it is never summarized.
    return None


def check_action_allowed(ledger: CommitmentLedger, action_target: str) -> None:
    """Pre-action guard: an irreversible write to a frozen target must block."""
    for e in ledger.open_non_rederivable():
        if e.kind is EntryKind.CONSTRAINT and action_target in e.text:
            raise CompactionLossError(
                f"action on {action_target!r} violates open constraint: {e.text!r}"
            )


# --- Reproduction of the observed failure ---
ledger = CommitmentLedger(entries=[
    LedgerEntry(EntryKind.CONSTRAINT, "do not touch billing/ledger.py (audit freeze)",
                non_rederivable=True),
    LedgerEntry(EntryKind.NEGATIVE_RESULT, "cannot change reconcile() signature; 3 callers",
                non_rederivable=True),
    LedgerEntry(EntryKind.OBLIGATION, "waiting on ticket #4412 before billing cleanup",
                non_rederivable=True),
])

# Turn 196: summarizer tries to cover the freeze constraint + negative result.
# Correct behavior: reject before the digest is committed.
commit_compaction(ledger, digest_covered_texts={
    "do not touch billing/ledger.py (audit freeze)",
    "cannot change reconcile() signature; 3 callers",
})  # -> raises CompactionLossError
