Using AI to write a brand new React app is easy. Using AI to refactor 10-year-old spaghetti code without breaking production is the true test of a Senior AI Engineer.
1The Analysis Phase
Do not let the AI touch the keyboard yet. Legacy code contains 'Chesterton's Fences'—blocks of weird logic that look like mistakes but were actually written to fix critical edge cases years ago. If you tell the AI to just 'clean it up', it will delete those fences. You must first command the AI to act as a forensic analyst. Ask it to read the code and document every input, output, API call, and weird boundary condition.
2The Testing Phase
AI is probabilistic text generation. You cannot trust it. To refactor safely, you need a deterministic boundary. Use the AI's forensic analysis to write a suite of Unit Tests. Do not test the new code; test the OLD code. Ensure the tests pass against the ugly legacy system. This locks in the exact behavior of the old system. The ugly code is now mathematically protected.
3The Surgical Translation Phase
Now you execute the refactor, but only in atomic chunks. Highlight one small block and prompt: 'Refactor this to modern syntax without changing the logic'. Accept the diff. Immediately run the tests. If they pass, the AI succeeded. If they fail, the AI deleted a Chesterton's Fence. You hit Ctrl+Z (Undo), paste the test error back into the AI, and demand a correction.
