# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-signature-after-an-extended-skill-renegotiation-in-a2a-v1-0.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-signature-after-an-extended-skill-renegotiation-in-a2a-v1-0.warrant.json
# Markdown SHA-256:   0a3b516e55f12d855eee72171f50d75d6ebb1a627148b3c16e7e92759842c451
# Code AST SHA-256:   5a13c0115bfad61c8390c3a924fca83315d090f574a5d493f074cf656e5bc51e
# Verified Classes:   StaleCardSignatureError, VerifiedCard, SkillUpdate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class StaleCardSignatureError(RuntimeError):
    """Raised when a capability is admitted under a cardHash that does not cover it."""


@dataclass
class VerifiedCard:
    agent_id: str
    card_version: int
    card_hash: str
    skills: frozenset


@dataclass
class SkillUpdate:
    agent_id: str
    card_version: int
    added_skills: list
    extensions: dict = field(default_factory=dict)


def canonical_hash(card_payload: dict) -> str:
    canonical = json.dumps(card_payload, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(canonical).hexdigest()


def merge_skill_update(
    cached: VerifiedCard,
    update: SkillUpdate,
    refetch_card,
) -> VerifiedCard:
    """Merge a SkillUpdate only if the new skills are covered by a freshly verified card.

    refetch_card(agent_id, card_version) -> (payload: dict, jws_valid: bool)
    """
    if update.card_version == cached.card_version:
        # Same version: any added skill is an unauthorized grant under this hash.
        if update.added_skills:
            raise StaleCardSignatureError(
                f"SkillUpdate for {update.agent_id} adds {update.added_skills} "
                f"at unchanged cardVersion {cached.card_version}; no re-signature covers them"
            )
        return cached

    payload, jws_valid = refetch_card(update.agent_id, update.card_version)
    if not jws_valid:
        raise StaleCardSignatureError(
            f"Re-fetched card v{update.card_version} for {update.agent_id} failed JWS verification"
        )

    fresh_hash = canonical_hash(payload)
    fresh_skills = frozenset(s["id"] for s in payload.get("skills", []))
    for skill in update.added_skills:
        if skill["id"] not in fresh_skills:
            raise StaleCardSignatureError(
                f"Skill {skill['id']} not present in verified card v{update.card_version} "
                f"(hash {fresh_hash}); refusing to bind capability to stale hash {cached.card_hash}"
            )

    return VerifiedCard(
        agent_id=update.agent_id,
        card_version=update.card_version,
        card_hash=fresh_hash,
        skills=fresh_skills,
    )
