# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-agent-card-is-being-re-served-under-a-stale-delegation-epoch-in-a2a-v1-0.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-agent-card-is-being-re-served-under-a-stale-delegation-epoch-in-a2a-v1-0.warrant.json
# Markdown SHA-256:   9cfb261fb307e4dc4370a0b57977a6595682417aa061ad87e2aac8c9c05ec915
# Code AST SHA-256:   2ad84f3eb2dff6e6b5e5d43e1e8d52538bbbf44e7acbf242f95e33b851660a86
# Verified Classes:   StaleDelegationEpochError, AgentCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class StaleDelegationEpochError(RuntimeError):
    """Raised when a signed Agent Card is structurally valid but its
    delegation epoch is below the receiver's persisted floor, or when
    discovery tiers disagree on epoch for the same issuer."""
    pass


@dataclass(frozen=True)
class AgentCard:
    issuer: str
    epoch: int
    key_id: str
    manifest_hash: str          # full hash, never a prefix
    delegation_scope: frozenset
    signature_valid: bool


def validate_for_delegation(
    card: AgentCard,
    epoch_floor: int,
    revoked_scopes: frozenset,
    origin_manifest_hash: Optional[str] = None,
) -> None:
    # Signature validity is necessary but not the gate.
    if not card.signature_valid:
        raise StaleDelegationEpochError(
            f"signature invalid for issuer={card.issuer} key={card.key_id}"
        )

    # The actual trust gate: epoch monotonicity against a local floor.
    if card.epoch < epoch_floor:
        raise StaleDelegationEpochError(
            f"stale epoch: issuer={card.issuer} card_epoch={card.epoch} "
            f"floor={epoch_floor} (edge cache likely outlived rotation)"
        )

    # Full-hash comparison across tiers; prefix matching is unsound.
    if origin_manifest_hash is not None and card.manifest_hash != origin_manifest_hash:
        raise StaleDelegationEpochError(
            f"manifest drift: issuer={card.issuer} epoch={card.epoch} "
            f"card_hash={card.manifest_hash[:16]}... origin_hash={origin_manifest_hash[:16]}..."
        )

    # Over-claim check: stale cards can retain revoked delegation authority.
    overclaimed = card.delegation_scope & revoked_scopes
    if overclaimed:
        raise StaleDelegationEpochError(
            f"stale card over-claims revoked scopes: issuer={card.issuer} "
            f"epoch={card.epoch} scopes={sorted(overclaimed)}"
        )


def persist_floor(issuer: str, observed_epoch: int, current_floor: int) -> int:
    # Floor only ratchets upward; never lower it on a stale read.
    return max(observed_epoch, current_floor)


if __name__ == "__main__":
    floor = persist_floor("vendor-a", 43, 0)
    stale = AgentCard(
        issuer="vendor-a",
        epoch=41,
        key_id="key-2026-11",
        manifest_hash=hashlib.sha256(b"batch_v2").hexdigest(),
        delegation_scope=frozenset({"delegate.cross_vendor"}),
        signature_valid=True,
    )
    try:
        validate_for_delegation(
            stale,
            epoch_floor=floor,
            revoked_scopes=frozenset({"delegate.cross_vendor"}),
            origin_manifest_hash=hashlib.sha256(b"batch_v3").hexdigest(),
        )
    except StaleDelegationEpochError as e:
        print(f"delegation refused (correct): {e}")
