# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-signature-across-an-a2a-task-handoff-when-the-peer-s-jwks-has-rotated-but-the-task-state-machine-has-al.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-signature-across-an-a2a-task-handoff-when-the-peer-s-jwks-has-rotated-but-the-task-state-machine-has-al.warrant.json
# Markdown SHA-256:   982f1a1c1b15381e2eb28133ee176c6707004f0791508bb835344e602fe7ce86
# Code AST SHA-256:   ea8e8c83bbb4df4010304d42bd37f7860db4db73d568f731bbc0c0d99917a459
# Verified Classes:   AuthorizationBasisOrphaned, EventSigningKeyUnknown, TaskRecord, PeerJWKS
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class AuthorizationBasisOrphaned(RuntimeError):
    """Raised when a live task's authorizing Agent Card kid is absent from the peer JWKS."""
    pass


class EventSigningKeyUnknown(RuntimeError):
    """Raised when a task event is signed by a kid not present in the peer JWKS."""
    pass


@dataclass
class TaskRecord:
    task_id: str
    state: str                          # submitted | working | input-required | completed
    card_kid: str                       # kid that signed the Agent Card at dispatch
    card_protected_b64: str             # pinned protected header, prevents TOCTOU substitution
    card_claims_hash: str               # sha256 of the capability claims acted upon


@dataclass
class PeerJWKS:
    kids: set = field(default_factory=set)


LIVE_STATES = {"submitted", "working", "input-required"}


def revalidate_live_tasks(tasks: list[TaskRecord], jwks: PeerJWKS) -> None:
    """
    Called on every JWKS refresh. Fails closed: any live task whose card kid
    is no longer published is escalated, not silently retried.
    """
    orphans = [
        t for t in tasks
        if t.state in LIVE_STATES and t.card_kid not in jwks.kids
    ]
    if orphans:
        ids = ", ".join(t.task_id for t in orphans)
        raise AuthorizationBasisOrphaned(
            f"card kid absent from JWKS for live tasks [{ids}]; "
            f"authorization basis indeterminate — halt side effects, "
            f"transition to input-required with reason=authorization-basis-orphaned"
        )


def verify_event(event_kid: str, jwks: PeerJWKS, task: TaskRecord) -> None:
    """
    Event-path verification must NOT reuse the card-path decision.
    Unknown event kid is a hard reject; do not retry, do not fall back to card kid.
    """
    if event_kid not in jwks.kids:
        raise EventSigningKeyUnknown(
            f"event for task {task.task_id} signed by kid {event_kid!r} "
            f"not present in peer JWKS; reject and quarantine"
        )
    if event_kid == task.card_kid:
        # Peer signing events with the same key that signed the card is expected
        # only if no rotation occurred; still fine, but log the coupling.
        pass


def pin_card_at_dispatch(card: dict, task_id: str) -> TaskRecord:
    sig = card["signatures"][0]
    protected = sig["protected"]
    header = json.loads(_b64d(protected))
    claims_hash = hashlib.sha256(
        json.dumps(card.get("capabilities", {}), sort_keys=True).encode()
    ).hexdigest()
    return TaskRecord(
        task_id=task_id,
        state="submitted",
        card_kid=header["kid"],
        card_protected_b64=protected,
        card_claims_hash=claims_hash,
    )


def _b64d(s: str) -> bytes:
    import base64
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
