Refactor a legacy JavaScript file with Cursor without breaking the thing
A 900-line file nobody understands, tests optional. The safe path: characterize first, refactor second, and let Cursor do the mechanical surgery while you hold the behavior.
Every legacy codebase has The File — the one everyone avoids, where a rename feels like defusing a bomb. Refactoring it with Cursor works, but the order of operations is everything. Doing it wrong produces confident breakage; doing it right takes an afternoon and produces a file the team stops avoiding.
Step zero, before any AI: characterize the current behavior. If tests exist, run them and note coverage. If they don't, write a few — not unit-test-perfection, just 'given this input, the file currently produces this output' checks at the boundaries. This is the safety net that makes every later step reversible. Cursor can write these characterization tests for you; paste the file and ask for tests that document what the code does, bugs included.
Then refactor in slices, never whole-file. Give Cursor one concern at a time — 'extract this 200-line function into named helpers, keep behavior identical' — with the characterization tests run after each slice. The prompt phrase 'keep behavior identical' matters: it stops the model from helpfully 'fixing' quirks that some caller somewhere depends on. Quirk preservation is the law of legacy work.
The two Cursor features that earn their keep here: inline chat on a selection for the surgical moves ('what does this callback close over?'), and composer for the file-wide renames where every reference must move together. Review every diff like a suspicious senior engineer — the model's most common legacy sin is confidently dropping a subtle guard clause because it 'looked redundant.' The tests you wrote in step zero are what catch that.
The finish line is regression green plus a diff you can explain line by line. If you can't explain a hunk, don't ship it — ask Cursor to justify it against the original. Done right, the file shrinks by a third, gains names the team recognizes, and stops being The File. The confidence comes from the tests, not the AI; the AI just does the moving.