commit 4292614d3aa14bc2706a966af7215238328429d4 Author: Zhongwei Li Date: Sat Nov 29 17:56:23 2025 +0800 Initial commit diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..c7f8498 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,15 @@ +{ + "name": "specweave-core", + "description": "Core software engineering practices including code review, refactoring, architecture design, design patterns, SOLID principles, clean code, technical debt management, and software craftsmanship.", + "version": "0.24.0", + "author": { + "name": "Anton Abyzov", + "email": "anton.abyzov@gmail.com" + }, + "skills": [ + "./skills" + ], + "commands": [ + "./commands" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..ae3e046 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# specweave-core + +Core software engineering practices including code review, refactoring, architecture design, design patterns, SOLID principles, clean code, technical debt management, and software craftsmanship. diff --git a/commands/architecture-review.md b/commands/architecture-review.md new file mode 100644 index 0000000..9aa94bc --- /dev/null +++ b/commands/architecture-review.md @@ -0,0 +1,288 @@ +# /specweave-core:architecture-review + +Review software architecture for scalability, maintainability, security, and alignment with best practices. + +You are an expert software architect who evaluates system design and architecture decisions. + +## Your Task + +Perform comprehensive architecture reviews covering design patterns, scalability, security, and technical debt. + +### 1. Architecture Review Framework + +**Evaluation Dimensions**: +- ✅ Scalability: Can it handle 10x growth? +- ✅ Maintainability: Can new developers understand it? +- ✅ Security: Defense in depth, least privilege +- ✅ Performance: Meets latency/throughput requirements +- ✅ Reliability: Fault tolerance, disaster recovery +- ✅ Cost: Infrastructure and operational costs +- ✅ Observability: Logging, monitoring, tracing + +### 2. Architecture Patterns Assessment + +**Microservices vs Monolith**: +```yaml +Monolith (Start Here): + Pros: + - Simple deployment + - Easy local development + - No distributed system complexity + - Lower operational overhead + Cons: + - Scaling entire app (not individual services) + - Slower build times as codebase grows + - Technology lock-in + + Best for: + - Startups, MVPs + - Small teams (< 10 engineers) + - Well-defined domain + +Microservices (Migrate When Needed): + Pros: + - Independent scaling + - Technology diversity + - Team autonomy + - Fault isolation + Cons: + - Distributed system complexity + - Higher operational overhead + - Network latency + - Data consistency challenges + + Best for: + - Large teams (> 20 engineers) + - Clear service boundaries + - Different scaling needs per service +``` + +**Event-Driven Architecture**: +```typescript +// Use when: +// - Decoupling producers/consumers +// - Async processing +// - Event sourcing +// - CQRS pattern + +interface EventBus { + publish(event: DomainEvent): Promise; + subscribe(eventType: string, handler: (event: T) => Promise): void; +} + +// Example: Order processing +await eventBus.publish({ + type: 'OrderPlaced', + orderId: '123', + userId: 'user-456', + total: 99.99, +}); + +// Multiple subscribers (inventory, email, analytics) +eventBus.subscribe('OrderPlaced', inventoryService.reserve); +eventBus.subscribe('OrderPlaced', emailService.sendConfirmation); +eventBus.subscribe('OrderPlaced', analyticsService.track); +``` + +**CQRS (Command Query Responsibility Segregation)**: +```typescript +// Separate read and write models + +// Command (Write) +class CreateUserCommand { + execute(data: UserData) { + // Validate + // Save to write database (normalized) + // Publish UserCreatedEvent + } +} + +// Query (Read) +class GetUserProfile { + execute(userId: string) { + // Read from read database (denormalized, optimized for reads) + // May use cache, different DB tech (e.g., Elasticsearch) + } +} +``` + +### 3. Scalability Review + +**Horizontal vs Vertical Scaling**: +```yaml +Horizontal Scaling (Add More Machines): + Requires: + - Stateless application servers + - Shared session store (Redis, database) + - Load balancer + - Database replication/sharding + + Benefits: + - No single point of failure + - Cost-effective with cloud auto-scaling + - Unlimited scaling potential + +Vertical Scaling (Bigger Machine): + Requires: + - Downtime for upgrades + - Eventually hits hardware limits + + Benefits: + - Simpler (no distributed system) + - No code changes needed +``` + +**Database Scaling Strategies**: +```yaml +Read Replicas: + - Offload read traffic (analytics, reports) + - Eventual consistency acceptable + - 80% reads, 20% writes + +Sharding: + - Partition data across multiple databases + - Shard key: user_id, tenant_id, region + - Complexity: cross-shard queries, rebalancing + +Caching: + - Redis for hot data (user sessions, product catalog) + - CDN for static assets + - Application-level caching +``` + +### 4. Security Architecture Review + +**Defense in Depth**: +```yaml +Network Layer: + - VPC with private subnets + - Security groups (whitelist) + - WAF for DDoS protection + +Application Layer: + - Input validation and sanitization + - Output encoding (XSS prevention) + - Parameterized queries (SQL injection) + - CSRF tokens + - Rate limiting + +Data Layer: + - Encryption at rest (database, S3) + - Encryption in transit (TLS) + - Secrets management (AWS Secrets Manager, Vault) + - Database access control (least privilege) + +Authentication/Authorization: + - Multi-factor authentication + - OAuth 2.0 / OpenID Connect + - JWT with short expiration + - Role-based access control (RBAC) +``` + +**Threat Modeling**: +```markdown +## STRIDE Analysis + +**Spoofing**: Can attacker impersonate user? +- Mitigation: MFA, session management + +**Tampering**: Can attacker modify data? +- Mitigation: Data integrity checks, audit logs + +**Repudiation**: Can user deny actions? +- Mitigation: Comprehensive audit trail + +**Information Disclosure**: Can attacker access sensitive data? +- Mitigation: Encryption, access control + +**Denial of Service**: Can attacker make system unavailable? +- Mitigation: Rate limiting, auto-scaling, WAF + +**Elevation of Privilege**: Can attacker gain admin access? +- Mitigation: Least privilege, input validation +``` + +### 5. Observability Review + +**Three Pillars**: +```yaml +Logging: + - Structured logging (JSON) + - Centralized (ELK, CloudWatch Logs) + - Request IDs for tracing + - Log levels: ERROR, WARN, INFO, DEBUG + +Metrics: + - RED: Rate, Errors, Duration + - USE: Utilization, Saturation, Errors + - Business metrics (orders/min, revenue) + - Infrastructure metrics (CPU, memory, disk) + +Tracing: + - Distributed tracing (OpenTelemetry, Jaeger) + - End-to-end request flow + - Performance bottleneck identification +``` + +### 6. Architecture Decision Records (ADRs) + +```markdown +# ADR-001: Use PostgreSQL for Primary Database + +## Status +Accepted + +## Context +Need persistent storage for user data, transactions, and analytics. + +## Decision +Use PostgreSQL as primary database. + +## Consequences + +**Pros**: +- ACID compliance (strong consistency) +- Rich query capabilities (joins, aggregations) +- Mature ecosystem, wide adoption +- JSON support for semi-structured data + +**Cons**: +- Vertical scaling limits (mitigated with read replicas) +- Complex sharding if needed +- Higher cost than NoSQL for massive scale + +**Alternatives Considered**: +- MongoDB: Less mature for transactions, eventual consistency +- DynamoDB: Lock-in to AWS, limited query flexibility +``` + +### 7. Technical Debt Assessment + +**Debt Quadrant** (Martin Fowler): +```yaml +Reckless + Deliberate: + "We don't have time for design" + Priority: HIGH - Fix immediately + +Prudent + Deliberate: + "We must ship now, will refactor later" + Priority: MEDIUM - Plan refactoring sprint + +Reckless + Inadvertent: + "What's layering?" + Priority: HIGH - Training + mentorship + +Prudent + Inadvertent: + "Now we know how we should have done it" + Priority: LOW - Document for next time +``` + +## When to Use + +- Pre-launch architecture review +- Quarterly architecture health checks +- Scaling preparation (before 10x growth) +- Post-incident architecture analysis +- Acquisition due diligence + +Evaluate architecture like a principal engineer! diff --git a/commands/code-review.md b/commands/code-review.md new file mode 100644 index 0000000..2362f65 --- /dev/null +++ b/commands/code-review.md @@ -0,0 +1,213 @@ +# /specweave-core:code-review + +Perform comprehensive code reviews with modern best practices, security analysis, and actionable feedback. + +You are an expert software engineer who conducts thorough, constructive code reviews. + +## Your Task + +Review code for quality, security, performance, maintainability, and adherence to best practices. + +### 1. Review Checklist + +**Code Quality**: +- ✅ Readability: Clear naming, consistent formatting +- ✅ Simplicity: No unnecessary complexity +- ✅ DRY: No code duplication +- ✅ SOLID principles adherence +- ✅ Appropriate design patterns +- ✅ Error handling and edge cases +- ✅ Type safety (TypeScript strict mode) + +**Security**: +- ✅ Input validation and sanitization +- ✅ No hardcoded secrets +- ✅ SQL injection prevention +- ✅ XSS protection +- ✅ Authentication and authorization +- ✅ Dependency vulnerabilities (npm audit) + +**Performance**: +- ✅ Algorithmic complexity (no O(n²) where O(n) suffices) +- ✅ Database query optimization +- ✅ Memory leaks prevention +- ✅ Caching strategies +- ✅ Bundle size impact + +**Testing**: +- ✅ Unit test coverage (80%+ for critical paths) +- ✅ Edge cases tested +- ✅ Mocking strategy +- ✅ Integration tests where needed + +**Documentation**: +- ✅ JSDoc/TSDoc for public APIs +- ✅ README updates +- ✅ Inline comments for complex logic +- ✅ Changelog entry + +### 2. Review Categories + +**Critical (Must Fix Before Merge)**: +- Security vulnerabilities +- Data loss risks +- Breaking changes without migration +- Functionality bugs +- Performance regressions (> 20% slower) + +**Major (Should Fix)**: +- Code smells +- Missing error handling +- Inconsistent patterns +- Poor naming +- Missing tests for critical paths + +**Minor (Nice to Have)**: +- Formatting inconsistencies +- TODOs without tickets +- Missing JSDoc +- Opportunities for refactoring + +**Nit (Optional)**: +- Stylistic preferences +- Alternative approaches +- Educational comments + +### 3. Feedback Template + +```markdown +## Summary +Brief overview of changes and overall assessment. + +## ✅ Strengths +- Clear separation of concerns +- Good test coverage (85%) +- Well-documented API + +## 🔴 Critical Issues +1. **SQL Injection Risk** (line 45) + - **Problem**: Direct string interpolation in query + - **Fix**: Use parameterized queries + ```typescript + // ❌ Bad + const query = `SELECT * FROM users WHERE id = ${userId}`; + + // ✅ Good + const query = 'SELECT * FROM users WHERE id = ?'; + db.execute(query, [userId]); + ``` + +## 🟡 Major Issues +2. **Missing Error Handling** (line 78) + - **Problem**: Unhandled promise rejection + - **Fix**: Add try-catch or .catch() + +## 🟢 Minor Suggestions +3. **Improve Variable Naming** (line 92) + - `data` → `userProfile` (more descriptive) + +## Questions +- Is this API endpoint rate-limited? +- Should we add caching for this query? +``` + +### 4. Security Review Patterns + +**Detect Common Vulnerabilities**: +```typescript +// SQL Injection +❌ db.query(`SELECT * FROM users WHERE email = '${email}'`) +✅ db.query('SELECT * FROM users WHERE email = ?', [email]) + +// XSS +❌ innerHTML = userInput +✅ textContent = userInput (or DOMPurify.sanitize()) + +// Hardcoded Secrets +❌ const API_KEY = 'sk-1234567890abcdef' +✅ const API_KEY = process.env.API_KEY + +// Insecure Dependencies +❌ "lodash": "4.17.10" (vulnerable) +✅ "lodash": "^4.17.21" (patched) +``` + +### 5. Performance Review + +**Identify Performance Issues**: +```typescript +// O(n²) complexity +❌ for (const user of users) { + for (const role of roles) { + if (user.roleId === role.id) { /* ... */ } + } + } + +✅ const roleMap = new Map(roles.map(r => [r.id, r])); + for (const user of users) { + const role = roleMap.get(user.roleId); + } + +// N+1 Query Problem +❌ for (const user of users) { + user.posts = await db.query('SELECT * FROM posts WHERE userId = ?', [user.id]); + } + +✅ const posts = await db.query('SELECT * FROM posts WHERE userId IN (?)', [userIds]); + const postsByUser = groupBy(posts, 'userId'); +``` + +### 6. Design Pattern Recognition + +**Identify Appropriate Patterns**: +- Factory Pattern: Object creation logic +- Strategy Pattern: Interchangeable algorithms +- Observer Pattern: Event-driven systems +- Repository Pattern: Data access abstraction +- Singleton Pattern: Shared state (use sparingly) + +### 7. Code Smell Detection + +**Common Smells**: +- Long functions (> 50 lines) +- Large classes (> 300 lines) +- Primitive obsession (use value objects) +- Feature envy (method uses another class more than its own) +- Data clumps (same group of params everywhere) +- Switch statements (consider polymorphism) + +### 8. Review Workflow + +1. **Read Description**: Understand the why +2. **Review Tests First**: Understand expected behavior +3. **Review Implementation**: Check against requirements +4. **Run Locally**: Verify functionality +5. **Check CI/CD**: Tests pass, coverage met +6. **Security Scan**: Static analysis, dependency check +7. **Provide Feedback**: Constructive, specific, actionable + +### 9. Best Practices + +**DO**: +- Be kind and constructive +- Explain the "why" behind suggestions +- Provide code examples for fixes +- Approve if only minor issues +- Ask questions to understand intent + +**DON'T**: +- Be condescending or dismissive +- Nitpick formatting (use automated tools) +- Rewrite entire implementation (pair program instead) +- Block merges for stylistic preferences +- Review your own code without second pair of eyes + +## When to Use + +- Pull request reviews +- Pre-merge code quality checks +- Security audits +- Performance optimization reviews +- Onboarding code walkthroughs + +Review code like a senior engineer! diff --git a/commands/refactor-plan.md b/commands/refactor-plan.md new file mode 100644 index 0000000..10ba64b --- /dev/null +++ b/commands/refactor-plan.md @@ -0,0 +1,249 @@ +# /specweave-core:refactor-plan + +Generate comprehensive refactoring plans with risk assessment, step-by-step execution, and rollback strategies. + +You are an expert software architect who plans safe, incremental refactoring strategies. + +## Your Task + +Create detailed refactoring plans that minimize risk while improving code quality. + +### 1. Refactoring Patterns + +**Extract Method**: +```typescript +// Before: Long function with multiple responsibilities +function processOrder(order: Order) { + // 50 lines of validation + // 30 lines of calculation + // 40 lines of persistence +} + +// After: Small, focused functions +function processOrder(order: Order) { + validateOrder(order); + const total = calculateTotal(order); + saveOrder(order, total); +} +``` + +**Extract Class**: +```typescript +// Before: God class +class User { + // User properties + // Email sending logic + // Password hashing logic + // Notification logic +} + +// After: Single responsibility +class User { /* core user data */ } +class EmailService { /* email logic */ } +class PasswordHasher { /* password logic */ } +class NotificationService { /* notifications */ } +``` + +**Replace Conditional with Polymorphism**: +```typescript +// Before: Switch statements +function calculateShipping(type: string, weight: number) { + switch (type) { + case 'express': return weight * 5; + case 'standard': return weight * 2; + case 'economy': return weight * 1; + } +} + +// After: Strategy pattern +interface ShippingStrategy { + calculate(weight: number): number; +} + +class ExpressShipping implements ShippingStrategy { + calculate(weight: number) { return weight * 5; } +} +``` + +**Introduce Parameter Object**: +```typescript +// Before: Long parameter lists +function createUser(name: string, email: string, age: number, address: string, phone: string) + +// After: Parameter object +interface UserData { + name: string; + email: string; + age: number; + address: string; + phone: string; +} + +function createUser(data: UserData) +``` + +### 2. Refactoring Plan Template + +```markdown +## Refactoring Plan: Extract Payment Processing + +### Current State +- 500-line PaymentController with mixed responsibilities +- Tightly coupled to database layer +- No unit tests (integration tests only) +- Duplicate payment validation logic in 3 places + +### Target State +- Payment domain services (validation, processing, reconciliation) +- Repository pattern for data access +- 80%+ unit test coverage +- Single source of truth for validation + +### Risk Assessment +**Risk Level**: Medium + +**Risks**: +1. Breaking existing payment flows (HIGH IMPACT) +2. Race conditions in concurrent payments (MEDIUM) +3. Performance regression (LOW) + +**Mitigation**: +1. Feature flag + parallel run (old + new code) +2. Transaction isolation + row-level locking +3. Performance testing before rollout + +### Prerequisites +- [ ] 100% integration test coverage of current behavior +- [ ] Performance baseline established +- [ ] Database migrations prepared +- [ ] Rollback plan documented +- [ ] Team review and approval + +### Execution Steps (10 steps, 2 weeks) + +**Week 1: Preparation + Safe Extractions** + +**Step 1** (Day 1): Add comprehensive integration tests +- Test all payment flows +- Test error scenarios +- Test edge cases (concurrent payments, retries) + +**Step 2** (Day 2): Extract validation logic +- Create PaymentValidator class +- Move validation from controller +- Tests: unit tests for validator +- **Safe**: Pure functions, no state changes + +**Step 3** (Day 3): Extract payment processing +- Create PaymentProcessor service +- Move core processing logic +- Tests: unit tests with mocks +- **Safe**: Existing controller calls new service + +**Week 2: Risky Changes + Rollout** + +**Step 7** (Day 8): Introduce repository pattern +- Create PaymentRepository interface +- Implement with existing DB calls +- **Risk**: Data access changes +- **Mitigation**: Feature flag, parallel run + +**Step 10** (Day 10): Final cutover +- Enable new code for 100% traffic +- Monitor for 48 hours +- Remove old code if stable + +### Testing Strategy +- Unit tests: 80%+ coverage +- Integration tests: All payment flows +- Load testing: 2x expected peak traffic +- Canary deployment: 1% → 10% → 50% → 100% + +### Rollback Plan +- Feature flag: Instant rollback to old code +- Database: Backward-compatible migrations +- Monitoring: Alert on error rate > 0.1% +- Rollback trigger: Any payment processing failure + +### Success Metrics +- ✅ All tests passing +- ✅ Code coverage > 80% +- ✅ Performance within 10% of baseline +- ✅ Zero production incidents +- ✅ Team velocity unchanged +``` + +### 3. Safety Strategies + +**Strangler Fig Pattern**: +```typescript +// Gradually replace old system +class PaymentController { + async processPayment(order: Order) { + if (featureFlags.newPaymentFlow) { + return newPaymentService.process(order); // New code + } else { + return legacyPaymentLogic(order); // Old code + } + } +} +``` + +**Parallel Run**: +```typescript +// Run both old and new, compare results +async function processPayment(order: Order) { + const oldResult = await legacyPayment(order); + + // Run new code in background, don't block + backgroundTask(async () => { + const newResult = await newPayment(order); + if (!isEqual(oldResult, newResult)) { + logger.warn('Payment results differ', { old: oldResult, new: newResult }); + } + }); + + return oldResult; // Use old result (safe) +} +``` + +### 4. Code Smell Prioritization + +**High Priority** (Security/Bugs): +- Null reference errors +- Memory leaks +- Race conditions +- Security vulnerabilities + +**Medium Priority** (Maintainability): +- God classes (> 500 lines) +- Long functions (> 50 lines) +- Cyclomatic complexity > 10 +- Code duplication (> 5 instances) + +**Low Priority** (Cleanup): +- Dead code +- Unused imports +- TODOs +- Console.log statements + +### 5. Workflow + +1. **Identify Target**: What needs refactoring? +2. **Assess Risk**: Impact analysis +3. **Create Plan**: Step-by-step breakdown +4. **Get Buy-in**: Team review +5. **Prepare**: Tests, baselines, migrations +6. **Execute**: Incremental changes +7. **Monitor**: Metrics, alerts +8. **Document**: Update architecture docs + +## When to Use + +- Planning large-scale refactoring +- Improving legacy codebases +- Reducing technical debt +- Preparing for new features +- Post-incident code improvements + +Refactor safely with detailed planning! diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..b5269d7 --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,65 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:anton-abyzov/specweave:plugins/specweave-core", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "c600ab57de316c181730ce511bfb66098a18bb3d", + "treeHash": "bede02713d37538beab72dd493aaa27f602e50b89ea155258cb135de24482a7f", + "generatedAt": "2025-11-28T10:13:55.383497Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "specweave-core", + "description": "Core software engineering practices including code review, refactoring, architecture design, design patterns, SOLID principles, clean code, technical debt management, and software craftsmanship.", + "version": "0.24.0" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "90d18c187f5572579bb884a9d113292d75e5364739453ae88818c08bb92f3a38" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "d91c3baac7d15af798b260bd836b990fdabdd883de53fa62cc8f30aaf2de9c7a" + }, + { + "path": "commands/code-review.md", + "sha256": "04b6c630fc93af29a6d3ef2dbfaa5d3fabd5c62bbd5dc1d5fc3c34b07ee688aa" + }, + { + "path": "commands/architecture-review.md", + "sha256": "8ba7a57871aad086cb90c1f0ce1f247883b20133874ed8dcbf2e7025aada63a4" + }, + { + "path": "commands/refactor-plan.md", + "sha256": "91dc6fb13001e45e6cb34f671e57801a4bf51c7608bae2482b064ab9e1b7d287" + }, + { + "path": "skills/design-patterns/SKILL.md", + "sha256": "74a7c26bc156ee7a7b0ee15ce8080846bd12f15e90952e0691ec862f5c6e1f06" + }, + { + "path": "skills/software-architecture/SKILL.md", + "sha256": "45b5edf3b530570870800e7c6d9e0fa6b7718ceead58cd48c9e7052965505d85" + }, + { + "path": "skills/code-quality/SKILL.md", + "sha256": "c288e2909a62b2ac0cd6dacd6e14a5dae6a3c780a237f2514132cb3102c96c24" + } + ], + "dirSha256": "bede02713d37538beab72dd493aaa27f602e50b89ea155258cb135de24482a7f" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file diff --git a/skills/code-quality/SKILL.md b/skills/code-quality/SKILL.md new file mode 100644 index 0000000..c549ddf --- /dev/null +++ b/skills/code-quality/SKILL.md @@ -0,0 +1,158 @@ +--- +name: code-quality +description: Expert code quality engineering covering clean code principles, SOLID, DRY, KISS, YAGNI, code smells, refactoring patterns, static analysis, linting, code coverage, mutation testing, and software craftsmanship. Activates for code quality, clean code, SOLID principles, code smells, refactoring, technical debt, code review, linting, eslint, prettier, static analysis, code coverage. +allowed-tools: Read, Grep, Glob +--- + +# Code Quality Expert + +Master of clean code principles, SOLID, and software craftsmanship. + +## SOLID Principles + +**Single Responsibility**: +```typescript +// ❌ Bad: Multiple responsibilities +class User { + save() { /* database logic */ } + sendEmail() { /* email logic */ } + hashPassword() { /* crypto logic */ } +} + +// ✅ Good: Single responsibility +class User { /* user data only */ } +class UserRepository { save(user: User) {} } +class EmailService { send(to: string, message: string) {} } +class PasswordHasher { hash(password: string) {} } +``` + +**Open/Closed**: +```typescript +// ✅ Open for extension, closed for modification +interface PaymentMethod { + processPayment(amount: number): Promise; +} + +class CreditCardPayment implements PaymentMethod { + async processPayment(amount: number) { /* ... */ } +} + +class PayPalPayment implements PaymentMethod { + async processPayment(amount: number) { /* ... */ } +} + +// Add new payment methods without modifying existing code +``` + +**Liskov Substitution**: +```typescript +// Subtypes must be substitutable for base types +class Bird { + fly() { /* ... */ } +} + +// ❌ Bad: Penguin can't fly, violates LSP +class Penguin extends Bird { + fly() { throw new Error('Cannot fly'); } +} + +// ✅ Good: Proper abstraction +interface Bird {} +interface FlyingBird extends Bird { fly(): void; } +class Sparrow implements FlyingBird { fly() {} } +class Penguin implements Bird {} // No fly method +``` + +**Interface Segregation**: +```typescript +// ❌ Bad: Fat interface +interface Worker { + work(): void; + eat(): void; + sleep(): void; +} + +// ✅ Good: Segregated interfaces +interface Workable { work(): void; } +interface Eatable { eat(): void; } +interface Sleepable { sleep(): void; } + +class Human implements Workable, Eatable, Sleepable {} +class Robot implements Workable {} // Doesn't need eat/sleep +``` + +**Dependency Inversion**: +```typescript +// ❌ Bad: High-level depends on low-level +class EmailService { + private smtp = new SMTPClient(); // Direct dependency +} + +// ✅ Good: Depend on abstraction +interface EmailClient { + send(to: string, message: string): Promise; +} + +class EmailService { + constructor(private client: EmailClient) {} +} +``` + +## Clean Code Principles + +**DRY (Don't Repeat Yourself)**: +```typescript +// ❌ Duplication +function validateEmail(email: string) { + return /^\S+@\S+\.\S+$/.test(email); +} +function validateUserEmail(email: string) { + return /^\S+@\S+\.\S+$/.test(email); // Duplicate +} + +// ✅ Single source of truth +const EMAIL_REGEX = /^\S+@\S+\.\S+$/; +const isValidEmail = (email: string) => EMAIL_REGEX.test(email); +``` + +**KISS (Keep It Simple)**: +```typescript +// ❌ Over-engineered +class AdvancedCalculatorFactoryBuilderSingleton { + private static instance: AdvancedCalculatorFactoryBuilderSingleton; + // 50 lines of unnecessary abstraction +} + +// ✅ Simple +const add = (a: number, b: number) => a + b; +``` + +**YAGNI (You Aren't Gonna Need It)**: +```typescript +// ❌ Premature abstraction +class User { + futureFeature1() {} // Not used yet + futureFeature2() {} // Not used yet + futureFeature3() {} // Not used yet +} + +// ✅ Only what's needed now +class User { + getCurrentFeatures() {} // Actually used +} +``` + +## Code Smells + +**Long Method**: > 50 lines → Extract methods +**Large Class**: > 300 lines → Extract classes +**Long Parameter List**: > 3 params → Parameter object +**Primitive Obsession**: Use value objects +**Data Clumps**: Group related data +**Switch Statements**: Replace with polymorphism + +## Testing Strategies + +**Test Coverage**: 80%+ for critical paths +**Mutation Testing**: Ensure test quality +**Test Pyramid**: Many unit, few integration, minimal E2E diff --git a/skills/design-patterns/SKILL.md b/skills/design-patterns/SKILL.md new file mode 100644 index 0000000..8673491 --- /dev/null +++ b/skills/design-patterns/SKILL.md @@ -0,0 +1,245 @@ +--- +name: design-patterns +description: Expert knowledge of Gang of Four (GoF) design patterns including creational (Singleton, Factory, Builder, Prototype), structural (Adapter, Decorator, Proxy, Facade), and behavioral (Strategy, Observer, Command, Template Method, Chain of Responsibility). Modern TypeScript/JavaScript implementations with real-world use cases. Activates for design patterns, factory pattern, singleton, strategy pattern, observer pattern, decorator pattern, adapter pattern, builder pattern, proxy pattern, facade pattern, template method. +allowed-tools: Read, Grep, Glob +--- + +# Design Patterns Expert + +Master of GoF design patterns with modern TypeScript implementations. + +## Creational Patterns + +**Factory Pattern**: +```typescript +interface Animal { + speak(): string; +} + +class Dog implements Animal { + speak() { return 'Woof!'; } +} + +class Cat implements Animal { + speak() { return 'Meow!'; } +} + +class AnimalFactory { + static create(type: 'dog' | 'cat'): Animal { + switch (type) { + case 'dog': return new Dog(); + case 'cat': return new Cat(); + } + } +} +``` + +**Singleton Pattern**: +```typescript +class Database { + private static instance: Database; + + private constructor() {} // Private constructor + + static getInstance(): Database { + if (!Database.instance) { + Database.instance = new Database(); + } + return Database.instance; + } +} +``` + +**Builder Pattern**: +```typescript +class UserBuilder { + private user: Partial = {}; + + setName(name: string) { + this.user.name = name; + return this; + } + + setEmail(email: string) { + this.user.email = email; + return this; + } + + build(): User { + if (!this.user.name || !this.user.email) { + throw new Error('Missing required fields'); + } + return this.user as User; + } +} + +// Usage +const user = new UserBuilder() + .setName('John') + .setEmail('john@example.com') + .build(); +``` + +## Structural Patterns + +**Adapter Pattern**: +```typescript +// Old API +class OldLogger { + logMessage(message: string) { console.log(message); } +} + +// New interface +interface Logger { + log(level: string, message: string): void; +} + +// Adapter +class LoggerAdapter implements Logger { + constructor(private oldLogger: OldLogger) {} + + log(level: string, message: string) { + this.oldLogger.logMessage(`[${level}] ${message}`); + } +} +``` + +**Decorator Pattern**: +```typescript +interface Coffee { + cost(): number; + description(): string; +} + +class SimpleCoffee implements Coffee { + cost() { return 5; } + description() { return 'Simple coffee'; } +} + +class MilkDecorator implements Coffee { + constructor(private coffee: Coffee) {} + + cost() { return this.coffee.cost() + 2; } + description() { return this.coffee.description() + ', milk'; } +} + +// Usage +let coffee: Coffee = new SimpleCoffee(); +coffee = new MilkDecorator(coffee); +coffee.cost(); // 7 +``` + +**Proxy Pattern**: +```typescript +class RealImage { + constructor(private filename: string) { + this.loadFromDisk(); + } + + private loadFromDisk() { + console.log('Loading:', this.filename); + } + + display() { + console.log('Displaying:', this.filename); + } +} + +class ProxyImage { + private realImage?: RealImage; + + constructor(private filename: string) {} + + display() { + if (!this.realImage) { + this.realImage = new RealImage(this.filename); // Lazy loading + } + this.realImage.display(); + } +} +``` + +## Behavioral Patterns + +**Strategy Pattern**: +```typescript +interface SortStrategy { + sort(data: number[]): number[]; +} + +class QuickSort implements SortStrategy { + sort(data: number[]) { /* quicksort */ return data; } +} + +class MergeSort implements SortStrategy { + sort(data: number[]) { /* mergesort */ return data; } +} + +class Sorter { + constructor(private strategy: SortStrategy) {} + + setStrategy(strategy: SortStrategy) { + this.strategy = strategy; + } + + sort(data: number[]) { + return this.strategy.sort(data); + } +} +``` + +**Observer Pattern**: +```typescript +interface Observer { + update(data: any): void; +} + +class Subject { + private observers: Observer[] = []; + + attach(observer: Observer) { + this.observers.push(observer); + } + + notify(data: any) { + this.observers.forEach(o => o.update(data)); + } +} + +class EmailObserver implements Observer { + update(data: any) { + console.log('Sending email:', data); + } +} +``` + +**Command Pattern**: +```typescript +interface Command { + execute(): void; + undo(): void; +} + +class SaveCommand implements Command { + constructor(private editor: Editor) {} + + execute() { this.editor.save(); } + undo() { this.editor.restore(); } +} + +class CommandInvoker { + private history: Command[] = []; + + execute(command: Command) { + command.execute(); + this.history.push(command); + } + + undo() { + const command = this.history.pop(); + command?.undo(); + } +} +``` + +Apply design patterns to solve common problems elegantly! diff --git a/skills/software-architecture/SKILL.md b/skills/software-architecture/SKILL.md new file mode 100644 index 0000000..20efe2c --- /dev/null +++ b/skills/software-architecture/SKILL.md @@ -0,0 +1,84 @@ +--- +name: software-architecture +description: Expert software architecture covering architectural patterns (microservices, monolith, event-driven, CQRS), scalability, distributed systems, CAP theorem, database architecture, API design, system design, domain-driven design (DDD), hexagonal architecture, and architecture decision records (ADRs). Activates for software architecture, system design, microservices, monolith, event-driven, CQRS, scalability, distributed systems, CAP theorem, DDD, hexagonal architecture, ADR. +allowed-tools: Read, Grep, Glob +--- + +# Software Architecture Expert + +Master of architectural patterns, system design, and scalability. + +## Architectural Patterns + +**Layered Architecture**: +``` +Presentation Layer (UI) + ↓ +Business Logic Layer (Services) + ↓ +Data Access Layer (Repositories) + ↓ +Database +``` + +**Hexagonal Architecture (Ports & Adapters)**: +```typescript +// Core Domain (business logic, no dependencies) +interface PaymentPort { + process(amount: number): Promise; +} + +// Adapter (infrastructure) +class StripeAdapter implements PaymentPort { + async process(amount: number) { /* Stripe API */ } +} + +// Application uses port, not concrete implementation +class CheckoutService { + constructor(private payment: PaymentPort) {} +} +``` + +**Event-Driven Architecture**: +```typescript +// Producer +eventBus.publish({ type: 'OrderPlaced', orderId: '123' }); + +// Consumers (decoupled) +eventBus.subscribe('OrderPlaced', inventoryService.reserve); +eventBus.subscribe('OrderPlaced', emailService.notify); +``` + +**CQRS** (Command Query Responsibility Segregation): +- Commands: Write operations, change state +- Queries: Read operations, no side effects +- Separate models for read/write optimization + +## Scalability Patterns + +**Horizontal Scaling**: Add more servers +**Vertical Scaling**: Bigger server +**Caching**: Redis, CDN, application cache +**Database Sharding**: Partition by key (user_id, region) +**Read Replicas**: Offload read traffic +**Load Balancing**: Distribute traffic evenly + +## CAP Theorem + +**Consistency**: All nodes see same data +**Availability**: Every request gets response +**Partition Tolerance**: System works despite network failures + +Can only guarantee 2 of 3: +- **CP**: Consistent + Partition-tolerant (sacrifice availability) +- **AP**: Available + Partition-tolerant (eventual consistency) +- **CA**: Consistent + Available (no partition tolerance, single node) + +## Domain-Driven Design + +**Ubiquitous Language**: Shared vocabulary +**Bounded Contexts**: Explicit boundaries +**Aggregates**: Consistency boundaries +**Entities**: Objects with identity +**Value Objects**: Immutable, no identity +**Domain Events**: Business occurrences