Loading...
Loading...
Systematic refactoring of codebase components through a structured 3-phase process. Use when asked to refactor, restructure, or improve specific components, modules, or areas of code. Produces research documentation, change proposals with code samples, and test plans. Triggers on requests like "refactor the authentication module", "restructure the data layer", "improve the API handlers", or "clean up the payment service".
npx skill4agent add baggiponte/skills code-refactor./docs/refactoring/./proposals/{output-directory}/
└── {component-name}-refactor/
├── 01-research.md # Phase 1: Component Analysis
├── 02-proposal.md # Phase 2: Change Proposals
└── 03-test-plan.md # Phase 3: Test Strategy{output-directory}/
└── {thread-name}-refactor/
├── component-a/
│ ├── 01-research.md
│ ├── 02-proposal.md
│ └── 03-test-plan.md
└── component-b/
├── 01-research.md
├── 02-proposal.md
└── 03-test-plan.md/codebase-librarian┌─────────────────────────────────────────────────────────────┐
│ CALLERS │
├─────────────────────────────────────────────────────────────┤
│ OrderController.create() ──┐ │
│ OrderController.update() ──┼──► PaymentService │
│ CheckoutWorker.process() ──┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ PaymentService │
├─────────────────────────────────────────────────────────────┤
│ processPayment() │
│ refundPayment() │
│ validateCard() │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ DEPENDENCIES │
├─────────────────────────────────────────────────────────────┤
│ StripeClient │ PaymentRepository │
│ FraudDetectionService │ EventEmitter │
└─────────────────────────────────────────────────────────────┘01-research.md# Research: [Component Name]
**Generated**: [Date]
**Scope**: [Component path/module]
## Executive Summary
[2-3 paragraphs covering:]
- Component's purpose and role in the system
- Key findings about current implementation
- Areas of concern or complexity discovered
## Component Analysis
### Core Behavior
[What the component does, its responsibilities]
### Internal Structure
[Classes, functions, modules that compose it]
### State & Data Flow
[How data moves through the component]
## Instantiation Patterns
| Location | Pattern | Parameters | Frequency |
|----------|---------|------------|-----------|
| `src/api/orders.ts:45` | Direct new | config, logger | 3 places |
| `src/workers/checkout.ts:12` | Factory | config | 1 place |
## Dependency Analysis
### Dependents (Who calls this)
| Caller | Method | Context |
|--------|--------|---------|
| `OrderController` | `processPayment()` | HTTP request handling |
| `CheckoutWorker` | `processPayment()` | Background job |
### Dependencies (What this calls)
| Dependency | Usage | Abstracted? |
|------------|-------|-------------|
| `StripeClient` | Payment processing | No - direct SDK |
| `PaymentRepository` | Persistence | Yes - interface |
### Execution Context
**Before invocation**: [What typically happens before this component is called]
**After invocation**: [What happens with the result]
## Call Graph
[ASCII diagram as shown above]
## Key Observations
- [Notable pattern or concern 1]
- [Notable pattern or concern 2]
- [Areas that may need attention during refactoring]02-proposal.md# Refactoring Proposal: [Component Name]
**Generated**: [Date]
**Based on**: 01-research.md
## Executive Summary
[Overview of proposed changes, expected benefits, and effort distribution]
---
## Quick Wins
### 1. [Change Title]
**Problem**
[What's wrong - reference research findings]
**Solution**
[What to do]
**Before**
```typescript
// src/services/payment.ts:45-52
class PaymentService {
constructor() {
this.stripe = new Stripe(process.env.STRIPE_KEY);
}
}// src/services/payment.ts:45-55
class PaymentService {
constructor(private readonly paymentGateway: PaymentGateway) {}
}
// src/ports/payment-gateway.ts (new)
interface PaymentGateway {
charge(amount: number, currency: string): Promise<ChargeResult>;
}src/services/payment.tssrc/composition-root.tssrc/ports/payment-gateway.ts| Change | Risk Level | Mitigation |
|---|---|---|
| [Change 1] | Low | Existing tests cover behavior |
| [Change 2] | Medium | Add integration tests first |
| [Change 3] | High | Feature flag, gradual rollout |
---
## Phase 3: Test Plan
**Goal**: Design tests that validate refactoring without regressions.
### Analysis Steps
1. **Audit existing tests** - What's already covered?
2. **Identify gaps** - What behavior lacks test coverage?
3. **Design new tests** - Focus on integration over unit tests
4. **Minimize mocks** - Prefer real dependencies when feasible
### Test Philosophy
- **Favor integration tests** - Test real interactions between components
- **Use mocks sparingly** - Only for external services, not internal dependencies
- **Test behavior, not implementation** - Tests should survive refactoring
- **Cover edge cases discovered in research** - Use Phase 1 findings
### Test Plan Output Format
Write to `03-test-plan.md`:
```markdown
# Test Plan: [Component Name] Refactoring
**Generated**: [Date]
**Based on**: 01-research.md, 02-proposal.md
## Executive Summary
[Overview of testing strategy and coverage goals]
## Current Test Coverage
### Existing Tests
| Test File | Type | Coverage | Notes |
|-----------|------|----------|-------|
| `payment.test.ts` | Unit | Core payment flow | Heavy mocking |
| `checkout.integration.ts` | Integration | Happy path only | No error cases |
### Coverage Gaps
- [ ] Error handling in `processPayment()`
- [ ] Concurrent payment attempts
- [ ] Retry behavior after transient failures
## Test Strategy
### Integration Tests (Preferred)
Tests that exercise real component interactions:
**Test: Payment processing end-to-end**
```typescript
// tests/integration/payment.test.ts
describe('PaymentService', () => {
let service: PaymentService;
let testDb: TestDatabase;
beforeEach(async () => {
testDb = await TestDatabase.create();
service = new PaymentService(
new StripeTestGateway(), // Test mode, real API
new PaymentRepository(testDb)
);
});
it('processes payment and persists record', async () => {
const result = await service.processPayment({
amount: 1000,
currency: 'usd',
customerId: 'cust_123'
});
expect(result.status).toBe('succeeded');
const record = await testDb.payments.findById(result.id);
expect(record).toBeDefined();
expect(record.amount).toBe(1000);
});
});// tests/unit/fraud-detection.test.ts
describe('FraudDetector', () => {
it('flags high-risk transactions', () => {
const detector = new FraudDetector();
const result = detector.assess({
amount: 10000,
newCustomer: true,
internationalCard: true
});
expect(result.riskLevel).toBe('high');
expect(result.requiresReview).toBe(true);
});
});| Test | Type | Purpose |
|---|---|---|
| Contract | Verify adapter implements interface correctly |
| Unit | Verify service works with any gateway |
// tests/contract/payment-gateway.test.ts
describe('PaymentGateway contract', () => {
const adapters = [
['Stripe', () => new StripePaymentAdapter(stripeTestClient)],
['Mock', () => new MockPaymentAdapter()],
];
test.each(adapters)('%s adapter implements contract', (name, createAdapter) => {
const adapter = createAdapter();
expect(adapter.charge).toBeDefined();
expect(adapter.refund).toBeDefined();
});
});
---
## References
For detailed guidance on each phase:
- **Phase 1 deep dive**: See [references/research-phase.md](references/research-phase.md) for advanced research techniques
- **Phase 2 patterns**: See [references/proposal-phase.md](references/proposal-phase.md) for common refactoring patterns
- **Phase 3 testing**: See [references/test-plan-phase.md](references/test-plan-phase.md) for test design patterns