# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-transcript-mid-tool-call-and-the-summarizer-s-lossy-guarantee-silently-drops-the-in-flight-tool-use-blo.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-transcript-mid-tool-call-and-the-summarizer-s-lossy-guarantee-silently-drops-the-in-flight-tool-use-blo.warrant.json
# Markdown SHA-256:   f07501d73760dd1c1e58d155079b3c2cc49fc18f09f6c49723d9ddef680e90d2
# Code AST SHA-256:   d324b4f050370671cb68a28dbb163507d9b404a9f671ee9c5475d1f3bc7d5731
# Verified Classes:   Block, OpenObligationCompactionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal

@dataclass
class Block:
    kind: Literal["text", "tool_use", "tool_result"]
    tool_use_id: str | None = None

class OpenObligationCompactionError(RuntimeError):
    """Raised when a compaction window would split an in-flight tool call."""
    pass

def select_compaction_window(transcript: list[Block], token_budget: int) -> list[Block]:
    """
    Return the prefix of `transcript` safe to evict-and-summarize.
    Refuses to include any tool_use lacking a matching tool_result (or vice versa).
    """
    # Map tool_use_id -> indices of its use/result blocks
    open_uses: dict[str, int] = {}
    closed: set[str] = set()
    for i, b in enumerate(transcript):
        if b.kind == "tool_use" and b.tool_use_id is not None:
            open_uses[b.tool_use_id] = i
        elif b.kind == "tool_result" and b.tool_use_id is not None:
            if b.tool_use_id in open_uses:
                closed.add(b.tool_use_id)

    # Find the latest index that is part of a still-open obligation
    pending_ids = set(open_uses) - closed
    if pending_ids:
        earliest_open = min(open_uses[tid] for tid in pending_ids)
        # Window must end strictly before the earliest pending tool_use
        safe_end = earliest_open
    else:
        safe_end = len(transcript)

    window = transcript[:safe_end]
    # Approximate token cost; caller supplies real counter in production.
    if len(window) > token_budget:
        # Trim only at a boundary that does not split a pair — here, whole blocks.
        window = window[:token_budget]

    # Final guard: verify the chosen window has no unpaired tool block.
    ids_in_window = {b.tool_use_id for b in window if b.tool_use_id}
    for tid in ids_in_window:
        has_use = any(b.kind == "tool_use" and b.tool_use_id == tid for b in window)
        has_res = any(b.kind == "tool_result" and b.tool_use_id == tid for b in window)
        if has_use != has_res:
            raise OpenObligationCompactionError(
                f"compaction window splits tool call {tid!r}; "
                f"suspend task at obligation boundary instead of summarizing"
            )
    return window
