Cursor · Coding

Refactoring

Keep tests fixed while Agent works in small steps, try risky changes in a worktree, and split big changes into reviewable pull requests.

Refactoring with Cursor

Separate structure from behavior

The danger with a refactor is that a behavior change slips in unnoticed among many moved lines. Fixed tests catch that. If you find a bug along the way, note it and fix it separately, so a reviewer can see which change did what.

Plan for the size of the diff

Agents can touch 40 files as easily as four, so think about review before you start. Small commits help most. For a risky attempt, a worktree keeps your checkout clean. If you already have one huge diff, the cleanup can come afterward with reworked commits or /split-to-prs.

Frequently asked
How do I refactor safely in Cursor?

Commit your work, mention the code and its tests, say the tests must keep passing unchanged, and ask for one step at a time. Read each diff and commit it before asking for the next.

What does /worktree do in Cursor?

It runs the rest of the chat in a separate Git checkout, so edits and test runs don't disturb your current branch. Use /apply-worktree to bring the changes back, or /delete-worktree to discard them.

What if my code has no tests?

Ask Agent to write characterization tests that record what the code does today, and commit those before you refactor. Those tests then act as your safety net.