# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-aaif-scope-when-the-signing-principal-is-itself-a-short-lived-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-aaif-scope-when-the-signing-principal-is-itself-a-short-lived-agent.warrant.json
# Markdown SHA-256:   125f983658b21bca84760f5713b30e3137e98cbb28c05d7be34fee197999d2d1
# Code AST SHA-256:   24beb2d2bad7c0f8776f7e49b5bd57bc733932b6a3ff7157df06abe7d1ee1c65
# Verified Classes:   DelegationLivenessError, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class DelegationLivenessError(RuntimeError):
    """Raised when a delegated AAIF scope is structurally valid but its signer chain is dead."""
    pass


@dataclass
class Credential:
    agent_id: str
    scope: frozenset
    exp: float  # epoch seconds
    signer_not_after: float = field(default=None)


def mint_delegated_scope(
    signer: Credential, child_id: str, child_scope: frozenset, desired_ttl: float
) -> Credential:
    now = time.time()
    if signer.exp <= now:
        raise DelegationLivenessError(
            f"signer {signer.agent_id} already expired; cannot delegate"
        )
    # Clamp: a child may never outlive its signer.
    clamped_exp = min(now + desired_ttl, signer.exp)
    if not child_scope <= signer.scope:
        raise DelegationLivenessError(
            f"scope escalation: {child_scope} not subset of {signer.scope}"
        )
    return Credential(
        agent_id=child_id,
        scope=child_scope,
        exp=clamped_exp,
        signer_not_after=signer.exp,
    )


def verify_chain_liveness(chain: list, now: float) -> None:
    """chain[0] is the presented leaf; chain[-1] is the root."""
    leaf = chain[0]
    if now >= leaf.exp:
        raise DelegationLivenessError(f"leaf {leaf.agent_id} expired")
    # The invariant: every signer in the chain must still be live at use time.
    for signer in chain[1:]:
        if now >= signer.exp:
            raise DelegationLivenessError(
                f"delegation chain dead: signer {signer.agent_id} expired at "
                f"{signer.exp:.0f}, scope presented at {now:.0f}"
            )
    # Defense in depth: leaf must not claim to outlive its immediate signer.
    if leaf.signer_not_after is not None and leaf.exp > leaf.signer_not_after + 1e-6:
        raise DelegationLivenessError(
            f"leaf {leaf.agent_id} exp {leaf.exp:.0f} exceeds signer_not_after "
            f"{leaf.signer_not_after:.0f}"
        )
