# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-pre-compaction-and-post-compaction-state-to-guarantee-task-critical-invariant-preservation-across-context-rollover.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-pre-compaction-and-post-compaction-state-to-guarantee-task-critical-invariant-preservation-across-context-rollover.warrant.json
# Markdown SHA-256:   094a4b948cc6023019b3aca47cf978bd5e1f9ecd911283f1153f2077c0c98681
# Code AST SHA-256:   cb794e00fd17485bd3f8a0f55a79cf1b465306f9a86b58f52afc152dc54e1558
# Verified Classes:   UnreconciledCommitmentError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class UnreconciledCommitmentError(RuntimeError):
    """Raised when a post-compaction instance cannot reconcile its commitment ledger."""
    pass


def reconcile_after_compaction(ledger: dict, summary: str, late_results: list) -> dict:
    """
    Enforce the rollover invariant: post-compaction live commitments must be a
    superset of pre-compaction unresolved commitments, and every late tool result
    must pair to an originating intent in the ledger.
    """
    unresolved = {c["id"] for c in ledger.get("commitments", []) if not c.get("resolved")}
    if not unresolved:
        # Empty ledger at boundary: summary-authoritative rollover is permitted.
        return {"mode": "summary_authoritative", "summary": summary, "commitments": []}

    # Non-empty ledger: summary-authoritative rollover is prohibited.
    if not ledger.get("transferred_verbatim"):
        raise UnreconciledCommitmentError(
            f"Compaction boundary crossed with {len(unresolved)} unresolved commitment(s) "
            f"but ledger was not transferred verbatim; summary-only continuation would drop "
            f"live obligations: {sorted(unresolved)}"
        )

    intent_ids = {c["id"] for c in ledger["commitments"]}
    orphaned = [r for r in late_results if r.get("correlation_id") not in intent_ids]
    if orphaned:
        raise UnreconciledCommitmentError(
            f"Late tool result(s) arrived with no originating intent in ledger: "
            f"{[r.get('correlation_id') for r in orphaned]}; pairing severed at boundary."
        )

    # Re-assert every live commitment before the instance is allowed to act.
    return {
        "mode": "ledger_authoritative",
        "commitments": [c for c in ledger["commitments"] if not c.get("resolved")],
        "paired_results": {r["correlation_id"]: r for r in late_results},
        "summary": summary,  # demoted to context, not authoritative
    }
