# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-agent-credential-has-silently-outlived-its-authorization-chain-the-aaif-attenuation-orphan-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-agent-credential-has-silently-outlived-its-authorization-chain-the-aaif-attenuation-orphan-problem.warrant.json
# Markdown SHA-256:   63a14cb0845d0fec9347a652324ed94a6db0b0680172d8046807b9a1414f8fbd
# Code AST SHA-256:   c8d6a02284e24c17ac3012e5cb2b40355f20db97f124c53ad6e011cff0e6aaee
# Verified Classes:   OrphanedDelegationError, StaleRevocationViewError, Credential, VerifierView
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class OrphanedDelegationError(RuntimeError):
    """Raised when a leaf credential's scope is no longer derivable from live ancestors."""
    pass


class StaleRevocationViewError(RuntimeError):
    """Raised when the verifier's revocation snapshot is older than allowed."""
    pass


@dataclass
class Credential:
    cred_id: str
    issuer_id: str
    scope: frozenset
    expires_at: float
    parent_hash: Optional[str]
    revoked: bool = False


@dataclass
class VerifierView:
    live_creds: dict            # cred_id -> Credential (current, authoritative)
    status_snapshot_at: float   # when the revocation view was last refreshed
    max_status_age: float       # allowed staleness


def verify_leaf(
    leaf: Credential,
    embedded_chain: list,       # [root, ..., leaf] as embedded in the token
    view: VerifierView,
    now: Optional[float] = None,
) -> bool:
    now = now if now is not None else time.time()

    # 1. Freshness of the revocation view — a stale snapshot can hide an orphan.
    if now - view.status_snapshot_at > view.max_status_age:
        raise StaleRevocationViewError(
            f"status snapshot age {now - view.status_snapshot_at:.0f}s "
            f"> max {view.max_status_age:.0f}s; cannot trust liveness"
        )

    # 2. Walk the embedded chain against the LIVE graph, not the embedded copy.
    live_scope = None
    live_depth = 0
    for link in embedded_chain:
        live = view.live_creds.get(link.cred_id)
        if live is None:
            # Ancestor no longer exists in the live graph: chain is severed.
            raise OrphanedDelegationError(
                f"ancestor {link.cred_id} absent from live graph; "
                f"leaf {leaf.cred_id} is an orphan at depth {live_depth}"
            )
        if live.revoked:
            raise OrphanedDelegationError(
                f"ancestor {link.cred_id} revoked; leaf {leaf.cred_id} "
                f"scope no longer derivable"
            )
        if live.expires_at <= now:
            raise OrphanedDelegationError(
                f"ancestor {link.cred_id} expired at {live.expires_at:.0f}; "
                f"leaf {leaf.cred_id} outlived its chain"
            )
        live_scope = live.scope if live_scope is None else (live_scope & live.scope)
        live_depth += 1

    # 3. Structural signal: embedded depth must equal reachable live depth.
    if live_depth != len(embedded_chain):
        raise OrphanedDelegationError(
            f"embedded depth {len(embedded_chain)} != live depth {live_depth}; "
            f"leaf {leaf.cred_id} references a broken chain"
        )

    # 4. Scope containment must hold against the LIVE intersection.
    if not leaf.scope <= live_scope:
        raise OrphanedDelegationError(
            f"leaf scope {set(leaf.scope)} not contained in live derivation "
            f"{set(live_scope)}; attenuated grant exceeds living ancestors"
        )

    return True
