In order to solve the harmonic oscillator, $$H=\frac{p^2}{2}+\frac{q^2}{2},$$ by using Hamilton-Jacobi theory we have to find a complete solution for the H-J equation, $$\frac{1}{2}\left(\frac{\partial S}{\partial q}\right)^2+\frac{q^2}{2}+\frac{\partial S}{\partial t}=0.$$ We seek for a solution $$S=W(q)+T(t),$$ which leads to the following ODE, $$\frac{dT}{dt}=-\alpha t,$$ $$\frac{dW}{dq}=\sqrt{2\alpha-q^2}.\tag 1$$
It is easy to solve those equations and then write $S(q,\alpha,t)$, from which we can get $$\beta=\frac{\partial S}{\partial \alpha}\Rightarrow q=\sqrt{2\alpha}\sin (t+\beta).$$
Now it comes my issue. When solving for momenta, $$p=\frac{\partial S}{\partial q}=\frac{dW}{dq}=\sqrt{2\alpha-q^2},\tag 2$$ and using the solution found for $q$ we obtain $$p=\sqrt{2\alpha}\sqrt{\cos^2(t+\beta)}=\sqrt{2\alpha}|\cos(t+\beta)|.$$
We know that the solution should be $p=\sqrt{2\alpha}\cos(t+\beta)$. I realize that even Eq. (2) is allowing only for positive momentum. So how to obtain the correct solution without forcing it by knowing the correct answer a priori?
Note that in obtaining (1) we actually should write $$\frac{dW}{dq}=\pm\sqrt{2\alpha-q^2},$$ but yet there is an ambiguity with the plus or minus sign.