# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-transcript-whose-summary-would-cross-a-tool-call-boundary-mid-pair.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-auto-compact-a-transcript-whose-summary-would-cross-a-tool-call-boundary-mid-pair.warrant.json
# Markdown SHA-256:   c17b056b6393a729a5eb9cddaf1786573704194e06b7257043f2909507d12521
# Code AST SHA-256:   a50ed86cfc133fa361c0b706bbe1cf42dfcfd519483cd615f7e47316b2def0a7
# Verified Classes:   CompactionBoundaryError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CompactionBoundaryError(RuntimeError):
    """Raised when an auto-compaction cut point would split a tool-call/result pair."""
    pass


def pair_span(transcript: list[dict], call_index: int) -> tuple[int, int]:
    """Return the inclusive [start, end] message span of the atomic unit that
    begins at transcript[call_index] (an assistant message with tool_calls)."""
    call_ids = {tc["id"] for tc in transcript[call_index].get("tool_calls", [])}
    if not call_ids:
        return (call_index, call_index)
    end = call_index
    seen: set[str] = set()
    for j in range(call_index + 1, len(transcript)):
        msg = transcript[j]
        if msg.get("role") != "tool":
            break
        seen.add(msg["tool_call_id"])
        end = j
        if seen >= call_ids:
            break
    if seen != call_ids:
        raise CompactionBoundaryError(
            f"tool_calls at index {call_index} have results {sorted(seen)} "
            f"but expected {sorted(call_ids)}; transcript already malformed"
        )
    return (call_index, end)


def safe_cut_point(transcript: list[dict], proposed: int) -> int:
    """Shift a proposed cut index to the nearest pair-safe boundary at or before it.
    A cut at index k means transcript[:k] is summarized, transcript[k:] kept verbatim."""
    if proposed <= 0 or proposed >= len(transcript):
        return proposed
    for i in range(proposed):
        if transcript[i].get("role") == "assistant" and transcript[i].get("tool_calls"):
            start, end = pair_span(transcript, i)
            if start < proposed <= end:
                # proposed lands inside the pair; shift to the pair's start
                return start
    return proposed


def compact(transcript: list[dict], budget: int, summarize) -> list[dict]:
    proposed = compute_cut_for_budget(transcript, budget)
    cut = safe_cut_point(transcript, proposed)
    if cut == 0 and proposed > 0:
        raise CompactionBoundaryError(
            "no pair-safe cut point exists before the budget boundary; "
            "must evict whole pairs or truncate oversized results instead"
        )
    compacted = [summarize(transcript[:cut])] + transcript[cut:]
    assert_pair_integrity(compacted)
    return compacted


def assert_pair_integrity(transcript: list[dict]) -> None:
    pending: set[str] = set()
    for msg in transcript:
        if msg.get("role") == "assistant":
            pending = {tc["id"] for tc in msg.get("tool_calls", [])}
        elif msg.get("role") == "tool":
            if msg["tool_call_id"] not in pending:
                raise CompactionBoundaryError(
                    f"orphaned tool result for call_id {msg['tool_call_id']}"
                )
            pending.discard(msg["tool_call_id"])
        elif msg.get("role") != "tool" and pending:
            raise CompactionBoundaryError(
                f"unanswered tool_calls {sorted(pending)} before non-tool message"
            )
    if pending:
        raise CompactionBoundaryError(f"unanswered tool_calls {sorted(pending)} at end")
