The google term you want is “structured transaction.” Any sequence of legal transactions clearly designed to do an illegal thing when done directly is to be treated the same as if it had been done as a single step.
The point of waiting e.g. 30 days is EXACTLY that it exposes you to gains/losses and you can rightly say the two actions are no longer connected.