# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-a-delegated-capability-token-after-a-credential-chain-re-anchor.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-a-delegated-capability-token-after-a-credential-chain-re-anchor.warrant.json
# Markdown SHA-256:   4b8a80390040124b694a1f198e78c6f61e95d94f8fb319112c0bce8afd30eb31
# Code AST SHA-256:   9f25b85c75cd6694ecc4f70af1f8c9b70d9c1d66e79e5c68e84eca5d13a3e537
# Verified Classes:   DelegationAuthorityDrift, Credential, DelegatedToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationAuthorityDrift(RuntimeError):
    """Raised when a delegated token's claimed capabilities exceed the
    current intersected authority of its ancestor chain."""


@dataclass
class Credential:
    cred_id: str
    subject: str
    capabilities: frozenset
    version: int


@dataclass
class DelegatedToken:
    token_id: str
    parent_id: str
    capabilities: frozenset


def resolve_current(cred_id: str, active: dict, aliases: dict) -> Optional[Credential]:
    if cred_id in active:
        return active[cred_id]
    successor = aliases.get(cred_id)
    if successor is None:
        return None
    return active.get(successor)


def verify_delegated_authority(
    token: DelegatedToken,
    active_credentials: dict,
    alias_table: dict,
    ancestor_tokens: dict,
) -> frozenset:
    """Re-derive effective authority by intersecting the token's claimed
    capabilities with the *current* capabilities of every ancestor link.

    Returns the effective capability set. Raises DelegationAuthorityDrift
    if the claimed set exceeds the derived set (drift) or the chain is
    orphaned.
    """
    effective = frozenset(token.capabilities)
    cursor_id = token.parent_id
    seen = set()

    while cursor_id is not None:
        if cursor_id in seen:
            raise DelegationAuthorityDrift(
                f"cycle detected in delegation chain at {cursor_id}"
            )
        seen.add(cursor_id)

        if cursor_id in ancestor_tokens:
            link = ancestor_tokens[cursor_id]
            effective = effective & link.capabilities
            cursor_id = link.parent_id
            continue

        resolved = resolve_current(cursor_id, active_credentials, alias_table)
        if resolved is None:
            raise DelegationAuthorityDrift(
                f"ORPHANED_DELEGATION: ancestor {cursor_id} has no active "
                f"credential and no resolvable successor"
            )

        # The critical step: intersect with the *current* capability set,
        # not the one embedded at issuance.
        narrowed = effective & resolved.capabilities
        if narrowed != effective:
            # Strict subset: authority has drifted beneath a live token.
            # Caller must re-scope to `narrowed`, not honor `effective`.
            raise DelegationAuthorityDrift(
                f"authority drift on {token.token_id}: ancestor "
                f"{cursor_id} (v{resolved.version}) narrowed from "
                f"{sorted(effective)} to {sorted(narrowed)}"
            )
        effective = narrowed
        cursor_id = None  # root reached

    return effective
