# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-auto-compaction-the-pre-compaction-tool-call-receipt-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-auto-compaction-the-pre-compaction-tool-call-receipt-gap.warrant.json
# Markdown SHA-256:   f249c983fd29d1004a58b355924ca054c62c3a97290753084bf987892e600f0a
# Code AST SHA-256:   07fedb6f8f908f1a6146285b4b0e1f064a1eb5ad1594750c8618c5c2289e57eb
# Verified Classes:   UnsettledCommitmentCompactionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class UnsettledCommitmentCompactionError(RuntimeError):
    """Raised when auto-compaction would evict a dispatched-but-unreceipted tool call."""
    pass


def compact_context(
    context_turns: list[dict],
    pending_calls: dict[str, dict],   # call_id -> {tool, args_hash, idempotency_key, receipt}
    token_usage: float,              # fraction of window, 0.0..1.0
    hard_ceiling: float = 0.99,
) -> dict:
    open_commitments = {
        cid: rec for cid, rec in pending_calls.items() if rec.get("receipt") is None
    }

    if not open_commitments:
        return {"mode": "threshold", "summarize_upto": len(context_turns), "pinned": {}}

    if token_usage < hard_ceiling:
        # Defer: correct behavior is to wait for receipts, not to compact.
        return {"mode": "deferred", "reason": "open_commitments", "pinned": open_commitments}

    # Hard ceiling reached with open commitments: compact only settled region,
    # pin commitments verbatim, and forbid the summarizer from touching them.
    settled_boundary = min(
        (i for i, t in enumerate(context_turns) if t.get("settled", True)),
        default=0,
    )
    if settled_boundary == 0:
        raise UnsettledCommitmentCompactionError(
            f"Cannot compact: {len(open_commitments)} open commitments and no settled "
            f"prefix to evict at {token_usage:.2%} window. Escalate to synchronous "
            f"reconciliation turn; do not summarize receipts."
        )
    return {
        "mode": "receipt_gated",
        "summarize_upto": settled_boundary,
        "pinned": open_commitments,
        "summarizer_excludes": list(open_commitments.keys()),
    }
