# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-credential-chain-when-per-tool-scoped-tokens-cross-an-authorization-scope-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegated-credential-chain-when-per-tool-scoped-tokens-cross-an-authorization-scope-boundary.warrant.json
# Markdown SHA-256:   6699eb3709089b1406e00c4749f191252d936d43e36c0fb5b971940f3e801456
# Code AST SHA-256:   8aff0db23caa4d33d4016031f8fd0e4945ffe9fed174aa96fe6e4c3bbb8754ed
# Verified Classes:   DelegationScopeViolation, Scope, Ancestor, LeafToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationScopeViolation(RuntimeError):
    """Raised when a leaf token's effective permission is not contained in
    every ancestor's *current* scope along its actual minting branch."""
    pass


@dataclass(frozen=True)
class Scope:
    tool: str
    resource_prefix: str
    audience: str

    def contains(self, tool: str, resource: str, audience: str) -> bool:
        return (
            self.tool == tool
            and resource.startswith(self.resource_prefix)
            and self.audience == audience
        )


@dataclass(frozen=True)
class Ancestor:
    name: str
    scope: Scope
    attenuation_epoch: int


@dataclass(frozen=True)
class LeafToken:
    tool: str
    resource: str
    audience: str
    mint_epoch: int
    branch_id: str


def verify_at_boundary(
    leaf: LeafToken,
    ancestors_on_branch: list[Ancestor],
    current_epoch: int,
) -> None:
    if not ancestors_on_branch:
        raise DelegationScopeViolation("empty delegation chain; no root to anchor trust")

    # Temporal attenuation: if any ancestor attenuated after the leaf was minted,
    # the cached validity is stale and containment must be re-checked (it is,
    # below, unconditionally — but flag the epoch skew explicitly).
    max_attenuation = max(a.attenuation_epoch for a in ancestors_on_branch)
    if max_attenuation > leaf.mint_epoch:
        # Not an error by itself; forces the containment walk to be authoritative.
        pass

    for anc in ancestors_on_branch:
        if not anc.scope.contains(leaf.tool, leaf.resource, leaf.audience):
            raise DelegationScopeViolation(
                f"leaf token for tool={leaf.tool!r} resource={leaf.resource!r} "
                f"audience={leaf.audience!r} on branch={leaf.branch_id!r} "
                f"is not contained in ancestor {anc.name!r} current scope "
                f"({anc.scope.tool!r}, {anc.scope.resource_prefix!r}, "
                f"{anc.scope.audience!r}); attenuation_epoch={anc.attenuation_epoch} "
                f"vs mint_epoch={leaf.mint_epoch}, now={current_epoch}"
            )
