# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-own-transcript-mid-tool-call-and-the-summarizer-drops-the-pending-invocation-s-argument-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-auto-compacts-its-own-transcript-mid-tool-call-and-the-summarizer-drops-the-pending-invocation-s-argument-binding.warrant.json
# Markdown SHA-256:   06b233e3ef748e031c1e38125bfd46104dacf5d72a370ef37db2b0d8c4d11059
# Code AST SHA-256:   77f3772c5d8034ec7824abd39b79d2d9c20f3df0ec6f7bce25acedd244266330
# Verified Classes:   CompactionFrameLossError, Invocation, CompactionEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field


class CompactionFrameLossError(RuntimeError):
    """Raised when a lossy compaction drops or merges a live pending invocation."""
    pass


@dataclass
class Invocation:
    call_id: str
    tool: str
    args: dict


@dataclass
class CompactionEvent:
    summary_text: str
    pending_before: list[Invocation]
    pending_after: list[Invocation] = field(default_factory=list)


def reconcile_after_compaction(event: CompactionEvent) -> list[Invocation]:
    """
    Enforce the invariant: the multiset of pending invocations is
    identity-preserving across a lossy compaction. Summaries may compress
    narrative; they may not change the cardinality or IDs of live frames.
    """
    before_ids = [inv.call_id for inv in event.pending_before]
    after_ids = [inv.call_id for inv in event.pending_after]

    if len(before_ids) != len(after_ids):
        raise CompactionFrameLossError(
            f"cardinality drift across compaction: "
            f"{len(before_ids)} pending before, {len(after_ids)} after; "
            f"summary={event.summary_text!r}"
        )

    missing = set(before_ids) - set(after_ids)
    if missing:
        raise CompactionFrameLossError(
            f"pending invocations elided by summarizer: {sorted(missing)}; "
            f"resume cannot reconstruct exact argument bindings"
        )

    # Frames are authoritative; summary is advisory and must not be trusted
    # to describe them. Return the durable frames, not any reconstruction.
    return event.pending_before


def resume_with_results(
    event: CompactionEvent, results_by_id: dict[str, dict]
) -> dict[str, dict]:
    try:
        frames = reconcile_after_compaction(event)
    except CompactionFrameLossError:
        # Halt rather than proceed on a degraded frame set.
        raise

    bound: dict[str, dict] = {}
    for inv in frames:
        if inv.call_id not in results_by_id:
            raise CompactionFrameLossError(
                f"no result for live frame {inv.call_id} ({inv.tool}); "
                f"refusing to substitute reconstructed call"
            )
        bound[inv.call_id] = {
            "tool": inv.tool,
            "args": inv.args,
            "result": results_by_id[inv.call_id],
        }
    return bound
