# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-auto-compaction-when-a-lossy-summary-would-silently-invalidate-a-pending-tool-call-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-auto-compaction-when-a-lossy-summary-would-silently-invalidate-a-pending-tool-call-commitment.warrant.json
# Markdown SHA-256:   a2d41c535efd619761b7813ac6a7d3e41a6d6a72ff2e8f56346da117899a5cb5
# Code AST SHA-256:   49f3385136c327e017ad055af6f3abc7f4543ce58ffc15e530b7d75a9f2c5651
# Verified Classes:   CompactionContinuityViolation, Obligation, Trajectory
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class CompactionContinuityViolation(RuntimeError):
    """Raised when a lossy summary would drop or invalidate a pending obligation."""


@dataclass(frozen=True)
class Obligation:
    call_id: str
    target: str
    postcondition: str
    idempotency_key: str | None = None


@dataclass
class Trajectory:
    narrative_turns: list[str] = field(default_factory=list)
    dispatched: dict[str, Obligation] = field(default_factory=dict)
    reconciled: set[str] = field(default_factory=set)

    def pending(self) -> list[Obligation]:
        return [o for cid, o in self.dispatched.items() if cid not in self.reconciled]


def guard_compaction(traj: Trajectory, summary_ledger: Iterable[Obligation]) -> list[Obligation]:
    """Enforce pending_obligations(resumed) >= pending_obligations(pre_compaction).

    The ledger appended to the summary must be a superset of the live pending set.
    If the harness cannot guarantee that, compaction must be refused.
    """
    pre = {o.call_id: o for o in traj.pending()}
    post = {o.call_id: o for o in summary_ledger}

    missing = set(pre) - set(post)
    if missing:
        raise CompactionContinuityViolation(
            f"lossy summary would drop {len(missing)} pending obligation(s): "
            f"{sorted(missing)}; refusing compaction while in flight"
        )

    for cid, pre_ob in pre.items():
        post_ob = post[cid]
        if post_ob.postcondition != pre_ob.postcondition:
            raise CompactionContinuityViolation(
                f"obligation {cid} preserved as symbol but precondition mutated: "
                f"{pre_ob.postcondition!r} -> {post_ob.postcondition!r}"
            )

    return list(post.values())


def resume_from_summary(traj: Trajectory, summary_ledger: Iterable[Obligation],
                        first_action_call_id: str | None) -> None:
    ledger = guard_compaction(traj, summary_ledger)
    pending_ids = {o.call_id for o in ledger}
    if first_action_call_id is not None and first_action_call_id in pending_ids:
        raise CompactionContinuityViolation(
            f"resumed agent re-dispatched {first_action_call_id!r} which the ledger "
            f"records as already in flight; halt and reconcile before proceeding"
        )
