# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-own-summary-of-a-pending-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-own-summary-of-a-pending-tool-call.warrant.json
# Markdown SHA-256:   2ac1c91931a87b31901bc89f5c6be29b3b0530973c125a965fffc7dc8409dd4f
# Code AST SHA-256:   9da7f85775be198ce127bb4c7b62cc650da819933bbc9d894b96e3e2d9b6636e
# Verified Classes:   CompactionPairSplitError, ToolCall, Transcript
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionPairSplitError(RuntimeError):
    """Raised when a compaction event would split an outstanding tool call from its result."""
    pass


@dataclass
class ToolCall:
    call_id: str
    resolved: bool = False


@dataclass
class Transcript:
    messages: list = field(default_factory=list)
    outstanding: dict = field(default_factory=dict)  # call_id -> ToolCall

    def emit_call(self, call_id: str) -> None:
        self.outstanding[call_id] = ToolCall(call_id=call_id)
        self.messages.append({"role": "assistant", "tool_call_id": call_id})

    def deliver_result(self, call_id: str, payload: dict) -> None:
        if call_id not in self.outstanding:
            raise CompactionPairSplitError(
                f"orphan tool_result for call_id={call_id!r}: "
                f"no matching tool_use in transcript (compaction split the pair)"
            )
        self.outstanding[call_id].resolved = True
        del self.outstanding[call_id]
        self.messages.append({"role": "tool", "tool_call_id": call_id, "payload": payload})

    def compact(self, evict_upto_index: int) -> None:
        # Invariant: the eviction window's right edge must not fall between
        # an assistant tool_use and its tool_result.
        for msg in self.messages[:evict_upto_index]:
            cid = msg.get("tool_call_id")
            if msg["role"] == "assistant" and cid in self.outstanding:
                raise CompactionPairSplitError(
                    f"compaction window ends at index {evict_upto_index} "
                    f"but call_id={cid!r} is still outstanding; "
                    f"snap eviction edge backward to the last complete pair"
                )


def compact_with_pair_snapping(tx: Transcript, target_index: int, max_snap: int = 64) -> int:
    """Return the largest index <= target_index that does not split a pair."""
    idx = target_index
    snapped = 0
    while idx > 0:
        try:
            tx.compact(idx)
            return idx
        except CompactionPairSplitError:
            idx -= 1
            snapped += 1
            if snapped > max_snap:
                raise CompactionPairSplitError(
                    f"could not find pair-safe eviction edge within {max_snap} tokens "
                    f"of target {target_index}; outstanding={list(tx.outstanding)}"
                )
    return 0
