重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
refactor-flow by vladm3105/aidoc-flow-framework
npx skills add https://github.com/vladm3105/aidoc-flow-framework --skill refactor-flow描述:代码重构辅助、技术债务管理和文档同步
类别:代码质量与维护
复杂度:中高(代码转换 + 可追溯性维护)
通过系统化重构提高代码质量,同时保持与规范的可追溯性。识别重构机会,指导安全转换,并确保文档与代码变更保持同步。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
graph TD
A[代码分析] --> B[检测代码异味]
B --> C{发现异味?}
C -->|否| D[代码质量良好]
C -->|是| E[确定问题优先级]
E --> F[检查测试覆盖率]
F --> G{测试充分?}
G -->|否| H[先编写测试]
G -->|是| I[规划重构]
H --> I
I --> J[生成重构步骤]
J --> K[执行重构]
K --> L[运行测试]
L --> M{测试通过?}
M -->|否| N[回滚更改]
M -->|是| O[更新文档]
N --> P[修订方法]
P --> I
O --> Q[验证可追溯性]
Q --> R[检查 ADR 合规性]
R --> S[生成重构报告]
S --> T[提交更改]
refactor-flow analyze --file src/auth/service.py
输出:
=== 重构分析:src/auth/service.py ===
发现的代码异味:6
[高] 过长方法 (第 45-156 行)
- 方法:authenticate_user()
- 长度:112 行
- 复杂度:15
- 建议:将验证逻辑提取到单独的方法中
- 预估工作量:2 小时
- 风险:低(测试覆盖率良好:95%)
[高] 重复代码 (85% 相似度)
- 位置:
* 第 201-215 行 (validate_password_strength)
* 第 234-248 行 (validate_new_password)
- 建议:将通用逻辑提取到共享验证器中
- 预估工作量:1 小时
- 风险:低
[中] 上帝类
- 类:UserAuthenticationService
- 职责:7 (认证、验证、日志记录、缓存、邮件、审计、会话)
- 建议:将邮件、审计和缓存提取到单独的服务中
- 预估工作量:4 小时
- 风险:中(影响多个消费者)
[中] 复杂条件语句 (第 89-103 行)
- 嵌套深度:4
- 建议:使用卫语句和提前返回
- 预估工作量:30 分钟
- 风险:低
[低] 魔法数字 (第 167, 189, 203 行)
- 值:3, 5, 10
- 建议:提取为命名常量
- 预估工作量:15 分钟
- 风险:非常低
[低] 死代码 (第 278-295 行)
- 方法:legacy_authentication()
- 最后使用时间:从未使用(6 个月前添加)
- 建议:如果确实未使用则移除
- 预估工作量:5 分钟
- 风险:非常低
技术债务分数:42/100 (高债务)
重构优先级:高
预估总工作量:7.75 小时
refactor-flow plan \
--file src/auth/service.py \
--priority high \
--output refactoring-plan.md
生成的计划:
# 重构计划:UserAuthenticationService
## 目标
降低认证服务的复杂度并提高可维护性
## 当前状态
- 复杂度:15 (高)
- 代码行数:356
- 测试覆盖率:95%
- 技术债务:42/100
## 目标状态
- 复杂度:<10 (可接受)
- 代码行数:<250
- 测试覆盖率:≥95%
- 技术债务:<20/100
## 重构步骤
### 步骤 1:提取密码验证 (优先级:高,风险:低)
**时长**:1 小时
**变更**:
1. 创建 `PasswordValidator` 类
2. 移动 `validate_password_strength()` 逻辑
3. 移除重复的验证代码
4. 更新测试
**重构前**:
```python
def validate_password_strength(self, password):
if len(password) < 8:
return False
if not any(c.isupper() for c in password):
return False
# ... 更多验证
重构后:
class PasswordValidator:
MIN_LENGTH = 8
MAX_LENGTH = 128
@classmethod
def validate(cls, password: str) -> ValidationResult:
if len(password) < cls.MIN_LENGTH:
return ValidationResult(valid=False, error="太短")
# ... 验证逻辑
验证:
时长:2 小时
变更:
_validate_credentials()_create_session()_audit_login_attempt()重构前 (复杂度:15):
def authenticate_user(self, username, password):
if username and password:
if self._validate_format(username):
user = self.db.get_user(username)
if user:
if user.is_active:
if self._check_password(password, user.password_hash):
# ... 还有 50 多行
重构后 (复杂度:5):
def authenticate_user(self, username: str, password: str) -> AuthResult:
credentials = self._validate_credentials(username, password)
if not credentials.valid:
return AuthResult(success=False, error=credentials.error)
user = self._get_active_user(username)
if not user:
return AuthResult(success=False, error="用户未找到")
if not self._verify_password(password, user):
self._audit_login_attempt(username, success=False)
return AuthResult(success=False, error="密码无效")
session = self._create_session(user)
self._audit_login_attempt(username, success=True)
return AuthResult(success=True, session=session)
验证:
时长:4 小时
变更:
EmailServiceAuditLoggerSessionCache影响分析:
迁移指南:
# 重构前
auth_service = UserAuthenticationService()
auth_service.send_verification_email(user)
# 重构后
auth_service = UserAuthenticationService()
email_service = EmailService()
email_service.send_verification(user)
验证:
所有消费者已更新
集成测试通过
文档已更新
refactor-flow execute \
--plan refactoring-plan.md \
--step 1 \
--dry-run
空运行输出:
=== 重构执行 (空运行) ===
步骤 1:提取密码验证
将要进行的变更:
1. 创建新文件:src/auth/validators.py
[+] 45 行
2. 修改文件:src/auth/service.py
[-] 30 行 (移除重复代码)
[~] 12 行 (更新为使用 PasswordValidator)
3. 创建测试文件:tests/auth/test_validators.py
[+] 67 行
差异预览:
────────────────────────────────────────
--- src/auth/service.py
+++ src/auth/service.py
@@ -1,5 +1,6 @@
from datetime import datetime
from typing import Optional
+from auth.validators import PasswordValidator
class UserAuthenticationService:
- def validate_password_strength(self, password: str) -> bool:
- if len(password) < 8:
- return False
- # ... (移除了 28 行)
+ def validate_password_strength(self, password: str) -> bool:
+ result = PasswordValidator.validate(password)
+ return result.valid
────────────────────────────────────────
测试影响:
- 需要更新的测试:3
- 新测试:8
- 总测试数:156 → 161
准备执行?(--dry-run 标志激活,未进行任何更改)
refactor-flow debt \
--module src/ \
--output reports/technical-debt.json
输出:
{
"summary": {
"total_debt_score": 35,
"critical_debt_items": 3,
"high_debt_items": 12,
"medium_debt_items": 28,
"estimated_hours": 87
},
"debt_by_category": {
"complexity": {
"score": 45,
"items": 8,
"estimated_hours": 24
},
"duplication": {
"score": 30,
"items": 15,
"estimated_hours": 18
},
"test_coverage": {
"score": 20,
"items": 12,
"estimated_hours": 30
},
"documentation": {
"score": 25,
"items": 9,
"estimated_hours": 15
}
},
"critical_items": [
{
"file": "src/data/processor.py",
"issue": "具有 12 个职责的上帝类",
"debt_score": 85,
"estimated_hours": 16,
"recommendation": "拆分为领域特定服务"
},
{
"file": "src/api/handlers.py",
"issue": "850 行,复杂度 45",
"debt_score": 92,
"estimated_hours": 20,
"recommendation": "将处理程序提取到单独的模块中"
}
],
"trend": {
"previous_score": 40,
"current_score": 35,
"change": -5,
"direction": "improving"
}
}
重构前:
def process_order(order):
# 验证订单 (15 行)
if not order.items:
raise ValueError("No items")
for item in order.items:
if item.quantity <= 0:
raise ValueError("Invalid quantity")
# ... 更多验证
# 计算总额 (10 行)
subtotal = sum(item.price * item.quantity for item in order.items)
tax = subtotal * 0.08
shipping = calculate_shipping(order)
total = subtotal + tax + shipping
# 处理支付 (20 行)
# ... 支付逻辑
return total
重构后:
def process_order(order: Order) -> Decimal:
self._validate_order(order)
total = self._calculate_total(order)
self._process_payment(order, total)
return total
def _validate_order(self, order: Order) -> None:
if not order.items:
raise ValueError("No items")
for item in order.items:
if item.quantity <= 0:
raise ValueError(f"Invalid quantity for {item.name}")
def _calculate_total(self, order: Order) -> Decimal:
subtotal = sum(item.price * item.quantity for item in order.items)
tax = subtotal * Decimal('0.08')
shipping = self._calculate_shipping(order)
return subtotal + tax + shipping
重构前:
def calculate_discount(customer, amount):
if customer.type == 'regular':
return amount * 0.05
elif customer.type == 'premium':
return amount * 0.10
elif customer.type == 'vip':
return amount * 0.20
else:
return 0
重构后:
class Customer(ABC):
@abstractmethod
def calculate_discount(self, amount: Decimal) -> Decimal:
pass
class RegularCustomer(Customer):
def calculate_discount(self, amount: Decimal) -> Decimal:
return amount * Decimal('0.05')
class PremiumCustomer(Customer):
def calculate_discount(self, amount: Decimal) -> Decimal:
return amount * Decimal('0.10')
class VIPCustomer(Customer):
def calculate_discount(self, amount: Decimal) -> Decimal:
return amount * Decimal('0.20')
重构前:
def create_user(username, email, first_name, last_name, birth_date,
address, city, state, zip_code, phone, preferences):
# ... 实现
重构后:
@dataclass
class UserProfile:
username: str
email: str
first_name: str
last_name: str
birth_date: date
contact_info: ContactInfo
preferences: UserPreferences
def create_user(profile: UserProfile) -> User:
# ... 实现
# 重构前
def authenticate_user(username, password):
"""
使用用户名和密码认证用户。
验证凭据,检查用户状态,创建会话。
可追溯性:REQ-AUTH-01, BDD-LOGIN-001
"""
# 重构后 - 更新所有受影响的文档字符串
def authenticate_user(username: str, password: str) -> AuthResult:
"""
使用用户名和密码认证用户。
参数:
username: 用户的登录名
password: 用户的密码
返回:
包含成功状态和会话的 AuthResult
可追溯性:REQ-AUTH-01, BDD-LOGIN-001
"""
def _validate_credentials(self, username: str, password: str) -> ValidationResult:
"""
验证用户名和密码格式。
可追溯性:REQ-AUTH-01
"""
# SPEC-AUTH-V1.md
## 认证服务 API
### 方法:authenticate_user()
**状态**:在 v1.2.0 中更新 (为清晰度重构)
**签名**:
```python
def authenticate_user(username: str, password: str) -> AuthResult
v1.2.0 中的变更:
可追溯性:REQ-AUTH-01
---
## 风险评估
### 低风险重构
- 重命名变量/方法 (借助 IDE 支持)
- 提取常量
- 内联临时变量
- 移除死代码
- 添加类型提示
- 改进文档字符串
### 中风险重构
- 提取方法
- 提取类
- 移动方法
- 用多态替换条件语句
- 引入参数对象
### 高风险重构
- 更改类层次结构
- 拆分数据库表
- 修改公共 API
- 更改认证机制
- 重构核心业务逻辑
### 风险缓解
1. **优秀的测试覆盖率**:高风险重构 ≥95%
2. **功能标志**:启用渐进式发布
3. **并行运行**:运行新旧代码,比较结果
4. **分阶段发布**:金丝雀部署
5. **回滚计划**:快速恢复能力
6. **监控**:过渡期间额外日志记录
---
## 工具访问
必需工具:
- `Read`:读取源文件和文档
- `Edit`:应用重构转换
- `Write`:创建新文件
- `Bash`:运行测试和分析工具
- `Grep`:搜索代码模式
必需库:
- rope:Python 重构库
- autopep8:代码格式化
- radon:复杂度指标
- pylint:代码分析
---
## 集成点
### 与 code-review
- 从审查中识别重构机会
- 验证重构质量
- 跟踪复杂度改进
### 与 test-automation
- 确保重构前存在测试
- 每个重构步骤后运行测试
- 验证覆盖率保持
### 与 doc-validator
- 同步文档与代码变更
- 重构后验证可追溯性
- 更新交叉引用
### 与 analytics-flow
- 跟踪技术债务趋势
- 衡量重构影响
- 报告债务削减进度
---
## 最佳实践
1. **测试先行**:重构前确保良好的测试覆盖率
2. **小步前进**:增量更改,频繁提交
3. **一次只做一件事**:不要将重构与新功能混合
4. **保持行为**:重构期间无功能变更
5. **持续运行测试**:每次小更改后
6. **审查变更**:重构的代码审查
7. **更新文档**:保持规范同步
8. **监控性能**:确保无性能回归
9. **沟通**:通知团队重大重构
10. **明智安排**:避免在关键截止日期期间进行
---
## 成功标准
- 代码复杂度降低到目标水平
- 测试覆盖率保持或提高
- 零功能回归
- 文档同步
- 可追溯性保持
- 团队理解变更
- 技术债务分数提高 ≥20%
---
## 备注
- 重构计划保存到 `plans/refactoring/`
- 重构报告在 `reports/refactoring/`
- 技术债务跟踪在 `metrics/technical-debt.json`
- 自动化重构需要人工审查
- 高风险重构需要团队批准
每周安装次数
49
仓库
GitHub 星标数
10
首次出现
2026年1月24日
安全审计
安装于
codex41
gemini-cli41
opencode39
claude-code39
github-copilot39
cursor39
Description : Code refactoring assistance, technical debt management, and documentation synchronization
Category : Code Quality & Maintenance
Complexity : Medium-High (code transformation + traceability maintenance)
Improve code quality through systematic refactoring while maintaining traceability to specifications. Identify refactoring opportunities, guide safe transformations, and ensure documentation stays synchronized with code changes.
graph TD
A[Code Analysis] --> B[Detect Code Smells]
B --> C{Smells Found?}
C -->|No| D[Code Quality Good]
C -->|Yes| E[Prioritize Issues]
E --> F[Check Test Coverage]
F --> G{Tests Adequate?}
G -->|No| H[Write Tests First]
G -->|Yes| I[Plan Refactoring]
H --> I
I --> J[Generate Refactoring Steps]
J --> K[Execute Refactoring]
K --> L[Run Tests]
L --> M{Tests Pass?}
M -->|No| N[Rollback Changes]
M -->|Yes| O[Update Documentation]
N --> P[Revise Approach]
P --> I
O --> Q[Validate Traceability]
Q --> R[Check ADR Compliance]
R --> S[Generate Refactoring Report]
S --> T[Commit Changes]
refactor-flow analyze --file src/auth/service.py
Output:
=== Refactoring Analysis: src/auth/service.py ===
Code Smells Found: 6
[HIGH] Long Method (Lines 45-156)
- Method: authenticate_user()
- Length: 112 lines
- Complexity: 15
- Recommendation: Extract validation logic to separate methods
- Estimated effort: 2 hours
- Risk: Low (good test coverage: 95%)
[HIGH] Duplicate Code (85% similarity)
- Locations:
* Lines 201-215 (validate_password_strength)
* Lines 234-248 (validate_new_password)
- Recommendation: Extract common logic to shared validator
- Estimated effort: 1 hour
- Risk: Low
[MEDIUM] God Class
- Class: UserAuthenticationService
- Responsibilities: 7 (authentication, validation, logging, caching, email, audit, session)
- Recommendation: Extract email, audit, and caching to separate services
- Estimated effort: 4 hours
- Risk: Medium (affects multiple consumers)
[MEDIUM] Complex Conditional (Lines 89-103)
- Nested depth: 4
- Recommendation: Use guard clauses and early returns
- Estimated effort: 30 minutes
- Risk: Low
[LOW] Magic Numbers (Lines 167, 189, 203)
- Values: 3, 5, 10
- Recommendation: Extract to named constants
- Estimated effort: 15 minutes
- Risk: Very low
[LOW] Dead Code (Lines 278-295)
- Method: legacy_authentication()
- Last used: Never (added 6 months ago)
- Recommendation: Remove if truly unused
- Estimated effort: 5 minutes
- Risk: Very low
Technical Debt Score: 42/100 (High debt)
Refactoring Priority: High
Estimated Total Effort: 7.75 hours
refactor-flow plan \
--file src/auth/service.py \
--priority high \
--output refactoring-plan.md
Generated plan:
# Refactoring Plan: UserAuthenticationService
## Objective
Reduce complexity and improve maintainability of authentication service
## Current State
- Complexity: 15 (High)
- Lines of code: 356
- Test coverage: 95%
- Technical debt: 42/100
## Target State
- Complexity: <10 (Acceptable)
- Lines of code: <250
- Test coverage: ≥95%
- Technical debt: <20/100
## Refactoring Steps
### Step 1: Extract Password Validation (Priority: High, Risk: Low)
**Duration**: 1 hour
**Changes**:
1. Create `PasswordValidator` class
2. Move `validate_password_strength()` logic
3. Remove duplicate validation code
4. Update tests
**Before**:
```python
def validate_password_strength(self, password):
if len(password) < 8:
return False
if not any(c.isupper() for c in password):
return False
# ... more validation
After :
class PasswordValidator:
MIN_LENGTH = 8
MAX_LENGTH = 128
@classmethod
def validate(cls, password: str) -> ValidationResult:
if len(password) < cls.MIN_LENGTH:
return ValidationResult(valid=False, error="Too short")
# ... validation logic
Verification :
Duration : 2 hours
Changes :
_validate_credentials()_create_session()_audit_login_attempt()Before (Complexity: 15):
def authenticate_user(self, username, password):
if username and password:
if self._validate_format(username):
user = self.db.get_user(username)
if user:
if user.is_active:
if self._check_password(password, user.password_hash):
# ... 50 more lines
After (Complexity: 5):
def authenticate_user(self, username: str, password: str) -> AuthResult:
credentials = self._validate_credentials(username, password)
if not credentials.valid:
return AuthResult(success=False, error=credentials.error)
user = self._get_active_user(username)
if not user:
return AuthResult(success=False, error="User not found")
if not self._verify_password(password, user):
self._audit_login_attempt(username, success=False)
return AuthResult(success=False, error="Invalid password")
session = self._create_session(user)
self._audit_login_attempt(username, success=True)
return AuthResult(success=True, session=session)
Verification :
Duration : 4 hours
Changes :
EmailService for email notificationsAuditLogger for security audit loggingSessionCache for session cachingImpact Analysis :
Migration Guide :
# Before
auth_service = UserAuthenticationService()
auth_service.send_verification_email(user)
# After
auth_service = UserAuthenticationService()
email_service = EmailService()
email_service.send_verification(user)
Verification :
All consumers updated
Integration tests pass
Documentation updated
refactor-flow execute \
--plan refactoring-plan.md \
--step 1 \
--dry-run
Dry-run output:
=== Refactoring Execution (DRY RUN) ===
Step 1: Extract Password Validation
Changes to be made:
1. Create new file: src/auth/validators.py
[+] 45 lines
2. Modify file: src/auth/service.py
[-] 30 lines (removed duplicate code)
[~] 12 lines (updated to use PasswordValidator)
3. Create test file: tests/auth/test_validators.py
[+] 67 lines
Diff preview:
────────────────────────────────────────
--- src/auth/service.py
+++ src/auth/service.py
@@ -1,5 +1,6 @@
from datetime import datetime
from typing import Optional
+from auth.validators import PasswordValidator
class UserAuthenticationService:
- def validate_password_strength(self, password: str) -> bool:
- if len(password) < 8:
- return False
- # ... (removed 28 lines)
+ def validate_password_strength(self, password: str) -> bool:
+ result = PasswordValidator.validate(password)
+ return result.valid
────────────────────────────────────────
Test impact:
- Tests to update: 3
- New tests: 8
- Total test count: 156 → 161
Ready to execute? (--dry-run flag active, no changes made)
refactor-flow debt \
--module src/ \
--output reports/technical-debt.json
Output:
{
"summary": {
"total_debt_score": 35,
"critical_debt_items": 3,
"high_debt_items": 12,
"medium_debt_items": 28,
"estimated_hours": 87
},
"debt_by_category": {
"complexity": {
"score": 45,
"items": 8,
"estimated_hours": 24
},
"duplication": {
"score": 30,
"items": 15,
"estimated_hours": 18
},
"test_coverage": {
"score": 20,
"items": 12,
"estimated_hours": 30
},
"documentation": {
"score": 25,
"items": 9,
"estimated_hours": 15
}
},
"critical_items": [
{
"file": "src/data/processor.py",
"issue": "God class with 12 responsibilities",
"debt_score": 85,
"estimated_hours": 16,
"recommendation": "Split into domain-specific services"
},
{
"file": "src/api/handlers.py",
"issue": "850 lines, complexity 45",
"debt_score": 92,
"estimated_hours": 20,
"recommendation": "Extract handlers to separate modules"
}
],
"trend": {
"previous_score": 40,
"current_score": 35,
"change": -5,
"direction": "improving"
}
}
Before :
def process_order(order):
# Validate order (15 lines)
if not order.items:
raise ValueError("No items")
for item in order.items:
if item.quantity <= 0:
raise ValueError("Invalid quantity")
# ... more validation
# Calculate total (10 lines)
subtotal = sum(item.price * item.quantity for item in order.items)
tax = subtotal * 0.08
shipping = calculate_shipping(order)
total = subtotal + tax + shipping
# Process payment (20 lines)
# ... payment logic
return total
After :
def process_order(order: Order) -> Decimal:
self._validate_order(order)
total = self._calculate_total(order)
self._process_payment(order, total)
return total
def _validate_order(self, order: Order) -> None:
if not order.items:
raise ValueError("No items")
for item in order.items:
if item.quantity <= 0:
raise ValueError(f"Invalid quantity for {item.name}")
def _calculate_total(self, order: Order) -> Decimal:
subtotal = sum(item.price * item.quantity for item in order.items)
tax = subtotal * Decimal('0.08')
shipping = self._calculate_shipping(order)
return subtotal + tax + shipping
Before :
def calculate_discount(customer, amount):
if customer.type == 'regular':
return amount * 0.05
elif customer.type == 'premium':
return amount * 0.10
elif customer.type == 'vip':
return amount * 0.20
else:
return 0
After :
class Customer(ABC):
@abstractmethod
def calculate_discount(self, amount: Decimal) -> Decimal:
pass
class RegularCustomer(Customer):
def calculate_discount(self, amount: Decimal) -> Decimal:
return amount * Decimal('0.05')
class PremiumCustomer(Customer):
def calculate_discount(self, amount: Decimal) -> Decimal:
return amount * Decimal('0.10')
class VIPCustomer(Customer):
def calculate_discount(self, amount: Decimal) -> Decimal:
return amount * Decimal('0.20')
Before :
def create_user(username, email, first_name, last_name, birth_date,
address, city, state, zip_code, phone, preferences):
# ... implementation
After :
@dataclass
class UserProfile:
username: str
email: str
first_name: str
last_name: str
birth_date: date
contact_info: ContactInfo
preferences: UserPreferences
def create_user(profile: UserProfile) -> User:
# ... implementation
# Before refactoring
def authenticate_user(username, password):
"""
Authenticate user with username and password.
Validates credentials, checks user status, creates session.
Traceability: REQ-AUTH-01, BDD-LOGIN-001
"""
# After refactoring - Update all affected docstrings
def authenticate_user(username: str, password: str) -> AuthResult:
"""
Authenticate user with username and password.
Args:
username: User's login name
password: User's password
Returns:
AuthResult containing success status and session
Traceability: REQ-AUTH-01, BDD-LOGIN-001
"""
def _validate_credentials(self, username: str, password: str) -> ValidationResult:
"""
Validate username and password format.
Traceability: REQ-AUTH-01
"""
# SPEC-AUTH-V1.md
## Authentication Service API
### Method: authenticate_user()
**Status**: Updated in v1.2.0 (refactored for clarity)
**Signature**:
```python
def authenticate_user(username: str, password: str) -> AuthResult
Changes in v1.2.0 :
Traceability : REQ-AUTH-01
---
## Risk Assessment
### Low Risk Refactorings
- Rename variables/methods (with IDE support)
- Extract constants
- Inline temporary variables
- Remove dead code
- Add type hints
- Improve docstrings
### Medium Risk Refactorings
- Extract method
- Extract class
- Move method
- Replace conditional with polymorphism
- Introduce parameter object
### High Risk Refactorings
- Change class hierarchy
- Split database tables
- Modify public API
- Change authentication mechanism
- Refactor core business logic
### Risk Mitigation
1. **Excellent test coverage**: ≥95% for high-risk refactorings
2. **Feature flags**: Enable gradual rollout
3. **Parallel run**: Run old and new code, compare results
4. **Staged rollout**: Canary deployment
5. **Rollback plan**: Quick revert capability
6. **Monitoring**: Extra logging during transition
---
## Tool Access
Required tools:
- `Read`: Read source files and documentation
- `Edit`: Apply refactoring transformations
- `Write`: Create new files
- `Bash`: Run tests and analysis tools
- `Grep`: Search for code patterns
Required libraries:
- rope: Python refactoring library
- autopep8: Code formatting
- radon: Complexity metrics
- pylint: Code analysis
---
## Integration Points
### With code-review
- Identify refactoring opportunities from reviews
- Validate refactoring quality
- Track complexity improvements
### With test-automation
- Ensure tests exist before refactoring
- Run tests after each refactoring step
- Verify coverage maintained
### With doc-validator
- Sync documentation with code changes
- Validate traceability after refactoring
- Update cross-references
### With analytics-flow
- Track technical debt trends
- Measure refactoring impact
- Report debt reduction progress
---
## Best Practices
1. **Test first**: Ensure good test coverage before refactoring
2. **Small steps**: Incremental changes, frequent commits
3. **One thing at a time**: Don't mix refactoring with new features
4. **Preserve behavior**: No functional changes during refactoring
5. **Run tests constantly**: After every small change
6. **Review changes**: Code review for refactorings
7. **Update documentation**: Keep specs synchronized
8. **Monitor performance**: Ensure no performance regressions
9. **Communicate**: Notify team of significant refactorings
10. **Schedule wisely**: Not during critical deadlines
---
## Success Criteria
- Code complexity reduced to target levels
- Test coverage maintained or improved
- Zero functional regressions
- Documentation synchronized
- Traceability preserved
- Team understands changes
- Technical debt score improved by ≥20%
---
## Notes
- Refactoring plans saved to `plans/refactoring/`
- Refactoring reports in `reports/refactoring/`
- Technical debt tracked in `metrics/technical-debt.json`
- Automated refactorings require manual review
- High-risk refactorings need team approval
Weekly Installs
49
Repository
GitHub Stars
10
First Seen
Jan 24, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex41
gemini-cli41
opencode39
claude-code39
github-copilot39
cursor39
GitHub Actions 官方文档查询助手 - 精准解答 CI/CD 工作流问题
53,800 周安装