# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-signed-agent-card-as-a-stale-capability-claim-rather-than-a-live-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-signed-agent-card-as-a-stale-capability-claim-rather-than-a-live-authorization.warrant.json
# Markdown SHA-256:   12f5e56ff9078977efcb9b146c103f255d00ecd84d682d547cde091d6e0f0705
# Code AST SHA-256:   da73a713fbb8c139e4821df8f992aa6228bf6be1b761f99bd1536c8f255016de
# Verified Classes:   StaleCapabilityClaimError, CapabilityRevocationError, AgentCard, RemoteResponse
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleCapabilityClaimError(RuntimeError):
    """Raised when a delegator would dispatch on a card whose freshness or
    schema no longer bounds the remote's actual capability surface."""
    pass


class CapabilityRevocationError(RuntimeError):
    """Raised when a remote response fails re-validation against the schema
    the delegator currently believes the remote honors."""
    pass


@dataclass
class AgentCard:
    agent_id: str
    capability_version: str
    signature_valid: bool
    issued_at: float
    expires_at: float
    output_schema: dict


@dataclass
class RemoteResponse:
    agent_id: str
    capability_version: str
    payload: dict


def card_content_hash(card: AgentCard) -> str:
    body = f"{card.agent_id}:{card.capability_version}:{card.output_schema}"
    return hashlib.sha256(body.encode()).hexdigest()


def admit_delegation(
    card: AgentCard,
    now: float,
    mutation_cadence_s: float,
    last_verified_hash: str | None,
) -> str:
    """Gate dispatch on signature validity AND freshness within mutation cadence
    AND capability-version re-verification. Returns the hash to cache."""
    if not card.signature_valid:
        raise StaleCapabilityClaimError(
            f"card for {card.agent_id} failed signature verification; hard reject"
        )
    age = now - card.issued_at
    if age >= min(card.expires_at - card.issued_at, mutation_cadence_s):
        raise StaleCapabilityClaimError(
            f"card for {card.agent_id} age {age:.0f}s exceeds mutation cadence "
            f"{mutation_cadence_s:.0f}s; signature valid but claim is stale, "
            f"re-fetch required before dispatch"
        )
    current = card_content_hash(card)
    if last_verified_hash is not None and current != last_verified_hash:
        raise StaleCapabilityClaimError(
            f"capability_version drift for {card.agent_id}: cached "
            f"{last_verified_hash[:8]} != current {current[:8]}"
        )
    return current


def admit_response(
    response: RemoteResponse,
    believed_card: AgentCard,
    believed_hash: str,
) -> dict:
    """Enforce response-boundary schema re-validation before merge into state."""
    if card_content_hash(believed_card) != believed_hash:
        raise CapabilityRevocationError(
            f"believed card hash for {response.agent_id} no longer matches "
            f"verified hash; capability surface changed mid-flight"
        )
    if response.capability_version != believed_card.capability_version:
        raise CapabilityRevocationError(
            f"response from {response.agent_id} carries version "
            f"{response.capability_version}, believed "
            f"{believed_card.capability_version}; quarantine batch"
        )
    expected = believed_card.output_schema
    for field, ftype in expected.items():
        if field not in response.payload:
            raise CapabilityRevocationError(
                f"response missing advertised field {field}; schema drift"
            )
        if not _type_matches(response.payload[field], ftype):
            raise CapabilityRevocationError(
                f"field {field} type drift: advertised {ftype}, "
                f"got {type(response.payload[field]).__name__}; "
                f"revoke capability, do not retry on same card"
            )
    return response.payload


def _type_matches(value, ftype: str) -> bool:
    mapping = {
        "array[string]": lambda v: isinstance(v, list) and all(isinstance(x, str) for x in v),
        "array[object]": lambda v: isinstance(v, list) and all(isinstance(x, dict) for x in v),
        "string": lambda v: isinstance(v, str),
        "object": lambda v: isinstance(v, dict),
    }
    return mapping.get(ftype, lambda v: True)(value)
