# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-context-compaction-from-silently-dropping-the-active-tool-call-contract.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-context-compaction-from-silently-dropping-the-active-tool-call-contract.warrant.json
# Markdown SHA-256:   0adbdd7d7942b4b85640245ce079a866d82473001ab151f23b1d964479049609
# Code AST SHA-256:   ad23974eb7dcdefd0f7c82b3262a21a7280f92f75dafc1085edc2912e4657817
# Verified Classes:   ObligationDropError, Obligation, CompactionBoundary
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ObligationDropError(RuntimeError):
    """Raised when a compaction pass silently drops an open obligation."""


@dataclass(frozen=True)
class Obligation:
    kind: str          # "pending_call" | "open_subgoal" | "unconsumed_cursor" | "pending_confirm"
    ref_id: str        # stable id from transport/plan layer, never model-authored


@dataclass
class CompactionBoundary:
    pinned: set[Obligation] = field(default_factory=set)

    def open_obligations(self, event_log: Iterable[dict], plan_graph: Iterable[dict]) -> set[Obligation]:
        """Derive open obligations from transport + plan layers, NOT from the model."""
        open_set: set[Obligation] = set()
        issued, resolved = {}, set()
        for ev in event_log:
            if ev["type"] == "tool_call":
                issued[ev["call_id"]] = ev
            elif ev["type"] == "tool_result":
                resolved.add(ev["call_id"])
                if ev.get("next_cursor"):
                    open_set.add(Obligation("unconsumed_cursor", ev["call_id"]))
        for call_id in issued:
            if call_id not in resolved:
                open_set.add(Obligation("pending_call", call_id))
        for node in plan_graph:
            if node.get("status") in ("open", "in_progress"):
                open_set.add(Obligation("open_subgoal", node["node_id"]))
        return open_set

    def compact(self, before: set[Obligation], summarize_fn) -> set[Obligation]:
        # In-flight window guard: never compact while a call is pending.
        if any(o.kind == "pending_call" for o in before):
            raise ObligationDropError(
                "compaction attempted with an in-flight tool call; "
                "checkpoint-and-restart instead of summarizing"
            )

        self.pinned |= before            # obligations cross verbatim
        after = summarize_fn(self.pinned)

        missing = before - after
        if missing:
            raise ObligationDropError(
                f"compaction dropped {len(missing)} open obligation(s): "
                f"{sorted(o.ref_id for o in missing)}"
            )
        return after


def run_compaction(boundary: CompactionBoundary, event_log, plan_graph, summarize_fn):
    before = boundary.open_obligations(event_log, plan_graph)
    return boundary.compact(before, summarize_fn)
