# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-auto-compaction-summary-has-silently-dropped-an-open-obligation-the-dangling-commitment-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-auto-compaction-summary-has-silently-dropped-an-open-obligation-the-dangling-commitment-invariant.warrant.json
# Markdown SHA-256:   c3b14aa6afcafe5bd69f74e17c8045efbcab9ff99a253c7d82a9a0df33c2f641
# Code AST SHA-256:   540827daeeb1262c0e204db0d53ce7b63d015c911d73092c8fdf976336b85644
# Verified Classes:   DanglingCommitmentError, Obligation, ObligationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

COMMITMENT_VERBS = ("i'll", "i will", "i'm going to", "i am going to")
TRIGGER_MARKERS = ("once", "after", "when", "by end of", "as soon as")


class DanglingCommitmentError(RuntimeError):
    """Raised when compaction would evict an open obligation without promoting it."""


@dataclass
class Obligation:
    source_turn: int
    text: str
    trigger: str
    status: str = "OPEN"

    def discharge(self, realized_tool_call: str) -> None:
        if not realized_tool_call:
            raise DanglingCommitmentError(
                "Obligation cannot be closed by prose; a realized tool-call record is required."
            )
        self.status = "CLOSED"


@dataclass
class ObligationLedger:
    entries: list[Obligation] = field(default_factory=list)

    def scan_and_promote(self, evicted_turns: Iterable[tuple[int, str]]) -> list[Obligation]:
        promoted: list[Obligation] = []
        for turn_no, text in evicted_turns:
            low = text.lower()
            has_verb = any(v in low for v in COMMITMENT_VERBS)
            trigger = next((m for m in TRIGGER_MARKERS if m in low), None)
            # A commitment with a future trigger and no realized tool call in-span
            # is an open obligation that must survive compaction.
            if has_verb and trigger and "tool_call" not in low:
                ob = Obligation(source_turn=turn_no, text=text.strip(), trigger=trigger)
                self.entries.append(ob)
                promoted.append(ob)
        return promoted

    def open_items(self) -> list[Obligation]:
        return [e for e in self.entries if e.status == "OPEN"]


def compact(evicted_turns, summarizer, ledger: ObligationLedger) -> str:
    promoted = ledger.scan_and_promote(evicted_turns)
    summary = summarizer([t for _, t in evicted_turns])

    # Guardrail: every promoted obligation must be present in the artifact verbatim.
    missing = [ob for ob in promoted if ob.text not in summary]
    if missing:
        # Do not silently proceed; the summarizer dropped debt.
        raise DanglingCommitmentError(
            f"Compaction dropped {len(missing)} open obligation(s) at turns "
            f"{[ob.source_turn for ob in missing]}; refusing to evict."
        )

    # Re-inject the live ledger so unresolved debt persists across the boundary.
    open_lines = "\n".join(
        f"[OPEN OBLIGATION turn {o.source_turn}] {o.text} (trigger: {o.trigger})"
        for o in ledger.open_items()
    )
    return summary + ("\n\nOBLIGATION LEDGER:\n" + open_lines if open_lines else "")


def close_obligation(ledger: ObligationLedger, turn: int, realized_tool_call: str) -> None:
    match = next((o for o in ledger.open_items() if o.source_turn == turn), None)
    if match is None:
        raise DanglingCommitmentError(f"No open obligation at turn {turn} to close.")
    match.discharge(realized_tool_call)
