# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-summary-induced-commitment-loss-when-auto-compaction-rewrites-its-own-task-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-summary-induced-commitment-loss-when-auto-compaction-rewrites-its-own-task-ledger.warrant.json
# Markdown SHA-256:   1777cf729059acef0d94279875e8b46d337a6525379a9ed92c57b3ebb4a38cee
# Code AST SHA-256:   950de6c0552b19459e1fadc4219ae9585fb5878c88eee8900dfac1a64250332e
# Verified Classes:   CommitmentOrphanedError, Commitment, CommitmentLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CommitmentOrphanedError(RuntimeError):
    """Raised when a compaction would drop a binding commitment without a surviving handle."""


@dataclass(frozen=True)
class Commitment:
    cid: str
    text: str
    anchor: str          # high-salience token, e.g. "BINDING-3" or "18:00 UTC"
    discharged: bool = False


@dataclass
class CommitmentLedger:
    commitments: dict[str, Commitment] = field(default_factory=dict)

    def register(self, c: Commitment) -> None:
        self.commitments[c.cid] = c

    def discharge(self, cid: str) -> None:
        c = self.commitments[cid]
        self.commitments[cid] = Commitment(c.cid, c.text, c.anchor, discharged=True)

    def active(self) -> Iterable[Commitment]:
        return (c for c in self.commitments.values() if not c.discharged)


def verify_compaction(ledger: CommitmentLedger, compacted_context: str) -> None:
    """
    Invariant: for every active commitment, the compacted context must contain
    either the verbatim obligation or its anchor. Otherwise retrieval can never
    be steered toward it, and the commitment is silently orphaned.
    """
    orphans: list[str] = []
    for c in ledger.active():
        if c.text not in compacted_context and c.anchor not in compacted_context:
            orphans.append(f"{c.cid} (anchor={c.anchor!r})")
    if orphans:
        raise CommitmentOrphanedError(
            "compaction would orphan active commitments; escalate to full-context "
            "checkpoint instead of summarizing: " + ", ".join(orphans)
        )


def compact_or_escalate(ledger: CommitmentLedger, proposed_summary: str) -> str:
    try:
        verify_compaction(ledger, proposed_summary)
    except CommitmentOrphanedError:
        # Refuse to compact: preserve continuity over token budget.
        raise
    return proposed_summary


if __name__ == "__main__":
    ledger = CommitmentLedger()
    ledger.register(Commitment("c1", "dry-run before each batch", "BINDING-3"))
    ledger.register(Commitment("c2", "no DDL after 18:00 UTC", "18:00 UTC"))

    bad_summary = "Agent reviewed schemas and planned a backfill with auditor oversight."
    try:
        compact_or_escalate(ledger, bad_summary)
    except CommitmentOrphanedError as e:
        print(f"BLOCKED: {e}")

    good_summary = (
        "Backfill planned. BINDING-3: dry-run before each batch. "
        "Constraint: no DDL after 18:00 UTC."
    )
    print("ACCEPTED:", compact_or_escalate(ledger, good_summary))
