# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-agent-card-signature-rotation-from-silently-voiding-in-flight-a2a-task-delegations.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-agent-card-signature-rotation-from-silently-voiding-in-flight-a2a-task-delegations.warrant.json
# Markdown SHA-256:   82542c2f8fc3ebde9d568fe5884776bae4af22da0a864d99df61520d1bb04922
# Code AST SHA-256:   03f5037eb8ead98b5fd949bb5700ca6b5a8c76384b93658ce1a7e5986695ec67
# Verified Classes:   CardContinuityViolation, CardKey, AgentCardSnapshot, TaskWarrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from datetime import datetime, timedelta


class CardContinuityViolation(RuntimeError):
    """Raised when a task warrant's bound card key is not honored for the
    full lifetime of the warrant — i.e., the delegatee retired the key
    before the warrant's commitment tail expired."""
    pass


@dataclass
class CardKey:
    kid: str
    thumbprint: str          # JWKS thumbprint of the key material
    active: bool
    valid_until: datetime    # must cover max warrant TTL for retired keys


@dataclass
class AgentCardSnapshot:
    card_hash: str           # hash of the canonical card document
    keys: dict[str, CardKey] = field(default_factory=dict)

    def resolve(self, kid: str, at: datetime) -> CardKey | None:
        k = self.keys.get(kid)
        if k is None:
            return None
        if not k.active and at > k.valid_until:
            return None
        return k


@dataclass
class TaskWarrant:
    task_id: str
    bound_kid: str
    bound_thumbprint: str
    bound_card_hash: str
    issued_at: datetime
    expires_at: datetime


def verify_warrant_against_card(
    warrant: TaskWarrant,
    card: AgentCardSnapshot,
    *,
    now: datetime,
    max_warrant_ttl: timedelta,
    clock_skew: timedelta = timedelta(seconds=30),
) -> None:
    if now > warrant.expires_at + clock_skew:
        raise CardContinuityViolation(
            f"warrant {warrant.task_id} expired at {warrant.expires_at}"
        )

    key = card.resolve(warrant.bound_kid, at=now)
    if key is None:
        raise CardContinuityViolation(
            f"warrant {warrant.task_id} bound to kid={warrant.bound_kid!r} "
            f"which is absent or past valid_until at {now.isoformat()}"
        )

    # Bind by content, not by kid string: a reissued kid must not satisfy
    # an old warrant.
    if key.thumbprint != warrant.bound_thumbprint:
        raise CardContinuityViolation(
            f"warrant {warrant.task_id}: kid={warrant.bound_kid!r} resolves to "
            f"thumbprint {key.thumbprint!r}, warrant bound to "
            f"{warrant.bound_thumbprint!r} — key reissue detected"
        )

    if warrant.bound_card_hash != card.card_hash:
        # Card document changed (e.g., rotation). This is acceptable only if
        # the bound key remains resolvable for the warrant's full lifetime.
        if key.active:
            raise CardContinuityViolation(
                f"warrant {warrant.task_id}: card hash mismatch and bound key "
                f"still marked active — inconsistent card state"
            )
        if key.valid_until < warrant.expires_at:
            raise CardContinuityViolation(
                f"warrant {warrant.task_id}: retired key valid_until "
                f"{key.valid_until.isoformat()} < warrant expiry "
                f"{warrant.expires_at.isoformat()} — retention window too short"
            )


def assert_publication_retention(
    retired_key: CardKey, max_warrant_ttl: timedelta, rotated_at: datetime
) -> None:
    required = rotated_at + max_warrant_ttl
    if retired_key.valid_until < required:
        raise CardContinuityViolation(
            f"retired kid={retired_key.kid!r} valid_until "
            f"{retired_key.valid_until.isoformat()} does not cover "
            f"max_warrant_ttl; required >= {required.isoformat()}"
        )
