Why did he command him to build a house in Yerushalayim?
Radak: Shim'i's house was in Bachurim.
What is considered "going to and fro, and leaving"?
Malbim: It is uprooting his primary residence from Yerushalayim. However, the next verse forbids more than this.
Why did he forbid him to leave?
Rashi: He should be available for Shlomo to find a sin for which he is Chayav Misah.
He knew that Shim'i would transgress, and be Chayav Misah. An Isur without any hope to permit it, is too hard for a person. 1 This is why everything that the Torah forbade, in some case it permitted it (Chulin 109b). 2 All know that one who disobeys the king is Chayav Misah. Shlomo added "Mos Tamus?" to further increase the pressure on Shim'i to transgress! (Heard from Rav A. Lopiansky.)
If there was no Kohen Gadol at the time that a Shogeg murderer was sentenced, he may never leave the Ir Miklat (Makos 2:7)! Perhaps there is easier, for even without the Isur, the murderer fears to leave, lest Go'el ha'Dam kill him. (PF)
Chulin 109b: E.g. liver is a Heter for blood, Dam Tahor is a Heter for Dam Nidah, Chelev Chayah is a Heter for Chelev, Yibum is a Heter for Eshes Ach, Eshes Yefas To'ar is a Heter for a Nochris, udder is a Heter for meat and milk. Rav Elyashiv (109b) - this is like the Heter of Eshes Yefas To'ar; the Torah permits due to the Yetzer ha'Ra, lest it be able to say that the Torah forbids more than a person can fulfill.