Animation flipping (the wrong way) when rotating
Your issue comes from the quaternion rotation of the hip bones flipping in the W value, as you guessed. The fix here is to negate the W value on frame 40 so that the hip doesn't have to do a full rotation. Setting the Rotation keyframe to [-1, 0, 0, 0] on frame 40 fixes the problem because the W value on frame 20 is -0.961.