The original question is in the thread title, and that's what this is addressing. You'll need to keep a running record of the frontmost app and the window count for all open apps -- if, after a window change, the frontmost app is still the same and the app's window count has decreased then you have closed a window.
@griffman raised the case of apps that auto-quit when you close their last window, but it turned out that was also covered because Actions (early enough in the macro) getting the front app and its window count hit the quitting app before it goes, returning its name and 0. That matches our test and we know we closed the window.
This works on a non-Spaces setup.
In the "application space" the next window under the Finder is the next Finder window, i.e. the one that had an index of 2 before you closed the window, or the Desktop if you closed the last (because Finder is a special case).
If you have interleaved windows in the UI, e.g. a Finder window, a TextEdit window behind that, another Finder window behind that, and want to get the next window in "UI order" then you are going to have to find a way to query the "display space".
Because of your use of Spaces, this could be a nightmare without some low-ish level coding -- particularly if you want to handle the "interleaved apps" case (which, I'd point out, your OS doesn't bother with...). It also looks like there will be considerable execution time, if only because of the number of KM Actions and system API calls needed (unless, again, you put all that into code).
While it's a fun exercise, first check to see if this isn't already a solved problem. Give Moom a try -- the AI search summary suggests it works within the active Space, so if you can get it to save your current window arrangement before you switch Spaces you should be able to reset the windows when you go back. No need to be constantly updating lists on every window change.
I know others here are more qualified to speak on Moom than me, and I'll be quickly corrected if wrong 