Retention of habitable atmospheres in planetary systems