Macbook external display rearranges homescreen
Because it's a laptop with its own screen, as soon as you unplug your Primary screen, the internal once again becomes Primary &amp; all windows will migrate to it.
Re-connecting the other display it will then once again reassign it as Primary - but the 'damage' has already been done &amp; it will not be able to correctly place the windows back where they were.
You may benefit from using a third party window manager. There are a few listed in the answers to this question - Do any window managers allow me to snap windows to the sides of the display?