# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-a-transcript-whose-lossy-summary-would-drop-an-unresolved-tool-call-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-a-transcript-whose-lossy-summary-would-drop-an-unresolved-tool-call-obligation.warrant.json
# Markdown SHA-256:   4017075356b51d52804d0304e6f4074c58ec44e696bb6692ae7daad0d60f8360
# Code AST SHA-256:   ef5ec1f33744b3e627286bf0d7486b42a8c4add3a72dfee5d77322974d89ce72
# Verified Classes:   ObligationPreservationError, Obligation, Ledger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ObligationPreservationError(RuntimeError):
    """Raised when a compaction would orphan a live tool-call obligation."""
    pass


@dataclass(frozen=True)
class Obligation:
    call_id: str
    tool: str
    args_digest: str
    issue_turn: int
    expected_consumer_turn: Optional[int]


@dataclass
class Ledger:
    live: dict[str, Obligation] = field(default_factory=dict)

    def open(self, o: Obligation) -> None:
        self.live[o.call_id] = o

    def resolve(self, call_id: str) -> None:
        self.live.pop(call_id, None)


def compact_transcript(
    transcript: list[str],
    ledger: Ledger,
    summarizer,
    obligation_table_in_summary: bool,
) -> list[str]:
    """
    Compaction gate. Refuses to compact when live obligations exist and the
    strategy would fold the obligation table into the summarized span.
    """
    if ledger.live and obligation_table_in_summary:
        orphaned = sorted(ledger.live.keys())
        raise ObligationPreservationError(
            f"refusing to compact: {len(orphaned)} live obligation(s) would be "
            f"folded into lossy summary span: {orphaned}. "
            f"Carry obligation table verbatim or defer compaction."
        )

    summary = summarizer(transcript)
    # Obligation table is carried outside the summarized span and re-emitted verbatim.
    obligation_block = [
        f"[OBLIGATION {o.call_id} tool={o.tool} args={o.args_digest} "
        f"issued@{o.issue_turn} consumer@{o.expected_consumer_turn}]"
        for o in ledger.live.values()
    ]
    return [summary, *obligation_block]


def on_tool_result(ledger: Ledger, call_id: str) -> None:
    if call_id not in ledger.live:
        raise ObligationPreservationError(
            f"ghost result: tool output for {call_id} has no live obligation; "
            f"compaction likely orphaned it. Result must be quarantined, not consumed."
        )
    ledger.resolve(call_id)
