# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-context-compaction-from-silently-severing-an-agent-s-tool-call-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-context-compaction-from-silently-severing-an-agent-s-tool-call-ledger.warrant.json
# Markdown SHA-256:   19e9989868e583fba88ab95bf0114f38cd1242220b3f9221dc138b99bc7909a0
# Code AST SHA-256:   d171071b32234de01377f941a2bf8fcd70ac975b89aa3ebffae1715ce0e6330f
# Verified Classes:   CompactionLedgerViolation, ToolCall, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionLedgerViolation(RuntimeError):
    """Raised when a compaction summary would sever a referenceable artifact."""


@dataclass
class ToolCall:
    call_id: str
    name: str
    idempotency_key: Optional[str] = None
    effectful: bool = False
    confirmed: bool = False


@dataclass
class Span:
    calls: list = field(default_factory=list)
    narrative: str = ""


def summarize_span(span: Span) -> str:
    # A naive summarizer: compresses narrative, drops identifiers.
    return span.narrative.strip()


def compact(span: Span, in_flight_calls: int, summary: str) -> Span:
    # Invariant 1: compaction must be quiescent w.r.t. the effect ledger.
    if in_flight_calls > 0:
        raise CompactionLedgerViolation(
            f"compaction attempted with {in_flight_calls} in-flight tool calls; "
            "defer until the ledger is quiescent"
        )

    # Invariant 2: every effectful, confirmed call must remain dereferenceable.
    # Its call_id and idempotency_key must survive into the summary as handles.
    missing = [
        c.call_id
        for c in span.calls
        if c.effectful and c.confirmed
        and (c.call_id not in summary or (c.idempotency_key and c.idempotency_key not in summary))
    ]
    if missing:
        raise CompactionLedgerViolation(
            "summary severs referenceable artifacts: "
            f"{missing}; retain call_id and idempotency_key as handles, "
            "do not paraphrase effectful calls"
        )

    # Invariant 3: ordering of effectful calls must be preserved in the summary.
    effectful_order = [c.call_id for c in span.calls if c.effectful]
    positions = [summary.find(cid) for cid in effectful_order]
    if positions != sorted(positions):
        raise CompactionLedgerViolation(
            "summary reorders effectful calls; ordering constraints lost"
        )

    return Span(calls=[], narrative=summary)


# Example: the double-refund trace, caught at compaction time.
bad = Span(
    calls=[
        ToolCall("call_881", "refund.issue", idempotency_key="idem_42", effectful=True, confirmed=True),
    ],
    narrative="The agent checked the account and confirmed the refund was already issued.",
)
try:
    compact(bad, in_flight_calls=0, summary=summarize_span(bad))
except CompactionLedgerViolation as e:
    raise CompactionLedgerViolation(f"refused lossy compaction: {e}") from e
