SKILL.md
---
name: engineering
description: |
Senior software engineering specialist for code implementation, debugging, and optimization.
[VAD] Full-stack development, debugging, performance optimization, test writing.
TypeScript (bun), Python (uv), JavaScript. Clean code, SOLID principles.
[NÄR] Use when: build, implement, code, fix bug, debug, optimize, refactor, test,
kod, implementera, bygg, fixa, debugga, optimera
[EXPERTISE] TypeScript, Python, web development, testing, clean code
🚨 TIER 1 - AUTO-ACTIVATION. No confirmation needed.
triggers:
# English triggers
- code
- implement
- build
- create
- write code
- function
- class
- module
- bug
- debug
- fix
- error
- broken
- refactor
- cleanup
- optimize
- performance
- slow
- memory
- algorithm
- test
# Swedish triggers
- kod
- implementera
- bygg
- bygga
- skapa
- skriv kod
- funktion
- klass
- modul
- bugg
- debugga
- felsök
- fixa
- fel
- trasig
- refaktorera
- optimera
- prestanda
domains:
- typescript
- python
- javascript
- web development
- backend
- frontend
- api
voice_id: <YOUR_VOICE_ID>
voice_name: George
voice_gender: male
tier: 1
stack_preferences:
- TypeScript > Python
- bun (not npm/yarn/pnpm)
- uv for Python (not pip)
---
# Engineering Skill
## 🎯 Role & Purpose
Engineering Specialist is your Senior Software Engineer specializing in code implementation, debugging, and technical problem-solving. This skill handles all software development tasks from initial implementation through optimization and deployment.
## When to Use This Skill
Auto-activates for:
- Code implementation and feature development
- Bug fixing and debugging
- Performance optimization
- Code refactoring and cleanup
- Test writing and quality assurance
- Technical problem-solving
## Core Expertise
- **Languages**: TypeScript, Python, JavaScript, modern web technologies
- **Debugging**: Systematic problem isolation and resolution
- **Optimization**: Performance tuning and efficiency improvements
- **Best Practices**: Clean code, SOLID principles, design patterns
- **Testing**: Unit tests, integration tests, TDD approach
## Workflow
See `workflows/` directory for detailed task workflows:
- `implement-feature.md` - Feature implementation process
- `debug-issue.md` - Systematic debugging methodology
- `optimize-code.md` - Performance optimization approach
## Reference Materials
See `reference/` directory for technical guidance:
- `coding-standards.md` - Code quality and style guidelines
- `testing-guide.md` - Testing strategies and best practices
## Response Format
Always end with:
```
🎯 COMPLETED: [SKILL:engineering] [Description of implementation]
🗣️ CUSTOM COMPLETED: [Voice-optimized message under 8 words]
```
## Stack Preferences
1. **Prefer TypeScript over Python** (per PAI stack preferences)
2. **Use bun for JavaScript/TypeScript** (not npm/yarn/pnpm)
3. **Use uv for Python** (not pip)
4. **Write clean, maintainable code**
5. **Test thoroughly before marking complete**
## Example Tasks
- "Implement user authentication with JWT"
- "Fix memory leak in data processor"
- "Optimize database query performance"
- "Refactor API handlers for maintainability"
- "Add comprehensive error handling"
reference/coding-standards.md
# Coding Standards & Best Practices
## Purpose
Maintain consistent, readable, maintainable code across all projects.
## Core Principles
### 1. Clean Code (Robert C. Martin)
- **Functions do one thing** - Single Responsibility Principle
- **Descriptive names** - Variable and function names explain purpose
- **Small functions** - Ideally < 20 lines, definitely < 50 lines
- **Avoid comments** - Code should be self-documenting
- **DRY** - Don't Repeat Yourself
### 2. SOLID Principles
- **S**ingle Responsibility - One reason to change
- **O**pen/Closed - Open for extension, closed for modification
- **L**iskov Substitution - Subtypes must be substitutable
- **I**nterface Segregation - Many specific interfaces > one general
- **D**dependency Inversion - Depend on abstractions, not concretions
### 3. KISS & YAGNI
- **KISS** - Keep It Simple, Stupid (simplest solution that works)
- **YAGNI** - You Aren't Gonna Need It (don't build for future maybes)
## Language-Specific Standards
### TypeScript
**Naming**:
- Classes: `PascalCase`
- Functions/Variables: `camelCase`
- Constants: `UPPER_SNAKE_CASE`
- Private members: `_leadingUnderscore`
**Style**:
```typescript
// ✅ Good
interface User {
id: string;
name: string;
email: string;
}
function getUserById(id: string): Promise<User | null> {
// Implementation
}
// ❌ Bad
function get_user(ID: string) { // Wrong naming, no return type
// Implementation
}
```
**Best Practices**:
- Use `const` by default, `let` when needed, never `var`
- Prefer interfaces over type aliases for objects
- Use async/await over raw promises
- Explicit return types on public functions
- Avoid `any` - use `unknown` if type truly unknown
### Python
**Naming** (PEP 8):
- Classes: `PascalCase`
- Functions/Variables: `snake_case`
- Constants: `UPPER_SNAKE_CASE`
- Private: `_leading_underscore`
**Style**:
```python
# ✅ Good
class UserRepository:
def get_user_by_id(self, user_id: str) -> Optional[User]:
"""Retrieve user by ID."""
# Implementation
pass
# ❌ Bad
class user_repository: # Wrong case
def GetUserByID(self, ID): # Wrong naming, no types
pass
```
**Best Practices**:
- Type hints on all public functions
- Docstrings for all public functions/classes
- Use list comprehensions for simple transformations
- Prefer f-strings for formatting
- Use context managers (`with`) for resources
## Code Organization
### File Structure
```
project/
├── src/
│ ├── models/ # Data models
│ ├── services/ # Business logic
│ ├── repositories/ # Data access
│ ├── utils/ # Helper functions
│ └── api/ # API routes/controllers
├── tests/ # Mirror src/ structure
└── docs/ # Documentation
```
### Module Size
- Max ~500 lines per file
- Split large files by concern
- Group related functionality
## Error Handling
### TypeScript
```typescript
// ✅ Good - Specific error types
class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = 'ValidationError';
}
}
try {
validateUser(data);
} catch (error) {
if (error instanceof ValidationError) {
// Handle validation error
}
throw error; // Re-throw unknown errors
}
// ❌ Bad - Silent failures
try {
validateUser(data);
} catch (error) {
console.log(error); // Just logging
}
```
### Python
```python
# ✅ Good - Specific exceptions
class ValidationError(Exception):
"""Raised when validation fails."""
pass
try:
validate_user(data)
except ValidationError as e:
# Handle validation error
logger.error(f"Validation failed: {e}")
raise
except Exception:
# Handle unexpected errors
logger.exception("Unexpected error")
raise
# ❌ Bad - Bare except
try:
validate_user(data)
except: # Catches everything including KeyboardInterrupt
pass
```
## Security Best Practices
### Input Validation
- **Validate all input** - Never trust user input
- **Whitelist > Blacklist** - Define what's allowed, not what's forbidden
- **Type checking** - Verify data types match expectations
### SQL Injection Prevention
```typescript
// ✅ Good - Parameterized queries
const user = await db.query(
'SELECT * FROM users WHERE id = $1',
[userId]
);
// ❌ Bad - String concatenation
const user = await db.query(
`SELECT * FROM users WHERE id = '${userId}'` // Vulnerable!
);
```
### Secrets Management
- **Never hardcode** secrets, API keys, passwords
- Use environment variables
- Use secret management services in production
- Add `.env` to `.gitignore`
### Authentication & Authorization
- Use established libraries (don't roll your own crypto)
- Hash passwords with bcrypt/argon2
- Use HTTPS for all auth endpoints
- Implement rate limiting
## Testing Standards
### Test Structure (AAA Pattern)
```typescript
describe('UserService', () => {
it('should create user with valid data', async () => {
// Arrange
const userData = { name: 'Test', email: 'test@example.com' };
// Act
const user = await userService.create(userData);
// Assert
expect(user.name).toBe('Test');
expect(user.email).toBe('test@example.com');
});
});
```
### Coverage Goals
- **Unit tests**: 80%+ coverage
- **Integration tests**: Critical paths
- **E2E tests**: Key user workflows
## Performance Guidelines
### Algorithm Complexity
- Know Big O of your algorithms
- O(n) > O(n²) for large datasets
- Use appropriate data structures:
- Hash maps for lookups: O(1)
- Sets for membership: O(1)
- Arrays for ordered data: O(n) search
### Database
- Add indexes for frequently queried fields
- Avoid N+1 queries (use joins or batch loading)
- Limit query results (pagination)
- Use connection pooling
### Async Operations
- Don't block on I/O
- Use async/await for concurrent operations
- Batch API requests when possible
## Documentation Standards
### Code Comments
```typescript
// ✅ Good - Explains WHY
// Using binary search because dataset is pre-sorted
// and can exceed 100K items (O(log n) vs O(n))
const index = binarySearch(items, target);
// ❌ Bad - States the obvious
// Search for target in items
const index = binarySearch(items, target);
```
### Function Documentation
```typescript
/**
* Retrieves user by ID with caching.
*
* @param userId - Unique user identifier
* @returns User object or null if not found
* @throws DatabaseError if connection fails
*
* @remarks
* Results are cached for 5 minutes. Use {@link getUserByIdUncached}
* for real-time data.
*/
async function getUserById(userId: string): Promise<User | null> {
// Implementation
}
```
## Git Commit Standards
### Commit Messages
```
type(scope): short description
Longer explanation if needed.
- Bullet points for details
- Reference issues: #123
```
**Types**: feat, fix, docs, refactor, test, chore
**Examples**:
```
feat(auth): add JWT token refresh
fix(api): handle null response from user service
docs(readme): update installation instructions
refactor(database): extract query builder
```
## Code Review Checklist
Before submitting code:
- [ ] Code follows project style guide
- [ ] All tests pass
- [ ] New tests added for new functionality
- [ ] No commented-out code
- [ ] No console.log/print statements
- [ ] Error handling implemented
- [ ] Security considerations addressed
- [ ] Performance acceptable
- [ ] Documentation updated
- [ ] Commit messages clear
## Anti-Patterns to Avoid
❌ **Magic Numbers** - Use named constants
❌ **God Objects** - Classes that do too much
❌ **Spaghetti Code** - Tangled dependencies
❌ **Copy-Paste** - Violates DRY
❌ **Premature Optimization** - Optimize after profiling
❌ **Not Invented Here** - Use established libraries
❌ **Gold Plating** - Over-engineering simple solutions
## Resources
- [Clean Code](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) - Robert C. Martin
- [The Pragmatic Programmer](https://pragprog.com/titles/tpp20/the-pragmatic-programmer-20th-anniversary-edition/)
- [PEP 8](https://pep8.org/) - Python Style Guide
- [TypeScript Guidelines](https://github.com/microsoft/TypeScript/wiki/Coding-guidelines)
- [OWASP Top 10](https://owasp.org/www-project-top-ten/) - Security
reference/testing-guide.md
# Testing Guide
## Purpose
Comprehensive guide to testing strategies, best practices, and implementation.
## Testing Philosophy
### Why Test?
- **Prevent bugs** reaching production
- **Enable refactoring** with confidence
- **Document behavior** through test cases
- **Faster development** (fix bugs early vs debugging production)
### Test Pyramid
```
/\
/ \ E2E (Few)
/ \ - Full user workflows
/------\
/ \ Integration (Some)
/ \ - Component interaction
/------------\
/______________\ Unit (Many)
- Individual functions/classes
```
**Ratio**: ~70% unit, ~20% integration, ~10% E2E
## Test Types
### Unit Tests
**Purpose**: Test individual functions/methods in isolation
**Characteristics**:
- Fast (< 1ms per test)
- No external dependencies (mock databases, APIs)
- Test one thing per test
- Predictable and deterministic
**Example (TypeScript/Jest)**:
```typescript
describe('validateEmail', () => {
it('should return true for valid email', () => {
expect(validateEmail('user@example.com')).toBe(true);
});
it('should return false for invalid email', () => {
expect(validateEmail('invalid-email')).toBe(false);
});
it('should return false for empty string', () => {
expect(validateEmail('')).toBe(false);
});
it('should return false for null', () => {
expect(validateEmail(null)).toBe(false);
});
});
```
**Example (Python/pytest)**:
```python
def test_validate_email_valid():
assert validate_email('user@example.com') is True
def test_validate_email_invalid():
assert validate_email('invalid-email') is False
def test_validate_email_empty():
assert validate_email('') is False
def test_validate_email_none():
assert validate_email(None) is False
```
### Integration Tests
**Purpose**: Test component interaction and data flow
**Characteristics**:
- Slower than unit tests (< 1s per test)
- May use test database or mock services
- Test realistic scenarios
- Verify components work together
**Example**:
```typescript
describe('UserService Integration', () => {
let db: Database;
let userService: UserService;
beforeAll(async () => {
db = await setupTestDatabase();
userService = new UserService(db);
});
afterAll(async () => {
await db.close();
});
it('should create user and retrieve by ID', async () => {
// Create user
const user = await userService.create({
name: 'Test User',
email: 'test@example.com'
});
// Verify creation
expect(user.id).toBeDefined();
// Retrieve user
const retrieved = await userService.getById(user.id);
// Verify retrieval
expect(retrieved).toEqual(user);
});
});
```
### End-to-End (E2E) Tests
**Purpose**: Test complete user workflows through the UI/API
**Characteristics**:
- Slowest tests (seconds per test)
- Use real or production-like environment
- Test critical user paths
- Most expensive to maintain
**Example (Playwright)**:
```typescript
test('user can complete checkout', async ({ page }) => {
// Navigate to product
await page.goto('/products/123');
// Add to cart
await page.click('button:text("Add to Cart")');
// Go to checkout
await page.click('a:text("Checkout")');
// Fill form
await page.fill('#email', 'user@example.com');
await page.fill('#cardNumber', '4242424242424242');
// Submit
await page.click('button:text("Complete Order")');
// Verify success
await expect(page.locator('.success-message')).toBeVisible();
});
```
## Test-Driven Development (TDD)
### Red-Green-Refactor Cycle
1. **Red**: Write failing test first
2. **Green**: Write minimal code to pass test
3. **Refactor**: Improve code while keeping tests green
**Example**:
```typescript
// 1. RED - Write failing test
describe('calculateDiscount', () => {
it('should apply 10% discount for orders over $100', () => {
expect(calculateDiscount(150)).toBe(15);
});
});
// 2. GREEN - Minimal implementation
function calculateDiscount(amount: number): number {
return amount > 100 ? amount * 0.1 : 0;
}
// 3. REFACTOR - Improve (tests still pass)
function calculateDiscount(
amount: number,
threshold: number = 100,
rate: number = 0.1
): number {
return amount > threshold ? amount * rate : 0;
}
```
## Testing Best Practices
### AAA Pattern (Arrange-Act-Assert)
```typescript
it('should format currency correctly', () => {
// Arrange - Set up test data
const amount = 1234.56;
const currency = 'USD';
// Act - Execute code under test
const result = formatCurrency(amount, currency);
// Assert - Verify outcome
expect(result).toBe('$1,234.56');
});
```
### Test Naming
**Good test names**:
- Describe what's being tested
- Specify expected behavior
- Readable as sentences
```typescript
// ✅ Good
it('should throw error when email is invalid')
it('should return empty array when no users exist')
it('should cache results for 5 minutes')
// ❌ Bad
it('test email')
it('works')
it('edge case')
```
### One Assertion Per Test (when possible)
```typescript
// ✅ Preferred - Easy to see what failed
it('should create user with correct name', () => {
const user = createUser({ name: 'John' });
expect(user.name).toBe('John');
});
it('should create user with correct email', () => {
const user = createUser({ email: 'john@example.com' });
expect(user.email).toBe('john@example.com');
});
// ⚠️ Acceptable - Related assertions
it('should create user with all fields', () => {
const user = createUser({ name: 'John', email: 'john@example.com' });
expect(user.name).toBe('John');
expect(user.email).toBe('john@example.com');
expect(user.id).toBeDefined();
});
```
### Test Isolation
Each test should be independent:
```typescript
// ✅ Good - Each test resets state
describe('UserService', () => {
let userService: UserService;
beforeEach(() => {
userService = new UserService(); // Fresh instance
});
it('test 1', () => { /* ... */ });
it('test 2', () => { /* ... */ });
});
// ❌ Bad - Shared state between tests
let userService = new UserService(); // Shared!
it('test 1', () => {
userService.addUser(user1); // Affects test 2
});
it('test 2', () => {
expect(userService.getUsers()).toHaveLength(0); // Fails!
});
```
## Mocking & Stubbing
### When to Mock
- External services (APIs, databases)
- Slow operations (file I/O, network)
- Non-deterministic behavior (random, dates)
### Mock Example (TypeScript/Jest)
```typescript
// Mock external service
jest.mock('./emailService');
it('should send email on user creation', async () => {
const mockSendEmail = jest.fn();
emailService.send = mockSendEmail;
await userService.create({ email: 'user@example.com' });
expect(mockSendEmail).toHaveBeenCalledWith({
to: 'user@example.com',
subject: 'Welcome'
});
});
```
### Stub Example (Python/pytest)
```python
def test_fetch_user_data(mocker):
# Stub external API call
mock_api = mocker.patch('user_service.api.get')
mock_api.return_value = {'id': '123', 'name': 'Test User'}
result = fetch_user_data('123')
assert result['name'] == 'Test User'
mock_api.assert_called_once_with('/users/123')
```
## Test Coverage
### Coverage Metrics
- **Line coverage**: % of code lines executed
- **Branch coverage**: % of conditional branches tested
- **Function coverage**: % of functions called
### Coverage Goals
- **80%+ overall** - Good baseline
- **100% for critical paths** - Auth, payments, security
- **Don't chase 100%** - Diminishing returns
### Viewing Coverage
```bash
# TypeScript (Jest)
npm test -- --coverage
# Python (pytest with coverage)
pytest --cov=src --cov-report=html
```
## Testing Anti-Patterns
❌ **Testing implementation details** - Test behavior, not internal structure
❌ **Fragile tests** - Break on irrelevant changes
❌ **Slow tests** - Unit tests should be fast
❌ **Interdependent tests** - Tests depend on execution order
❌ **Hidden dependencies** - Setup buried in helper functions
❌ **Testing frameworks** - Don't test library code
❌ **Ignoring failing tests** - Fix or delete, don't skip
## Testing Tools
### TypeScript/JavaScript
- **Jest**: Full-featured test framework
- **Vitest**: Fast Vite-native testing
- **Playwright**: E2E browser testing
- **Supertest**: HTTP API testing
### Python
- **pytest**: Modern testing framework
- **unittest**: Standard library testing
- **mock**: Mocking library (built into unittest.mock)
- **pytest-cov**: Coverage plugin
## Writing Testable Code
### Dependency Injection
```typescript
// ✅ Testable - Dependencies injected
class UserService {
constructor(private db: Database) {}
async getUser(id: string) {
return this.db.query('SELECT * FROM users WHERE id = ?', [id]);
}
}
// Easy to test with mock database
const mockDb = { query: jest.fn() };
const service = new UserService(mockDb);
// ❌ Hard to test - Hard-coded dependency
class UserService {
async getUser(id: string) {
const db = new Database(); // Can't replace!
return db.query('SELECT * FROM users WHERE id = ?', [id]);
}
}
```
### Pure Functions
```typescript
// ✅ Testable - Pure function
function calculateTax(amount: number, rate: number): number {
return amount * rate;
}
// ❌ Hard to test - Side effects
function calculateTax(order: Order): void {
const tax = order.total * 0.1;
order.tax = tax; // Side effect!
database.save(order); // Side effect!
}
```
## Test Organization
### File Structure
```
project/
├── src/
│ ├── services/
│ │ └── userService.ts
│ └── utils/
│ └── validation.ts
└── tests/
├── unit/
│ ├── services/
│ │ └── userService.test.ts
│ └── utils/
│ └── validation.test.ts
├── integration/
│ └── userFlow.test.ts
└── e2e/
└── checkout.test.ts
```
### Test File Naming
- `*.test.ts` or `*.spec.ts` for tests
- `*.test.tsx` for React component tests
- `test_*.py` for Python tests (pytest convention)
## Continuous Integration
### Run Tests on CI
```yaml
# GitHub Actions example
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
- run: npm install
- run: npm test
- run: npm run test:e2e
```
### Pre-commit Hooks
```json
{
"husky": {
"hooks": {
"pre-commit": "npm test",
"pre-push": "npm run test:integration"
}
}
}
```
## Resources
- [Test Driven Development](https://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530) - Kent Beck
- [Growing Object-Oriented Software, Guided by Tests](http://www.growing-object-oriented-software.com/)
- [Jest Documentation](https://jestjs.io/)
- [Pytest Documentation](https://docs.pytest.org/)
- [Testing Library](https://testing-library.com/) - React/DOM testing
- [Playwright](https://playwright.dev/) - E2E testing
workflows/debug-issue.md
# Debugging Workflow
## Purpose
Systematic methodology for identifying and resolving bugs and errors.
## When to Use
- Application crashes or errors
- Unexpected behavior
- Performance degradation
- Test failures
## Process
### 1. Reproduce the Issue (5-15 min)
- Document exact steps to reproduce
- Identify consistent vs intermittent behavior
- Note environment details (OS, versions, config)
- Capture error messages and stack traces
**Deliverable**: Reproducible test case
### 2. Isolate the Problem (10-30 min)
- Use binary search debugging (comment out code sections)
- Add strategic logging statements
- Use debugger with breakpoints
- Check recent code changes (git blame/log)
- Review error logs and metrics
**Tools**: Debugger, logging, git history
**Deliverable**: Narrowed-down problem area
### 3. Root Cause Analysis (15-45 min)
- Examine suspect code carefully
- Check assumptions and edge cases
- Review data flow and state changes
- Verify external dependencies (APIs, databases)
- Test hypotheses with targeted changes
**Deliverable**: Understanding of WHY the bug occurs
### 4. Implement Fix (varies)
- Write minimal fix that addresses root cause
- Avoid "shotgun debugging" (random changes)
- Consider side effects and regressions
- Add defensive programming where appropriate
**Deliverable**: Working fix
### 5. Verify Fix (10-20 min)
- Test original reproduction case
- Test related functionality (regression check)
- Add test case to prevent future recurrence
- Verify in production-like environment
**Deliverable**: Verified, tested fix
### 6. Document & Prevent (5-10 min)
- Document the bug and fix
- Add comments explaining non-obvious fixes
- Consider code improvements to prevent similar bugs
- Update tests and validation
**Deliverable**: Complete solution with preventive measures
## Debugging Techniques
### Rubber Duck Debugging
Explain code line-by-line (even to yourself) to spot logic errors.
### Divide and Conquer
Binary search through code: comment out half, test, repeat.
### Add Logging
Strategic print/log statements to trace execution flow.
### Use Debugger
Breakpoints, watch variables, step through code.
### Check Assumptions
Question everything: variable types, null checks, boundary conditions.
## Common Bug Categories
1. **Logic Errors**: Incorrect algorithm or conditional logic
2. **Type Errors**: Wrong data types or conversions
3. **Null/Undefined**: Missing null checks
4. **Race Conditions**: Async timing issues
5. **Off-by-One**: Array index errors
6. **Memory Issues**: Leaks, excessive allocation
7. **Integration**: External API/service failures
## Completion Checklist
- [ ] Bug reproduced consistently
- [ ] Root cause identified
- [ ] Minimal fix implemented
- [ ] Original issue verified fixed
- [ ] No regressions introduced
- [ ] Test added to prevent recurrence
- [ ] Documentation updated
## Example Output
```
🎯 COMPLETED: [SKILL:engineering] Memory leak in data processor fixed
🗣️ CUSTOM COMPLETED: Bug fixed and tested
```
## Related Workflows
- `implement-feature.md` - Return to after fixing tests during development
- `optimize-code.md` - Use after fixing performance-related bugs
workflows/implement-feature.md
# Feature Implementation Workflow
## Purpose
Systematic approach for implementing new features with quality and testing built-in.
## When to Use
- Building new functionality
- Adding capabilities to existing systems
- Creating new modules or components
## Process
### 1. Requirements Analysis (5-10 min)
- Review feature specification
- Identify edge cases and error scenarios
- Clarify acceptance criteria
- List technical dependencies
**Deliverable**: Clear understanding of what to build
### 2. Design Planning (10-15 min)
- Sketch component architecture
- Identify data structures needed
- Plan API interfaces or function signatures
- Consider extensibility and maintenance
**Deliverable**: Technical design notes
### 3. Implementation (varies)
- Write code incrementally
- Follow coding standards (see `reference/coding-standards.md`)
- Add inline documentation for complex logic
- Handle errors gracefully
- Use stack preferences (TypeScript/bun, Python/uv)
**Deliverable**: Working implementation
### 4. Testing (15-30 min)
- Write unit tests for core functionality
- Test edge cases and error paths
- Verify integration with existing code
- Check performance if relevant
**Deliverable**: Tested, verified code
### 5. Documentation (5-10 min)
- Update relevant documentation
- Add usage examples if needed
- Document configuration options
- Note any breaking changes
**Deliverable**: Complete, documented feature
### 6. Review & Refactor (10-15 min)
- Self-review for code quality
- Refactor for clarity if needed
- Verify adherence to SOLID principles
- Check for security issues
**Deliverable**: Production-ready code
## Completion Checklist
- [ ] Requirements understood and addressed
- [ ] Code follows project standards
- [ ] Error handling implemented
- [ ] Tests written and passing
- [ ] Documentation updated
- [ ] Security considerations addressed
- [ ] Performance acceptable
- [ ] Code reviewed (self or peer)
## Example Output
```
🎯 COMPLETED: [SKILL:engineering] User authentication with JWT implemented
🗣️ CUSTOM COMPLETED: Auth feature ready
```
## Related Workflows
- `debug-issue.md` - For fixing bugs discovered during testing
- `optimize-code.md` - For performance improvements after initial implementation
workflows/optimize-code.md
# Code Optimization Workflow
## Purpose
Systematic approach to improving performance and efficiency without breaking functionality.
## When to Use
- Performance issues identified
- Resource constraints (memory, CPU)
- Scalability concerns
- User complaints about slowness
## Process
### 1. Measure & Profile (15-30 min)
- **NEVER optimize without measuring first**
- Use profiling tools to identify bottlenecks
- Measure baseline performance metrics
- Identify hotspots (where time is actually spent)
- Document current metrics
**Tools**:
- Python: cProfile, line_profiler, memory_profiler
- JavaScript: Chrome DevTools, Node.js profiler
- TypeScript: Same as JavaScript
**Deliverable**: Performance profile with hotspots identified
### 2. Prioritize Targets (10 min)
- Focus on biggest bottlenecks first (80/20 rule)
- Consider ROI of optimization effort
- Avoid premature optimization
- Check if issue is algorithmic vs implementation
**Deliverable**: Ordered list of optimization targets
### 3. Research Solutions (15-30 min)
- Review algorithm complexity (Big O)
- Consider different data structures
- Look for standard optimization patterns
- Check library/framework best practices
**Common Optimizations**:
- O(n²) → O(n log n) with better algorithm
- Linear search → Hash table lookup
- Repeated calculation → Caching/memoization
- Synchronous → Asynchronous processing
- Database: N+1 queries → Batch queries
**Deliverable**: Optimization strategy
### 4. Implement Optimization (varies)
- Make ONE change at a time
- Keep original code commented for comparison
- Maintain correctness while improving performance
- Document trade-offs (memory vs speed, readability vs performance)
**Deliverable**: Optimized code
### 5. Measure Improvement (10-15 min)
- Re-run profiling with same test data
- Compare new metrics to baseline
- Verify correctness maintained
- Test edge cases still work
**Deliverable**: Performance metrics showing improvement
### 6. Iterate or Complete (varies)
- If target met → document and finish
- If not met → return to step 2 with new data
- If regression → rollback and try different approach
**Deliverable**: Optimized, verified code with metrics
## Optimization Techniques
### Algorithmic
- Better algorithm (O(n²) → O(n log n))
- Different data structure (list → set, dict)
- Reduce redundant work
### Caching
- Memoization for expensive calculations
- Query result caching
- Computed property caching
### Database
- Add indexes for frequent queries
- Batch operations to reduce round-trips
- Use connection pooling
- Optimize query complexity
### Async/Parallel
- Async I/O instead of blocking
- Parallel processing for CPU-bound tasks
- Background processing for slow operations
### Memory
- Use generators instead of lists (Python)
- Stream processing for large files
- Limit in-memory data structures
## Anti-Patterns to Avoid
❌ Optimizing before measuring (premature optimization)
❌ Making code unreadable for minor gains
❌ Optimizing the wrong bottleneck
❌ Breaking functionality for speed
❌ Ignoring maintenance costs of complex optimization
## Completion Checklist
- [ ] Baseline metrics captured
- [ ] Profiling identified actual bottlenecks
- [ ] Optimization targets prioritized
- [ ] Implementation maintains correctness
- [ ] Performance improvement measured and documented
- [ ] Trade-offs understood and documented
- [ ] Edge cases still work
- [ ] Code remains maintainable
## Example Output
```
🎯 COMPLETED: [SKILL:engineering] Database query optimized - 80% faster
🗣️ CUSTOM COMPLETED: Query optimized
```
## Metrics to Track
- **Response Time**: Before vs after
- **Throughput**: Requests/second
- **Resource Usage**: CPU, memory, disk I/O
- **Latency**: p50, p95, p99 percentiles
- **Database**: Query time, number of queries
## Related Workflows
- `debug-issue.md` - For investigating performance bugs
- `implement-feature.md` - Optimization during initial development