# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-delegated-aaif-credential-from-outliving-the-scope-it-was-minted-for.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-delegated-aaif-credential-from-outliving-the-scope-it-was-minted-for.warrant.json
# Markdown SHA-256:   5257a73a20e3279ef9db7a16f030225c5504c3eabd3bd4e337d0f93f0bf84937
# Code AST SHA-256:   7c5e672b0533a9877993a83b3ca8733b1ed18aafb76028c30a564969c3728df5
# Verified Classes:   DelegationScopeError, Credential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationScopeError(RuntimeError):
    """Raised when a delegated credential violates attenuation or revocation invariants."""


@dataclass(frozen=True)
class Credential:
    jti: str
    parent_jti: str | None
    chain: tuple[str, ...]          # full ancestor chain, root-first, ending at this jti
    scope: FrozenSet[str]           # structural scope atoms, e.g. {"tools:read"}
    ttl_s: int
    minted_at: float


def mint_child(parent: Credential, child_jti: str, child_scope: FrozenSet[str],
               now: float) -> Credential:
    # Invariant 1: monotone attenuation — child scope must be a subset of parent scope.
    if not child_scope.issubset(parent.scope):
        widened = child_scope - parent.scope
        raise DelegationScopeError(
            f"scope widening at mint: child {child_jti} adds {sorted(widened)} "
            f"not held by parent {parent.jti}"
        )
    # Invariant 2: chain must be flattened — parent's chain plus parent's own jti.
    expected_chain = parent.chain + (parent.jti,)
    if parent.chain and parent.chain[-1] != parent.jti:
        raise DelegationScopeError(
            f"parent {parent.jti} chain is malformed: tail {parent.chain[-1]!r}"
        )
    return Credential(
        jti=child_jti,
        parent_jti=parent.jti,
        chain=expected_chain + (child_jti,),
        scope=child_scope,
        ttl_s=min(parent.ttl_s, parent.ttl_s),  # child may not outlive parent
        minted_at=now,
    )


def authorize(cred: Credential, revoked: FrozenSet[str], now: float) -> None:
    # Revocation dominance: any jti in the flattened chain being revoked kills the leaf.
    hit = revoked.intersection(cred.chain)
    if hit:
        raise DelegationScopeError(
            f"credential {cred.jti} rejected: ancestor(s) {sorted(hit)} revoked"
        )
    if now - cred.minted_at > cred.ttl_s:
        raise DelegationScopeError(f"credential {cred.jti} expired")


def cache_key(cred: Credential) -> tuple[str, str, int]:
    # Cache key must bind the whole chain, not just the leaf jti.
    return (cred.chain[0], cred.jti, hash(frozenset(cred.scope)))
