← Refactoring and maintenance guides

How to refactor with agents safely

How-To Refactoring and maintenance Intermediate 1151001HOWTO-1151001

HOWTO-1151001Refactoring and maintenanceIntermediate

This guide shows you how to refactor with agents safely in a spec-driven development workflow.

Agents are useful at mechanical refactors, but they can also make confident structural changes that quietly alter behavior, widen dependencies, or touch files outside the intended boundary. SpecDD gives the agent and the reviewer a shared contract for what must be preserved.

The safest pattern is to keep the agent focused: one target, one refactor goal, a reviewed plan, small steps, and checks that prove behavior stayed the same.

Short answer

Ask the agent to refactor a named subject, not a broad area. Review its plan before edits when the refactor is risky. Require preservation of Must, Must not, Forbids, scenarios, public contracts, and write authority. Keep prompts small, run checks, and reject changes that move behavior or ownership without a reviewed spec update.

When to use this guide

Use this guide when:

Steps

1. Name the refactor target

Good:

Refactor the Itinerary validation internals.

Weak:

Clean up the trips area.

The first prompt names a human subject. The second invites broad edits.

2. Ask for a preservation plan

For anything beyond a tiny cleanup, ask for the plan first:

Plan the Itinerary validation refactor.

Review whether the plan preserves:

If the plan includes behavior changes, split the work.

3. Limit write scope

The agent should edit only files authorized by Can modify or Owns.

If the refactor needs another area, decide why:

Do not treat referenced context as editable scope.

4. Refactor one step at a time

Useful prompts:

Extract the Itinerary validation result builder.
Move the Itinerary validation tests with the renamed helper.
Update the Itinerary validation spec paths after the file move.

Each prompt asks for one action. Review between steps when the refactor is risky.

5. Preserve behavior explicitly

Before accepting the result, compare the diff against:

A refactor that makes tests pass by changing expected behavior is not safe.

6. Run checks

Run:

If checks cannot run, keep that uncertainty visible.

7. Review the agent’s final report

The report should name:

Do not accept a vague “done” report for a structural change.

Common mistakes

How to verify the result

The agent-assisted refactor is safe when:

← Refactoring and maintenance guides