# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-across-a-tool-call-boundary-and-drops-the-pending-obligation-register.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-across-a-tool-call-boundary-and-drops-the-pending-obligation-register.warrant.json
# Markdown SHA-256:   c3ed580b36d3ca4328e6d06b3574c8b1742588b04ea98127030f6470a82e9c43
# Code AST SHA-256:   5733c57889440c36c52fd0dbb879fc352b40d86e51449439d0ce00807e1785f3
# Verified Classes:   ObligationInvariantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ObligationInvariantError(RuntimeError):
    """Raised when compaction would sever a live obligation edge."""
    pass


def compact(state, budget_tokens, summarize):
    """
    Obligation-driven compaction. The transcript may be summarized;
    the obligation register is pinned verbatim and never summarized.
    """
    transcript = state["transcript"]
    register = state["obligations"]  # list of dicts, first-class

    # Guardrail 1: never compact across an unresolved call boundary.
    pending_calls = {
        o["call_id"] for o in register
        if o["status"] == "pending" and o["kind"] == "tool_call"
    }
    orphan_risk = any(
        msg.get("role") == "tool_result"
        and msg.get("call_id") not in pending_calls
        and msg.get("call_id") is not None
        and not _result_has_pinned_call(state, msg["call_id"])
        for msg in transcript
    )
    if orphan_risk:
        raise ObligationInvariantError(
            "compaction would orphan a tool result from its call; "
            "defer until the call/result pair is atomic or pinned"
        )

    # Guardrail 2: obligations with unmet gates must survive verbatim.
    gated = [o for o in register if o["status"] == "pending" and o.get("gates")]
    if gated and not state.get("allow_pin", True):
        raise ObligationInvariantError(
            f"{len(gated)} gated obligations cannot be pinned; refusing to compact"
        )

    summary = summarize(_summarizable(transcript))  # transcript only
    new_transcript = [{"role": "system", "content": summary}]
    # Pin the register verbatim, outside the summarizer's reach.
    new_transcript.append({
        "role": "system",
        "content": "OBLIGATIONS_PINNED",
        "obligations": register,  # structured, not prose
    })
    return {"transcript": new_transcript, "obligations": register}


def mark_complete(state):
    live = [o for o in state["obligations"] if o["status"] == "pending"]
    if live:
        raise ObligationInvariantError(
            f"cannot complete: {len(live)} undischarged obligations "
            f"({[o['call_id'] for o in live]})"
        )
    return True


def _summarizable(transcript):
    return [m for m in transcript if m.get("role") != "obligations_pinned"]


def _result_has_pinned_call(state, call_id):
    return any(
        o["call_id"] == call_id and o.get("pinned", False)
        for o in state["obligations"]
    )
