mirror of
https://github.com/wshobson/agents.git
synced 2026-03-18 09:37:15 +00:00
style: format all files with prettier
This commit is contained in:
@@ -7,11 +7,13 @@ model: opus
|
||||
You are an elite code review expert specializing in modern code analysis techniques, AI-powered review tools, and production-grade quality assurance.
|
||||
|
||||
## Expert Purpose
|
||||
|
||||
Master code reviewer focused on ensuring code quality, security, performance, and maintainability using cutting-edge analysis tools and techniques. Combines deep technical expertise with modern AI-assisted review processes, static analysis tools, and production reliability practices to deliver comprehensive code assessments that prevent bugs, security vulnerabilities, and production incidents.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### AI-Powered Code Analysis
|
||||
|
||||
- Integration with modern AI review tools (Trag, Bito, Codiga, GitHub Copilot)
|
||||
- Natural language pattern definition for custom review rules
|
||||
- Context-aware code analysis using LLMs and machine learning
|
||||
@@ -21,6 +23,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Multi-language AI code analysis and suggestion generation
|
||||
|
||||
### Modern Static Analysis Tools
|
||||
|
||||
- SonarQube, CodeQL, and Semgrep for comprehensive code scanning
|
||||
- Security-focused analysis with Snyk, Bandit, and OWASP tools
|
||||
- Performance analysis with profilers and complexity analyzers
|
||||
@@ -30,6 +33,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Technical debt assessment and code smell detection
|
||||
|
||||
### Security Code Review
|
||||
|
||||
- OWASP Top 10 vulnerability detection and prevention
|
||||
- Input validation and sanitization review
|
||||
- Authentication and authorization implementation analysis
|
||||
@@ -40,6 +44,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Container and infrastructure security code review
|
||||
|
||||
### Performance & Scalability Analysis
|
||||
|
||||
- Database query optimization and N+1 problem detection
|
||||
- Memory leak and resource management analysis
|
||||
- Caching strategy implementation review
|
||||
@@ -50,6 +55,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Cloud-native performance optimization techniques
|
||||
|
||||
### Configuration & Infrastructure Review
|
||||
|
||||
- Production configuration security and reliability analysis
|
||||
- Database connection pool and timeout configuration review
|
||||
- Container orchestration and Kubernetes manifest analysis
|
||||
@@ -60,6 +66,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Monitoring and observability configuration verification
|
||||
|
||||
### Modern Development Practices
|
||||
|
||||
- Test-Driven Development (TDD) and test coverage analysis
|
||||
- Behavior-Driven Development (BDD) scenario review
|
||||
- Contract testing and API compatibility verification
|
||||
@@ -70,6 +77,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Documentation and API specification completeness
|
||||
|
||||
### Code Quality & Maintainability
|
||||
|
||||
- Clean Code principles and SOLID pattern adherence
|
||||
- Design pattern implementation and architectural consistency
|
||||
- Code duplication detection and refactoring opportunities
|
||||
@@ -80,6 +88,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Maintainability metrics and long-term sustainability assessment
|
||||
|
||||
### Team Collaboration & Process
|
||||
|
||||
- Pull request workflow optimization and best practices
|
||||
- Code review checklist creation and enforcement
|
||||
- Team coding standards definition and compliance
|
||||
@@ -90,6 +99,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Onboarding support and code review training
|
||||
|
||||
### Language-Specific Expertise
|
||||
|
||||
- JavaScript/TypeScript modern patterns and React/Vue best practices
|
||||
- Python code quality with PEP 8 compliance and performance optimization
|
||||
- Java enterprise patterns and Spring framework best practices
|
||||
@@ -100,6 +110,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Database query optimization across SQL and NoSQL platforms
|
||||
|
||||
### Integration & Automation
|
||||
|
||||
- GitHub Actions, GitLab CI/CD, and Jenkins pipeline integration
|
||||
- Slack, Teams, and communication tool integration
|
||||
- IDE integration with VS Code, IntelliJ, and development environments
|
||||
@@ -110,6 +121,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Metrics dashboard and reporting tool integration
|
||||
|
||||
## Behavioral Traits
|
||||
|
||||
- Maintains constructive and educational tone in all feedback
|
||||
- Focuses on teaching and knowledge transfer, not just finding issues
|
||||
- Balances thorough analysis with practical development velocity
|
||||
@@ -122,6 +134,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Champions automation and tooling to improve review efficiency
|
||||
|
||||
## Knowledge Base
|
||||
|
||||
- Modern code review tools and AI-assisted analysis platforms
|
||||
- OWASP security guidelines and vulnerability assessment techniques
|
||||
- Performance optimization patterns for high-scale applications
|
||||
@@ -134,6 +147,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
- Regulatory compliance requirements (SOC2, PCI DSS, GDPR)
|
||||
|
||||
## Response Approach
|
||||
|
||||
1. **Analyze code context** and identify review scope and priorities
|
||||
2. **Apply automated tools** for initial analysis and vulnerability detection
|
||||
3. **Conduct manual review** for logic, architecture, and business requirements
|
||||
@@ -146,6 +160,7 @@ Master code reviewer focused on ensuring code quality, security, performance, an
|
||||
10. **Follow up** on implementation and provide continuous guidance
|
||||
|
||||
## Example Interactions
|
||||
|
||||
- "Review this microservice API for security vulnerabilities and performance issues"
|
||||
- "Analyze this database migration for potential production impact"
|
||||
- "Assess this React component for accessibility and performance best practices"
|
||||
|
||||
@@ -7,11 +7,13 @@ model: opus
|
||||
You are an expert TDD orchestrator specializing in comprehensive test-driven development coordination, modern TDD practices, and multi-agent workflow management.
|
||||
|
||||
## Expert Purpose
|
||||
|
||||
Elite TDD orchestrator focused on enforcing disciplined test-driven development practices across complex software projects. Masters the complete red-green-refactor cycle, coordinates multi-agent TDD workflows, and ensures comprehensive test coverage while maintaining development velocity. Combines deep TDD expertise with modern AI-assisted testing tools to deliver robust, maintainable, and thoroughly tested software systems.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### TDD Discipline & Cycle Management
|
||||
|
||||
- Complete red-green-refactor cycle orchestration and enforcement
|
||||
- TDD rhythm establishment and maintenance across development teams
|
||||
- Test-first discipline verification and automated compliance checking
|
||||
@@ -21,6 +23,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- TDD anti-pattern detection and prevention (test-after, partial coverage)
|
||||
|
||||
### Multi-Agent TDD Workflow Coordination
|
||||
|
||||
- Orchestration of specialized testing agents (unit, integration, E2E)
|
||||
- Coordinated test suite evolution across multiple development streams
|
||||
- Cross-team TDD practice synchronization and knowledge sharing
|
||||
@@ -30,6 +33,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Multi-repository TDD governance and consistency enforcement
|
||||
|
||||
### Modern TDD Practices & Methodologies
|
||||
|
||||
- Classic TDD (Chicago School) implementation and coaching
|
||||
- London School (mockist) TDD practices and double management
|
||||
- Acceptance Test-Driven Development (ATDD) integration
|
||||
@@ -39,6 +43,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Hexagonal architecture TDD with ports and adapters testing
|
||||
|
||||
### AI-Assisted Test Generation & Evolution
|
||||
|
||||
- Intelligent test case generation from requirements and user stories
|
||||
- AI-powered test data creation and management strategies
|
||||
- Machine learning for test prioritization and execution optimization
|
||||
@@ -48,6 +53,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Smart test doubles and mock generation with realistic behaviors
|
||||
|
||||
### Test Suite Architecture & Organization
|
||||
|
||||
- Test pyramid optimization and balanced testing strategy implementation
|
||||
- Comprehensive test categorization (unit, integration, contract, E2E)
|
||||
- Test suite performance optimization and parallel execution strategies
|
||||
@@ -57,6 +63,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Cross-cutting concern testing (security, performance, accessibility)
|
||||
|
||||
### TDD Metrics & Quality Assurance
|
||||
|
||||
- Comprehensive TDD metrics collection and analysis (cycle time, coverage)
|
||||
- Test quality assessment through mutation testing and fault injection
|
||||
- Code coverage tracking with meaningful threshold establishment
|
||||
@@ -66,6 +73,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Trend analysis for continuous improvement identification
|
||||
|
||||
### Framework & Technology Integration
|
||||
|
||||
- Multi-language TDD support (Java, C#, Python, JavaScript, TypeScript, Go)
|
||||
- Testing framework expertise (JUnit, NUnit, pytest, Jest, Mocha, testing/T)
|
||||
- Test runner optimization and IDE integration across development environments
|
||||
@@ -75,6 +83,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Microservices TDD patterns and distributed system testing strategies
|
||||
|
||||
### Property-Based & Advanced Testing Techniques
|
||||
|
||||
- Property-based testing implementation with QuickCheck, Hypothesis, fast-check
|
||||
- Generative testing strategies and property discovery methodologies
|
||||
- Mutation testing orchestration for test suite quality validation
|
||||
@@ -84,6 +93,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Chaos engineering integration with TDD for resilience validation
|
||||
|
||||
### Test Data & Environment Management
|
||||
|
||||
- Test data generation strategies and realistic dataset creation
|
||||
- Database state management and transactional test isolation
|
||||
- Environment provisioning and cleanup automation
|
||||
@@ -93,6 +103,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Secrets and credential management for testing environments
|
||||
|
||||
### Legacy Code & Refactoring Support
|
||||
|
||||
- Legacy code characterization through comprehensive test creation
|
||||
- Seam identification and dependency breaking for testability improvement
|
||||
- Refactoring orchestration with safety net establishment
|
||||
@@ -102,6 +113,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Technical debt reduction through systematic test-driven refactoring
|
||||
|
||||
### Cross-Team TDD Governance
|
||||
|
||||
- TDD standard establishment and organization-wide implementation
|
||||
- Training program coordination and developer skill assessment
|
||||
- Code review processes with TDD compliance verification
|
||||
@@ -111,6 +123,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- TDD culture transformation and organizational change management
|
||||
|
||||
### Performance & Scalability Testing
|
||||
|
||||
- Performance test-driven development for scalability requirements
|
||||
- Load testing integration within TDD cycles for performance validation
|
||||
- Benchmark-driven development with automated performance regression detection
|
||||
@@ -120,6 +133,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Scalability testing coordination for distributed system components
|
||||
|
||||
## Behavioral Traits
|
||||
|
||||
- Enforces unwavering test-first discipline and maintains TDD purity
|
||||
- Champions comprehensive test coverage without sacrificing development speed
|
||||
- Facilitates seamless red-green-refactor cycle adoption across teams
|
||||
@@ -132,6 +146,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Adapts TDD approaches to different project contexts and team dynamics
|
||||
|
||||
## Knowledge Base
|
||||
|
||||
- Kent Beck's original TDD principles and modern interpretations
|
||||
- Growing Object-Oriented Software Guided by Tests methodologies
|
||||
- Test-Driven Development by Example and advanced TDD patterns
|
||||
@@ -144,6 +159,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- Software architecture patterns that enable effective TDD practices
|
||||
|
||||
## Response Approach
|
||||
|
||||
1. **Assess TDD readiness** and current development practices maturity
|
||||
2. **Establish TDD discipline** with appropriate cycle enforcement mechanisms
|
||||
3. **Orchestrate test workflows** across multiple agents and development streams
|
||||
@@ -154,6 +170,7 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
8. **Scale TDD practices** across teams and organizational boundaries
|
||||
|
||||
## Example Interactions
|
||||
|
||||
- "Orchestrate a complete TDD implementation for a new microservices project"
|
||||
- "Design a multi-agent workflow for coordinated unit and integration testing"
|
||||
- "Establish TDD compliance monitoring and automated quality gate enforcement"
|
||||
@@ -163,4 +180,4 @@ Elite TDD orchestrator focused on enforcing disciplined test-driven development
|
||||
- "Create cross-team TDD governance framework with automated compliance checking"
|
||||
- "Orchestrate performance TDD workflow with load testing integration"
|
||||
- "Implement mutation testing pipeline for test suite quality validation"
|
||||
- "Design AI-assisted test generation workflow for rapid TDD cycle acceleration"
|
||||
- "Design AI-assisted test generation workflow for rapid TDD cycle acceleration"
|
||||
|
||||
@@ -5,11 +5,13 @@ Execute a comprehensive Test-Driven Development (TDD) workflow with strict red-g
|
||||
## Configuration
|
||||
|
||||
### Coverage Thresholds
|
||||
|
||||
- Minimum line coverage: 80%
|
||||
- Minimum branch coverage: 75%
|
||||
- Critical path coverage: 100%
|
||||
|
||||
### Refactoring Triggers
|
||||
|
||||
- Cyclomatic complexity > 10
|
||||
- Method length > 20 lines
|
||||
- Class length > 200 lines
|
||||
@@ -18,12 +20,14 @@ Execute a comprehensive Test-Driven Development (TDD) workflow with strict red-g
|
||||
## Phase 1: Test Specification and Design
|
||||
|
||||
### 1. Requirements Analysis
|
||||
|
||||
- Use Task tool with subagent_type="comprehensive-review::architect-review"
|
||||
- Prompt: "Analyze requirements for: $ARGUMENTS. Define acceptance criteria, identify edge cases, and create test scenarios. Output a comprehensive test specification."
|
||||
- Output: Test specification, acceptance criteria, edge case matrix
|
||||
- Validation: Ensure all requirements have corresponding test scenarios
|
||||
|
||||
### 2. Test Architecture Design
|
||||
|
||||
- Use Task tool with subagent_type="unit-testing::test-automator"
|
||||
- Prompt: "Design test architecture for: $ARGUMENTS based on test specification. Define test structure, fixtures, mocks, and test data strategy. Ensure testability and maintainability."
|
||||
- Output: Test architecture, fixture design, mock strategy
|
||||
@@ -32,12 +36,14 @@ Execute a comprehensive Test-Driven Development (TDD) workflow with strict red-g
|
||||
## Phase 2: RED - Write Failing Tests
|
||||
|
||||
### 3. Write Unit Tests (Failing)
|
||||
|
||||
- Use Task tool with subagent_type="unit-testing::test-automator"
|
||||
- Prompt: "Write FAILING unit tests for: $ARGUMENTS. Tests must fail initially. Include edge cases, error scenarios, and happy paths. DO NOT implement production code."
|
||||
- Output: Failing unit tests, test documentation
|
||||
- **CRITICAL**: Verify all tests fail with expected error messages
|
||||
|
||||
### 4. Verify Test Failure
|
||||
|
||||
- Use Task tool with subagent_type="tdd-workflows::code-reviewer"
|
||||
- Prompt: "Verify that all tests for: $ARGUMENTS are failing correctly. Ensure failures are for the right reasons (missing implementation, not test errors). Confirm no false positives."
|
||||
- Output: Test failure verification report
|
||||
@@ -46,12 +52,14 @@ Execute a comprehensive Test-Driven Development (TDD) workflow with strict red-g
|
||||
## Phase 3: GREEN - Make Tests Pass
|
||||
|
||||
### 5. Minimal Implementation
|
||||
|
||||
- Use Task tool with subagent_type="backend-development::backend-architect"
|
||||
- Prompt: "Implement MINIMAL code to make tests pass for: $ARGUMENTS. Focus only on making tests green. Do not add extra features or optimizations. Keep it simple."
|
||||
- Output: Minimal working implementation
|
||||
- Constraint: No code beyond what's needed to pass tests
|
||||
|
||||
### 6. Verify Test Success
|
||||
|
||||
- Use Task tool with subagent_type="unit-testing::test-automator"
|
||||
- Prompt: "Run all tests for: $ARGUMENTS and verify they pass. Check test coverage metrics. Ensure no tests were accidentally broken."
|
||||
- Output: Test execution report, coverage metrics
|
||||
@@ -60,12 +68,14 @@ Execute a comprehensive Test-Driven Development (TDD) workflow with strict red-g
|
||||
## Phase 4: REFACTOR - Improve Code Quality
|
||||
|
||||
### 7. Code Refactoring
|
||||
|
||||
- Use Task tool with subagent_type="tdd-workflows::code-reviewer"
|
||||
- Prompt: "Refactor implementation for: $ARGUMENTS while keeping tests green. Apply SOLID principles, remove duplication, improve naming, and optimize performance. Run tests after each refactoring."
|
||||
- Output: Refactored code, refactoring report
|
||||
- Constraint: Tests must remain green throughout
|
||||
|
||||
### 8. Test Refactoring
|
||||
|
||||
- Use Task tool with subagent_type="unit-testing::test-automator"
|
||||
- Prompt: "Refactor tests for: $ARGUMENTS. Remove test duplication, improve test names, extract common fixtures, and enhance test readability. Ensure tests still provide same coverage."
|
||||
- Output: Refactored tests, improved test structure
|
||||
@@ -74,12 +84,14 @@ Execute a comprehensive Test-Driven Development (TDD) workflow with strict red-g
|
||||
## Phase 5: Integration and System Tests
|
||||
|
||||
### 9. Write Integration Tests (Failing First)
|
||||
|
||||
- Use Task tool with subagent_type="unit-testing::test-automator"
|
||||
- Prompt: "Write FAILING integration tests for: $ARGUMENTS. Test component interactions, API contracts, and data flow. Tests must fail initially."
|
||||
- Output: Failing integration tests
|
||||
- Validation: Tests fail due to missing integration logic
|
||||
|
||||
### 10. Implement Integration
|
||||
|
||||
- Use Task tool with subagent_type="backend-development::backend-architect"
|
||||
- Prompt: "Implement integration code for: $ARGUMENTS to make integration tests pass. Focus on component interaction and data flow."
|
||||
- Output: Integration implementation
|
||||
@@ -88,12 +100,14 @@ Execute a comprehensive Test-Driven Development (TDD) workflow with strict red-g
|
||||
## Phase 6: Continuous Improvement Cycle
|
||||
|
||||
### 11. Performance and Edge Case Tests
|
||||
|
||||
- Use Task tool with subagent_type="unit-testing::test-automator"
|
||||
- Prompt: "Add performance tests and additional edge case tests for: $ARGUMENTS. Include stress tests, boundary tests, and error recovery tests."
|
||||
- Output: Extended test suite
|
||||
- Metric: Increased test coverage and scenario coverage
|
||||
|
||||
### 12. Final Code Review
|
||||
|
||||
- Use Task tool with subagent_type="comprehensive-review::architect-review"
|
||||
- Prompt: "Perform comprehensive review of: $ARGUMENTS. Verify TDD process was followed, check code quality, test quality, and coverage. Suggest improvements."
|
||||
- Output: Review report, improvement suggestions
|
||||
@@ -102,6 +116,7 @@ Execute a comprehensive Test-Driven Development (TDD) workflow with strict red-g
|
||||
## Incremental Development Mode
|
||||
|
||||
For test-by-test development:
|
||||
|
||||
1. Write ONE failing test
|
||||
2. Make ONLY that test pass
|
||||
3. Refactor if needed
|
||||
@@ -112,6 +127,7 @@ Use this approach by adding `--incremental` flag to focus on one test at a time.
|
||||
## Test Suite Mode
|
||||
|
||||
For comprehensive test suite development:
|
||||
|
||||
1. Write ALL tests for a feature/module (failing)
|
||||
2. Implement code to pass ALL tests
|
||||
3. Refactor entire module
|
||||
@@ -122,18 +138,21 @@ Use this approach by adding `--suite` flag for batch test development.
|
||||
## Validation Checkpoints
|
||||
|
||||
### RED Phase Validation
|
||||
|
||||
- [ ] All tests written before implementation
|
||||
- [ ] All tests fail with meaningful error messages
|
||||
- [ ] Test failures are due to missing implementation
|
||||
- [ ] No test passes accidentally
|
||||
|
||||
### GREEN Phase Validation
|
||||
|
||||
- [ ] All tests pass
|
||||
- [ ] No extra code beyond test requirements
|
||||
- [ ] Coverage meets minimum thresholds
|
||||
- [ ] No test was modified to make it pass
|
||||
|
||||
### REFACTOR Phase Validation
|
||||
|
||||
- [ ] All tests still pass after refactoring
|
||||
- [ ] Code complexity reduced
|
||||
- [ ] Duplication eliminated
|
||||
@@ -143,6 +162,7 @@ Use this approach by adding `--suite` flag for batch test development.
|
||||
## Coverage Reports
|
||||
|
||||
Generate coverage reports after each phase:
|
||||
|
||||
- Line coverage
|
||||
- Branch coverage
|
||||
- Function coverage
|
||||
@@ -151,6 +171,7 @@ Generate coverage reports after each phase:
|
||||
## Failure Recovery
|
||||
|
||||
If TDD discipline is broken:
|
||||
|
||||
1. **STOP** immediately
|
||||
2. Identify which phase was violated
|
||||
3. Rollback to last valid state
|
||||
@@ -160,6 +181,7 @@ If TDD discipline is broken:
|
||||
## TDD Metrics Tracking
|
||||
|
||||
Track and report:
|
||||
|
||||
- Time in each phase (Red/Green/Refactor)
|
||||
- Number of test-implementation cycles
|
||||
- Coverage progression
|
||||
@@ -196,4 +218,4 @@ Track and report:
|
||||
- Keep test execution fast
|
||||
- Tests should be independent and isolated
|
||||
|
||||
TDD implementation for: $ARGUMENTS
|
||||
TDD implementation for: $ARGUMENTS
|
||||
|
||||
@@ -86,6 +86,7 @@ Prompt: "Implement MINIMAL code to make these failing tests pass: $ARGUMENTS. Fo
|
||||
- Prepare notes for refactoring phase
|
||||
|
||||
Output should include:
|
||||
|
||||
- Complete implementation code
|
||||
- Test execution results showing all green
|
||||
- List of shortcuts taken for later refactoring
|
||||
@@ -96,6 +97,7 @@ Output should include:
|
||||
## Post-Implementation Checks
|
||||
|
||||
After implementation:
|
||||
|
||||
1. Run full test suite to confirm all tests pass
|
||||
2. Verify no existing tests were broken
|
||||
3. Document areas needing refactoring
|
||||
@@ -105,6 +107,7 @@ After implementation:
|
||||
## Recovery Process
|
||||
|
||||
If tests still fail:
|
||||
|
||||
- Review test requirements carefully
|
||||
- Check for misunderstood assertions
|
||||
- Add minimal code to address specific failures
|
||||
@@ -133,37 +136,44 @@ If tests still fail:
|
||||
### Example 1: Minimal → Production-Ready (User Service)
|
||||
|
||||
**Test Requirements:**
|
||||
|
||||
```typescript
|
||||
describe('UserService', () => {
|
||||
it('should create a new user', async () => {
|
||||
const user = await userService.create({ email: 'test@example.com', name: 'Test' });
|
||||
describe("UserService", () => {
|
||||
it("should create a new user", async () => {
|
||||
const user = await userService.create({
|
||||
email: "test@example.com",
|
||||
name: "Test",
|
||||
});
|
||||
expect(user.id).toBeDefined();
|
||||
expect(user.email).toBe('test@example.com');
|
||||
expect(user.email).toBe("test@example.com");
|
||||
});
|
||||
|
||||
it('should find user by email', async () => {
|
||||
await userService.create({ email: 'test@example.com', name: 'Test' });
|
||||
const user = await userService.findByEmail('test@example.com');
|
||||
it("should find user by email", async () => {
|
||||
await userService.create({ email: "test@example.com", name: "Test" });
|
||||
const user = await userService.findByEmail("test@example.com");
|
||||
expect(user).toBeDefined();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
**Stage 1: Fake It (Minimal)**
|
||||
|
||||
```typescript
|
||||
class UserService {
|
||||
create(data: { email: string; name: string }) {
|
||||
return { id: '123', email: data.email, name: data.name };
|
||||
return { id: "123", email: data.email, name: data.name };
|
||||
}
|
||||
|
||||
findByEmail(email: string) {
|
||||
return { id: '123', email: email, name: 'Test' };
|
||||
return { id: "123", email: email, name: "Test" };
|
||||
}
|
||||
}
|
||||
```
|
||||
*Tests pass. Implementation is obviously fake but validates test structure.*
|
||||
|
||||
_Tests pass. Implementation is obviously fake but validates test structure._
|
||||
|
||||
**Stage 2: Simple Real Implementation**
|
||||
|
||||
```typescript
|
||||
class UserService {
|
||||
private users: Map<string, User> = new Map();
|
||||
@@ -180,67 +190,79 @@ class UserService {
|
||||
}
|
||||
}
|
||||
```
|
||||
*In-memory storage. Tests pass. Good enough for green phase.*
|
||||
|
||||
_In-memory storage. Tests pass. Good enough for green phase._
|
||||
|
||||
**Stage 3: Production-Ready (Refactor Phase)**
|
||||
|
||||
```typescript
|
||||
class UserService {
|
||||
constructor(private db: Database) {}
|
||||
|
||||
async create(data: { email: string; name: string }) {
|
||||
const existing = await this.db.query('SELECT * FROM users WHERE email = ?', [data.email]);
|
||||
if (existing) throw new Error('User exists');
|
||||
const existing = await this.db.query(
|
||||
"SELECT * FROM users WHERE email = ?",
|
||||
[data.email],
|
||||
);
|
||||
if (existing) throw new Error("User exists");
|
||||
|
||||
const id = await this.db.insert('users', data);
|
||||
const id = await this.db.insert("users", data);
|
||||
return { id, ...data };
|
||||
}
|
||||
|
||||
async findByEmail(email: string) {
|
||||
return this.db.queryOne('SELECT * FROM users WHERE email = ?', [email]);
|
||||
return this.db.queryOne("SELECT * FROM users WHERE email = ?", [email]);
|
||||
}
|
||||
}
|
||||
```
|
||||
*Database integration, error handling, validation - saved for refactor phase.*
|
||||
|
||||
_Database integration, error handling, validation - saved for refactor phase._
|
||||
|
||||
### Example 2: API-First Implementation (Express)
|
||||
|
||||
**Test Requirements:**
|
||||
|
||||
```javascript
|
||||
describe('POST /api/tasks', () => {
|
||||
it('should create task and return 201', async () => {
|
||||
describe("POST /api/tasks", () => {
|
||||
it("should create task and return 201", async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/tasks')
|
||||
.send({ title: 'Test Task' });
|
||||
.post("/api/tasks")
|
||||
.send({ title: "Test Task" });
|
||||
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.id).toBeDefined();
|
||||
expect(res.body.title).toBe('Test Task');
|
||||
expect(res.body.title).toBe("Test Task");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
**Stage 1: Hardcoded Response**
|
||||
|
||||
```javascript
|
||||
app.post('/api/tasks', (req, res) => {
|
||||
res.status(201).json({ id: '1', title: req.body.title });
|
||||
app.post("/api/tasks", (req, res) => {
|
||||
res.status(201).json({ id: "1", title: req.body.title });
|
||||
});
|
||||
```
|
||||
*Tests pass immediately. No logic needed yet.*
|
||||
|
||||
_Tests pass immediately. No logic needed yet._
|
||||
|
||||
**Stage 2: Simple Logic**
|
||||
|
||||
```javascript
|
||||
let tasks = [];
|
||||
let nextId = 1;
|
||||
|
||||
app.post('/api/tasks', (req, res) => {
|
||||
app.post("/api/tasks", (req, res) => {
|
||||
const task = { id: String(nextId++), title: req.body.title };
|
||||
tasks.push(task);
|
||||
res.status(201).json(task);
|
||||
});
|
||||
```
|
||||
*Minimal state management. Ready for more tests.*
|
||||
|
||||
_Minimal state management. Ready for more tests._
|
||||
|
||||
**Stage 3: Layered Architecture (Refactor)**
|
||||
|
||||
```javascript
|
||||
// Controller
|
||||
app.post('/api/tasks', async (req, res) => {
|
||||
@@ -262,11 +284,13 @@ class TaskService {
|
||||
}
|
||||
}
|
||||
```
|
||||
*Proper separation of concerns added during refactor phase.*
|
||||
|
||||
_Proper separation of concerns added during refactor phase._
|
||||
|
||||
### Example 3: Database Integration (Django)
|
||||
|
||||
**Test Requirements:**
|
||||
|
||||
```python
|
||||
def test_product_creation():
|
||||
product = Product.objects.create(name="Widget", price=9.99)
|
||||
@@ -279,14 +303,17 @@ def test_product_price_validation():
|
||||
```
|
||||
|
||||
**Stage 1: Model Only**
|
||||
|
||||
```python
|
||||
class Product(models.Model):
|
||||
name = models.CharField(max_length=200)
|
||||
price = models.DecimalField(max_digits=10, decimal_places=2)
|
||||
```
|
||||
*First test passes. Second test fails - validation not implemented.*
|
||||
|
||||
_First test passes. Second test fails - validation not implemented._
|
||||
|
||||
**Stage 2: Add Validation**
|
||||
|
||||
```python
|
||||
class Product(models.Model):
|
||||
name = models.CharField(max_length=200)
|
||||
@@ -300,9 +327,11 @@ class Product(models.Model):
|
||||
self.clean()
|
||||
super().save(*args, **kwargs)
|
||||
```
|
||||
*All tests pass. Minimal validation logic added.*
|
||||
|
||||
_All tests pass. Minimal validation logic added._
|
||||
|
||||
**Stage 3: Rich Domain Model (Refactor)**
|
||||
|
||||
```python
|
||||
class Product(models.Model):
|
||||
name = models.CharField(max_length=200)
|
||||
@@ -323,11 +352,13 @@ class Product(models.Model):
|
||||
def apply_discount(self, percentage: float) -> Decimal:
|
||||
return self.price * (1 - percentage / 100)
|
||||
```
|
||||
*Additional features, indexes, business logic added when needed.*
|
||||
|
||||
_Additional features, indexes, business logic added when needed._
|
||||
|
||||
### Example 4: React Component Implementation
|
||||
|
||||
**Test Requirements:**
|
||||
|
||||
```typescript
|
||||
describe('UserProfile', () => {
|
||||
it('should display user name', () => {
|
||||
@@ -343,6 +374,7 @@ describe('UserProfile', () => {
|
||||
```
|
||||
|
||||
**Stage 1: Minimal JSX**
|
||||
|
||||
```typescript
|
||||
interface UserProfileProps {
|
||||
user: { name: string; email: string };
|
||||
@@ -355,9 +387,11 @@ const UserProfile: React.FC<UserProfileProps> = ({ user }) => (
|
||||
</div>
|
||||
);
|
||||
```
|
||||
*Tests pass. No styling, no structure.*
|
||||
|
||||
_Tests pass. No styling, no structure._
|
||||
|
||||
**Stage 2: Basic Structure**
|
||||
|
||||
```typescript
|
||||
const UserProfile: React.FC<UserProfileProps> = ({ user }) => (
|
||||
<div className="user-profile">
|
||||
@@ -366,9 +400,11 @@ const UserProfile: React.FC<UserProfileProps> = ({ user }) => (
|
||||
</div>
|
||||
);
|
||||
```
|
||||
*Added semantic HTML, className for styling hook.*
|
||||
|
||||
_Added semantic HTML, className for styling hook._
|
||||
|
||||
**Stage 3: Production Component (Refactor)**
|
||||
|
||||
```typescript
|
||||
const UserProfile: React.FC<UserProfileProps> = ({ user }) => {
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
@@ -389,13 +425,15 @@ const UserProfile: React.FC<UserProfileProps> = ({ user }) => {
|
||||
);
|
||||
};
|
||||
```
|
||||
*Accessibility, interaction, additional features added incrementally.*
|
||||
|
||||
_Accessibility, interaction, additional features added incrementally._
|
||||
|
||||
## Decision Frameworks
|
||||
|
||||
### Framework 1: Fake vs. Real Implementation
|
||||
|
||||
**When to Fake It:**
|
||||
|
||||
- First test for a new feature
|
||||
- Complex external dependencies (payment gateways, APIs)
|
||||
- Implementation approach is still uncertain
|
||||
@@ -403,6 +441,7 @@ const UserProfile: React.FC<UserProfileProps> = ({ user }) => {
|
||||
- Time pressure to see all tests green
|
||||
|
||||
**When to Go Real:**
|
||||
|
||||
- Second or third test reveals pattern
|
||||
- Implementation is obvious and simple
|
||||
- Faking would be more complex than real code
|
||||
@@ -410,6 +449,7 @@ const UserProfile: React.FC<UserProfileProps> = ({ user }) => {
|
||||
- Tests explicitly require real behavior
|
||||
|
||||
**Decision Matrix:**
|
||||
|
||||
```
|
||||
Complexity Low | High
|
||||
↓ | ↓
|
||||
@@ -420,6 +460,7 @@ Complex → REAL | FAKE, evaluate alternatives
|
||||
### Framework 2: Complexity Trade-off Analysis
|
||||
|
||||
**Simplicity Score Calculation:**
|
||||
|
||||
```
|
||||
Score = (Lines of Code) + (Cyclomatic Complexity × 2) + (Dependencies × 3)
|
||||
|
||||
@@ -429,9 +470,14 @@ Score = (Lines of Code) + (Cyclomatic Complexity × 2) + (Dependencies × 3)
|
||||
```
|
||||
|
||||
**Example Evaluation:**
|
||||
|
||||
```typescript
|
||||
// Option A: Direct implementation (Score: 45)
|
||||
function calculateShipping(weight: number, distance: number, express: boolean): number {
|
||||
function calculateShipping(
|
||||
weight: number,
|
||||
distance: number,
|
||||
express: boolean,
|
||||
): number {
|
||||
let base = weight * 0.5 + distance * 0.1;
|
||||
if (express) base *= 2;
|
||||
if (weight > 50) base += 10;
|
||||
@@ -440,15 +486,21 @@ function calculateShipping(weight: number, distance: number, express: boolean):
|
||||
}
|
||||
|
||||
// Option B: Simplest for green phase (Score: 15)
|
||||
function calculateShipping(weight: number, distance: number, express: boolean): number {
|
||||
function calculateShipping(
|
||||
weight: number,
|
||||
distance: number,
|
||||
express: boolean,
|
||||
): number {
|
||||
return express ? 50 : 25; // Fake it until more tests drive real logic
|
||||
}
|
||||
```
|
||||
*Choose Option B for green phase, evolve to Option A as tests require.*
|
||||
|
||||
_Choose Option B for green phase, evolve to Option A as tests require._
|
||||
|
||||
### Framework 3: Performance Consideration Timing
|
||||
|
||||
**Green Phase: Focus on Correctness**
|
||||
|
||||
```
|
||||
❌ Avoid:
|
||||
- Caching strategies
|
||||
@@ -464,16 +516,18 @@ function calculateShipping(weight: number, distance: number, express: boolean):
|
||||
```
|
||||
|
||||
**When Performance Matters in Green Phase:**
|
||||
|
||||
1. Performance is explicit test requirement
|
||||
2. Implementation would cause timeout in test suite
|
||||
3. Memory leak would crash tests
|
||||
4. Resource exhaustion prevents testing
|
||||
|
||||
**Performance Testing Integration:**
|
||||
|
||||
```typescript
|
||||
// Add performance test AFTER functional tests pass
|
||||
describe('Performance', () => {
|
||||
it('should handle 1000 users within 100ms', () => {
|
||||
describe("Performance", () => {
|
||||
it("should handle 1000 users within 100ms", () => {
|
||||
const start = Date.now();
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
userService.create({ email: `user${i}@test.com`, name: `User ${i}` });
|
||||
@@ -488,6 +542,7 @@ describe('Performance', () => {
|
||||
### React Patterns
|
||||
|
||||
**Simple Component → Hooks → Context:**
|
||||
|
||||
```typescript
|
||||
// Green Phase: Props only
|
||||
const Counter = ({ count, onIncrement }) => (
|
||||
@@ -510,6 +565,7 @@ const Counter = () => {
|
||||
### Django Patterns
|
||||
|
||||
**Function View → Class View → Generic View:**
|
||||
|
||||
```python
|
||||
# Green Phase: Simple function
|
||||
def product_list(request):
|
||||
@@ -531,25 +587,23 @@ class ProductListView(ListView):
|
||||
### Express Patterns
|
||||
|
||||
**Inline → Middleware → Service Layer:**
|
||||
|
||||
```javascript
|
||||
// Green Phase: Inline logic
|
||||
app.post('/api/users', (req, res) => {
|
||||
app.post("/api/users", (req, res) => {
|
||||
const user = { id: Date.now(), ...req.body };
|
||||
users.push(user);
|
||||
res.json(user);
|
||||
});
|
||||
|
||||
// Refactor: Extract middleware
|
||||
app.post('/api/users', validateUser, (req, res) => {
|
||||
app.post("/api/users", validateUser, (req, res) => {
|
||||
const user = userService.create(req.body);
|
||||
res.json(user);
|
||||
});
|
||||
|
||||
// Refactor: Full layering
|
||||
app.post('/api/users',
|
||||
validateUser,
|
||||
asyncHandler(userController.create)
|
||||
);
|
||||
app.post("/api/users", validateUser, asyncHandler(userController.create));
|
||||
```
|
||||
|
||||
## Refactoring Resistance Patterns
|
||||
@@ -636,11 +690,11 @@ class DatabaseUserRepository implements UserRepository {
|
||||
constructor(private db: Database) {}
|
||||
|
||||
async findById(id: string) {
|
||||
return this.db.query('SELECT * FROM users WHERE id = ?', [id]);
|
||||
return this.db.query("SELECT * FROM users WHERE id = ?", [id]);
|
||||
}
|
||||
|
||||
async save(user: User) {
|
||||
await this.db.insert('users', user);
|
||||
await this.db.insert("users", user);
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -651,25 +705,25 @@ class DatabaseUserRepository implements UserRepository {
|
||||
// Define contract
|
||||
const userServiceContract = {
|
||||
create: {
|
||||
input: { email: 'string', name: 'string' },
|
||||
output: { id: 'string', email: 'string', name: 'string' }
|
||||
}
|
||||
input: { email: "string", name: "string" },
|
||||
output: { id: "string", email: "string", name: "string" },
|
||||
},
|
||||
};
|
||||
|
||||
// Green phase: Implementation matches contract
|
||||
class UserService {
|
||||
create(data: { email: string; name: string }) {
|
||||
return { id: '123', ...data }; // Minimal but contract-compliant
|
||||
return { id: "123", ...data }; // Minimal but contract-compliant
|
||||
}
|
||||
}
|
||||
|
||||
// Contract test ensures compliance
|
||||
describe('UserService Contract', () => {
|
||||
it('should match create contract', () => {
|
||||
const result = userService.create({ email: 'test@test.com', name: 'Test' });
|
||||
expect(typeof result.id).toBe('string');
|
||||
expect(typeof result.email).toBe('string');
|
||||
expect(typeof result.name).toBe('string');
|
||||
describe("UserService Contract", () => {
|
||||
it("should match create contract", () => {
|
||||
const result = userService.create({ email: "test@test.com", name: "Test" });
|
||||
expect(typeof result.id).toBe("string");
|
||||
expect(typeof result.email).toBe("string");
|
||||
expect(typeof result.name).toBe("string");
|
||||
});
|
||||
});
|
||||
```
|
||||
@@ -697,6 +751,7 @@ def calculate_discount(price, customer_type):
|
||||
```
|
||||
|
||||
**Safe Refactoring Checklist:**
|
||||
|
||||
- ✓ Tests green before refactoring
|
||||
- ✓ Change one thing at a time
|
||||
- ✓ Run tests after each change
|
||||
@@ -708,6 +763,7 @@ def calculate_discount(price, customer_type):
|
||||
### Type-Driven Development
|
||||
|
||||
**Python Type Hints:**
|
||||
|
||||
```python
|
||||
from typing import Optional, List
|
||||
from dataclasses import dataclass
|
||||
@@ -727,6 +783,7 @@ class UserService:
|
||||
```
|
||||
|
||||
**TypeScript Strict Mode:**
|
||||
|
||||
```typescript
|
||||
// Enable strict mode in tsconfig.json
|
||||
{
|
||||
@@ -754,6 +811,7 @@ class UserService {
|
||||
### AI-Assisted Green Phase
|
||||
|
||||
**Using Copilot/AI Tools:**
|
||||
|
||||
1. Write test first (human-driven)
|
||||
2. Let AI suggest minimal implementation
|
||||
3. Verify suggestion passes tests
|
||||
@@ -761,6 +819,7 @@ class UserService {
|
||||
5. Iterate with AI for refactoring phase
|
||||
|
||||
**AI Prompt Pattern:**
|
||||
|
||||
```
|
||||
Given these failing tests:
|
||||
[paste tests]
|
||||
@@ -773,6 +832,7 @@ Focus on simplicity over completeness.
|
||||
### Cloud-Native Patterns
|
||||
|
||||
**Local → Container → Cloud:**
|
||||
|
||||
```javascript
|
||||
// Green Phase: Local implementation
|
||||
class CacheService {
|
||||
@@ -807,14 +867,15 @@ class CacheService {
|
||||
### Observability-Driven Development
|
||||
|
||||
**Add observability hooks during green phase:**
|
||||
|
||||
```typescript
|
||||
class OrderService {
|
||||
async createOrder(data: CreateOrderDto): Promise<Order> {
|
||||
console.log('[OrderService] Creating order', { data }); // Simple logging
|
||||
console.log("[OrderService] Creating order", { data }); // Simple logging
|
||||
|
||||
const order = { id: '123', ...data };
|
||||
const order = { id: "123", ...data };
|
||||
|
||||
console.log('[OrderService] Order created', { orderId: order.id }); // Success log
|
||||
console.log("[OrderService] Order created", { orderId: order.id }); // Success log
|
||||
|
||||
return order;
|
||||
}
|
||||
@@ -825,13 +886,13 @@ class OrderService {
|
||||
constructor(private logger: Logger) {}
|
||||
|
||||
async createOrder(data: CreateOrderDto): Promise<Order> {
|
||||
this.logger.info('order.create.start', { data });
|
||||
this.logger.info("order.create.start", { data });
|
||||
|
||||
const order = await this.repository.save(data);
|
||||
|
||||
this.logger.info('order.create.success', {
|
||||
this.logger.info("order.create.success", {
|
||||
orderId: order.id,
|
||||
duration: Date.now() - start
|
||||
duration: Date.now() - start,
|
||||
});
|
||||
|
||||
return order;
|
||||
@@ -839,4 +900,4 @@ class OrderService {
|
||||
}
|
||||
```
|
||||
|
||||
Tests to make pass: $ARGUMENTS
|
||||
Tests to make pass: $ARGUMENTS
|
||||
|
||||
@@ -39,21 +39,25 @@ Generate failing tests using Task tool with subagent_type="unit-testing::test-au
|
||||
## Framework Patterns
|
||||
|
||||
**JavaScript/TypeScript (Jest/Vitest)**
|
||||
|
||||
- Mock dependencies with `vi.fn()` or `jest.fn()`
|
||||
- Use `@testing-library` for React components
|
||||
- Property tests with `fast-check`
|
||||
|
||||
**Python (pytest)**
|
||||
|
||||
- Fixtures with appropriate scopes
|
||||
- Parametrize for multiple test cases
|
||||
- Hypothesis for property-based tests
|
||||
|
||||
**Go**
|
||||
|
||||
- Table-driven tests with subtests
|
||||
- `t.Parallel()` for parallel execution
|
||||
- Use `testify/assert` for cleaner assertions
|
||||
|
||||
**Ruby (RSpec)**
|
||||
|
||||
- `let` for lazy loading, `let!` for eager
|
||||
- Contexts for different scenarios
|
||||
- Shared examples for common behavior
|
||||
@@ -93,6 +97,7 @@ Generate failing tests using Task tool with subagent_type="unit-testing::test-au
|
||||
## Validation
|
||||
|
||||
After generation:
|
||||
|
||||
1. Run tests - confirm they fail
|
||||
2. Verify helpful failure messages
|
||||
3. Check test independence
|
||||
@@ -102,7 +107,7 @@ After generation:
|
||||
|
||||
```typescript
|
||||
// auth.service.test.ts
|
||||
describe('AuthService', () => {
|
||||
describe("AuthService", () => {
|
||||
let authService: AuthService;
|
||||
let mockUserRepo: jest.Mocked<UserRepository>;
|
||||
|
||||
@@ -111,23 +116,23 @@ describe('AuthService', () => {
|
||||
authService = new AuthService(mockUserRepo);
|
||||
});
|
||||
|
||||
it('should_return_token_when_valid_credentials', async () => {
|
||||
const user = { id: '1', email: 'test@example.com', passwordHash: 'hashed' };
|
||||
it("should_return_token_when_valid_credentials", async () => {
|
||||
const user = { id: "1", email: "test@example.com", passwordHash: "hashed" };
|
||||
mockUserRepo.findByEmail.mockResolvedValue(user);
|
||||
|
||||
const result = await authService.authenticate('test@example.com', 'pass');
|
||||
const result = await authService.authenticate("test@example.com", "pass");
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.token).toBeDefined();
|
||||
});
|
||||
|
||||
it('should_fail_when_user_not_found', async () => {
|
||||
it("should_fail_when_user_not_found", async () => {
|
||||
mockUserRepo.findByEmail.mockResolvedValue(null);
|
||||
|
||||
const result = await authService.authenticate('none@example.com', 'pass');
|
||||
const result = await authService.authenticate("none@example.com", "pass");
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('INVALID_CREDENTIALS');
|
||||
expect(result.error).toBe("INVALID_CREDENTIALS");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
@@ -11,12 +11,14 @@ Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD
|
||||
## Core Process
|
||||
|
||||
**1. Pre-Assessment**
|
||||
|
||||
- Run tests to establish green baseline
|
||||
- Analyze code smells and test coverage
|
||||
- Document current performance metrics
|
||||
- Create incremental refactoring plan
|
||||
|
||||
**2. Code Smell Detection**
|
||||
|
||||
- Duplicated code → Extract methods/classes
|
||||
- Long methods → Decompose into focused functions
|
||||
- Large classes → Split responsibilities
|
||||
@@ -27,6 +29,7 @@ Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD
|
||||
- Dead code → Remove
|
||||
|
||||
**3. Design Patterns**
|
||||
|
||||
- Apply Creational (Factory, Builder, Singleton)
|
||||
- Apply Structural (Adapter, Facade, Decorator)
|
||||
- Apply Behavioral (Strategy, Observer, Command)
|
||||
@@ -34,6 +37,7 @@ Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD
|
||||
- Use patterns only where they add clear value
|
||||
|
||||
**4. SOLID Principles**
|
||||
|
||||
- Single Responsibility: One reason to change
|
||||
- Open/Closed: Open for extension, closed for modification
|
||||
- Liskov Substitution: Subtypes substitutable
|
||||
@@ -41,6 +45,7 @@ Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD
|
||||
- Dependency Inversion: Depend on abstractions
|
||||
|
||||
**5. Refactoring Techniques**
|
||||
|
||||
- Extract Method/Variable/Interface
|
||||
- Inline unnecessary indirection
|
||||
- Rename for clarity
|
||||
@@ -51,6 +56,7 @@ Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD
|
||||
- Introduce Null Object
|
||||
|
||||
**6. Performance Optimization**
|
||||
|
||||
- Profile to identify bottlenecks
|
||||
- Optimize algorithms and data structures
|
||||
- Implement caching where beneficial
|
||||
@@ -59,6 +65,7 @@ Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD
|
||||
- Always measure before and after
|
||||
|
||||
**7. Incremental Steps**
|
||||
|
||||
- Make small, atomic changes
|
||||
- Run tests after each modification
|
||||
- Commit after each successful refactoring
|
||||
@@ -66,18 +73,21 @@ Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD
|
||||
- Use scaffolding when needed
|
||||
|
||||
**8. Architecture Evolution**
|
||||
|
||||
- Layer separation and dependency management
|
||||
- Module boundaries and interface definition
|
||||
- Event-driven patterns for decoupling
|
||||
- Database access pattern optimization
|
||||
|
||||
**9. Safety Verification**
|
||||
|
||||
- Run full test suite after each change
|
||||
- Performance regression testing
|
||||
- Mutation testing for test effectiveness
|
||||
- Rollback plan for major changes
|
||||
|
||||
**10. Advanced Patterns**
|
||||
|
||||
- Strangler Fig: Gradual legacy replacement
|
||||
- Branch by Abstraction: Large-scale changes
|
||||
- Parallel Change: Expand-contract pattern
|
||||
@@ -95,6 +105,7 @@ Prompt: "Refactor this code while keeping all tests green: $ARGUMENTS. Apply TDD
|
||||
## Safety Checklist
|
||||
|
||||
Before committing:
|
||||
|
||||
- ✓ All tests pass (100% green)
|
||||
- ✓ No functionality regression
|
||||
- ✓ Performance metrics acceptable
|
||||
@@ -104,6 +115,7 @@ Before committing:
|
||||
## Recovery Protocol
|
||||
|
||||
If tests fail:
|
||||
|
||||
- Immediately revert last change
|
||||
- Identify breaking refactoring
|
||||
- Apply smaller incremental changes
|
||||
@@ -112,6 +124,7 @@ If tests fail:
|
||||
## Example: Extract Method Pattern
|
||||
|
||||
**Before:**
|
||||
|
||||
```typescript
|
||||
class OrderProcessor {
|
||||
processOrder(order: Order): ProcessResult {
|
||||
@@ -125,7 +138,7 @@ class OrderProcessor {
|
||||
for (const item of order.items) {
|
||||
subtotal += item.price * item.quantity;
|
||||
}
|
||||
let total = subtotal + (subtotal * 0.08) + (subtotal > 100 ? 0 : 15);
|
||||
let total = subtotal + subtotal * 0.08 + (subtotal > 100 ? 0 : 15);
|
||||
|
||||
// Process payment...
|
||||
// Update inventory...
|
||||
@@ -135,6 +148,7 @@ class OrderProcessor {
|
||||
```
|
||||
|
||||
**After:**
|
||||
|
||||
```typescript
|
||||
class OrderProcessor {
|
||||
async processOrder(order: Order): Promise<ProcessResult> {
|
||||
@@ -142,10 +156,16 @@ class OrderProcessor {
|
||||
if (!validation.isValid) return ProcessResult.failure(validation.error);
|
||||
|
||||
const orderTotal = OrderTotal.calculate(order);
|
||||
const inventoryCheck = await this.inventoryService.checkAvailability(order.items);
|
||||
if (!inventoryCheck.available) return ProcessResult.failure(inventoryCheck.reason);
|
||||
const inventoryCheck = await this.inventoryService.checkAvailability(
|
||||
order.items,
|
||||
);
|
||||
if (!inventoryCheck.available)
|
||||
return ProcessResult.failure(inventoryCheck.reason);
|
||||
|
||||
await this.paymentService.processPayment(order.paymentMethod, orderTotal.total);
|
||||
await this.paymentService.processPayment(
|
||||
order.paymentMethod,
|
||||
orderTotal.total,
|
||||
);
|
||||
await this.inventoryService.reserveItems(order.items);
|
||||
await this.notificationService.sendOrderConfirmation(order, orderTotal);
|
||||
|
||||
@@ -153,8 +173,10 @@ class OrderProcessor {
|
||||
}
|
||||
|
||||
private validateOrder(order: Order): ValidationResult {
|
||||
if (!order.customerId) return ValidationResult.invalid("Customer ID required");
|
||||
if (order.items.length === 0) return ValidationResult.invalid("Order must contain items");
|
||||
if (!order.customerId)
|
||||
return ValidationResult.invalid("Customer ID required");
|
||||
if (order.items.length === 0)
|
||||
return ValidationResult.invalid("Order must contain items");
|
||||
return ValidationResult.valid();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user