# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-hierarchical-auto-compaction-has-silently-orphaned-a-tool-call-dependency-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-hierarchical-auto-compaction-has-silently-orphaned-a-tool-call-dependency-chain.warrant.json
# Markdown SHA-256:   a5e1bf81b12b728dce35f62d0e66f0bfafa888e199c59a39c59b293fe3036267
# Code AST SHA-256:   5e84e61c7334bcb903c339592d42ac5c46574b7a0b98708c00b5d200b1f3af66
# Verified Classes:   CompactionOrphanedToolCallError, ToolCall, ExecutorLedger, CompactedContext
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionOrphanedToolCallError(RuntimeError):
    """Raised when hierarchical compaction drops an unresolved tool call
    from the compacted context while the executor ledger still holds it open."""
    pass


@dataclass
class ToolCall:
    call_id: str
    status: str  # "pending" | "terminal"
    continuation_token: Optional[str] = None


@dataclass
class ExecutorLedger:
    open_calls: dict[str, ToolCall] = field(default_factory=dict)

    def open_call_ids(self) -> set[str]:
        return {cid for cid, c in self.open_calls.items() if c.status == "pending"}


@dataclass
class CompactedContext:
    # Structured sidecar of pending calls the summarizer was allowed to emit.
    declared_pending: set[str] = field(default_factory=set)


def commit_compaction(ledger: ExecutorLedger, context: CompactedContext) -> None:
    """Reconciliation gate: refuse to commit a compaction that orphans any
    in-flight tool call. Terminality is read from the ledger, never inferred
    from summary prose."""
    ledger_open = ledger.open_call_ids()
    orphaned = ledger_open - context.declared_pending
    if orphaned:
        raise CompactionOrphanedToolCallError(
            f"Compaction would orphan unresolved tool calls {sorted(orphaned)}; "
            f"ledger holds {sorted(ledger_open)} open but compacted context "
            f"declares {sorted(context.declared_pending)}. Refusing to commit; "
            f"re-summarize with open-call pinning or structured sidecar emission."
        )
    # Safe to commit: every open call survived as machine-readable state.
    return None


# Trigger trace from the observed incident:
ledger = ExecutorLedger(open_calls={
    "call_18_fetch": ToolCall(call_id="call_18_fetch", status="pending",
                              continuation_token="tok_p2_of_5"),
})
context = CompactedContext(declared_pending=set())  # summarizer emitted prose only

try:
    commit_compaction(ledger, context)
except CompactionOrphanedToolCallError as e:
    print(f"BLOCKED: {e}")
    # Recovery: pin the open call, re-summarize with sidecar emission.
    context.declared_pending.add("call_18_fetch")
    commit_compaction(ledger, context)
    print("RECOVERED: compaction committed with call_18_fetch pinned.")
