# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-lossy-auto-compaction-checkpoint-when-the-audit-trail-cannot-reconstruct-a-dropped-tool-call-obligation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-lossy-auto-compaction-checkpoint-when-the-audit-trail-cannot-reconstruct-a-dropped-tool-call-obligation.warrant.json
# Markdown SHA-256:   06e7201ca6af6f1e345cd37f0c60795261197f7b25d52caf62538a0bb34b6f6b
# Code AST SHA-256:   263089ade6973a20799919c66e9717df07de4c19cc1d7f84cc9a9312cbae81ba
# Verified Classes:   CompactionObligationLoss
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CompactionObligationLoss(RuntimeError):
    """Raised when a lossy compaction would drop or falsely close an obligation."""
    pass


NON_TERMINAL = {"timeout", "partial", "pending", "retry", "rate_limited"}


def audit_compaction(span_events, summary_ledger):
    """
    span_events: list of dicts with keys:
        kind: "tool_call" | "intention" | "conditional"
        status: terminal status string (for tool_call)
        artifact: witness id if terminal success, else None
        obligation_id: stable id
    summary_ledger: dict obligation_id -> "closed"|"carried"|"dropped"
                    as emitted by the summarizer.
    Returns list of carried obligations; raises on any loss.
    """
    carried = []
    for ev in span_events:
        oid = ev["obligation_id"]
        disposition = summary_ledger.get(oid)

        if disposition is None:
            raise CompactionObligationLoss(
                f"obligation {oid} vanished from summary ledger entirely"
            )

        if ev["kind"] == "tool_call" and ev["status"] in NON_TERMINAL:
            # Non-terminal tool results can NEVER be summarized as closed.
            if disposition == "closed":
                raise CompactionObligationLoss(
                    f"obligation {oid} has non-terminal status "
                    f"'{ev['status']}' but summary marked it closed"
                )
            carried.append(oid)

        elif ev["kind"] in ("intention", "conditional"):
            if disposition == "closed":
                raise CompactionObligationLoss(
                    f"obligation {oid} is an unfulfilled {ev['kind']} "
                    f"but summary narrated it as completed"
                )
            carried.append(oid)

        elif disposition == "closed" and not ev.get("artifact"):
            # Claimed complete with no witnessing artifact.
            raise CompactionObligationLoss(
                f"obligation {oid} marked closed without a witness artifact; "
                f"summary is unfalsifiable and must not replace the span"
            )

    return carried
