# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-auto-compaction-as-a-lossy-checkpoint-rather-than-a-resumable-state-and-how-does-retrieval-backed-rehydra.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-auto-compaction-as-a-lossy-checkpoint-rather-than-a-resumable-state-and-how-does-retrieval-backed-rehydra.warrant.json
# Markdown SHA-256:   44bc953475d0c25aa1d56973538c8640f0cb29401f7f2e7a773298bdfaa377a0
# Code AST SHA-256:   a43d795af50624df6e3db1154ab4d4a84664d86ab14b8aafd838bb049c07a423
# Verified Classes:   CompactionContinuityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CompactionContinuityError(RuntimeError):
    """Raised when an instance attempts to resume from a lossy compaction summary
    without re-establishing state from the authoritative ledger."""
    pass


def resume_after_compaction(
    summary: str,
    ledger: list[dict],
    resident_context_tokens: int,
    budget_tokens: int,
    task_is_state_dependent: bool,
) -> dict:
    # Compaction is only a resumable checkpoint if state is externally authoritative.
    if resident_context_tokens > budget_tokens:
        raise CompactionContinuityError(
            f"context still over budget ({resident_context_tokens} > {budget_tokens}); "
            "compaction did not bound resident state"
        )

    if task_is_state_dependent:
        # Summary is a pointer, not a checkpoint. Rehydrate from the ledger.
        if not ledger:
            raise CompactionContinuityError(
                "state-dependent task resumed with empty ledger; "
                "summary cannot substitute for side-effect record"
            )

        applied = [e["handle"] for e in ledger if e["status"] == "applied"]
        deferred = [e["handle"] for e in ledger if e["status"] == "deferred"]
        ordered = [e["handle"] for e in sorted(ledger, key=lambda e: e["seq"])]

        # Identifier-keyed rehydration: refuse to proceed on summary prose alone.
        if any(h not in ordered for h in applied):
            raise CompactionContinuityError(
                "applied handle set inconsistent with ordered ledger; "
                "refusing to resume on unverified state"
            )

        # Negative results must survive compaction.
        if any(e["status"] == "deferred" and not e.get("failure_sig") for e in ledger):
            raise CompactionContinuityError(
                "deferred action lacks failure signature; "
                "negative result would be lost on resume"
            )

        return {
            "mode": "checkpoint-and-reestablish",
            "summary_role": "index_only",
            "applied": applied,
            "deferred": deferred,
            "order": ordered,
            "reestablishment_required": True,
        }

    # Forward-only work: summary-as-context is safe.
    return {
        "mode": "bound-and-continue",
        "summary_role": "context",
        "reestablishment_required": False,
    }
