When AI agents mix imperative control flow with stochastic LLM calls, you get unmaintainable spaghetti. Here's how to refactor them into reliable state machines.