# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-live-tool-call-chain-and-the-summary-elides-a-pending-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-live-tool-call-chain-and-the-summary-elides-a-pending-obligation.warrant.json
# Markdown SHA-256:   7bf5768ff536fda6f0580653456de9ed7ff6ecc9d799f63905fb8b57a517d2dc
# Code AST SHA-256:   4eb62991a4c001e64e71174d536d20bef4ab6c04973aaf12b21dfd001238c0fc
# Verified Classes:   ObligationElisionError, Obligation, ContextState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ObligationElisionError(RuntimeError):
    """Raised when a compaction pass would drop or abstract an open obligation."""
    pass


@dataclass(frozen=True)
class Obligation:
    handle: str                 # correlation id / callback token / branch label
    kind: str                   # "inflight_call" | "deferred_branch" | "scheduled_recheck"
    predicate: str              # the guard that must still be evaluated
    deadline: Optional[float]   # wall-clock budget, None if unbounded
    source_ref: str             # pointer to the artifact that will satisfy it


@dataclass
class ContextState:
    content_tokens: int
    obligations: dict[str, Obligation] = field(default_factory=dict)
    pinned_region: dict[str, Obligation] = field(default_factory=dict)


def compact(state: ContextState, summarizer, budget_tokens: int) -> ContextState:
    # 1. Hoist obligations out of any span the summarizer will touch.
    hoisted = dict(state.obligations)

    # 2. Summarize content only; obligations are never passed to the summarizer.
    new_content = summarizer(state.content_tokens, budget_tokens)

    # 3. Rebuild pinned region verbatim from hoisted obligations.
    pinned = {h: o for h, o in hoisted.items()}

    post = ContextState(
        content_tokens=new_content,
        obligations=hoisted,
        pinned_region=pinned,
    )

    # 4. Invariant: post-compaction obligation set is a superset of pre.
    missing = set(state.obligations) - set(post.obligations)
    if missing:
        raise ObligationElisionError(
            f"compaction dropped open obligations: {sorted(missing)}"
        )

    # 5. Invariant: pinned region must be a fixed point (no further abstraction).
    for handle, ob in post.pinned_region.items():
        if post.pinned_region.get(handle) != ob:
            raise ObligationElisionError(
                f"pinned obligation {handle} was mutated by compaction"
            )

    # 6. Refuse to proceed if an obligation's handle is not resolvable.
    for handle, ob in post.obligations.items():
        if not ob.source_ref or not ob.handle:
            raise ObligationElisionError(
                f"obligation {handle} lost its resolvable handle/source_ref"
            )

    return post


def guarded_compact(
    state: ContextState,
    summarizer,
    budget_tokens: int,
    quiescent: bool,
) -> ContextState:
    # Mid-chain compaction with a live obligation set is only permitted
    # when the pinning mechanism is active; otherwise refuse.
    if state.obligations and not quiescent:
        if not state.pinned_region:
            raise ObligationElisionError(
                "refusing mid-chain compaction: "
                f"{len(state.obligations)} open obligations with no pinned region"
            )
    return compact(state, summarizer, budget_tokens)
