# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-stale-agent-card-across-an-org-boundary-during-signed-artifact-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-stale-agent-card-across-an-org-boundary-during-signed-artifact-exchange.warrant.json
# Markdown SHA-256:   0702e1f917a327da2797dbdcd6eefde051f4d9a1ce767c76bc5d2f6fd2d089b4
# Code AST SHA-256:   71068acea657c7e2b4c7f54d7254af4c758581453298b6551c485ca9f3e12150
# Verified Classes:   StaleAgentCardKeyError, RevokedAgentCardKeyError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleAgentCardKeyError(RuntimeError):
    """Raised when an artifact is signed with a keyId absent from the
    delegating peer's cached Agent Card, and the key is newer than the
    Card's issuedAt (stale discovery, not revocation)."""
    pass


class RevokedAgentCardKeyError(RuntimeError):
    """Raised when the artifact keyId is older than the Card issuedAt,
    indicating the origin revoked a key the delegate still trusts."""
    pass


def classify_signature_failure(
    artifact_key_id: str,
    card_keys: dict[str, int],  # keyId -> notBefore epoch
    card_issued_at: int,
) -> None:
    if artifact_key_id in card_keys:
        # Key is known to the Card; a verification failure here is forgery,
        # not a discovery problem. Caller handles separately.
        return

    # Key is unknown to the cached Card. Decide by age relative to Card issue.
    # We cannot know the unknown key's notBefore, so we infer from the fact
    # that the origin signs with its *current* key: an unknown key that the
    # origin presents now must be newer than a Card that predates it.
    newest_known = max(card_keys.values()) if card_keys else 0
    if card_issued_at >= newest_known:
        # Card was issued at or after every key it advertises; an unknown
        # key presented now is a rotation that postdates our cache.
        raise StaleAgentCardKeyError(
            f"artifact key {artifact_key_id!r} unknown to Card issued at "
            f"{card_issued_at}; origin rotated after cache. Re-resolve Card, "
            f"do NOT re-delegate."
        )
    raise RevokedAgentCardKeyError(
        f"artifact key {artifact_key_id!r} unknown and Card issued at "
        f"{card_issued_at} predates newest known key {newest_known}; "
        f"treat as revocation, terminal."
    )


def verify_delegated_artifact(
    artifact_key_id: str,
    card_keys: dict[str, int],
    card_issued_at: int,
    card_ttl_seconds: int,
    origin_overlap_seconds: int,
) -> str:
    if card_ttl_seconds >= origin_overlap_seconds:
        # Invariant violation: cache outlives the overlap window.
        raise StaleAgentCardKeyError(
            f"card_ttl {card_ttl_seconds}s >= overlap {origin_overlap_seconds}s; "
            f"stale-key rejection is guaranteed on rotation."
        )
    classify_signature_failure(artifact_key_id, card_keys, card_issued_at)
    return "verified"
