# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-capability-token-has-silently-widened-across-a-cross-domain-attestation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-capability-token-has-silently-widened-across-a-cross-domain-attestation-boundary.warrant.json
# Markdown SHA-256:   b3ca5e701108ef6874f8f189776475b59393f7483cb3e62beca43c32a8c5ef25
# Code AST SHA-256:   48c4097ffc121f8d549b7e06dff58aa1fa89025676403a870ad5f78c056297b9
# Verified Classes:   ScopeWideningError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScopeWideningError(RuntimeError):
    """Raised when post-chain effective scope exceeds issuer-declared scope."""


def derive_effective_scope(token: dict, hop_can_parse_chain: bool) -> frozenset[str]:
    declared = frozenset(token.get("scope", []))
    chain = token.get("delegation_chain", [])

    if chain and not hop_can_parse_chain:
        # Fail-closed: unparseable restriction collapses scope to empty.
        return frozenset()

    effective = set(declared)
    for link in chain:
        restriction = frozenset(link.get("narrowed_to", []))
        effective &= restriction  # intersect, never union

    result = frozenset(effective)

    if not result.issubset(declared):
        # Arithmetically impossible under intersection; signals a widening bug.
        raise ScopeWideningError(
            f"effective scope {sorted(result)} exceeds declared {sorted(declared)}"
        )
    return result


def admit_cross_domain(token: dict, hop_can_parse_chain: bool) -> frozenset[str]:
    scope = derive_effective_scope(token, hop_can_parse_chain)
    if not scope:
        raise ScopeWideningError("no admissible scope after chain evaluation; reject token")
    return scope
