# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-lossy-summarization-of-in-flight-tool-call-obligations-during-automatic-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-lossy-summarization-of-in-flight-tool-call-obligations-during-automatic-context-compaction.warrant.json
# Markdown SHA-256:   6e83afaf074ecc3df4af212ad643663734c9a6371399c8b5f879c4da1348931f
# Code AST SHA-256:   af685cd9ae2e2b3581cee6652f877dc83a7f8f443070189e0f7fa5ac29f2d83e
# Verified Classes:   CompactionUnsound, CallState, Obligation, ObligationLedger, CompactionDecision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class CompactionUnsound(RuntimeError):
    """Raised when compaction would elide an unreconciled obligation."""
    pass


class CallState(Enum):
    ISSUED = "issued"
    TERMINAL_OK = "terminal_ok"
    TERMINAL_ERR = "terminal_err"


@dataclass
class Obligation:
    call_id: str
    tool: str
    idempotency_key: str
    params_hash: str
    state: CallState
    effect_logged: bool = False


@dataclass
class ObligationLedger:
    rows: dict[str, Obligation] = field(default_factory=dict)

    def record_issued(self, ob: Obligation) -> None:
        self.rows[ob.call_id] = ob

    def record_terminal(self, call_id: str, ok: bool, effect_logged: bool) -> None:
        ob = self.rows[call_id]
        ob.state = CallState.TERMINAL_OK if ok else CallState.TERMINAL_ERR
        ob.effect_logged = effect_logged

    def outstanding(self) -> list[Obligation]:
        return [r for r in self.rows.values() if r.state is CallState.ISSUED]

    def unreconciled_side_effects(self) -> list[Obligation]:
        return [
            r for r in self.rows.values()
            if r.state is CallState.TERMINAL_OK and not r.effect_logged
        ]


class CompactionDecision(Enum):
    COMPACT = "compact"
    DEFER_AND_FLUSH = "defer_and_flush"
    REFUSE = "refuse"


def decide_compaction(
    ledger: ObligationLedger,
    context_utilization: float,
    can_externalize: bool,
) -> CompactionDecision:
    """
    Gate automatic compaction on obligation state, NOT on token pressure.
    context_utilization is recorded for telemetry but must not drive the
    compact/refuse boundary on its own.
    """
    outstanding = ledger.outstanding()
    unreconciled = ledger.unreconciled_side_effects()

    # Side effects already applied but not durably logged: summarizing the
    # transcript would destroy the only record that they happened.
    if unreconciled and not can_externalize:
        raise CompactionUnsound(
            f"{len(unreconciled)} applied side effect(s) lack durable effect logs; "
            f"compaction would permit duplicate execution. "
            f"call_ids={[r.call_id for r in unreconciled]}"
        )

    if not outstanding and not unreconciled:
        return CompactionDecision.COMPACT

    if can_externalize:
        # Open obligations exist but can be flushed to structured storage and
        # re-injected verbatim; summarize only the closed region behind them.
        return CompactionDecision.DEFER_AND_FLUSH

    # Open obligations exist and cannot be externalized. Summarizing now is
    # guaranteed to either drop the obligation or paraphrase it into a
    # re-executable form.
    raise CompactionUnsound(
        f"cannot compact: {len(outstanding)} issued-but-unreconciled call(s) "
        f"and no externalization path. call_ids={[r.call_id for r in outstanding]}"
    )


def compact(
    ledger: ObligationLedger,
    context_utilization: float,
    can_externalize: bool,
    summarize_closed_region,
    reinject_pinned_block,
) -> str:
    decision = decide_compaction(ledger, context_utilization, can_externalize)
    if decision is CompactionDecision.COMPACT:
        return summarize_closed_region()
    if decision is CompactionDecision.DEFER_AND_FLUSH:
        flush = [
            {
                "call_id": r.call_id,
                "tool": r.tool,
                "idempotency_key": r.idempotency_key,
                "params_hash": r.params_hash,
                "state": r.state.value,
            }
            for r in ledger.outstanding()
        ]
        return summarize_closed_region() + "\n" + reinject_pinned_block(flush)
    # Unreachable: decide_compaction raises instead of returning REFUSE without info.
    raise CompactionUnsound(f"unhandled decision {decision}")
