# 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-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-agent-credential-has-silently-outlived-its-authorization-scope.warrant.json
# Markdown SHA-256:   1b0571827dbe96e2b508a28d4a2bd2c8e9d9b86c676325e072dbde31185149c1
# Code AST SHA-256:   c488cfbf6e6e2d0603b64651144d61386f1219653302821aaaabcb89fe8bcc01
# Verified Classes:   OrphanedDelegationError, DelegatedCredential, Principal
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping, Set


class OrphanedDelegationError(RuntimeError):
    """Raised when a delegated credential's chain root no longer holds the asserted capability."""
    pass


@dataclass(frozen=True)
class DelegatedCredential:
    credential_id: str
    delegator_id: str          # principal or parent credential this was minted from
    parent_credential_id: str | None
    asserted_scope: Set[str]
    expires_at: float


@dataclass
class Principal:
    principal_id: str
    current_capabilities: Set[str] = field(default_factory=set)


def evaluate_delegation(
    leaf: DelegatedCredential,
    credentials: Mapping[str, DelegatedCredential],
    principals: Mapping[str, Principal],
    now: float,
    revoked_credential_ids: Set[str],
) -> Set[str]:
    """
    Live chain re-evaluation. Returns the effective scope, which is the
    intersection of the leaf's asserted scope with every ancestor's *current*
    capability set. Raises OrphanedDelegationError if any hop is unsatisfiable.
    """
    if leaf.expires_at <= now:
        raise OrphanedDelegationError(
            f"credential {leaf.credential_id} expired at {leaf.expires_at}, now {now}"
        )
    if leaf.credential_id in revoked_credential_ids:
        raise OrphanedDelegationError(
            f"credential {leaf.credential_id} is revoked"
        )

    effective = set(leaf.asserted_scope)
    cursor: DelegatedCredential | None = leaf

    while cursor is not None:
        if cursor.credential_id in revoked_credential_ids:
            raise OrphanedDelegationError(
                f"ancestor credential {cursor.credential_id} is revoked"
            )

        if cursor.parent_credential_id is None:
            # Root hop: delegator_id names a principal, not a credential.
            root = principals.get(cursor.delegator_id)
            if root is None:
                raise OrphanedDelegationError(
                    f"root principal {cursor.delegator_id} no longer exists"
                )
            missing = effective - root.current_capabilities
            if missing:
                # The structural signal of silent over-privilege:
                # chain is cryptographically sound, but the root's authority
                # has been narrowed since mint time.
                raise OrphanedDelegationError(
                    f"root principal {root.principal_id} no longer holds "
                    f"{sorted(missing)}; delegated credential "
                    f"{leaf.credential_id} is orphaned"
                )
            effective &= root.current_capabilities
            break

        parent = credentials.get(cursor.parent_credential_id)
        if parent is None:
            raise OrphanedDelegationError(
                f"parent credential {cursor.parent_credential_id} unresolvable"
            )
        # Each hop may not exceed its parent's *asserted* scope at use time;
        # the root check above enforces the *current* authority.
        over = effective - parent.asserted_scope
        if over:
            raise OrphanedDelegationError(
                f"credential {cursor.credential_id} exceeds parent "
                f"{parent.credential_id} in {sorted(over)}"
            )
        effective &= parent.asserted_scope
        cursor = parent

    return effective


def authorize_action(
    leaf: DelegatedCredential,
    required: Set[str],
    credentials: Mapping[str, DelegatedCredential],
    principals: Mapping[str, Principal],
    now: float,
    revoked_credential_ids: Set[str],
) -> None:
    effective = evaluate_delegation(
        leaf, credentials, principals, now, revoked_credential_ids
    )
    missing = required - effective
    if missing:
        raise OrphanedDelegationError(
            f"action requires {sorted(missing)}; effective delegated scope is "
            f"{sorted(effective)}"
        )
