It is a legitimately a difficult problem, perhaps among the most difficult problems in governing. How do you create and maintain a government for centuries which keeps its primary goal of serving the people. The US founders thought about this very much drawing on philosophers modern and ancient and they did a pretty good job setting up checks and balances, or more bluntly, competition.
How do you keep the CIA and its like in check? Create opposing government entities specifically immune to its actions and allow them to compete for prestige. This is why we have three branches of government, two houses of congress with different election strategies, etc. Set up separation of powers, imbue the population to value and cherish that separation, and honestly, hope for the best.