# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-revoked-skill-mid-execution-when-the-revocation-arrives-after-the-skill-manifest-was-already-cached-and-trusted.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-revoked-skill-mid-execution-when-the-revocation-arrives-after-the-skill-manifest-was-already-cached-and-trusted.warrant.json
# Markdown SHA-256:   110cc496ef3d9b97399cd49fd4607189ffcea8acd066c4d9f9b1439ab097d7d4
# Code AST SHA-256:   0212bfdcce7b0503bceb6eb8a989618d7c141de45d55989d2e949e29e8b3ee44
# Verified Classes:   RevokedSkillError, RevocationFeedUnavailable, CachedManifest, TrustState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Mapping


class RevokedSkillError(RuntimeError):
    """Raised when a cached skill manifest is no longer authorized at use time."""


class RevocationFeedUnavailable(RuntimeError):
    """Raised when the agent cannot determine the live revocation epoch."""


@dataclass(frozen=True)
class CachedManifest:
    skill_id: str
    asserted_epoch: int          # E_manifest, signed by registry
    sbom_closure: frozenset[str]  # all node IDs in the dependency graph


@dataclass
class TrustState:
    local_epoch: int = 0
    revoked_nodes: frozenset[str] = field(default_factory=frozenset)


def drain_revocation_feed(feed) -> TrustState:
    """Advance E_local from the registry feed. Must be monotonic and signed."""
    try:
        snapshot = feed.fetch()
    except Exception as exc:  # network, signature failure, timeout
        raise RevocationFeedUnavailable(
            "cannot determine live revocation epoch; failing closed"
        ) from exc
    if snapshot.epoch < 0:
        raise RevocationFeedUnavailable("feed returned non-monotonic epoch")
    return TrustState(
        local_epoch=snapshot.epoch,
        revoked_nodes=frozenset(snapshot.revoked_node_ids),
    )


def authorize_invocation(manifest: CachedManifest, trust: TrustState) -> None:
    """The single decision point before every skill invocation."""
    if trust.local_epoch < manifest.asserted_epoch:
        raise RevokedSkillError(
            f"stale trust epoch for {manifest.skill_id}: "
            f"E_local={trust.local_epoch} < E_manifest={manifest.asserted_epoch}"
        )
    hit = manifest.sbom_closure & trust.revoked_nodes
    if hit:
        raise RevokedSkillError(
            f"{manifest.skill_id} depends on revoked node(s): {sorted(hit)}"
        )


def invoke_skill(manifest: CachedManifest, feed, payload: Mapping) -> object:
    trust = drain_revocation_feed(feed)
    authorize_invocation(manifest, trust)
    return manifest.skill_id  # placeholder for the actual skill call
