# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-stale-agent-card-signature-after-the-key-rotates-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-stale-agent-card-signature-after-the-key-rotates-mid-task.warrant.json
# Markdown SHA-256:   5fb2be727d6cb90434558274a81377908215a27a6610cfee6a0a0052faf41ac4
# Code AST SHA-256:   10a30696065c2955df65ab2e60ace37bb7c44aee394e0b6794edd2ad3144cf29
# Verified Classes:   StaleCardSignatureError, RotationChainBrokenError, JwksSnapshot, PinnedTaskTrust
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class StaleCardSignatureError(RuntimeError):
    """Raised when an artifact's signing kid cannot be chained to the
    JWKS snapshot pinned at task-initiation time."""
    pass


class RotationChainBrokenError(StaleCardSignatureError):
    """Raised when a JWKS snapshot transition is not signed by the
    previous snapshot's active key — i.e. a substitution, not a rotation."""
    pass


@dataclass
class JwksSnapshot:
    snapshot_hash: str
    kids: frozenset[str]
    fetched_at: float
    signed_by_previous: Optional[str] = None  # kid of the key that signed this snapshot


@dataclass
class PinnedTaskTrust:
    task_id: str
    snapshot: JwksSnapshot
    card_ttl: float
    initiated_at: float = field(default_factory=time.time)

    def revalidate_on_terminal(self, artifact_kid: str, fresh: JwksSnapshot) -> None:
        # Transition policy: re-validate only on terminal-state events.
        if artifact_kid in self.snapshot.kids:
            return  # artifact signed under a key we already trusted
        if artifact_kid not in fresh.kids:
            raise StaleCardSignatureError(
                f"artifact kid {artifact_kid!r} absent from fresh JWKS "
                f"snapshot {fresh.snapshot_hash[:12]}; task {self.task_id} "
                f"cannot be completed under pinned trust"
            )
        # Artifact is under a new kid. The rotation must be chained:
        # fresh snapshot must be signed by a key we trusted at pin time.
        if fresh.signed_by_previous not in self.snapshot.kids:
            raise RotationChainBrokenError(
                f"JWKS transition {self.snapshot.snapshot_hash[:12]} -> "
                f"{fresh.snapshot_hash[:12]} signed by "
                f"{fresh.signed_by_previous!r}, not in pinned kid set; "
                f"possible key substitution on task {self.task_id}"
            )
        # Legitimate rotation: advance the pin.
        self.snapshot = fresh

    def revalidate_on_unknown_kid(self, artifact_kid: str, fetch_jwks) -> None:
        # Lazy policy: only fetch when kid is unknown. MUST fail closed.
        if artifact_kid in self.snapshot.kids:
            return
        try:
            fresh = fetch_jwks()
        except Exception as exc:
            raise StaleCardSignatureError(
                f"JWKS fetch failed during unknown-kid revalidation for "
                f"task {self.task_id}; failing closed"
            ) from exc
        self.revalidate_on_terminal(artifact_kid, fresh)
