Take proper care with the order of operations when replacing tasks.

This logic is fragile and should probably be removed entirely.

Testing Done:
Manually verified that this fixes foursquare.web's issues with replacing all tasks in a goal.

ci running.

Reviewed at https://rbcommons.com/s/twitter/r/1221/
Sync of https://github.com/pantsbuild/pants/commit/1ea10df644eaf0d4b62e9c43e7890d2ded0614cf