# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-under-a-lossy-summarization-budget-and-silently-drops-the-antecedent-of-an-open-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-under-a-lossy-summarization-budget-and-silently-drops-the-antecedent-of-an-open-obligation.warrant.json
# Markdown SHA-256:   3ff5b1cb35127c676c6530ec37f6d12b2071cb7b0f72b0732db05e3b06a857e3
# Code AST SHA-256:   a36f76710a91fbc83161cefea326edcb46229f9aa8f78b9109667e1b119916cc
# Verified Classes:   ReferentialClosureError, Obligation, ObligationRegister
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReferentialClosureError(RuntimeError):
    """Raised when a post-compaction context cannot resolve a live obligation's antecedent."""
    pass


@dataclass
class Obligation:
    obligation_id: str
    description: str
    required_identifiers: frozenset[str]  # tokens that MUST survive compaction verbatim


@dataclass
class ObligationRegister:
    open: dict[str, Obligation] = field(default_factory=dict)

    def add(self, ob: Obligation) -> None:
        self.open[ob.obligation_id] = ob

    def close(self, obligation_id: str) -> None:
        self.open.pop(obligation_id, None)


def compact_context(
    raw_span: str,
    register: ObligationRegister,
    summarizer,
    sidecar_identifiers: frozenset[str],
) -> tuple[str, frozenset[str]]:
    """
    Perform lossy summarization, then verify referential closure.
    Returns (summary, sidecar). Raises if any open obligation's antecedent
    is unresolvable from summary + sidecar.
    """
    summary = summarizer(raw_span)  # abstractive, unconditioned on state
    sidecar = frozenset(sidecar_identifiers)

    # Invariant: every identifier required by an open obligation must be
    # present verbatim in either the sidecar or the summary text.
    for ob in register.open.values():
        for ident in ob.required_identifiers:
            resolvable = (ident in sidecar) or (ident in summary)
            if not resolvable:
                raise ReferentialClosureError(
                    f"Compaction rejected: obligation {ob.obligation_id!r} "
                    f"({ob.description!r}) requires antecedent {ident!r}, "
                    f"which is absent from both summary and sidecar. "
                    f"Drain the obligation or pin the identifier before compacting."
                )
    return summary, sidecar


def resume_from_compaction(
    summary: str,
    sidecar: frozenset[str],
    register: ObligationRegister,
) -> list[str]:
    """Reconstruct the live task set; fail closed if any obligation is orphaned."""
    live: list[str] = []
    for ob in register.open.values():
        if not ob.required_identifiers.issubset(sidecar | frozenset(summary.split())):
            raise ReferentialClosureError(
                f"Cannot resume: obligation {ob.obligation_id!r} is orphaned "
                f"post-compaction; antecedent set {set(ob.required_identifiers)} "
                f"not fully bound."
            )
        live.append(ob.obligation_id)
    return live
