# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-regain-revoked-capabilities-after-a-mid-task-checkpoint-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-regain-revoked-capabilities-after-a-mid-task-checkpoint-resume.warrant.json
# Markdown SHA-256:   2566e7da714b939475755390de8145d57990898d0ea08f4649f9c2a106eb9272
# Code AST SHA-256:   ad5d69ce9bee6d9c0687c0ca392d771512e952d56fd03592b27e6f43dbd3d5bf
# Verified Classes:   AttenuationLaunderingError, StaleCheckpointError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AttenuationLaunderingError(RuntimeError):
    """Raised when a checkpoint resume would grant capabilities that were
    attenuated after the checkpoint was sealed."""
    pass


class StaleCheckpointError(RuntimeError):
    """Raised when a checkpoint predates the latest attenuation for its task."""
    pass


def resume_instance(checkpoint: dict, ledger, manifest: dict) -> dict:
    task_id = checkpoint["task_id"]
    sealed_caps = set(checkpoint["capabilities"])          # C at seal time
    sealed_hwm = checkpoint["ledger_high_water"]

    # Guard 1: refuse to resume from a checkpoint older than current policy.
    current_hwm = ledger.high_water(task_id)
    if current_hwm > sealed_hwm:
        raise StaleCheckpointError(
            f"task {task_id}: checkpoint hwm={sealed_hwm} < ledger hwm={current_hwm}; "
            f"replay missed attenuations before resuming"
        )

    # Guard 2: effective caps = manifest ceiling INTERSECT sealed INTERSECT live ledger.
    # The manifest is an upper bound, never the grant.
    manifest_caps = set(manifest["capabilities"])
    live_attenuated = ledger.outstanding_attenuations(task_id)  # set of revoked caps
    effective = (sealed_caps & manifest_caps) - live_attenuated

    # Guard 3: monotonicity — refuse any widening across the resume seam.
    if not effective.issubset(sealed_caps):
        widened = effective - sealed_caps
        raise AttenuationLaunderingError(
            f"task {task_id}: resume would widen capabilities by {sorted(widened)}; "
            f"attenuation monotonicity violated"
        )

    return {
        "task_id": task_id,
        "capabilities": effective,
        "ledger_high_water": current_hwm,
    }
