@botlearn/refactor 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +35 -0
- package/knowledge/anti-patterns.md +92 -0
- package/knowledge/best-practices.md +147 -0
- package/knowledge/domain.md +193 -0
- package/manifest.json +28 -0
- package/package.json +38 -0
- package/skill.md +48 -0
- package/strategies/main.md +150 -0
- package/tests/benchmark.json +496 -0
- package/tests/smoke.json +64 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
---
|
|
2
|
+
strategy: refactor
|
|
3
|
+
version: 1.0.0
|
|
4
|
+
steps: 6
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Code Refactoring Strategy
|
|
8
|
+
|
|
9
|
+
## Step 1: Smell Detection
|
|
10
|
+
- Receive the target code from the user — may be a specific method, class, module, or an entire file
|
|
11
|
+
- Invoke @botlearn/code-review to perform initial structural analysis and identify quality issues
|
|
12
|
+
- Scan the code systematically for each smell category from knowledge/domain.md:
|
|
13
|
+
- **Bloaters**: Long Methods (>20 lines), Large Classes (>10 public methods), Long Parameter Lists (>3 params), Primitive Obsession, Data Clumps
|
|
14
|
+
- **OO Abusers**: Switch Statements on type, Temporary Fields, Refused Bequest, Parallel Inheritance
|
|
15
|
+
- **Change Preventers**: Divergent Change, Shotgun Surgery, Feature Envy
|
|
16
|
+
- **Dispensables**: Duplicate Code, Dead Code, Lazy Class, Speculative Generality
|
|
17
|
+
- **Couplers**: Inappropriate Intimacy, Message Chains, Middle Man
|
|
18
|
+
- Compute baseline metrics:
|
|
19
|
+
- Cyclomatic complexity per method
|
|
20
|
+
- Cognitive complexity per method
|
|
21
|
+
- Afferent/efferent coupling per class
|
|
22
|
+
- Duplication ratio (duplicated lines / total lines)
|
|
23
|
+
- Depth of inheritance tree
|
|
24
|
+
- Output a prioritized smell inventory: `[smell_name, location, severity (P0-P3), estimated_effort]`
|
|
25
|
+
- IF no significant smells are detected (all methods CC < 10, no duplication, no structural issues) THEN report "code is clean" with metrics and stop
|
|
26
|
+
|
|
27
|
+
## Step 2: Pattern Matching
|
|
28
|
+
- For each detected smell, consult the refactoring technique mapping in knowledge/domain.md to identify candidate transformations
|
|
29
|
+
- Map smells to refactoring techniques:
|
|
30
|
+
- Long Method → Extract Method, Decompose Conditional
|
|
31
|
+
- Large Class → Extract Class, Extract Interface
|
|
32
|
+
- Switch Statements → Replace Conditional with Polymorphism, Strategy Pattern
|
|
33
|
+
- Duplicate Code → Extract Method, Pull Up Method, Template Method
|
|
34
|
+
- Feature Envy → Move Method, Move Field
|
|
35
|
+
- Long Parameter List → Introduce Parameter Object, Builder Pattern
|
|
36
|
+
- Primitive Obsession → Replace Primitive with Value Object
|
|
37
|
+
- Message Chains → Hide Delegate, introduce Facade
|
|
38
|
+
- Deep Inheritance → Replace Inheritance with Composition
|
|
39
|
+
- For each candidate transformation, evaluate:
|
|
40
|
+
- **Applicability**: Does this technique fit the specific code context?
|
|
41
|
+
- **Risk**: What could go wrong? How complex is the transformation?
|
|
42
|
+
- **Impact**: How much will this improve the target metric?
|
|
43
|
+
- **Dependencies**: Does this transformation depend on another being completed first?
|
|
44
|
+
- IF a smell maps to a GoF design pattern THEN verify the pattern is justified:
|
|
45
|
+
- Identify at least 2-3 concrete variations that the pattern would abstract over
|
|
46
|
+
- Confirm the pattern reduces complexity rather than increasing it
|
|
47
|
+
- Check against knowledge/anti-patterns.md #5 (Premature Abstraction) and #6 (Pattern Fever)
|
|
48
|
+
- Output a candidate transformation list: `[transformation, target_smell, pattern_if_any, risk_level, expected_improvement]`
|
|
49
|
+
|
|
50
|
+
## Step 3: Refactoring Plan
|
|
51
|
+
- Order candidate transformations by dependency topology:
|
|
52
|
+
1. Foundational transformations first (Extract Interface, Introduce Parameter Object) — these enable later steps
|
|
53
|
+
2. Structural transformations second (Extract Class, Move Method) — these reshape the code
|
|
54
|
+
3. Pattern introductions third (Strategy, Template Method) — these add design structure
|
|
55
|
+
4. Cleanup last (Remove Dead Code, Inline Temp, Rename) — these polish the result
|
|
56
|
+
- For each transformation step, specify:
|
|
57
|
+
- **What**: Exact transformation to apply (e.g., "Extract lines 42-67 of `processOrder()` into `validateOrderItems()`")
|
|
58
|
+
- **Why**: The smell it addresses and the metric it improves
|
|
59
|
+
- **How**: Step-by-step mechanical instructions
|
|
60
|
+
- **Verify**: What test(s) to run to confirm equivalence
|
|
61
|
+
- **Rollback**: How to revert if verification fails
|
|
62
|
+
- Estimate total plan duration and per-step complexity
|
|
63
|
+
- IF the total plan exceeds 10 transformations THEN split into phases:
|
|
64
|
+
- Phase A: Critical smells (P0-P1) — must-do
|
|
65
|
+
- Phase B: Important smells (P2) — should-do
|
|
66
|
+
- Phase C: Polish (P3) — nice-to-have
|
|
67
|
+
- Present the plan to the user for approval before proceeding
|
|
68
|
+
- IF the user requests modifications to the plan THEN adjust and re-present
|
|
69
|
+
|
|
70
|
+
## Step 4: Incremental Transform
|
|
71
|
+
- Before starting: verify the test suite passes (green baseline)
|
|
72
|
+
- IF test coverage on target code is below 80% THEN:
|
|
73
|
+
- Write characterization tests to capture current behavior
|
|
74
|
+
- Achieve adequate coverage before proceeding
|
|
75
|
+
- Commit the new tests as a separate step
|
|
76
|
+
- Execute each transformation step from the plan sequentially:
|
|
77
|
+
1. Announce the step: what will change and why
|
|
78
|
+
2. Apply the mechanical transformation
|
|
79
|
+
3. Verify the code compiles / passes syntax checks
|
|
80
|
+
4. Run the relevant test suite
|
|
81
|
+
5. IF tests pass THEN mark step complete and proceed
|
|
82
|
+
6. IF tests fail THEN:
|
|
83
|
+
- Analyze the failure — is it a bug in the refactoring or a test that was overly specific to the old structure?
|
|
84
|
+
- IF refactoring bug THEN rollback the step and try an alternative approach
|
|
85
|
+
- IF test is structure-dependent THEN update the test (document why) and re-run
|
|
86
|
+
7. Commit the step with a descriptive refactoring message
|
|
87
|
+
- Apply transformations using these mechanical recipes:
|
|
88
|
+
- **Extract Method**: Identify the code block → determine parameters (variables read) and return values (variables written) → create new method with those params/returns → replace original block with method call → verify
|
|
89
|
+
- **Extract Class**: Identify the responsibility boundary → create new class → move related fields and methods → replace direct access with delegation → update callers → verify
|
|
90
|
+
- **Replace Conditional with Polymorphism**: Identify the type discriminator → create an interface with the varying behavior → create concrete classes for each case → replace conditional with polymorphic call → verify
|
|
91
|
+
- **Introduce Parameter Object**: Identify the parameter group → create a class/type for the group → replace parameter list with the new object → update all callers → verify
|
|
92
|
+
- Track progress: steps completed / total steps; metrics improvement so far
|
|
93
|
+
|
|
94
|
+
## Step 5: Equivalence Verification
|
|
95
|
+
- After all transformation steps are complete, perform comprehensive verification:
|
|
96
|
+
- **Test Suite Verification**:
|
|
97
|
+
- Run the complete test suite (unit + integration) — ALL tests must pass
|
|
98
|
+
- IF any test fails THEN diagnose and fix before proceeding; do NOT skip failing tests
|
|
99
|
+
- **Behavioral Contract Check** (from knowledge/best-practices.md):
|
|
100
|
+
- [ ] All public method signatures unchanged (or changes are explicitly approved)
|
|
101
|
+
- [ ] All preconditions preserved (same input validation, same parameter constraints)
|
|
102
|
+
- [ ] All postconditions preserved (same return values, same state changes)
|
|
103
|
+
- [ ] All invariants preserved (same object consistency rules)
|
|
104
|
+
- [ ] All exception/error behavior preserved (same errors for same invalid inputs)
|
|
105
|
+
- [ ] All side effects preserved (same external calls, same writes, same logging)
|
|
106
|
+
- **Regression Check**:
|
|
107
|
+
- IF snapshot tests exist THEN compare output snapshots before and after
|
|
108
|
+
- IF integration tests exist THEN run them against the refactored code
|
|
109
|
+
- IF performance-sensitive code was refactored THEN run benchmarks and compare
|
|
110
|
+
- **Static Analysis Check**:
|
|
111
|
+
- Run linter/static analyzer on refactored code
|
|
112
|
+
- Verify no new warnings or errors introduced
|
|
113
|
+
- Verify type safety is preserved or improved
|
|
114
|
+
- IF any verification check fails THEN:
|
|
115
|
+
- Identify the specific transformation step that caused the failure
|
|
116
|
+
- Rollback to the last known-good state
|
|
117
|
+
- Apply an alternative transformation approach
|
|
118
|
+
- Re-run verification
|
|
119
|
+
|
|
120
|
+
## Step 6: Quality Measurement
|
|
121
|
+
- Compute post-refactoring metrics on the same scope as the baseline:
|
|
122
|
+
- Cyclomatic complexity per method (target: 20%+ reduction)
|
|
123
|
+
- Cognitive complexity per method (target: 20%+ reduction)
|
|
124
|
+
- Afferent/efferent coupling per class (target: reduced Ce, stable or increased Ca)
|
|
125
|
+
- Duplication ratio (target: 50%+ reduction in duplicated lines)
|
|
126
|
+
- Depth of inheritance tree (target: no increase; decrease if it was excessive)
|
|
127
|
+
- Lines of code per method and per class (context-dependent — reduction is good only if clarity improves)
|
|
128
|
+
- Calculate quality improvement deltas:
|
|
129
|
+
- `delta_cc = (baseline_cc - final_cc) / baseline_cc * 100`
|
|
130
|
+
- `delta_cognitive = (baseline_cognitive - final_cognitive) / baseline_cognitive * 100`
|
|
131
|
+
- `delta_coupling = (baseline_ce - final_ce) / baseline_ce * 100`
|
|
132
|
+
- `delta_duplication = (baseline_dup - final_dup) / baseline_dup * 100`
|
|
133
|
+
- Present a summary report:
|
|
134
|
+
```
|
|
135
|
+
## Refactoring Summary
|
|
136
|
+
- Smells resolved: N of M detected
|
|
137
|
+
- Transformations applied: K steps
|
|
138
|
+
- Complexity reduction: X% (cyclomatic), Y% (cognitive)
|
|
139
|
+
- Coupling reduction: Z%
|
|
140
|
+
- Duplication reduction: W%
|
|
141
|
+
- Tests: all passing (N tests)
|
|
142
|
+
- Behavioral equivalence: verified
|
|
143
|
+
```
|
|
144
|
+
- IF quality improvement is below the 40% target on key metrics THEN:
|
|
145
|
+
- Identify remaining high-impact smells
|
|
146
|
+
- Recommend Phase B/C refactoring steps for future sessions
|
|
147
|
+
- Provide recommendations for maintaining quality:
|
|
148
|
+
- Suggest linter rules to prevent regression of resolved smells
|
|
149
|
+
- Recommend test coverage targets for the refactored code
|
|
150
|
+
- Flag any technical debt items discovered but deferred during this session
|