# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-signing-key-agent-card-when-the-delegated-task-s-purpose-claim-outlives-the-vendor-s-key-rotation-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-signing-key-agent-card-when-the-delegated-task-s-purpose-claim-outlives-the-vendor-s-key-rotation-window.warrant.json
# Markdown SHA-256:   f528601c4e154814f30640f7bbf96747f76bd68fccd31acaafb3d596af9a4f36
# Code AST SHA-256:   55db13722bfbed2f6688eebc7d00693c939e0c44deb66db4988fa6c1d8eb0540
# Verified Classes:   StaleCardBinding, CachedCard, DelegationToken
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleCardBinding(RuntimeError):
    """Raised when a live task's delegation token cannot be re-anchored to a
    currently-valid Agent Card signing key, and no card_kid binding exists to
    prove the token was issued against a retired-but-legitimate key."""
    pass


@dataclass
class CachedCard:
    kid: str
    fetched_at: float
    cache_ttl: float


@dataclass
class DelegationToken:
    purpose: str
    aud: str
    exp: float
    card_kid: Optional[str]  # None if caller did not bind the card key


def revalidate_running_task(
    card: CachedCard,
    token: DelegationToken,
    live_jwks_kids: set,
    task_status: str,
    now: Optional[float] = None,
) -> str:
    """Cross-check card verification against live task status.

    Returns 'ok' or 'reanchor' when the skew is detectable and recoverable.
    Raises StaleCardBinding when the skew is present but unrecoverable.
    """
    now = time.time() if now is None else now

    card_still_verifiable = card.kid in live_jwks_kids
    task_live = task_status == "working"

    # No divergence: card verifies, task live (or both settled).
    if card_still_verifiable:
        return "ok"

    # Card key retired. Is the task still running on it?
    if not task_live:
        # Task already finished; stale card is harmless.
        return "ok"

    # Divergence: task live, card key gone. Can we prove the token was
    # issued against this (now-retired) key?
    if token.card_kid is not None and token.card_kid == card.kid:
        # Binding proves legitimacy; re-anchor to current key via fresh handshake.
        return "reanchor"

    # No binding, or binding points elsewhere: cannot distinguish retired-key
    # issuance from forgery/replay. Fail closed.
    raise StaleCardBinding(
        f"live task (purpose={token.purpose!r}, aud={token.aud!r}) "
        f"authorized under retired card kid={card.kid!r}; "
        f"token.card_kid={token.card_kid!r}; live kids={sorted(live_jwks_kids)}. "
        f"Card cache age={now - card.fetched_at:.0f}s (ttl={card.cache_ttl}s). "
        f"Cannot re-anchor; aborting delegation."
    )
