# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a-signed-capability-graph-whose-delegated-sub-capabilities-were-revoked-upstream-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a-signed-capability-graph-whose-delegated-sub-capabilities-were-revoked-upstream-mid-handoff.warrant.json
# Markdown SHA-256:   e7fbfeb41ca3277c9664bb3bcb043c47e7581ac692241cddf904c99724dd311b
# Code AST SHA-256:   e97ccc59418c85ba282106c5ce9e65dee50e19072dff66e94311d28dc1ca95f5
# Verified Classes:   StaleCapabilityGraph, CapabilityEdge
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleCapabilityGraph(RuntimeError):
    """Raised when a signature-valid edge is not provably non-revoked at act time."""
    pass


@dataclass
class CapabilityEdge:
    issuer: str
    subject: str
    cap: str
    signature_valid: bool
    attestation_time: float          # when issuer last asserted non-revocation
    propagation_bound_s: float       # issuer's max revocation propagation delay
    revoked: bool = False


def assert_edge_actionable(edge: CapabilityEdge, now: Optional[float] = None) -> None:
    now = time.time() if now is None else now

    if not edge.signature_valid:
        raise StaleCapabilityGraph(
            f"edge {edge.issuer}->{edge.subject} signature invalid"
        )
    if edge.revoked:
        raise StaleCapabilityGraph(
            f"edge {edge.issuer}->{edge.subject} revoked at issuer"
        )
    # Freshness invariant: attestation must be newer than the issuer's
    # worst-case revocation propagation delay, else a revocation could have
    # landed unseen.
    age = now - edge.attestation_time
    if age > edge.propagation_bound_s:
        raise StaleCapabilityGraph(
            f"edge {edge.issuer}->{edge.subject} attestation age {age:.0f}s "
            f"exceeds propagation bound {edge.propagation_bound_s:.0f}s; "
            f"graph may be stale — re-resolve, do NOT retry"
        )


def traverse_graph(edges, now: Optional[float] = None) -> None:
    # Walk root->leaf; any non-actionable edge aborts the whole traversal,
    # because a broken link invalidates every capability below it.
    for edge in edges:
        assert_edge_actionable(edge, now=now)


def handle_peer_denial(status_code: int, graph_edges) -> str:
    # The critical taxonomy fix: a 403 from a peer is evidence the local
    # graph is stale, not a transient tool failure.
    if status_code == 403:
        raise StaleCapabilityGraph(
            "peer denied a signature-valid capability; local graph is stale. "
            "Invalidate cache and re-resolve — retrying the same graph is unsafe."
        )
    return "transient"
