# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-exceed-its-delegated-scope-when-aaif-token-exchange-re-derives-authority-from-a-stale-credential-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-exceed-its-delegated-scope-when-aaif-token-exchange-re-derives-authority-from-a-stale-credential-chain.warrant.json
# Markdown SHA-256:   9e0760d5d4b5b613d84a6c544da05812de9df69ea7c447ef592253aeb38b62e4
# Code AST SHA-256:   57039fb378a08a67dfed511704d491ed07237941c9961d4101b670b23b92b57b
# Verified Classes:   ChainHashMismatchError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ChainHashMismatchError(RuntimeError):
    """Raised when a presented delegated-scope token's parent_chain_hash
    does not match the snapshot used to mint it. Fail closed; never fall
    back to live-registry re-derivation."""
    pass


def resolve_effective_scope(token, chain_snapshot_store):
    """
    token: object with .scope (frozenset), .parent_chain_hash (str),
           .aud (str), .exp (float)
    chain_snapshot_store: maps parent_chain_hash -> snapshot object with
           .chain_scopes (frozenset) and .aud (str)

    Returns the effective scope as token.scope ∩ snapshot.chain_scopes.
    Raises ChainHashMismatchError on any hash miss or audience mismatch.
    """
    snapshot = chain_snapshot_store.get(token.parent_chain_hash)
    if snapshot is None:
        # The snapshot the token was minted against is gone or was never
        # pinned. Re-deriving from the live registry here is exactly the
        # broadening bug. Refuse.
        raise ChainHashMismatchError(
            f"no pinned chain snapshot for parent_chain_hash="
            f"{token.parent_chain_hash!r}; refusing live re-derivation"
        )

    if snapshot.aud != token.aud:
        raise ChainHashMismatchError(
            f"audience drift: token.aud={token.aud!r} "
            f"snapshot.aud={snapshot.aud!r}"
        )

    # Enforce monotonic narrowing against the *snapshot*, not the live chain.
    effective = frozenset(token.scope) & frozenset(snapshot.chain_scopes)
    if not effective.issubset(frozenset(token.scope)):
        # Defensive: intersection cannot exceed token.scope, but assert the
        # invariant explicitly so a future refactor cannot widen it.
        raise ChainHashMismatchError(
            "effective scope exceeds token scope; narrowing invariant broken"
        )
    return effective
