# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-oauth-scope-as-revoked-when-a-verifiable-agent-credential-vac-chain-re-validates-but-the-scope-s.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-oauth-scope-as-revoked-when-a-verifiable-agent-credential-vac-chain-re-validates-but-the-scope-s.warrant.json
# Markdown SHA-256:   5807cb9d9286f0f2757dac1c060f79ab7952f17599b29fd5b054411a6f16bbe1
# Code AST SHA-256:   3c555f67c3fa3bba2a8bc24bb0ef0553b515a551cf2949bc90c9dbc2402a42e4
# Verified Classes:   DelegationDepthCollapseError, Credential, Token
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class DelegationDepthCollapseError(RuntimeError):
    """Raised when a token's act-claim depth exceeds the live VAC chain depth,
    indicating a revoked or expired intermediate was silently dropped."""
    pass


@dataclass
class Credential:
    subject: str
    delegation_depth: int
    scope_attenuation: frozenset[str]
    valid: bool


@dataclass
class Token:
    active: bool
    scope: frozenset[str]
    act_chain: list[str]  # ordered actor identifiers, oldest first


def verify_delegated_scope(token: Token, chain: list[Credential]) -> frozenset[str]:
    if not token.active:
        raise DelegationDepthCollapseError("token inactive; fail closed")

    live = [c for c in chain if c.valid]
    warranted = frozenset.intersection(*(c.scope_attenuation for c in live)) if live else frozenset()

    # Depth check: token's act chain must not outrun the live credential chain.
    if len(token.act_chain) > len(live):
        missing = set(token.act_chain) - {c.subject for c in live}
        raise DelegationDepthCollapseError(
            f"depth collapse: act_chain={token.act_chain} live_chain="
            f"{[c.subject for c in live]} missing_intermediates={sorted(missing)}"
        )

    if not token.scope <= warranted:
        raise DelegationDepthCollapseError(
            f"scope escalation: token={sorted(token.scope)} warranted={sorted(warranted)}"
        )

    return token.scope
