# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-a2a-artifact-has-outlived-the-agent-card-that-authorized-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-a2a-artifact-has-outlived-the-agent-card-that-authorized-it.warrant.json
# Markdown SHA-256:   1828d160aafbc3a5cdd138b84bcd082b3baed8599085f91bef3191083fec5d06
# Code AST SHA-256:   68368b5224caad62fa0caaa0cbe0ae1ac754a3fcdedd7ae8df4feecbd2fda611
# Verified Classes:   WarrantStaleError, PinnedWarrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class WarrantStaleError(RuntimeError):
    """Raised when an artifact's signing key is not covered by the card pinned at task submission."""
    pass


@dataclass(frozen=True)
class PinnedWarrant:
    card_hash: str
    allowed_kids: frozenset[str]
    allowed_capabilities: frozenset[str]


def pin_warrant(card: dict) -> PinnedWarrant:
    canonical = json.dumps(card, sort_keys=True, separators=(",", ":")).encode()
    return PinnedWarrant(
        card_hash=hashlib.sha256(canonical).hexdigest(),
        allowed_kids=frozenset(k["kid"] for k in card.get("publicKeys", [])),
        allowed_capabilities=frozenset(card.get("capabilities", {}).keys()),
    )


def verify_artifact_against_pinned(
    artifact_jws_header: dict,
    required_capability: str,
    pinned: PinnedWarrant,
    current_card: dict,
) -> None:
    kid = artifact_jws_header.get("kid")
    if kid is None:
        raise WarrantStaleError("artifact JWS header missing kid; cannot bind to pinned warrant")

    # The load-bearing check: the signer must be covered by the card pinned at submission.
    # A re-fetch of the current card is NOT a valid substitute for this lookup.
    if kid not in pinned.allowed_kids:
        raise WarrantStaleError(
            f"artifact signed by kid={kid!r} which is absent from pinned card "
            f"{pinned.card_hash[:12]}...; refusing re-fetch-on-unknown-kid fallback"
        )

    if required_capability not in pinned.allowed_capabilities:
        raise WarrantStaleError(
            f"task requires capability {required_capability!r} not present in pinned warrant"
        )

    # Capability drift is permitted (warrant was valid at submission) but must be surfaced.
    current_caps = frozenset(current_card.get("capabilities", {}).keys())
    if required_capability not in current_caps:
        # Caller is expected to record capability_drift=True on the task; not a hard failure.
        artifact_jws_header["_capability_drift"] = True
