# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-scope-token-whose-act-chain-exceeds-the-verifier-s-own-trust-horizon-even-when-every-signature-v.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-scope-token-whose-act-chain-exceeds-the-verifier-s-own-trust-horizon-even-when-every-signature-v.warrant.json
# Markdown SHA-256:   b064ce4ba5ed69555ea137ef2f32bc3f5b723abd6965ddf31ac508f094880ee9
# Code AST SHA-256:   ae0caee5bf095429d1c28b88103c2d5caff87178089a9d1e2aa030d4bc89e6fd
# Verified Classes:   ScopeChainViolation, ActLink, VerifierPolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeChainViolation(RuntimeError):
    """Raised when a delegated scope token is signature-valid but not authorization-valid."""
    pass


@dataclass
class ActLink:
    issuer: str
    scope: frozenset
    max_delegation_depth: Optional[int] = None
    parent: Optional["ActLink"] = None


@dataclass
class VerifierPolicy:
    trust_anchors: frozenset
    max_traversal_hops: int = 8


def verify_delegated_scope(
    leaf: ActLink,
    policy: VerifierPolicy,
    *,
    signature_valid: bool = True,
) -> None:
    # Cryptographic predicate (assumed pre-checked by caller, asserted here).
    if not signature_valid:
        raise ScopeChainViolation("signature invalid at leaf")

    # Walk act chain to root, enforcing attenuation and collecting depth bounds.
    chain = []
    node: Optional[ActLink] = leaf
    hops = 0
    while node is not None:
        if hops > policy.max_traversal_hops:
            raise ScopeChainViolation(
                f"act chain exceeds traversal budget {policy.max_traversal_hops}"
            )
        chain.append(node)
        node = node.parent
        hops += 1

    root = chain[-1]
    depth = len(chain) - 1  # hops from root to leaf

    # Anchoring predicate: root must be in local trust anchors.
    if root.issuer not in policy.trust_anchors:
        raise ScopeChainViolation(
            f"chain root {root.issuer!r} not in trust anchors; "
            f"signature-valid but off-anchor delegation refused"
        )

    # Depth predicate: minimum declared bound along the chain governs.
    declared_bounds = [
        n.max_delegation_depth
        for n in chain
        if n.max_delegation_depth is not None
    ]
    if declared_bounds:
        effective_bound = min(declared_bounds)
        if depth > effective_bound:
            raise ScopeChainViolation(
                f"delegation depth {depth} exceeds declared bound {effective_bound}"
            )

    # Attenuation predicate: each child scope must be a subset of its parent.
    for child, parent in zip(chain, chain[1:]):
        if not child.scope.issubset(parent.scope):
            raise ScopeChainViolation(
                f"scope widening at {child.issuer!r}: "
                f"{set(child.scope) - set(parent.scope)} not granted by parent"
            )
