S&P, Nasdaq edge to record closes, energy stocks buoyant