Refactoring
Refactor code with a passing test baseline, a plan that states what stays fixed, and an architecture-focused review.
A refactor changes structure and adds no behavior, so the existing tests should pass before the change and after it without being edited.
Best for: Code improvement, tech debt reduction Time estimate: 15 to 45 minutes Skills used: mk:scout, mk:plan-creator, mk:cook, mk:review Agents involved: planner, tester, developer, reviewer, architect (if a pattern changes)
Step 1: Scout the current structure
/mk:scout payment modulemk:scout maps the module with parallel Explore agents: files and dependencies, the patterns in use, entry points and a size estimate.
Step 2: Plan the refactor
/mk:plan-creator refactor payment module: extract a service layer from the controllersThe planner writes the plan under tasks/plans/YYMMDD-name/. For a refactor it should state what moves, splits or is renamed, what must not change (external API contracts, test behavior) and which files carry risk (many dependents, shared utilities). Agree the plan before building. If the refactor introduces a new pattern, such as moving from MVC to a service layer, the architect agent records the decision in an ADR (see Architecture Decisions).
Step 3: Record the baseline
Run the full test suite before any change and note the result:
87 tests passing. Any failure after the refactor is a regression.Step 4: Refactor in small steps
/mk:cook tasks/plans/<plan-dir>/plan.mdThe developer follows the plan and runs the tests after each change. When a test fails, it adjusts the approach, up to three attempts:
Move payment logic to src/services/payment.service.ts 87/87 passing
Update controllers to use the service 85/87 passing: two integration tests import the old path
Update the test imports 87/87 passingThe post-write.cjs hook scans every file write for security patterns while this runs.
Step 5: Review
/mk:review checks five dimensions. For a refactor, look at:
- Architecture fit: does the change improve the pattern or make it worse?
- Behavior: tests should pass without being modified.
- Performance: no new N+1 queries or unnecessary re-renders.
Read the verdict before you ship with /mk:ship; the ship check then runs lint, related tests and a type-check at commit time.
What keeps a refactor safe
| Risk | What helps |
|---|---|
| Breaking behavior | The test baseline before and after, run by the tester and developer |
| Scope creep | The plan lists what changes and what does not |
| Unreviewed pattern change | The architect records new patterns in an ADR |
| Security regression | post-write.cjs scans each file write |
Next
Writing Tests covers adding coverage to untested code.