# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-context-mid-tool-call-and-resumes-with-a-summary-that-contradicts-the-tool-s-in-flight-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-context-mid-tool-call-and-resumes-with-a-summary-that-contradicts-the-tool-s-in-flight-side-effects.warrant.json
# Markdown SHA-256:   91b93c3c89c9f93a69737546334a7ded55f77a2cc66a9343944f21454ddfa864
# Code AST SHA-256:   631c663a44b6923f3a007a95e11103b04138f6cbe516476ae68a5f6ad83fb6c1
# Verified Classes:   ObligationViolation, Obligation, ObligationLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ObligationViolation(RuntimeError):
    """Raised when compaction would abstract an unresolved side effect."""
    pass


@dataclass
class Obligation:
    call_id: str
    tool: str
    args: dict
    handle: Optional[str] = None      # e.g. refund_id, job_id
    status: str = "pending"           # pending | settled | failed
    terminal: bool = False


@dataclass
class ObligationLedger:
    _open: dict[str, Obligation] = field(default_factory=dict)

    def register(self, call_id: str, tool: str, args: dict) -> None:
        self._open[call_id] = Obligation(call_id=call_id, tool=tool, args=args)

    def attach_handle(self, call_id: str, handle: str) -> None:
        self._open[call_id].handle = handle

    def resolve(self, call_id: str, status: str) -> None:
        if call_id in self._open:
            ob = self._open[call_id]
            ob.status = status
            ob.terminal = status in ("settled", "failed")

    def open_obligations(self) -> list[Obligation]:
        return [o for o in self._open.values() if not o.terminal]


def compact(
    transcript: list[dict],
    ledger: ObligationLedger,
    summarize_fn,
    buffer_limit: int = 0,
) -> dict:
    """
    Compact the transcript only if the obligation invariant holds.
    Returns {"summary": str, "ledger": list[dict]} for re-injection.
    """
    open_obs = ledger.open_obligations()

    if open_obs and len(open_obs) > buffer_limit:
        # Cannot safely summarize; a side effect is indeterminate.
        raise ObligationViolation(
            f"Refusing to compact with {len(open_obs)} unresolved obligation(s): "
            + ", ".join(f"{o.tool}({o.call_id})={o.status}" for o in open_obs)
            + ". Escalate; do not force compaction."
        )

    # Obligations are lifted OUT of the summarizable region and re-injected
    # verbatim. The summarizer never sees them and cannot dereference them.
    summarizable = [
        t for t in transcript
        if t.get("call_id") not in {o.call_id for o in open_obs}
    ]
    summary = summarize_fn(summarizable)

    return {
        "summary": summary,
        "ledger": [
            {"call_id": o.call_id, "tool": o.tool, "args": o.args,
             "handle": o.handle, "status": o.status}
            for o in open_obs
        ],
    }
