# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-silently-invalidated-an-agent-s-in-flight-tool-call-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-auto-compaction-has-silently-invalidated-an-agent-s-in-flight-tool-call-ledger.warrant.json
# Markdown SHA-256:   2288895a4445439b13a66cf3b0980e5c8ffa976dd79bfaf60260c5817616be3e
# Code AST SHA-256:   f3df0d122ae265886b0404ceeb0189d40f59aba48f8102cdb495de4b4e95d05c
# Verified Classes:   CompactionInvariantError, CallRecord, Ledger
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class CompactionInvariantError(RuntimeError):
    """Raised when a compaction transform would violate ledger conservation."""
    pass


@dataclass
class CallRecord:
    call_id: str
    tool: str
    status: str  # "pending" | "closed"
    side_effect: bool = False


@dataclass
class Ledger:
    calls: Dict[str, CallRecord] = field(default_factory=dict)

    def open_calls(self) -> List[CallRecord]:
        return [c for c in self.calls.values() if c.status == "pending"]

    def digest(self) -> dict:
        return {
            "open": sorted(c.call_id for c in self.open_calls()),
            "closed": sorted(c.call_id for c in self.calls.values() if c.status == "closed"),
            "side_effects": sum(1 for c in self.calls.values() if c.side_effect),
        }


def compact(transcript: List[dict], ledger: Ledger, summarize) -> tuple:
    """
    Compact the transcript under a structural contract.
    Open-call markers are hoisted out and re-injected verbatim; the summarizer
    never sees them. The post-compaction ledger digest must conserve open calls
    and closed calls (modulo newly closed) or we refuse.
    """
    before = ledger.digest()

    # Hoist unresolved protocol state out of the summarizer's reach.
    hoisted = [m for m in transcript if m.get("type") == "tool_call" and m.get("status") == "pending"]
    compactable = [m for m in transcript if m not in hoisted]

    summary = summarize(compactable)

    # Re-inject verbatim; the summarizer cannot have altered these.
    rebuilt = [{"type": "tool_call", **h} for h in hoisted] + [{"type": "summary", "text": summary}]

    after = ledger.digest()

    # Conservation checks.
    if after["open"] != before["open"]:
        raise CompactionInvariantError(
            f"open-call set changed across compaction: {before['open']} -> {after['open']}"
        )
    lost_closed = set(before["closed"]) - set(after["closed"])
    if lost_closed:
        raise CompactionInvariantError(
            f"closed calls lost from ledger across compaction: {sorted(lost_closed)}"
        )
    if after["side_effects"] < before["side_effects"]:
        raise CompactionInvariantError(
            f"side-effect count regressed: {before['side_effects']} -> {after['side_effects']}"
        )

    # Verify every hoisted marker survived into the rebuilt transcript.
    rebuilt_ids = {m.get("call_id") for m in rebuilt if m.get("type") == "tool_call"}
    for c in hoisted:
        if c["call_id"] not in rebuilt_ids:
            raise CompactionInvariantError(
                f"pending call {c['call_id']} not preserved verbatim across compaction"
            )

    return rebuilt, ledger


def route_response(ledger: Ledger, call_id: str, result: dict) -> None:
    """Responses must match a known call by id; orphans are fatal, not dropped."""
    if call_id not in ledger.calls:
        raise CompactionInvariantError(
            f"orphan response for unknown call_id={call_id!r}: "
            f"compaction likely destroyed the request reference"
        )
    rec = ledger.calls[call_id]
    if rec.status != "pending":
        raise CompactionInvariantError(
            f"response for non-pending call {call_id} (status={rec.status})"
        )
    rec.status = "closed"
