# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-signed-agent-card-after-cross-vendor-task-resumption-and-what-invariant-preserves-skill-manifes.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-peer-s-signed-agent-card-after-cross-vendor-task-resumption-and-what-invariant-preserves-skill-manifes.warrant.json
# Markdown SHA-256:   80b816f42b6bdf49e9142373598fdc8f03c34c559c83ac0ad8940de0d1496f32
# Code AST SHA-256:   fdcce703bff80f835ce625596c98661f409a28a3d797fcda5df1fa48feaeae53
# Verified Classes:   ManifestContinuityError, CardRef, Checkpoint, MigrationAttestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ManifestContinuityError(RuntimeError):
    """Raised when a resumed task's skill manifest cannot be proven continuous
    with the manifest under which the task was last checkpointed."""


@dataclass(frozen=True)
class CardRef:
    skill_id: str
    manifest_hash: str
    key_id: str
    expires_at: float


@dataclass(frozen=True)
class Checkpoint:
    task_id: str
    skill_id: str
    manifest_hash: str
    key_id: str
    seq: int
    issued_at: float


@dataclass(frozen=True)
class MigrationAttestation:
    task_id: str
    from_hash: str
    to_hash: str
    signed_by_key: str
    rotation_ts: float


def authorize_resume(
    checkpoint: Checkpoint,
    current_card: CardRef,
    migrations: list[MigrationAttestation],
    auditor_countersigned: bool,
) -> str:
    """Return one of: CONTINUE, MIGRATE, HALT, ABANDON.

    Enforces the invariant: the (skill_id, manifest_hash, key_id) tuple at
    resume must be reachable from the checkpoint's tuple via hash-equality
    or a signed migration edge whose rotation postdates the checkpoint.
    """
    # Skill must still exist on the live card.
    if current_card.skill_id != checkpoint.skill_id:
        return "ABANDON"

    # Hash-equal fast path.
    if (current_card.manifest_hash == checkpoint.manifest_hash
            and current_card.key_id == checkpoint.key_id):
        if not auditor_countersigned:
            raise ManifestContinuityError(
                f"task {checkpoint.task_id}: hash-equal resume without auditor countersignature"
            )
        return "CONTINUE"

    # Hash mismatch: require a migration attestation chained to the current key.
    edge = next(
        (m for m in migrations
         if m.task_id == checkpoint.task_id
         and m.from_hash == checkpoint.manifest_hash
         and m.to_hash == current_card.manifest_hash
         and m.signed_by_key == current_card.key_id),
        None,
    )
    if edge is None:
        # Distinguish "originator still reachable, needs attestation" from abandonment.
        if current_card.skill_id == checkpoint.skill_id:
            return "HALT"
        return "ABANDON"

    if edge.rotation_ts <= checkpoint.issued_at:
        raise ManifestContinuityError(
            f"task {checkpoint.task_id}: migration edge predates last checkpoint "
            f"(rotation_ts={edge.rotation_ts} <= checkpoint.issued_at={checkpoint.issued_at})"
        )

    if not auditor_countersigned:
        raise ManifestContinuityError(
            f"task {checkpoint.task_id}: migration resume requires auditor countersignature"
        )

    return "MIGRATE"
