# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-compaction-from-silently-deleting-the-referent-of-a-live-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-compaction-from-silently-deleting-the-referent-of-a-live-obligation.warrant.json
# Markdown SHA-256:   3544df68a92c0b6978d08a4fb05d46353d361ecb03d707b6732446b0d1f9a3d6
# Code AST SHA-256:   f2245b80b249a0aa939aab15ae6d6402daafb9cd191a7fd3fc1cb8bd32adb230
# Verified Classes:   UnresolvedObligationError, Obligation, CompactedContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnresolvedObligationError(RuntimeError):
    """Raised when compaction would leave a live obligation without a
    verbatim, resolvable referent. Fail closed; never reconstruct."""
    pass


@dataclass
class Obligation:
    referent_id: str          # byte-for-byte, never paraphrased
    qualifier: str            # e.g. cluster / environment
    modality: str             # MUST_NOT_CLOSE_UNTIL | MUST_VERIFY | MAY_PROCEED
    discharge_predicate: str
    discharged: bool = False

    def is_live(self) -> bool:
        return not self.discharged


@dataclass
class CompactedContext:
    narrative_summary: str
    obligations: list[Obligation] = field(default_factory=list)


def compact(narrative: str, obligations: list[Obligation],
            resolver) -> CompactedContext:
    # Narrative is compacted lossily; obligations are carried verbatim.
    summary = lossy_summarize(narrative)
    carried = [o for o in obligations if o.is_live()]

    for ob in carried:
        # Referent must survive and still resolve against the world.
        if not ob.referent_id or ob.referent_id.startswith("~"):
            raise UnresolvedObligationError(
                f"obligation referent lost during compaction: {ob!r}")
        if ob.modality not in {"MUST_NOT_CLOSE_UNTIL", "MUST_VERIFY",
                               "MAY_PROCEED"}:
            raise UnresolvedObligationError(
                f"obligation polarity tag missing/invalid: {ob!r}")
        if not resolver(ob.referent_id, ob.qualifier):
            raise UnresolvedObligationError(
                f"referent no longer resolvable post-compaction: "
                f"{ob.referent_id}@{ob.qualifier}")

    return CompactedContext(narrative_summary=summary, obligations=carried)


def lossy_summarize(text: str) -> str:
    # Placeholder for the narrative-only summarizer.
    return text[: max(1, len(text) // 8)]
