# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-its-delegated-scope-when-an-aaif-capability-attestation-is-silently-widened-by-a-transitive-re-delegation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-its-delegated-scope-when-an-aaif-capability-attestation-is-silently-widened-by-a-transitive-re-delegation-hop.warrant.json
# Markdown SHA-256:   7ee8de907914fcb9d66bbec5eb2a04d6a7a6765a08e7243227f220535a0546f1
# Code AST SHA-256:   cb8b8b8d80620b55fef7ad0d167a4ba7144088353207a88b4cffb7195279841a
# Verified Classes:   ScopeWideningError, UncanonicalizableHopError, Hop, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

class ScopeWideningError(RuntimeError):
    """Raised when a re-delegation hop widens scope under canonical expansion."""
    pass

class UncanonicalizableHopError(RuntimeError):
    """Raised when a hop's scope cannot be expressed in the authority's lattice."""
    pass

@dataclass(frozen=True)
class Hop:
    delegator: str
    # raw, dialect-specific scope as declared by this hop
    raw_resources: tuple[str, ...]
    raw_verbs: tuple[str, ...]
    dialect: str  # "glob-single", "glob-recursive", "enumerated", ...

@dataclass
class Credential:
    root_resources: frozenset[str]
    root_verbs: frozenset[str]
    hops: list[Hop] = field(default_factory=list)

def _expand(resources: Iterable[str], dialect: str, authority_dialect: str) -> frozenset[str]:
    # Canonicalize into the AUTHORITY's dialect. Any hop using a dialect we
    # cannot faithfully translate is a widening risk -> fail closed.
    if dialect not in ("glob-single", "glob-recursive", "enumerated"):
        raise UncanonicalizableHopError(f"unknown dialect {dialect!r}")
    out = set()
    for r in resources:
        if r.endswith("/*"):
            base = r[:-2]
            if dialect == "glob-recursive" and authority_dialect != "glob-recursive":
                # recursive expansion under a single-segment authority widens
                raise ScopeWideningError(
                    f"hop expanded {r!r} recursively; authority dialect "
                    f"{authority_dialect!r} forbids cross-segment match"
                )
            out.add(base + "/*")
        else:
            out.add(r)
    return frozenset(out)

def rederive_effective_scope(cred: Credential, authority_dialect: str) -> tuple[frozenset[str], frozenset[str]]:
    """Re-derive effective scope from root + ordered hop deltas, in the
    authority's canonical lattice. Never trust declared scope on multi-hop."""
    eff_res = cred.root_resources
    eff_verbs = cred.root_verbs
    for i, hop in enumerate(cred.hops):
        hop_res = _expand(hop.raw_resources, hop.dialect, authority_dialect)
        hop_verbs = frozenset(hop.raw_verbs)
        # narrowing must hold in BOTH dimensions; type-stable set compare.
        if not hop_res.issubset(eff_res):
            raise ScopeWideningError(
                f"hop {i} ({hop.delegator}) resource scope {sorted(hop_res)} "
                f"not subset of upstream {sorted(eff_res)}"
            )
        if not hop_verbs.issubset(eff_verbs):
            raise ScopeWideningError(
                f"hop {i} ({hop.delegator}) verb scope {sorted(hop_verbs)} "
                f"not subset of upstream {sorted(eff_verbs)}"
            )
        eff_res, eff_verbs = hop_res, hop_verbs
    return eff_res, eff_verbs

def accept_credential(cred: Credential, authority_dialect: str, declared_scope: tuple[frozenset[str], frozenset[str]]) -> tuple[frozenset[str], frozenset[str]]:
    if len(cred.hops) <= 1:
        # single hop: no transitive closure to mis-expand
        return declared_scope
    effective = rederive_effective_scope(cred, authority_dialect)
    if effective != declared_scope:
        # declared scope is strictly wider than what the chain can justify
        raise ScopeWideningError(
            f"declared scope {sorted(declared_scope[0])} exceeds re-derived "
            f"effective scope {sorted(effective[0])}; refusing to trust chain"
        )
    return effective
