# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-past-a-capability-revocation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-cached-agent-card-past-a-capability-revocation-boundary.warrant.json
# Markdown SHA-256:   a54d36a966a7296b4ad0ea5a2ee0624533294f9f1eae73802e4c050c839c99e3
# Code AST SHA-256:   4b5e7de4a0784c5123db5d85de299778931d9b0e8f19f4568572bd18eee3e7c1
# Verified Classes:   StaleCapabilityError, CachedCard, LiveCard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleCapabilityError(RuntimeError):
    """Raised when a dispatch would execute a skill against a superseded card version."""


@dataclass(frozen=True)
class CachedCard:
    agent_id: str
    version: int
    skills: frozenset[str]
    fetched_at: float


@dataclass(frozen=True)
class LiveCard:
    agent_id: str
    version: int
    skills: frozenset[str]
    revocation_epoch: int


# Skills whose execution is irreversible or privileged: never trust the cache.
PRIVILEGED_SKILLS = frozenset({"redact_pii", "transfer_funds", "delete_account"})


def attest_and_dispatch(
    cached: CachedCard,
    live: LiveCard,
    skill: str,
    now: float,
    max_trust_ttl: float = 3600.0,
    cached_revocation_epoch: int = 0,
) -> str:
    if skill not in cached.skills:
        raise StaleCapabilityError(
            f"skill {skill!r} not in cached card v{cached.version} for {cached.agent_id}"
        )

    # Invariant 1: privileged skills require live attestation, full stop.
    if skill in PRIVILEGED_SKILLS:
        if live.version != cached.version:
            raise StaleCapabilityError(
                f"privileged skill {skill!r}: cached v{cached.version} != live v{live.version}; "
                f"re-plan required"
            )
        if live.revocation_epoch != cached_revocation_epoch:
            raise StaleCapabilityError(
                f"privileged skill {skill!r}: revocation epoch advanced "
                f"{cached_revocation_epoch}->{live.revocation_epoch}"
            )
        if skill not in live.skills:
            raise StaleCapabilityError(
                f"privileged skill {skill!r} revoked in live card v{live.version}"
            )
        return f"dispatch:{cached.agent_id}:{skill}:v{live.version}"

    # Invariant 2: non-privileged skills may trust the cache, but only within
    # TTL AND only if the version floor still holds.
    if now - cached.fetched_at > max_trust_ttl:
        raise StaleCapabilityError(
            f"cached card v{cached.version} for {cached.agent_id} exceeded TTL "
            f"({now - cached.fetched_at:.0f}s > {max_trust_ttl:.0f}s)"
        )
    if cached.version < live.version:
        # Narrowing may have occurred; re-plan rather than risk a revoked skill.
        raise StaleCapabilityError(
            f"version floor violated: cached v{cached.version} < live v{live.version}"
        )
    return f"dispatch:{cached.agent_id}:{skill}:v{cached.version}"


def record_episodic(dispatch_token: str, card_version: int, success: bool) -> dict:
    # Episodic records are version-pinned so distillation can drop stale evidence.
    if not success:
        raise StaleCapabilityError(f"refusing to record failed dispatch {dispatch_token}")
    return {"token": dispatch_token, "card_version": card_version, "positive": True}
