# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-credential-whose-scope-was-narrowed-by-a-downstream-vendor-s-attestation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-credential-whose-scope-was-narrowed-by-a-downstream-vendor-s-attestation-chain.warrant.json
# Markdown SHA-256:   484712f9129e3bbb15f7d9f4210bc89a9451e1bee4a67d052a26a2a037316a05
# Code AST SHA-256:   41e72d257db0236a467d9b15264096962dab7a6599f427d88281d79f2bcab0e3
# Verified Classes:   ScopeSubstitutionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ScopeSubstitutionError(RuntimeError):
    """Raised when a hop's attested scope is not a faithful refinement of the upstream grant."""
    pass


def compute_effective_scope(grant_chain):
    """
    grant_chain: list of hops, each dict with keys:
      'granted'    : set[str]  (upstream tokens this hop received)
      'attested'   : set[str]  (tokens this hop emitted)
      'manifest'   : dict[str, str] | None  (upstream_token -> downstream_token, signed)
    Returns the set of downstream tokens safe to authorize at the terminal agent.
    """
    effective = set(grant_chain[0]['granted'])

    for i, hop in enumerate(grant_chain[1:], start=1):
        attested = hop['attested']
        manifest = hop.get('manifest')

        # No signed manifest: cannot prove refinement. Fail closed on any token
        # whose qualifier may have been consumed by an unverifiable mapping.
        if manifest is None:
            for tok in attested:
                if ':' in tok and tok.count(':') >= 2:
                    # qualified token with unrecoverable upstream meaning
                    raise ScopeSubstitutionError(
                        f"hop {i}: attested token {tok!r} carries qualifiers but no "
                        f"signed vocabulary_manifest; denotation containment unprovable"
                    )
            effective &= attested
            continue

        # Manifest present: verify it is a total, injective refinement of upstream.
        for up_tok in effective:
            if up_tok not in manifest:
                raise ScopeSubstitutionError(
                    f"hop {i}: manifest is not total over upstream token {up_tok!r}"
                )
            down_tok = manifest[up_tok]
            if down_tok not in attested:
                raise ScopeSubstitutionError(
                    f"hop {i}: manifest maps {up_tok!r} -> {down_tok!r} but {down_tok!r} "
                    f"absent from attested scope"
                )

        # Reject any attested token that is not the image of an upstream token:
        # it is either a substitution or an unattested widening.
        image = {manifest[t] for t in effective}
        for tok in attested:
            if tok not in image:
                raise ScopeSubstitutionError(
                    f"hop {i}: attested token {tok!r} has no upstream preimage; "
                    f"possible vocabulary substitution (coarse-to-fine widening)"
                )

        effective = image

    return effective
