The Panama Canal treaty of 1977 contains a "protect and defend" section.
And that allows the US to maintain an armed force in Panama.
Article IV Paragraph 5.
It didn't take 22 years to train them. It was an intentionally slow transition which included not just training but adjustments to infrastructure. Politically it help sell the plan to both sides while maintaining a significant level of control which was in our strategic interest.