Custom map_meta_cap filter does not return [‘do_not_allow’]

I don’t know how to make it restrict access correctly.

Try this, which uses get_post_ancestors():

function staby_cap_filter( $allcaps, $cap, $args, $user ) {
    // Get the current user's roles.
    $roles = (array) $user->roles;

    /* Do nothing if:
       1. The above roles doesn't include 'test', or
       2. edit_post is not the capability being checked, or
       3. The post ID was not specified, or
       4. pages_id is empty.
    */
    if ( ! in_array( 'test', $roles ) ||
        ( 'edit_post' !== $args[0] ) || empty( $args[2] ) ||
        empty( $allcaps['pages_id'] )
    ) {
        return $allcaps;
    }

    // Get the first ancestor of the current post that's being checked.
    $parent_ids   = get_post_ancestors( $args[2] );
    $first_parent = array_pop( $parent_ids );

    $allowed_ids = array_intersect(
        array( $first_parent, $args[2] ),
        $allcaps['pages_id']
    );

    // Disable the capability if the post ID is not in the allowed list.
    if ( empty( $allowed_ids ) ) {
        $allcaps[ $cap[0] ] = false;
    }

    return $allcaps;
}
add_filter( 'user_has_cap', 'staby_cap_filter', 10, 4 );

Additionally, I suggest you to use the switch_theme action instead of load-themes.php, to add the custom role, or create a plugin and then do something like this.