# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rehydrate-a-compacted-transcript-and-confidently-re-execute-a-tool-call-whose-side-effect-already-committed-before-the-summary-bo.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rehydrate-a-compacted-transcript-and-confidently-re-execute-a-tool-call-whose-side-effect-already-committed-before-the-summary-bo.warrant.json
# Markdown SHA-256:   dea34bde19804ba6b13ded354219e34c9f1852d8c2f91129953e7f0315555cba
# Code AST SHA-256:   db3491ebeed277185778a461df231e523d8d571b54b41bf33602d76a1d8edbca
# Verified Classes:   CompactionReplayError, LedgerEntry, ActionLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionReplayError(RuntimeError):
    """Raised when a rehydrated plan would re-issue a call that already committed."""


@dataclass
class LedgerEntry:
    call_id: str
    tool: str
    args_hash: str
    status: str          # "committed" | "pending" | "abandoned"
    txn_id: Optional[str] = None


@dataclass
class ActionLedger:
    # Pinned OUTSIDE the compaction region; never summarized.
    entries: list[LedgerEntry] = field(default_factory=list)

    def committed_hashes(self) -> set[tuple[str, str]]:
        return {(e.tool, e.args_hash) for e in self.entries if e.status == "committed"}

    def record(self, entry: LedgerEntry) -> None:
        self.entries.append(entry)


def rehydrate_and_plan(
    summary: str,
    planned_calls: list[dict],
    ledger: ActionLedger,
) -> list[dict]:
    """
    First action after rehydration: reconcile the summary-derived plan against
    the pinned ledger BEFORE executing anything. Any planned call whose
    (tool, args_hash) already committed is a replay candidate.
    """
    committed = ledger.committed_hashes()
    safe_plan: list[dict] = []

    for call in planned_calls:
        key = (call["tool"], call["args_hash"])
        if key in committed:
            # The summary implied this as a goal; the ledger proves it is done.
            # Do NOT re-issue. Route through idempotency check or skip.
            raise CompactionReplayError(
                f"Planned call {call['tool']}({call['args_hash'][:8]}) matches a "
                f"committed ledger entry; refusing to re-execute across the "
                f"compaction boundary. Summary said: {summary[:60]!r}"
            )
        safe_plan.append(call)

    return safe_plan
