# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-transcript-mid-task-and-the-summarizer-silently-drops-the-pending-tool-call-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-transcript-mid-task-and-the-summarizer-silently-drops-the-pending-tool-call-ledger.warrant.json
# Markdown SHA-256:   da3ac2e92e01afb678a412f5040c7ad96cdc3a8ff0dc5ecd5443036a49732e0e
# Code AST SHA-256:   bfa649c5265dbb94dc7c170b3d46f59fdc9b3b9f01a7a34b6a8b35ecb6ac7225
# Verified Classes:   LedgerCompactionViolation, LedgerEntry, Transcript
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class LedgerCompactionViolation(RuntimeError):
    """Raised when compaction would sever an open tool-call ledger entry."""


@dataclass
class LedgerEntry:
    call_id: str
    tool: str
    args: dict[str, Any]
    status: str  # "open" | "closed"
    result: Any = None

    def arg_hash(self) -> str:
        blob = json.dumps({"tool": self.tool, "args": self.args}, sort_keys=True)
        return hashlib.sha256(blob.encode()).hexdigest()


@dataclass
class Transcript:
    entries: list[LedgerEntry] = field(default_factory=list)

    def open_calls(self) -> list[LedgerEntry]:
        return [e for e in self.entries if e.status == "open"]


def compact(
    transcript: Transcript,
    summarize,
    *,
    structured_carry: bool,
) -> dict[str, Any]:
    """
    Compact a transcript. Closed entries may be summarized.
    Open entries MUST be carried verbatim, or compaction must refuse.
    """
    open_entries = transcript.open_calls()

    if open_entries and not structured_carry:
        # The boundary violation: text summarization cannot preserve
        # call IDs / argument hashes for unresolved calls.
        raise LedgerCompactionViolation(
            f"refusing to compact {len(open_entries)} open ledger entries "
            f"without structured carry: "
            f"{[e.call_id for e in open_entries]}. "
            f"Drain the ledger or checkpoint to durable storage first."
        )

    closed = [e for e in transcript.entries if e.status == "closed"]
    summary = summarize([e.result for e in closed]) if closed else ""

    # Re-emit open entries byte-identical, with pinned argument hashes.
    pending_calls = [
        {
            "call_id": e.call_id,
            "tool": e.tool,
            "args": e.args,
            "arg_hash": e.arg_hash(),
            "status": "pending",
        }
        for e in open_entries
    ]

    return {
        "summary": summary,
        "pending_calls": pending_calls,  # router rebuilds from this
        "carried_count": len(pending_calls),
    }


def resume_router(compacted: dict[str, Any]) -> dict[str, dict[str, Any]]:
    """Rebuild the open-call table from post-compaction state only."""
    router: dict[str, dict[str, Any]] = {}
    for p in compacted["pending_calls"]:
        router[p["call_id"]] = p
    return router


def resolve_result(router: dict[str, dict[str, Any]], call_id: str, result: Any) -> None:
    if call_id not in router:
        # Orphan result: would otherwise be injected as a bare tool message
        # and misread by the model as an instruction.
        raise LedgerCompactionViolation(
            f"result for {call_id} has no landing zone in post-compaction router; "
            f"refusing to inject as orphan turn"
        )
    router[call_id]["result"] = result
    router[call_id]["status"] = "resolved"
