# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-a-context-window-that-contains-an-in-flight-tool-call-warrant-and-how-does-premature-compacti.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-compact-a-context-window-that-contains-an-in-flight-tool-call-warrant-and-how-does-premature-compacti.warrant.json
# Markdown SHA-256:   590055a0df5549273df72e04841420ab9599a58ee50c6f9f7ef5c91a4239ba55
# Code AST SHA-256:   4634190572709aef7059a70bd2d2e94eef56d2c2a66d1d8133015f0ab874bf61
# Verified Classes:   WarrantState, Warrant, UnsafeCompactionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Iterable


class WarrantState(Enum):
    ISSUED = "issued"
    DISPATCHED = "dispatched"
    VERIFIED = "verified"
    EXPIRED_UNCONSUMED = "expired_unconsumed"


@dataclass(frozen=True)
class Warrant:
    call_id: str
    arg_hash: str  # hash over canonical serialization of dispatched bytes
    state: WarrantState


class UnsafeCompactionError(RuntimeError):
    """Raised when a compaction span contains a warrant that is not yet consumed."""


def assert_span_compactable(
    span_call_ids: Iterable[str],
    ledger: dict[str, Warrant],
) -> None:
    """Enforce the warrant-consumption frontier before compacting a span.

    A span is compactable only if every call it contains has a warrant in a
    terminal, verification-complete state. In-flight warrants pin the span.
    """
    blocking: list[str] = []
    for call_id in span_call_ids:
        warrant = ledger.get(call_id)
        if warrant is None:
            # Missing ledger entry is itself a violation: we cannot prove the
            # call was ever warranted, so we must not summarize through it.
            blocking.append(f"{call_id}:NO_LEDGER_ENTRY")
            continue
        if warrant.state not in (WarrantState.VERIFIED, WarrantState.EXPIRED_UNCONSUMED):
            blocking.append(f"{call_id}:{warrant.state.value}")

    if blocking:
        raise UnsafeCompactionError(
            "refusing to compact span; in-flight or unverifiable warrants pin it: "
            + ", ".join(blocking)
            + " -- defer compaction, flush pinned span verbatim, and resume via ledger pointer"
        )


def compact_span(
    span_call_ids: list[str],
    ledger: dict[str, Warrant],
    summarizer,
) -> str:
    assert_span_compactable(span_call_ids, ledger)
    return summarizer(span_call_ids)
