# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-trajectory-compaction-from-silently-orphaning-in-flight-tool-obligations.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-trajectory-compaction-from-silently-orphaning-in-flight-tool-obligations.warrant.json
# Markdown SHA-256:   079e01c33aaf4d04ef44f05e8efe2a6b195b4aeecbe9d4ffec7f95d8c8980c6b
# Code AST SHA-256:   fb15f3baf28140689c72299b48f3658b83d1240581f1ed3abf0767bdb0764c5f
# Verified Classes:   OrphanedObligationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OrphanedObligationError(RuntimeError):
    """Raised when a compaction step would discard a live, unclosed obligation
    without carrying its handle forward or reconciling it against ground truth."""
    pass


def compact_trajectory(
    trajectory: list,
    open_obligations: list[dict],
    reconcile_fn,
    digest_schema_has_obligation_field: bool,
) -> dict:
    """
    open_obligations: list of {handle_id, kind, opened_at, close_predicate}
    reconcile_fn: callable(handle_id) -> "live" | "closed" | "unknown"
    Returns a digest that is obligation-preserving.
    """
    if not open_obligations:
        return _summarize(trajectory)

    if not digest_schema_has_obligation_field:
        # The digest cannot represent handles. Refuse to compact lossily.
        raise OrphanedObligationError(
            f"cannot compact: {len(open_obligations)} live obligation(s) "
            f"but digest schema has no obligation field; "
            f"handles would be dropped: {[o['handle_id'] for o in open_obligations]}"
        )

    carried = []
    for ob in open_obligations:
        state = reconcile_fn(ob["handle_id"])
        if state == "unknown":
            # Cannot confirm; do not proceed on a guess.
            raise OrphanedObligationError(
                f"cannot compact: obligation {ob['handle_id']} ({ob['kind']}) "
                f"state is unknown; reconciliation required before discard"
            )
        if state == "live":
            # Carry verbatim, identifier intact. No paraphrase.
            carried.append(dict(ob))
        # state == "closed": discharged, safe to drop.

    digest = _summarize(trajectory)
    digest["open_obligations"] = carried  # side channel, not summarized
    return digest
