Systematize the refactoring skill to ensure the refactoring process is safe, traceable, and meets quality standards.
Language
- Accept questions in both Chinese and English
- Always respond in Chinese
- Generate all documents in Chinese
Trigger Conditions
- The user needs to refactor existing code
- The user requests optimizing code quality
- The user mentions technical debt or code remediation
- The user requests reviewing and improving an existing implementation
Core Principles
Refactoring Safety Principles
┌─────────────────────────────────────────────────────────┐
│ 重构前必须满足 │
├─────────────────────────────────────────────────────────┤
│ 1. 有明确的重构范围 │
│ 2. 有足够的测试覆盖(≥80%) │
│ 3. 所有测试通过 │
├─────────────────────────────────────────────────────────┤
│ 重构过程中 │
├─────────────────────────────────────────────────────────┤
│ 1. 小步重构,每步可验证 │
│ 2. 每步后运行测试 │
│ 3. 不添加新功能 │
├─────────────────────────────────────────────────────────┤
│ 重构后必须满足 │
├─────────────────────────────────────────────────────────┤
│ 1. 所有测试通过 │
│ 2. 覆盖率不降低 │
│ 3. 生成重构报告 │
└─────────────────────────────────────────────────────────┘
Collaboration with Other Skills
| Scenario | Collaborating Skill | Description |
|---|---|---|
| Code cannot be tested | /retrofit |
Establish a baseline to record the current state and external constraints, then confirm the target behavior with the user before rewriting |
| UI refactoring | /ui-orchestrator |
Apply UI constraint specifications |
| Code quality check | /code-quality |
Apply MTE principles |
| Needs documentation | keel process | Generate specification documents |
| Write/supplement tests | /testing-guide |
Test quality constraints (assertions, mocks, mutation testing) |
| Update description after refactoring | /code-self-describe |
Update module self-description (--update) |
Workflow
1. 确定重构范围
│
├── 用户指定范围 → Step 2
└── 未指定范围 → 系统审查 → 发现问题 → 用户确认范围
│
▼
2. 评估测试状态
│
├── 有测试且覆盖 ≥80% → Step 4
├── 有测试但覆盖 <80% → Step 3(补充测试)
└── 无测试 → Step 3(新建测试)
│
▼
3. 补充/新建测试
│
├── 可测试 → 编写测试 → 确保覆盖率 ≥80% → Step 4
└── 不可测试 → 标记为"需要重写" → Step 5
│
▼
4. 执行重构
│
├── 普通代码 → 应用 /code-quality
└── UI 代码 → 应用 /ui-orchestrator
│
▼
5. 重写流程(如需要)
│
└── /retrofit 建基线 → 与用户确认目标行为 → 正常 keel 流程 → 重新实现
│
▼
6. 验证与报告
│
├── 运行所有测试
├── 检查覆盖率
└── 生成重构报告
Step 1: Determine the refactoring scope
1.1 User-specified scope
If the user explicitly specifies the refactoring scope, use it directly.
用户指定范围示例:
- "重构 src/services/user.ts"
- "重构用户认证模块"
- "优化 UserService 类"
1.2 Systematic review (when no scope is specified)
Review the code using the following checklist:
Code Smells Checklist
Thresholds excerpted from
/code-qualityCore Threshold Table, changes must be synchronized in the same commit; P0/P1 are the fix priority mappings for this skill.
| Issue Type | Detection Method | Priority Rule |
|---|---|---|
| Long function | Line count > 50 | P0 if > 100, P1 if > 50 |
| Too many parameters | Parameters > 5 | P1 |
| Excessively deep nesting | Nesting > 3 levels | P1 |
| Duplicated code | Similar code blocks > 3 occurrences | P0 |
| God class | Line count > 500 or responsibilities > 3 | P0 |
| Feature envy | Frequently accesses data of other classes | P2 |
| Data clumps | Multiple parameters always appear together | P2 |
Review Report Template
# 代码审查报告
## 审查范围
- **目录**: <path>
- **文件数**: <count>
- **代码行数**: <lines>
## 发现的问题
### P0 - 必须修复
| # | 文件 | 问题 | 描述 |
|---|------|------|------|
| 1 | `src/services/user.ts` | 上帝类 | UserService 超过 800 行,包含 5 种职责 |
| 2 | `src/utils/helper.ts` | 重复代码 | processData 函数在 4 处有相似实现 |
### P1 - 建议修复
| # | 文件 | 问题 | 描述 |
|---|------|------|------|
| 1 | `src/api/handler.ts:45` | 过长函数 | handleRequest 函数 78 行 |
| 2 | `src/models/order.ts:120` | 过深嵌套 | validateOrder 嵌套 4 层 |
### P2 - 可选修复
| # | 文件 | 问题 | 描述 |
|---|------|------|------|
| 1 | `src/services/payment.ts` | 特性依恋 | 频繁访问 Order 对象属性 |
## 建议重构顺序
1. [ ] UserService 拆分(P0,影响范围大)
2. [ ] 消除 processData 重复(P0,多处引用)
3. [ ] handleRequest 拆分(P1)
4. [ ] validateOrder 简化(P1)
## 预计影响
- 涉及文件: 12
- 可能影响的测试: 45
- 风险评估: 中
1.3 User confirmation
Use AskUserQuestion to let the user confirm the refactoring scope:
发现以下问题,请选择要重构的范围:
1. **全部重构** - 按优先级依次处理所有问题
2. **仅 P0** - 只处理必须修复的问题
3. **指定范围** - 手动选择要重构的项目
4. **暂不重构** - 仅保存审查报告
Step 2: Assess test status
2.1 Detect test coverage
# 检测测试框架
# Jest / Vitest / Mocha / pytest 等
# 运行覆盖率报告
npm run test:coverage # 或对应命令
# 检查目标文件覆盖率
2.2 Test status classification
Coverage thresholds excerpted from
/testing-guideCore Threshold Table, changes must be synchronized in the same commit (the ≥80% throughout this file comes from the same source).
| Status | Condition | Next Step |
|---|---|---|
| Sufficient | Line coverage ≥80%, branch coverage ≥80% | → Step 4 Execute refactoring |
| Insufficient | Tests exist but coverage <80% | → Step 3 Supplement tests |
| No tests | No test files in the target scope | → Step 3 Create tests |
| Untestable | The code structure makes it impossible to write effective tests | → Step 5 Rewrite process |
2.3 Testability assessment
Conditions under which code is judged "untestable":
不可测试的代码特征:
- [ ] 硬编码外部依赖(数据库、API、文件系统)
- [ ] 无法注入依赖(构造函数中 new 具体类)
- [ ] 业务逻辑与 IO 混合,无法分离
- [ ] 全局状态依赖
- [ ] 无法 Mock 的第三方库深度耦合
如果满足 2 个以上条件,标记为"不可测试"
Step 3: Add/create tests
Important: When writing tests, you must follow the
/testing-guidequality constraints
3.1 Test strategy
Refer to the /testing-guide test quality pyramid:
测试质量要求(从基础到高级):
Level 1: 覆盖率 - 行/分支 ≥ 80%
Level 2: 断言质量 - 禁止弱断言,验证具体值
Level 3: 测试有效性 - 变异得分 ≥ 80%(推荐)
3.2 Test writing conventions
Follow the constraints of /testing-guide :
- Tests are based on requirements, not code
- Every test must have concrete assertions(weak assertions such as toBeDefined, toBeTruthy are prohibited)
- Test names describe expected behavior:
[方法] 应该 [行为] 当 [条件] - Mocks are only used for external dependencies, do not mock internal implementations
3.3 Coverage verification
# 运行测试并检查覆盖率
npm run test:coverage -- --collectCoverageFrom='<target-path>'
# 确保满足:
# - 行覆盖率 ≥ 80%
# - 分支覆盖率 ≥ 80%
3.4 Mutation testing verification (recommended)
# 验证测试有效性
npx stryker run --mutate '<target-path>'
# 目标:变异得分 ≥ 80%
For detailed test writing guidance, Mock strategies, and mutation testing configuration, refer to
/testing-guide
Step 4: Perform refactoring
4.1 Pre-refactoring checks
- All tests pass
- Git branch created or rollback available
4.2 Refactoring strategy
General code refactoring
Apply /code-quality MTE principles:
| Problem | Refactoring technique | Verification |
|---|---|---|
| Long function | Extract function | Each function ≤50 lines |
| Too many parameters | Parameter object | Parameters ≤5 |
| Too deep nesting | Early return, extract function | Nesting ≤3 levels |
| Duplicate code | Extract common function | No duplicate blocks |
| God class | Split responsibilities | Single responsibility per class |
UI code refactoring
UI refactoring goes through /ui-orchestrator routing to the corresponding UI skill for execution. For review criteria such as layout / tokens / interaction states / empty states, see dev-workflow's ui-quality-checklist。
Three items specific to refactoring that neither of the above two covers:
- Animations only use
transform/opacity(other properties trigger reflow, and are the most likely to introduce performance regressions during refactoring) - Follow
prefers-reduced-motion - Prefer accessible primitives already available in the component library, and do not implement interactive controls yourself
4.3 Small-step refactoring principle
每次重构步骤:
1. 执行一个重构操作
2. 运行测试
3. 测试通过 → 继续下一步
4. 测试失败 → 回滚,重新分析
5. 提交(可选,推荐频繁提交)
4.4 Refactoring progress tracking
Use TodoWrite to track refactoring progress:
重构任务示例:
1. [x] 提取 validateUser 函数
2. [x] 将 UserService 拆分为 UserQueryService
3. [ ] 将 UserService 拆分为 UserCommandService
4. [ ] 消除 processData 重复
Step 5: Rewrite process
When code is judged "untestable", enter the rewrite process. See references/rewrite-flow.md。
Step 6: Verification and reporting
6.1 Verification checklist
- No new lint warnings
- Functional behavior unchanged
6.2 Refactoring report template
See references/report-template.md
Output
Output file
docs/devdocs/
├── 05-refactor-audit.md # 代码审查报告(Step 1)
├── 05-refactor-plan.md # 重构计划(Step 1 确认后)
├── 05-refactor-report.md # 重构报告(Step 6)
└── 05-refactor-rewrite.md # 重写报告(如适用)
File naming rules
- General refactoring:
05-refactor-*.md - If it targets a specific module:
05-refactor-<module>-*.md
Constraints
Scope constraints
- When no scope is specified, a code review must be performed first
- The user must confirm the refactoring scope
Test constraints
- Tests must be added first when there are no tests or coverage is insufficient
- When code is untestable, the rewrite process must be entered
- Coverage must not decrease after refactoring
Process constraints
- Tests must be run after each refactoring step
- New features must not be added during refactoring
Collaboration constraints
- UI refactoring must apply the
/ui-orchestratorconstraints - Code refactoring must apply the
/code-qualityMTE principles - Before rewriting, a baseline must be established with
/retrofitand the target behavior must be confirmed with the user before requirements can be defined
Documentation constraints
- A refactoring report must be generated
- During rewriting, keel documentation must be generated
- The report must include a before-and-after comparison
Error Handling
See references/error-handling.mdfor details (test failures, insufficient coverage, untestable code)
Integration with keel
See references/devdocs-integration.mdfor details (process location diagram, call relationship diagram)