# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-summarization-induced-obligation-loss-during-hierarchical-auto-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-summarization-induced-obligation-loss-during-hierarchical-auto-compaction.warrant.json
# Markdown SHA-256:   43239594107937fe3a382a235a94715229b3db0149c0851c0a52b59011ffd817
# Code AST SHA-256:   6c66d05390753c1d6b1bf73ede30b7c6ff1381016c8aedf188e703cd3a763fd8
# Verified Classes:   ObligationLossError, Obligation, ChildSummary
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ObligationLossError(RuntimeError):
    """Raised when a compaction would drop or corrupt a live obligation."""


@dataclass(frozen=True)
class Obligation:
    oid: str
    constraint: str          # e.g. "do not call rotate() before T+900s"
    expiry: float | None     # absolute deadline, None = no time expiry
    discharged: bool = False
    source_retained: bool = False  # is the source span still reachable?


@dataclass
class ChildSummary:
    prose: str
    header: dict[str, str] = field(default_factory=dict)  # oid -> verbatim constraint


def compact(
    live_obligations: Iterable[Obligation],
    summarizer_prose: str,
    now: float,
) -> ChildSummary:
    """
    Build a child summary that is guaranteed to carry every must-carry obligation.
    Aborts (raises) rather than emitting a lossy checkpoint.
    """
    child = ChildSummary(prose=summarizer_prose)

    for ob in live_obligations:
        if ob.discharged:
            continue
        if ob.expiry is not None and now >= ob.expiry:
            continue  # expired; safe to drop

        if ob.source_retained:
            # re-derivable: pointer only, no verbatim carry needed
            child.header[ob.oid] = f"pointer:{ob.oid}"
            continue

        # must-carry: emit verbatim, then verify presence and polarity
        child.header[ob.oid] = ob.constraint

    # Post-emit audit: every must-carry obligation must be present verbatim.
    for ob in live_obligations:
        if ob.discharged or (ob.expiry is not None and now >= ob.expiry):
            continue
        if ob.source_retained:
            continue
        if child.header.get(ob.oid) != ob.constraint:
            raise ObligationLossError(
                f"compaction would drop live obligation {ob.oid!r} "
                f"(constraint={ob.constraint!r}); aborting checkpoint"
            )

    return child
