# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-transcript-mid-tool-call-and-the-summarizer-elides-the-pending-call-sentinel.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-transcript-mid-tool-call-and-the-summarizer-elides-the-pending-call-sentinel.warrant.json
# Markdown SHA-256:   83e73686d378f74cf3ee13d102a84f2a6fd452b203414f70edda9bcae3dd6269
# Code AST SHA-256:   b4d9117a7f468e07f708ad3b30ca1908611faa404fab9aa9727c97e91edadcf4
# Verified Classes:   CompactionFrameViolation, Transcript
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionFrameViolation(RuntimeError):
    """Raised when compaction would run or has run over an open tool-call frame."""
    pass


@dataclass
class Transcript:
    messages: list = field(default_factory=list)

    def open_frames(self) -> set:
        opened, closed = set(), set()
        for m in self.messages:
            for blk in m.get("blocks", []):
                if blk["type"] == "tool_use":
                    opened.add(blk["id"])
                elif blk["type"] == "tool_result":
                    closed.add(blk["id"])
        return opened - closed


def compact(transcript: Transcript, summarize, hard: bool = False) -> Transcript:
    frames = transcript.open_frames()
    if frames and not hard:
        # soft path: defer, do not summarize over an open frame
        raise CompactionFrameViolation(
            f"compaction deferred: open tool frames {sorted(frames)}"
        )
    if frames and hard:
        # hard path: pin frames verbatim, never narrate them
        pinned = [m for m in transcript.messages
                  if any(b["id"] in frames for b in m.get("blocks", []))]
        summary = summarize(transcript.messages)
        # invariant check: pinned frames must survive as real blocks
        surviving = {b["id"] for m in pinned for b in m.get("blocks", [])
                     if b["type"] == "tool_use"}
        if not frames.issubset(surviving):
            raise CompactionFrameViolation(
                f"pinned frame ledger incomplete: missing {frames - surviving}"
            )
        return Transcript(messages=[{"role": "system", "blocks": [
            {"type": "summary", "text": summary}]}] + pinned)
    return Transcript(messages=[{"role": "system", "blocks": [
        {"type": "summary", "text": summarize(transcript.messages)}]}])


def ingest_result(transcript: Transcript, result_id: str) -> None:
    if result_id not in transcript.open_frames() and not any(
        b.get("id") == result_id
        for m in transcript.messages for b in m.get("blocks", [])
        if b["type"] == "tool_use"
    ):
        raise CompactionFrameViolation(
            f"orphaned tool_result {result_id}: no matching tool_use in context"
        )
