# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scratchpad-compaction-from-silently-dropping-the-typed-referent-of-an-open-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scratchpad-compaction-from-silently-dropping-the-typed-referent-of-an-open-obligation.warrant.json
# Markdown SHA-256:   9dc669ae85ffe9c30c877f88a26e2eb41b7e3064c041fa8392b6eb1cc6434dd2
# Code AST SHA-256:   6f462da547ce73618cdeb8b09c03a3ec098b99f406fd61585c70f37a4483c65e
# Verified Classes:   DanglingObligationRef, Record
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DanglingObligationRef(RuntimeError):
    """Raised when a compacted scratchpad leaves an open record without a live referent."""
    pass


@dataclass
class Record:
    rid: str
    kind: str                      # "entity" | "obligation" | "hypothesis" | "constraint"
    text: str
    status: str = "open"           # immutable across compaction
    ref: Optional[str] = None      # immutable across compaction
    supports: list[str] = field(default_factory=list)


def assert_reference_closure(records: list[Record]) -> None:
    """Invariant: every open record's ref/supports must resolve to a retained record.

    This is the guardrail that compaction must pass before the agent may resume.
    """
    live_ids = {r.rid for r in records}
    for r in records:
        if r.status != "open":
            continue
        targets = ([r.ref] if r.ref else []) + list(r.supports)
        for t in targets:
            if t not in live_ids:
                raise DanglingObligationRef(
                    f"open record {r.rid!r} ({r.kind}) references missing {t!r}; "
                    f"compaction severed a live referent — reject and restore checkpoint"
                )


def resume_after_compaction(compacted: list[Record]) -> list[Record]:
    # Fail closed: a dangling ref is a hard fault, never a warning.
    assert_reference_closure(compacted)
    return compacted


# Trace of the observed failure: ref dropped by the compactor.
bad = [
    Record("E17", "entity", "vendor contract PDF, chunk set C3"),
    Record("O4", "obligation", "verify clause 7.2", ref=None),   # ref severed
    Record("C1", "constraint", "do not answer until O4 resolved", supports=["O4"]),
]
resume_after_compaction(bad)  # raises DanglingObligationRef
