# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-auto-compaction-against-the-loss-of-in-flight-tool-call-warrants-in-long-horizon-transcripts.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-auto-compaction-against-the-loss-of-in-flight-tool-call-warrants-in-long-horizon-transcripts.warrant.json
# Markdown SHA-256:   872d74675de2e9ab1a6001e6a11e0817020ce223f2b74b6d8466daa7ca7a9b72
# Code AST SHA-256:   efc3209aa8ffcd2a865221b6e46fa48de0bd760a27795fc6f7867ae15a0e7b0e
# Verified Classes:   UnpinnedWarrantError, Warrant, Transcript
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UnpinnedWarrantError(RuntimeError):
    """Raised when compaction would evict an open tool-call warrant."""
    pass


@dataclass
class Warrant:
    call_id: str
    tool: str
    result: Optional[str] = None  # None => still open
    pinned: bool = False


@dataclass
class Transcript:
    warrants: dict[str, Warrant] = field(default_factory=dict)
    pinned_region: set[str] = field(default_factory=set)


def assert_compaction_safe(tx: Transcript, mid_stream: bool) -> None:
    """Guard invoked before any auto-compaction cycle.

    Rejects compaction if (a) any tool result is mid-stream, or
    (b) any open warrant is not structurally pinned in the reserved region.
    """
    if mid_stream:
        raise UnpinnedWarrantError(
            "compaction fired during an in-flight result stream; "
            "call/result pairing is not yet closed"
        )
    for cid, w in tx.warrants.items():
        if w.result is None and cid not in tx.pinned_region:
            raise UnpinnedWarrantError(
                f"open warrant {cid} ({w.tool}) is unpinned; "
                f"summarizer would sever its call_id and enable silent re-issue"
            )


def compact(tx: Transcript, mid_stream: bool = False) -> Transcript:
    assert_compaction_safe(tx, mid_stream=mid_stream)
    # Only closed, non-pinned history is eligible for summarization.
    surviving = {
        cid: w for cid, w in tx.warrants.items()
        if cid in tx.pinned_region or w.result is not None
    }
    return Transcript(warrants=surviving, pinned_region=set(tx.pinned_region))
