This skill helps you improve code quality through incremental refactoring while preserving behavior, guided by the test suite as the contract.
npx playbooks add skill matthew-plusprogramming/monorepo --skill refactor
Before beginning work, read these files for project-specific guidelines:
.claude/memory-bank/best-practices/code-quality.md.claude/memory-bank/best-practices/software-principles.md.claude/memory-bank/testing.guidelines.mdImprove code quality without changing behavior. Make code more maintainable, readable, and efficient while ensuring all existing tests continue to pass.
This skill dispatches the refactorer subagent. Behavior preservation is the contract: the test suite must pass before refactoring (baseline) and after refactoring (verification). See .claude/agents/refactorer.md for the full agent contract (input schema, return contract, escalation format).
refactoreropus (per CLAUDE.md MANDATORY model rule)npm test green (all existing tests passing)npm test green (same tests passing, no regressions)If baseline tests are not green, STOP and fix failing tests before dispatch — refactoring on a red suite cannot prove behavior preservation.
Unlike implementation (/implement) which follows spec groups, refactoring uses test suite as contract. However:
/code-review may identify quality improvements. These become refactor tasks (separate from original spec).Unlike implementation (spec-driven), refactoring uses the test suite as the contract.
| Aspect | Implementation | Refactoring |
| ---------- | ------------------- | ------------------------- |
| Contract | Spec with ACs | Test suite |
| Success | All ACs implemented | All tests still pass |
| Constraint | Follow spec exactly | Preserve behavior exactly |
Before ANY refactoring:
# Check test coverage of targets
npm test -- --coverage --collectCoverageFrom="src/services/target.ts"
Required: >80% coverage on refactoring targets.
If coverage <80%: STOP. Tests must be added first. This is a separate task.
# Run full test suite
npm test
# Record baseline
npm test -- --json > /tmp/baseline-tests.json
# Type check
npx tsc --noEmit
# Lint
npm run lint
Document baseline:
## Baseline (pre-refactor)
- Tests: 147 passing, 0 failing
- Type errors: 0
- Lint warnings: 12
- Coverage: 84%
Never refactor everything at once. Work incrementally:
1. Identify smallest change that improves code
2. Make change
3. Run tests
4. Commit if green
5. Repeat
Each commit should be:
// Before: 50-line function
async processOrder(order: Order) {
// validation logic (20 lines)
// calculation logic (15 lines)
// persistence logic (15 lines)
}
// After: Extracted methods
async processOrder(order: Order) {
await this.validateOrder(order);
const totals = this.calculateTotals(order);
await this.persistOrder(order, totals);
}
// Before: Type checking
function getPrice(type: string) {
if (type === 'premium') return 99;
if (type === 'basic') return 49;
return 0;
}
// After: Polymorphism
interface PricingStrategy {
getPrice(): number;
}
class PremiumPricing implements PricingStrategy {
getPrice() {
return 99;
}
}
// Before: Hard-coded dependency
class OrderService {
private db = new Database();
}
// After: Injected dependency
class OrderService {
constructor(private db: Database) {}
}
# After EVERY change
npm test
# Verify same test count
npm test -- --json | jq '.numTotalTests'
# Verify no failures
npm test -- --json | jq '.numFailedTests' # Must be 0
If tests fail: Your change altered behavior. Revert immediately.
## Refactoring Log
**Related Spec Group** (if applicable): sg-order-processing
### Change 1: Extract validation logic
- **Files**: src/services/order.ts
- **Pattern**: Extract Method
- **Rationale**: 50-line method violated SRP (identified in /code-review)
- **Atomic Specs Affected**: as-001, as-002 (test evidence still valid)
- **Tests**: 147 passing ✓
- **Commit**: abc123
### Change 2: Add dependency injection
- **Files**: src/services/order.ts, src/di/container.ts
- **Pattern**: Dependency Injection
- **Rationale**: Enable testing without real database
- **Atomic Specs Affected**: None (infrastructure change)
- **Tests**: 147 passing ✓
- **Commit**: def456
# Full test suite
npm test
# Type check
npx tsc --noEmit
# Lint (should improve, not regress)
npm run lint
# Build
npm run build
# Coverage (should not decrease)
npm test -- --coverage
## Refactoring Complete
**Scope**: Tech debt in authentication services
**Related Spec Group** (if applicable): sg-logout-button
**Files Modified**: 4
**Commits**: 6
**Metrics**:
| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Tests | 147 | 147 | - |
| Coverage | 84% | 86% | +2% |
| Lint warnings | 12 | 4 | -8 |
| Cyclomatic complexity | 24 | 12 | -50% |
**Changes Made**:
1. Extracted validation logic into AuthValidator class
2. Added dependency injection to AuthService
3. Consolidated error handling patterns
4. Removed dead code (3 unused methods)
**Behavior Changes**: None (all tests pass unchanged)
**Atomic Spec Impact**: None (all Test Evidence in as-001, as-002, as-003 still valid)
Tests define correct behavior. You do NOT modify tests unless:
If tests fail after your change:
## Blocked: Insufficient Test Coverage
Target: src/services/legacy-auth.ts
Current coverage: 34%
Required: 80%
**Cannot safely refactor without tests.**
Recommendation: Add tests first (separate task)
## Refactoring Reverted
Change: Extracted validation into separate method
Result: 3 tests failed
Analysis: Tests were asserting on internal method call order
**Recommendation**: Tests need updating to test behavior, not implementation.
This requires explicit approval before proceeding.
## Blocked: Coverage Decreased
Before: 84%
After: 79%
Analysis: Removed dead code that had tests covering unreachable paths
**Options**:
1. Remove obsolete tests (requires approval)
2. Keep dead code (defeats purpose)
Recommendation: Option 1 with careful review
Before refactoring:
/test to add coverage firstAfter refactoring:
/code-review to validate quality improvements/security if changes touch security-sensitive codeSpec group context (when applicable):
Refactoring is typically standalone - not part of feature workflow. However, it may follow a spec group when code review identifies quality improvements.
If you can't prove behavior is preserved (tests pass), don't make the change.
Refactoring is NOT:
If you find bugs during refactoring:
Refactoring scope expands easily. Resist.
# Bad (scope creep)
Started: Refactor OrderService
Also did: Fixed bug in PaymentService
Also did: Updated logging format
# Good (bounded)
Scope: Extract validation logic from OrderService
Done: Extract validation logic from OrderService
Out of scope: Similar issues in PaymentService (logged for future)
Before:
async processOrder(order: Order) {
// 20 lines of validation
if (!order.items) throw new Error('No items');
if (order.items.length === 0) throw new Error('Empty order');
// ... more validation
// 15 lines of calculation
let total = 0;
for (const item of order.items) {
total += item.price * item.quantity;
}
// ... more calculation
// 15 lines of persistence
await this.db.save(order);
// ... more persistence
}
After:
async processOrder(order: Order) {
this.validateOrder(order);
const total = this.calculateTotal(order);
await this.persistOrder(order, total);
}
private validateOrder(order: Order) { /* extracted */ }
private calculateTotal(order: Order) { /* extracted */ }
private async persistOrder(order: Order, total: number) { /* extracted */ }
Validation: All 12 order tests still pass ✓
Request: Refactor legacy payment service
Analysis:
npm test -- --coverage --collectCoverageFrom="src/services/payment.ts"
# Coverage: 23%
Response:
## Blocked: Insufficient Coverage
Cannot safely refactor src/services/payment.ts with 23% coverage.
**Recommendation**:
1. Create separate task to add tests
2. Achieve >80% coverage
3. Then proceed with refactoring
This protects against accidentally changing behavior.Weekly roundup of top Claude Code skills, MCP servers, and AI coding tips.