Refactoring
Keep tests fixed while Agent works in small steps, try risky changes in a worktree, and split big changes into reviewable pull requests.
-
How Do You Refactor Safely in Cursor? @-mention the code and its tests, say the tests must pass without being modified, and ask for one structural step at a time. Level 2: Context
- 1Commit, tests green
- 2One structural step
- 3Tests still green
- 4Commit
Repeat until the refactor is done -
How Do You Turn a Big Agent Change Into PRs People Can Review? Build freely, and then clean up. Level 3: Workflows
- 1Reset to main
- 2Read all the changes
- 3Plan a logical sequence
- 4Create clean commits
- 5Diff against the original
-
How Do You Try a Risky Refactor Without Touching Your Checkout? Start the task with /worktree in the Agent input. Level 3: Workflows
- 1/worktree task
- 2Agent works in a copy
- 3Review the result
- 4/apply-worktree or /delete-worktree
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.
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.