# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-a-delegated-capability-token-and-silently-widens-its-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-a-delegated-capability-token-and-silently-widens-its-scope.warrant.json
# Markdown SHA-256:   ad3a4196e09a75f69434494cf4fbadc17ad45208c6dd31d87d6b562bce4b9322
# Code AST SHA-256:   757f2cfe69253b3458480a9719cb8affdd67f30551a899fc0a78ebd5491bc300
# Verified Classes:   ScopeEscalationError, Scope, Token
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ScopeEscalationError(RuntimeError):
    """Raised when a delegated token's scope is not a subset of its ancestors'."""


@dataclass(frozen=True)
class Scope:
    tools: frozenset[str]
    paths: tuple[str, ...]

    def is_subset_of(self, other: "Scope") -> bool:
        if not self.tools.issubset(other.tools):
            return False
        return all(any(p.startswith(q) for q in other.paths) for p in self.paths)


@dataclass(frozen=True)
class Token:
    token_id: str
    issuer: str
    scope: Scope
    parent_id: Optional[str]
    parent_claims: Optional[Scope]
    signature_valid: bool


def verify_chain(leaf: Token, chain: dict[str, Token]) -> Scope:
    """Fold ancestor scopes and reject if the leaf widens beyond the intersection."""
    if not leaf.signature_valid:
        raise ScopeEscalationError(f"token {leaf.token_id}: invalid signature")

    effective = leaf.scope
    cursor = leaf
    seen: set[str] = set()

    while cursor.parent_id is not None:
        if cursor.parent_id in seen:
            raise ScopeEscalationError(
                f"token {leaf.token_id}: cycle at {cursor.parent_id}"
            )
        seen.add(cursor.parent_id)

        parent = chain.get(cursor.parent_id)
        if parent is None:
            raise ScopeEscalationError(
                f"token {leaf.token_id}: missing ancestor {cursor.parent_id}"
            )
        if cursor.parent_claims is not None and cursor.parent_claims != parent.scope:
            raise ScopeEscalationError(
                f"token {cursor.token_id}: parent_claims diverge from ancestor record"
            )
        if not effective.is_subset_of(parent.scope):
            raise ScopeEscalationError(
                f"token {leaf.token_id}: scope {effective} not subset of "
                f"ancestor {parent.token_id} scope {parent.scope}"
            )
        effective = Scope(
            tools=effective.tools & parent.scope.tools,
            paths=tuple(p for p in effective.paths
                        if any(p.startswith(q) for q in parent.scope.paths)),
        )
        cursor = parent

    return effective


def authorize_tool_call(leaf: Token, chain: dict[str, Token],
                        tool: str, path: str) -> None:
    effective = verify_chain(leaf, chain)
    if tool not in effective.tools:
        raise ScopeEscalationError(
            f"tool {tool!r} not in effective scope {sorted(effective.tools)}"
        )
    if not any(path.startswith(prefix) for prefix in effective.paths):
        raise ScopeEscalationError(
            f"path {path!r} outside effective scope {effective.paths}"
        )
