Initial commit
This commit is contained in:
553
commands/review/README.md
Normal file
553
commands/review/README.md
Normal file
@@ -0,0 +1,553 @@
|
||||
# Code Review Skill
|
||||
|
||||
Comprehensive code review system with specialized operations for different review types and focus areas. Provides structured, actionable feedback with priority levels and detailed analysis across security, performance, quality, accessibility, and PR reviews.
|
||||
|
||||
## Overview
|
||||
|
||||
The review skill orchestrates multi-category code reviews through a router-based architecture. Each operation targets specific review concerns while maintaining consistent output formats and depth levels.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
review/
|
||||
├── skill.md # Router - orchestrates review operations
|
||||
├── full.md # Comprehensive multi-category review
|
||||
├── security.md # Security-focused review (OWASP Top 10)
|
||||
├── performance.md # Performance optimization review
|
||||
├── quality.md # Code quality and maintainability review
|
||||
├── pr.md # Pull request review with git integration
|
||||
└── accessibility.md # Accessibility (a11y) compliance review
|
||||
```
|
||||
|
||||
## Available Operations
|
||||
|
||||
### `/review full`
|
||||
**Comprehensive Review** - All categories covered
|
||||
|
||||
Performs complete code review covering:
|
||||
- Security (authentication, injection prevention, data protection)
|
||||
- Performance (database, backend, frontend, network)
|
||||
- Code Quality (organization, error handling, type safety)
|
||||
- Architecture (design patterns, scalability, maintainability)
|
||||
- Testing (coverage, quality, edge cases)
|
||||
- Documentation (code comments, project docs)
|
||||
- Accessibility (for frontend code)
|
||||
|
||||
**Best for**: Feature completeness reviews, pre-production audits, comprehensive assessment
|
||||
|
||||
---
|
||||
|
||||
### `/review security`
|
||||
**Security-Focused Review** - OWASP Top 10 compliance
|
||||
|
||||
Deep security audit focusing on:
|
||||
- Authentication & Authorization (JWT, session management, RBAC)
|
||||
- Input Validation & Injection Prevention (SQL, XSS, CSRF, command injection)
|
||||
- Data Protection (encryption, secrets management, PII handling)
|
||||
- Security Headers (CSP, HSTS, X-Frame-Options)
|
||||
- Dependency Vulnerabilities (npm audit, pip-audit)
|
||||
- OWASP Top 10 comprehensive check
|
||||
|
||||
**Best for**: Payment systems, authentication modules, API endpoints, compliance audits
|
||||
|
||||
---
|
||||
|
||||
### `/review performance`
|
||||
**Performance-Focused Review** - Optimization analysis
|
||||
|
||||
Performance optimization across:
|
||||
- Database Performance (N+1 queries, indexes, connection pooling)
|
||||
- Backend Performance (algorithms, async operations, caching)
|
||||
- Frontend Performance (React optimization, bundle size, virtualization)
|
||||
- Network Performance (API calls, compression, CDN)
|
||||
- Scalability Assessment (horizontal/vertical scaling)
|
||||
|
||||
**Best for**: Dashboard components, API services, data-heavy features, production optimization
|
||||
|
||||
---
|
||||
|
||||
### `/review quality`
|
||||
**Code Quality Review** - Maintainability and craftsmanship
|
||||
|
||||
Software craftsmanship review covering:
|
||||
- Code Organization (naming, function size, structure)
|
||||
- Error Handling (validation, meaningful errors, graceful degradation)
|
||||
- Type Safety (TypeScript, proper types, no any)
|
||||
- Testing (coverage, quality, edge cases)
|
||||
- Documentation (comments, README, API docs)
|
||||
- SOLID Principles (SRP, DI, OCP, LSP, ISP)
|
||||
- Design Patterns (appropriate usage, anti-patterns)
|
||||
|
||||
**Best for**: Refactoring efforts, technical debt assessment, maintainability improvements
|
||||
|
||||
---
|
||||
|
||||
### `/review pr`
|
||||
**Pull Request Review** - Git-integrated change analysis
|
||||
|
||||
PR-specific review with git context:
|
||||
- PR metadata validation (title, description, size)
|
||||
- Change scope assessment (no scope creep, aligned with description)
|
||||
- Commit quality (meaningful messages, atomic commits)
|
||||
- Impact analysis (risk assessment, backward compatibility)
|
||||
- All review categories applied to changes only
|
||||
- Test coverage for new/changed code
|
||||
- Documentation updates
|
||||
|
||||
**Best for**: Code review collaboration, GitHub/GitLab workflows, team reviews
|
||||
|
||||
---
|
||||
|
||||
### `/review accessibility`
|
||||
**Accessibility Review** - WCAG compliance (a11y)
|
||||
|
||||
Accessibility audit for inclusive design:
|
||||
- Semantic HTML (proper elements, heading hierarchy)
|
||||
- ARIA (roles, properties, labels, live regions)
|
||||
- Keyboard Navigation (tab order, focus management, shortcuts)
|
||||
- Screen Reader Compatibility (alt text, labels, announcements)
|
||||
- Color & Contrast (WCAG AA/AAA ratios, color-blind friendly)
|
||||
- Responsive Design (zoom support, touch targets)
|
||||
- WCAG 2.1 compliance (Level A, AA, AAA)
|
||||
|
||||
**Best for**: UI components, checkout flows, forms, public-facing applications
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```bash
|
||||
/10x-fullstack-engineer:review <operation> scope:"<what-to-review>" [depth:"<level>"] [focus:"<area>"]
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Required | Values | Default | Description |
|
||||
|-----------|----------|--------|---------|-------------|
|
||||
| `operation` | Yes | `full`, `security`, `performance`, `quality`, `pr`, `accessibility` | - | Review type |
|
||||
| `scope` | Yes | Any string | - | What to review (files, modules, features, PR) |
|
||||
| `depth` | No | `quick`, `standard`, `deep` | `standard` | Review thoroughness |
|
||||
| `focus` | No | Any string | - | Additional emphasis areas |
|
||||
|
||||
### Review Depth Levels
|
||||
|
||||
| Depth | Time | Coverage | Use Case |
|
||||
|-------|------|----------|----------|
|
||||
| **Quick** | 5-15 min | High-level scan, critical issues only, obvious bugs | Quick checks, initial assessment, time-constrained |
|
||||
| **Standard** | 20-40 min | All major categories, thorough review, actionable feedback | Regular code reviews, PR reviews, feature reviews |
|
||||
| **Deep** | 45-90+ min | Comprehensive analysis, architecture review, complete audit | Pre-production, security audits, technical debt assessment |
|
||||
|
||||
### Examples
|
||||
|
||||
#### Comprehensive Feature Review
|
||||
```bash
|
||||
/10x-fullstack-engineer:review full scope:"authentication feature" depth:"deep"
|
||||
```
|
||||
Reviews all security, performance, quality, testing, and documentation aspects of the auth feature.
|
||||
|
||||
---
|
||||
|
||||
#### Security Audit for Critical Module
|
||||
```bash
|
||||
/10x-fullstack-engineer:review security scope:"payment processing module" depth:"deep"
|
||||
```
|
||||
Deep security audit focusing on OWASP Top 10, PCI DSS considerations, and vulnerability scanning.
|
||||
|
||||
---
|
||||
|
||||
#### Performance Analysis
|
||||
```bash
|
||||
/10x-fullstack-engineer:review performance scope:"dashboard rendering and data loading" depth:"standard"
|
||||
```
|
||||
Analyzes database queries, rendering optimization, bundle size, and API call efficiency.
|
||||
|
||||
---
|
||||
|
||||
#### Code Quality Check
|
||||
```bash
|
||||
/10x-fullstack-engineer:review quality scope:"src/utils and src/helpers" depth:"quick"
|
||||
```
|
||||
Quick scan for code organization, duplication, naming, and obvious quality issues.
|
||||
|
||||
---
|
||||
|
||||
#### Pull Request Review
|
||||
```bash
|
||||
/10x-fullstack-engineer:review pr scope:"PR #456 - Add user permissions" depth:"standard"
|
||||
```
|
||||
Reviews PR changes with git integration, assesses impact, checks tests, and provides GitHub-compatible feedback.
|
||||
|
||||
---
|
||||
|
||||
#### Accessibility Compliance
|
||||
```bash
|
||||
/10x-fullstack-engineer:review accessibility scope:"checkout flow components" depth:"deep" level:"AA"
|
||||
```
|
||||
Comprehensive WCAG 2.1 Level AA compliance review with screen reader testing recommendations.
|
||||
|
||||
---
|
||||
|
||||
#### Quick Security Scan
|
||||
```bash
|
||||
/10x-fullstack-engineer:review security scope:"recent changes in API layer" depth:"quick"
|
||||
```
|
||||
Fast security scan for obvious vulnerabilities in recent changes.
|
||||
|
||||
---
|
||||
|
||||
#### Performance Hot Spot
|
||||
```bash
|
||||
/10x-fullstack-engineer:review performance scope:"UserList component" depth:"standard" focus:"rendering and memory"
|
||||
```
|
||||
Standard performance review with extra focus on rendering performance and memory leaks.
|
||||
|
||||
---
|
||||
|
||||
## Review Categories
|
||||
|
||||
All operations assess findings across these categories:
|
||||
|
||||
### Security 🔒
|
||||
- Authentication & authorization
|
||||
- Input validation & sanitization
|
||||
- Injection prevention (SQL, XSS, command)
|
||||
- Secrets management
|
||||
- Data protection (encryption, PII)
|
||||
- OWASP Top 10 vulnerabilities
|
||||
|
||||
### Performance ⚡
|
||||
- Database optimization (queries, indexes, N+1)
|
||||
- Backend efficiency (algorithms, async, caching)
|
||||
- Frontend optimization (React, bundle, rendering)
|
||||
- Network optimization (API calls, compression)
|
||||
- Scalability considerations
|
||||
|
||||
### Code Quality 📝
|
||||
- Organization & naming
|
||||
- Function size & complexity
|
||||
- Error handling
|
||||
- Type safety (TypeScript)
|
||||
- Code duplication (DRY)
|
||||
- SOLID principles
|
||||
|
||||
### Testing 🧪
|
||||
- Unit test coverage
|
||||
- Integration tests
|
||||
- Component/E2E tests
|
||||
- Test quality & meaningfulness
|
||||
- Edge case coverage
|
||||
|
||||
### Documentation 📚
|
||||
- Code comments
|
||||
- JSDoc/docstrings
|
||||
- README accuracy
|
||||
- API documentation
|
||||
- Architecture docs (ADRs)
|
||||
|
||||
### Accessibility ♿
|
||||
- Semantic HTML
|
||||
- ARIA usage
|
||||
- Keyboard navigation
|
||||
- Screen reader compatibility
|
||||
- WCAG compliance
|
||||
|
||||
## Priority Levels
|
||||
|
||||
Reviews classify findings by priority:
|
||||
|
||||
| Priority | Symbol | Meaning | Action Required |
|
||||
|----------|--------|---------|-----------------|
|
||||
| **Critical** | 🚨 | Security vulnerabilities, data integrity issues, breaking bugs | Must fix before merge/deploy |
|
||||
| **High** | ⚠️ | Performance bottlenecks, major quality issues, missing tests | Should fix before merge |
|
||||
| **Medium** | ℹ️ | Code quality improvements, refactoring opportunities, minor issues | Consider fixing |
|
||||
| **Low** | 💡 | Nice-to-have improvements, style suggestions, optimizations | Optional |
|
||||
|
||||
## Output Format
|
||||
|
||||
All review operations produce structured feedback:
|
||||
|
||||
```markdown
|
||||
# [Review Type]: [Scope]
|
||||
|
||||
## Executive Summary
|
||||
- Overall assessment and rating
|
||||
- Key metrics (coverage, performance, quality)
|
||||
- Recommendation (Approve/Request Changes/Needs Info)
|
||||
- Priority actions
|
||||
|
||||
## Critical Issues 🚨
|
||||
- File paths and line numbers
|
||||
- Clear problem description
|
||||
- Risk/impact explanation
|
||||
- Code examples (current vs. suggested)
|
||||
- Testing recommendations
|
||||
|
||||
## High Priority Issues ⚠️
|
||||
- Similar structure to critical
|
||||
- Actionable suggestions
|
||||
|
||||
## Medium Priority Issues ℹ️
|
||||
- Improvement opportunities
|
||||
- Refactoring suggestions
|
||||
|
||||
## Low Priority Issues 💡
|
||||
- Nice-to-have enhancements
|
||||
- Style improvements
|
||||
|
||||
## Positive Observations ✅
|
||||
- Good practices to maintain
|
||||
- Strengths in the code
|
||||
|
||||
## Detailed Review by Category
|
||||
- Category-specific analysis
|
||||
- Metrics and scoring
|
||||
- Specific recommendations
|
||||
|
||||
## Recommendations
|
||||
- Immediate actions (this week)
|
||||
- Short-term improvements (this month)
|
||||
- Long-term enhancements (this quarter)
|
||||
|
||||
## Review Metadata
|
||||
- Reviewer, date, depth, time spent
|
||||
- Issue counts by priority
|
||||
```
|
||||
|
||||
## Review Focus Areas
|
||||
|
||||
### Security Focus Areas
|
||||
- **Authentication**: JWT validation, session management, MFA
|
||||
- **Authorization**: RBAC, permission checks, resource access
|
||||
- **Input Validation**: All user inputs validated and sanitized
|
||||
- **Injection Prevention**: SQL, XSS, CSRF, command, path traversal
|
||||
- **Secrets Management**: No hardcoded credentials, environment variables
|
||||
- **Data Protection**: Encryption at rest/transit, PII handling
|
||||
- **Dependencies**: Vulnerability scanning (npm audit, pip-audit)
|
||||
|
||||
### Performance Focus Areas
|
||||
- **Database**: Query optimization, N+1 prevention, indexes, connection pooling
|
||||
- **Backend**: Algorithm complexity, async operations, caching, rate limiting
|
||||
- **Frontend**: React optimization (memo, useMemo, useCallback), virtualization, bundle size
|
||||
- **Network**: API batching, compression, CDN, prefetching
|
||||
|
||||
### Quality Focus Areas
|
||||
- **Organization**: Clear naming, function size (<50 lines), DRY principle
|
||||
- **Error Handling**: All errors caught, meaningful messages, proper logging
|
||||
- **Type Safety**: No `any` types, explicit return types, proper interfaces
|
||||
- **Testing**: >80% coverage for critical code, meaningful tests, edge cases
|
||||
- **Documentation**: Complex logic explained, public APIs documented, README current
|
||||
|
||||
### Accessibility Focus Areas
|
||||
- **Semantic HTML**: Proper elements, heading hierarchy, landmarks
|
||||
- **ARIA**: Correct roles, properties, labels, live regions
|
||||
- **Keyboard**: Full keyboard access, logical tab order, visible focus
|
||||
- **Screen Reader**: Alt text, form labels, announcements, reading order
|
||||
- **Contrast**: WCAG AA (4.5:1 text, 3:1 UI), AAA (7:1 text, 4.5:1 large text)
|
||||
|
||||
## Common Review Workflows
|
||||
|
||||
### Pre-Merge PR Review
|
||||
```bash
|
||||
# 1. Standard PR review
|
||||
/10x-fullstack-engineer:review pr scope:"PR #123" depth:"standard"
|
||||
|
||||
# 2. If security-sensitive changes detected, follow up with:
|
||||
/10x-fullstack-engineer:review security scope:"payment module changes" depth:"deep"
|
||||
|
||||
# 3. If performance-critical changes, analyze:
|
||||
/10x-fullstack-engineer:review performance scope:"database query changes" depth:"standard"
|
||||
```
|
||||
|
||||
### Pre-Production Audit
|
||||
```bash
|
||||
# 1. Comprehensive review of feature
|
||||
/10x-fullstack-engineer:review full scope:"new checkout feature" depth:"deep"
|
||||
|
||||
# 2. Dedicated security audit
|
||||
/10x-fullstack-engineer:review security scope:"checkout feature" depth:"deep"
|
||||
|
||||
# 3. Accessibility compliance (if user-facing)
|
||||
/10x-fullstack-engineer:review accessibility scope:"checkout UI" depth:"deep" level:"AA"
|
||||
```
|
||||
|
||||
### Technical Debt Assessment
|
||||
```bash
|
||||
# 1. Quality review to identify debt
|
||||
/10x-fullstack-engineer:review quality scope:"legacy auth module" depth:"deep"
|
||||
|
||||
# 2. Performance assessment
|
||||
/10x-fullstack-engineer:review performance scope:"legacy auth module" depth:"standard"
|
||||
|
||||
# 3. Security review (critical for old code)
|
||||
/10x-fullstack-engineer:review security scope:"legacy auth module" depth:"deep"
|
||||
```
|
||||
|
||||
### Quick Daily Reviews
|
||||
```bash
|
||||
# Quick review of recent changes
|
||||
/10x-fullstack-engineer:review quality scope:"today's commits" depth:"quick"
|
||||
|
||||
# Fast security scan
|
||||
/10x-fullstack-engineer:review security scope:"API changes today" depth:"quick"
|
||||
```
|
||||
|
||||
## Integration with 10x-fullstack-engineer Agent
|
||||
|
||||
All review operations leverage the **10x-fullstack-engineer** agent for:
|
||||
- Cross-stack expertise (frontend, backend, database, infrastructure)
|
||||
- Pattern recognition across different tech stacks
|
||||
- Best practices knowledge (React, Node.js, Python, Go, etc.)
|
||||
- Constructive, actionable feedback
|
||||
- Architectural understanding
|
||||
- Security awareness (OWASP, common vulnerabilities)
|
||||
- Performance optimization techniques
|
||||
|
||||
## Review Best Practices
|
||||
|
||||
### For Reviewers
|
||||
1. **Be Specific**: Always include file paths and line numbers
|
||||
2. **Be Constructive**: Suggest solutions, not just problems
|
||||
3. **Explain Why**: Help understand reasoning behind recommendations
|
||||
4. **Provide Examples**: Show both problematic and corrected code
|
||||
5. **Acknowledge Good Work**: Recognize strengths and good practices
|
||||
6. **Prioritize by Impact**: Security and data integrity first
|
||||
7. **Be Actionable**: Every issue should have clear next steps
|
||||
8. **Ask Questions**: When intent is unclear, ask rather than assume
|
||||
|
||||
### For Code Authors
|
||||
1. **Provide Context**: Explain design decisions in PR descriptions
|
||||
2. **Address Critical Issues First**: Focus on 🚨 and ⚠️ items
|
||||
3. **Ask for Clarification**: If feedback is unclear, ask
|
||||
4. **Update Tests**: Add tests for issues found
|
||||
5. **Document Decisions**: Update docs based on feedback
|
||||
6. **Iterative Improvement**: Don't try to fix everything at once
|
||||
|
||||
## Testing & Validation
|
||||
|
||||
Reviews recommend testing approaches:
|
||||
|
||||
### Security Testing
|
||||
- Dependency vulnerability scanning (npm audit, pip-audit)
|
||||
- Manual penetration testing for critical areas
|
||||
- OWASP ZAP or Burp Suite for web apps
|
||||
- Security unit tests (auth, validation)
|
||||
|
||||
### Performance Testing
|
||||
- Load testing (k6, Artillery, Locust)
|
||||
- Profiling (Chrome DevTools, clinic.js)
|
||||
- Bundle analysis (webpack-bundle-analyzer)
|
||||
- Lighthouse audits
|
||||
|
||||
### Accessibility Testing
|
||||
- Automated tools (axe-core, pa11y, Lighthouse)
|
||||
- Manual keyboard navigation testing
|
||||
- Screen reader testing (NVDA, JAWS, VoiceOver)
|
||||
- Color contrast analyzers
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding Focus Areas
|
||||
```bash
|
||||
# Add custom focus to any review
|
||||
/10x-fullstack-engineer:review full scope:"API layer" depth:"standard" focus:"error handling and logging"
|
||||
```
|
||||
|
||||
### Adjusting Depth
|
||||
- **Quick**: Time-constrained, pre-commit hooks, CI/CD gates
|
||||
- **Standard**: Regular PR reviews, feature completeness checks
|
||||
- **Deep**: Pre-production, security audits, architecture reviews
|
||||
|
||||
### Combining Operations
|
||||
For complex reviews, run multiple operations:
|
||||
```bash
|
||||
# 1. Full review for baseline
|
||||
/10x-fullstack-engineer:review full scope:"feature" depth:"standard"
|
||||
|
||||
# 2. Deep dive on specific concern
|
||||
/10x-fullstack-engineer:review security scope:"feature auth logic" depth:"deep"
|
||||
|
||||
# 3. Performance analysis
|
||||
/10x-fullstack-engineer:review performance scope:"feature data loading" depth:"standard"
|
||||
```
|
||||
|
||||
## Tools & Resources
|
||||
|
||||
### Recommended Tools
|
||||
- **Linting**: ESLint (eslint-plugin-jsx-a11y), Pylint, golangci-lint
|
||||
- **Security**: npm audit, pip-audit, Snyk, OWASP Dependency-Check
|
||||
- **Performance**: Lighthouse, Chrome DevTools, webpack-bundle-analyzer
|
||||
- **Accessibility**: axe DevTools, WAVE, Lighthouse, pa11y
|
||||
- **Testing**: Jest, Pytest, Go test, Cypress, Playwright
|
||||
|
||||
### Documentation References
|
||||
- **Security**: OWASP Top 10, CWE Top 25, SANS Top 25
|
||||
- **Performance**: Web Vitals, Core Web Vitals, Performance Best Practices
|
||||
- **Quality**: Clean Code, SOLID Principles, Design Patterns
|
||||
- **Accessibility**: WCAG 2.1, ARIA Authoring Practices
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Review scope too large"
|
||||
**Solution**: Break into smaller reviews
|
||||
```bash
|
||||
# Instead of:
|
||||
/10x-fullstack-engineer:review full scope:"entire application" depth:"deep"
|
||||
|
||||
# Do:
|
||||
/10x-fullstack-engineer:review full scope:"authentication module" depth:"deep"
|
||||
/10x-fullstack-engineer:review full scope:"payment module" depth:"deep"
|
||||
/10x-fullstack-engineer:review full scope:"user management" depth:"deep"
|
||||
```
|
||||
|
||||
### "Not enough context provided"
|
||||
**Solution**: Be more specific about scope
|
||||
```bash
|
||||
# Instead of:
|
||||
/10x-fullstack-engineer:review security scope:"code" depth:"standard"
|
||||
|
||||
# Do:
|
||||
/10x-fullstack-engineer:review security scope:"src/auth module - JWT validation and session management" depth:"standard"
|
||||
```
|
||||
|
||||
### "Need faster reviews"
|
||||
**Solution**: Use quick depth for initial pass
|
||||
```bash
|
||||
# Quick pass first
|
||||
/10x-fullstack-engineer:review quality scope:"new feature" depth:"quick"
|
||||
|
||||
# Then deep dive on issues found
|
||||
/10x-fullstack-engineer:review security scope:"authentication logic" depth:"deep"
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
To extend or customize review operations:
|
||||
|
||||
1. Review operations are in `/commands/review/*.md`
|
||||
2. Router logic is in `/commands/review/skill.md`
|
||||
3. Each operation follows a consistent structure:
|
||||
- Parse parameters from `$ARGUMENTS`
|
||||
- Gather context (git, project structure)
|
||||
- Execute category-specific checklists
|
||||
- Provide structured output
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Command | Best For | Time | Focus |
|
||||
|---------|----------|------|-------|
|
||||
| `/review full` | Complete assessment | 45-60 min | All categories |
|
||||
| `/review security` | Security audit | 30-90 min | OWASP Top 10, vulnerabilities |
|
||||
| `/review performance` | Optimization | 30-90 min | Speed, scalability, efficiency |
|
||||
| `/review quality` | Maintainability | 30-90 min | Clean code, SOLID, patterns |
|
||||
| `/review pr` | Pull requests | 20-30 min | Changes, impact, tests |
|
||||
| `/review accessibility` | WCAG compliance | 30-90 min | a11y, ARIA, keyboard, screen readers |
|
||||
|
||||
---
|
||||
|
||||
**Created by**: 10x Fullstack Engineer Plugin
|
||||
**Version**: 1.0.0
|
||||
**Last Updated**: 2025-10-14
|
||||
864
commands/review/accessibility.md
Normal file
864
commands/review/accessibility.md
Normal file
@@ -0,0 +1,864 @@
|
||||
# Accessibility Review
|
||||
|
||||
Performs comprehensive accessibility (a11y) audit focusing on WCAG compliance, screen reader compatibility, keyboard navigation, and inclusive design principles.
|
||||
|
||||
## Parameters
|
||||
|
||||
**Received from router**: `$ARGUMENTS` (after removing 'accessibility' operation)
|
||||
|
||||
Expected format: `scope:"review-scope" [depth:"quick|standard|deep"] [level:"A|AA|AAA"]`
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Parse Parameters
|
||||
|
||||
Extract from $ARGUMENTS:
|
||||
- **scope**: What to review (required) - components, pages, features
|
||||
- **depth**: Review thoroughness (default: "standard")
|
||||
- **level**: WCAG compliance level (default: "AA")
|
||||
|
||||
## WCAG Compliance Levels
|
||||
|
||||
- **Level A**: Minimum accessibility (basic compliance)
|
||||
- **Level AA**: Standard accessibility (recommended target)
|
||||
- **Level AAA**: Enhanced accessibility (gold standard)
|
||||
|
||||
### 2. Gather Context
|
||||
|
||||
**Identify UI Components**:
|
||||
```bash
|
||||
# Find frontend components
|
||||
find . -name "*.tsx" -o -name "*.jsx" -o -name "*.vue" -o -name "*.svelte" | head -20
|
||||
|
||||
# Check for accessibility tooling
|
||||
cat package.json | grep -E "axe|pa11y|lighthouse|eslint-plugin-jsx-a11y"
|
||||
|
||||
# Look for ARIA usage
|
||||
grep -r "aria-" --include="*.tsx" --include="*.jsx" --include="*.html" | head -20
|
||||
|
||||
# Check for role attributes
|
||||
grep -r 'role=' --include="*.tsx" --include="*.jsx" --include="*.html" | head -20
|
||||
```
|
||||
|
||||
### 3. Semantic HTML Review
|
||||
|
||||
**Proper HTML Structure**:
|
||||
- [ ] Semantic HTML elements used (`<header>`, `<nav>`, `<main>`, `<footer>`, `<article>`, `<section>`)
|
||||
- [ ] Headings in logical order (h1 → h2 → h3, no skipping)
|
||||
- [ ] Lists use `<ul>`, `<ol>`, `<dl>` appropriately
|
||||
- [ ] Tables use `<table>`, `<th>`, `<caption>` properly
|
||||
- [ ] Forms use `<form>`, `<label>`, `<fieldset>`, `<legend>`
|
||||
- [ ] Buttons use `<button>` (not styled divs)
|
||||
- [ ] Links use `<a>` with href attribute
|
||||
|
||||
**Document Structure**:
|
||||
- [ ] Single `<h1>` per page describing main content
|
||||
- [ ] Landmark regions defined (`<header>`, `<nav>`, `<main>`, `<aside>`, `<footer>`)
|
||||
- [ ] Skip to main content link present
|
||||
- [ ] Page has meaningful `<title>`
|
||||
- [ ] Language attribute on `<html>` element
|
||||
|
||||
**Code Examples - Semantic HTML**:
|
||||
|
||||
```html
|
||||
<!-- ❌ BAD: Non-semantic markup -->
|
||||
<div class="header">
|
||||
<div class="nav">
|
||||
<div class="nav-item" onclick="navigate('/home')">Home</div>
|
||||
<div class="nav-item" onclick="navigate('/about')">About</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="main-content">
|
||||
<div class="title">Welcome</div>
|
||||
<div class="text">Content here</div>
|
||||
</div>
|
||||
|
||||
<!-- ✅ GOOD: Semantic HTML -->
|
||||
<header>
|
||||
<nav aria-label="Main navigation">
|
||||
<ul>
|
||||
<li><a href="/home">Home</a></li>
|
||||
<li><a href="/about">About</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
<h1>Welcome</h1>
|
||||
<p>Content here</p>
|
||||
</main>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- ❌ BAD: Incorrect heading hierarchy -->
|
||||
<h1>Main Title</h1>
|
||||
<h3>Subsection</h3> <!-- Skipped h2! -->
|
||||
<h2>Another Section</h2> <!-- Wrong order! -->
|
||||
|
||||
<!-- ✅ GOOD: Logical heading order -->
|
||||
<h1>Main Title</h1>
|
||||
<h2>Section</h2>
|
||||
<h3>Subsection</h3>
|
||||
<h2>Another Section</h2>
|
||||
<h3>Another Subsection</h3>
|
||||
```
|
||||
|
||||
### 4. ARIA (Accessible Rich Internet Applications)
|
||||
|
||||
**ARIA Attributes**:
|
||||
- [ ] ARIA used only when semantic HTML insufficient
|
||||
- [ ] ARIA roles appropriate and correct
|
||||
- [ ] ARIA properties accurately reflect state
|
||||
- [ ] ARIA labels provide meaningful descriptions
|
||||
- [ ] Dynamic content changes announced
|
||||
|
||||
**Common ARIA Patterns**:
|
||||
- [ ] Buttons: `role="button"` with `aria-pressed` for toggles
|
||||
- [ ] Dialogs: `role="dialog"`, `aria-modal="true"`, `aria-labelledby`
|
||||
- [ ] Tabs: `role="tablist"`, `role="tab"`, `role="tabpanel"`, `aria-selected`
|
||||
- [ ] Menus: `role="menu"`, `role="menuitem"`, `aria-haspopup`
|
||||
- [ ] Alerts: `role="alert"` or `aria-live="assertive"`
|
||||
- [ ] Loading: `aria-busy="true"`, `aria-live="polite"`
|
||||
|
||||
**ARIA Best Practices**:
|
||||
- [ ] First rule of ARIA: Don't use ARIA (prefer semantic HTML)
|
||||
- [ ] ARIA doesn't change behavior, only semantics
|
||||
- [ ] ARIA attributes are valid and supported
|
||||
- [ ] Required ARIA attributes present
|
||||
- [ ] ARIA properties reflect current state
|
||||
|
||||
**Code Examples - ARIA**:
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: Div as button without proper ARIA
|
||||
<div onClick={handleClick} className="button">
|
||||
Click me
|
||||
</div>
|
||||
|
||||
// ✅ GOOD: Proper button element (no ARIA needed)
|
||||
<button onClick={handleClick}>
|
||||
Click me
|
||||
</button>
|
||||
|
||||
// ✅ ACCEPTABLE: Div with complete button semantics
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={handleClick}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleClick()}
|
||||
aria-label="Click me"
|
||||
>
|
||||
Click me
|
||||
</div>
|
||||
```
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: No ARIA for custom dropdown
|
||||
<div className="dropdown">
|
||||
<div onClick={toggle}>Menu</div>
|
||||
{isOpen && (
|
||||
<div className="menu">
|
||||
<div onClick={handleOption1}>Option 1</div>
|
||||
<div onClick={handleOption2}>Option 2</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
// ✅ GOOD: Proper ARIA for dropdown
|
||||
<div className="dropdown">
|
||||
<button
|
||||
aria-haspopup="true"
|
||||
aria-expanded={isOpen}
|
||||
onClick={toggle}
|
||||
>
|
||||
Menu
|
||||
</button>
|
||||
{isOpen && (
|
||||
<ul role="menu">
|
||||
<li role="menuitem">
|
||||
<button onClick={handleOption1}>Option 1</button>
|
||||
</li>
|
||||
<li role="menuitem">
|
||||
<button onClick={handleOption2}>Option 2</button>
|
||||
</li>
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
```
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: Loading state not announced
|
||||
{isLoading && <div className="spinner">Loading...</div>}
|
||||
|
||||
// ✅ GOOD: Loading state announced to screen readers
|
||||
{isLoading && (
|
||||
<div role="status" aria-live="polite">
|
||||
<span className="spinner" aria-hidden="true"></span>
|
||||
<span className="sr-only">Loading...</span>
|
||||
</div>
|
||||
)}
|
||||
```
|
||||
|
||||
### 5. Keyboard Navigation
|
||||
|
||||
**Keyboard Accessibility**:
|
||||
- [ ] All interactive elements keyboard accessible
|
||||
- [ ] Tab order is logical and follows visual order
|
||||
- [ ] Focus indicators visible and clear
|
||||
- [ ] No keyboard traps (can always tab away)
|
||||
- [ ] Skip links for keyboard users
|
||||
- [ ] Shortcuts don't conflict with browser/screen reader
|
||||
- [ ] Custom controls have keyboard support
|
||||
|
||||
**Keyboard Interactions**:
|
||||
- [ ] Enter/Space activates buttons and links
|
||||
- [ ] Arrow keys navigate lists and menus
|
||||
- [ ] Escape closes dialogs and menus
|
||||
- [ ] Tab moves to next element
|
||||
- [ ] Shift+Tab moves to previous element
|
||||
- [ ] Home/End navigate to start/end
|
||||
|
||||
**Focus Management**:
|
||||
- [ ] Focus visible (no `outline: none` without alternative)
|
||||
- [ ] Focus moved appropriately (dialogs, route changes)
|
||||
- [ ] Focus restored when closing dialogs
|
||||
- [ ] Focus not lost during dynamic updates
|
||||
- [ ] Focus indicator meets contrast requirements (3:1)
|
||||
|
||||
**Code Examples - Keyboard Navigation**:
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: No keyboard support for custom control
|
||||
<div onClick={handleClick} className="custom-button">
|
||||
Click me
|
||||
</div>
|
||||
|
||||
// ✅ GOOD: Full keyboard support
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={handleClick}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleClick();
|
||||
}
|
||||
}}
|
||||
className="custom-button"
|
||||
>
|
||||
Click me
|
||||
</div>
|
||||
```
|
||||
|
||||
```css
|
||||
/* ❌ BAD: Removed focus indicator */
|
||||
*:focus {
|
||||
outline: none; /* Never do this without alternative! */
|
||||
}
|
||||
|
||||
/* ✅ GOOD: Enhanced focus indicator */
|
||||
*:focus {
|
||||
outline: 2px solid #4A90E2;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ✅ BETTER: Visible focus, hidden for mouse users */
|
||||
*:focus-visible {
|
||||
outline: 2px solid #4A90E2;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: Dialog doesn't trap focus
|
||||
function Dialog({ isOpen, onClose, children }) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="dialog">
|
||||
<button onClick={onClose}>Close</button>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ✅ GOOD: Dialog with focus trap
|
||||
function Dialog({ isOpen, onClose, children }) {
|
||||
const dialogRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
// Focus first focusable element
|
||||
const firstFocusable = dialogRef.current?.querySelector(
|
||||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
(firstFocusable as HTMLElement)?.focus();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={dialogRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
onKeyDown={(e) => e.key === 'Escape' && onClose()}
|
||||
>
|
||||
<button onClick={onClose}>Close</button>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Screen Reader Compatibility
|
||||
|
||||
**Screen Reader Considerations**:
|
||||
- [ ] All content accessible to screen readers
|
||||
- [ ] Images have alt text (or marked decorative)
|
||||
- [ ] Form inputs have associated labels
|
||||
- [ ] Error messages announced
|
||||
- [ ] Dynamic content changes announced
|
||||
- [ ] Hidden content not read by screen readers
|
||||
- [ ] Reading order matches visual order
|
||||
|
||||
**Text Alternatives**:
|
||||
- [ ] Images have descriptive alt text
|
||||
- [ ] Decorative images have `alt=""` or `aria-hidden="true"`
|
||||
- [ ] Icon buttons have accessible names
|
||||
- [ ] SVG graphics have `<title>` and `<desc>`
|
||||
- [ ] Video/audio has captions and transcripts
|
||||
- [ ] Complex images have long descriptions
|
||||
|
||||
**Form Accessibility**:
|
||||
- [ ] Labels associated with inputs (`<label for="...">` or wrapping)
|
||||
- [ ] Required fields indicated (`required` or `aria-required`)
|
||||
- [ ] Error messages associated with fields (`aria-describedby`)
|
||||
- [ ] Fieldsets group related inputs
|
||||
- [ ] Form validation errors announced
|
||||
- [ ] Help text associated with inputs
|
||||
|
||||
**Code Examples - Screen Readers**:
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: No alt text
|
||||
<img src="/logo.png" />
|
||||
|
||||
// ✅ GOOD: Descriptive alt text
|
||||
<img src="/logo.png" alt="Company Logo" />
|
||||
|
||||
// ✅ GOOD: Decorative image
|
||||
<img src="/decorative-border.png" alt="" />
|
||||
<img src="/background.png" aria-hidden="true" />
|
||||
```
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: Icon button without accessible name
|
||||
<button onClick={handleDelete}>
|
||||
<TrashIcon />
|
||||
</button>
|
||||
|
||||
// ✅ GOOD: Icon button with accessible name
|
||||
<button onClick={handleDelete} aria-label="Delete item">
|
||||
<TrashIcon aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
// ✅ ALSO GOOD: Visually hidden text
|
||||
<button onClick={handleDelete}>
|
||||
<TrashIcon aria-hidden="true" />
|
||||
<span className="sr-only">Delete item</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: Form without labels
|
||||
<input type="text" placeholder="Enter your name" />
|
||||
|
||||
// ✅ GOOD: Properly labeled form field
|
||||
<label htmlFor="name">Name</label>
|
||||
<input type="text" id="name" placeholder="Enter your name" />
|
||||
|
||||
// ✅ ALSO GOOD: Wrapping label
|
||||
<label>
|
||||
Name
|
||||
<input type="text" placeholder="Enter your name" />
|
||||
</label>
|
||||
```
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: Error not associated with field
|
||||
<input type="email" id="email" />
|
||||
{error && <div className="error">Invalid email</div>}
|
||||
|
||||
// ✅ GOOD: Error associated with field
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
aria-invalid={!!error}
|
||||
aria-describedby={error ? "email-error" : undefined}
|
||||
/>
|
||||
{error && (
|
||||
<div id="email-error" className="error" role="alert">
|
||||
Invalid email
|
||||
</div>
|
||||
)}
|
||||
```
|
||||
|
||||
### 7. Color and Contrast
|
||||
|
||||
**Color Contrast** (WCAG AA):
|
||||
- [ ] Normal text: 4.5:1 contrast ratio minimum
|
||||
- [ ] Large text (18pt+ or 14pt+ bold): 3:1 minimum
|
||||
- [ ] UI components: 3:1 contrast with adjacent colors
|
||||
- [ ] Focus indicators: 3:1 contrast with background
|
||||
- [ ] WCAG AAA: 7:1 for normal text, 4.5:1 for large text
|
||||
|
||||
**Color Usage**:
|
||||
- [ ] Information not conveyed by color alone
|
||||
- [ ] Color blind friendly palette
|
||||
- [ ] Links distinguishable without color (underline, icon)
|
||||
- [ ] Form validation errors not color-only
|
||||
- [ ] Charts/graphs have patterns or labels
|
||||
|
||||
**Code Examples - Color and Contrast**:
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: Color only to indicate error
|
||||
<input
|
||||
type="text"
|
||||
style={{ borderColor: hasError ? 'red' : 'gray' }}
|
||||
/>
|
||||
|
||||
// ✅ GOOD: Multiple indicators for error
|
||||
<input
|
||||
type="text"
|
||||
aria-invalid={hasError}
|
||||
aria-describedby={hasError ? "error-message" : undefined}
|
||||
style={{
|
||||
borderColor: hasError ? 'red' : 'gray',
|
||||
borderWidth: hasError ? '2px' : '1px'
|
||||
}}
|
||||
/>
|
||||
{hasError && (
|
||||
<div id="error-message" role="alert">
|
||||
<ErrorIcon aria-hidden="true" />
|
||||
This field is required
|
||||
</div>
|
||||
)}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// ❌ BAD: Link only differentiated by color
|
||||
<a href="/more" style={{ color: 'blue', textDecoration: 'none' }}>
|
||||
Read more
|
||||
</a>
|
||||
|
||||
// ✅ GOOD: Link with underline
|
||||
<a href="/more" style={{ color: 'blue', textDecoration: 'underline' }}>
|
||||
Read more
|
||||
</a>
|
||||
|
||||
// ✅ ALSO GOOD: Link with icon
|
||||
<a href="/more" style={{ color: 'blue' }}>
|
||||
Read more <ArrowIcon aria-hidden="true" />
|
||||
</a>
|
||||
```
|
||||
|
||||
### 8. Responsive and Adaptive Design
|
||||
|
||||
**Viewport and Zoom**:
|
||||
- [ ] Content adapts to viewport size
|
||||
- [ ] Text can be resized to 200% without loss of functionality
|
||||
- [ ] No horizontal scrolling at 320px width
|
||||
- [ ] Touch targets at least 44x44 pixels (mobile)
|
||||
- [ ] Pinch-to-zoom not disabled
|
||||
|
||||
**Media Queries**:
|
||||
- [ ] Reduced motion preferences respected
|
||||
- [ ] High contrast mode supported
|
||||
- [ ] Dark mode accessible
|
||||
- [ ] Print styles appropriate
|
||||
|
||||
**Code Examples - Responsive**:
|
||||
|
||||
```css
|
||||
/* ❌ BAD: Disables zoom */
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
|
||||
|
||||
/* ✅ GOOD: Allows zoom */
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
```
|
||||
|
||||
```css
|
||||
/* ✅ GOOD: Respect reduced motion preference */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// ✅ GOOD: Touch targets sized appropriately
|
||||
<button style={{
|
||||
minWidth: '44px',
|
||||
minHeight: '44px',
|
||||
padding: '12px'
|
||||
}}>
|
||||
Click me
|
||||
</button>
|
||||
```
|
||||
|
||||
### 9. Multimedia Accessibility
|
||||
|
||||
**Video Accessibility**:
|
||||
- [ ] Captions for all audio content
|
||||
- [ ] Audio descriptions for visual content
|
||||
- [ ] Transcript provided
|
||||
- [ ] Controls keyboard accessible
|
||||
- [ ] Auto-play disabled or user-controlled
|
||||
|
||||
**Audio Accessibility**:
|
||||
- [ ] Transcripts provided
|
||||
- [ ] Visual indicators for audio cues
|
||||
- [ ] User can control volume and playback
|
||||
|
||||
**Code Examples - Multimedia**:
|
||||
|
||||
```html
|
||||
<!-- ✅ GOOD: Video with captions and transcript -->
|
||||
<video controls>
|
||||
<source src="video.mp4" type="video/mp4">
|
||||
<track kind="captions" src="captions.vtt" srclang="en" label="English">
|
||||
<track kind="descriptions" src="descriptions.vtt" srclang="en" label="English">
|
||||
</video>
|
||||
<details>
|
||||
<summary>Video Transcript</summary>
|
||||
<p>[Full transcript here]</p>
|
||||
</details>
|
||||
```
|
||||
|
||||
### 10. Automated Testing
|
||||
|
||||
**Run Accessibility Audits**:
|
||||
```bash
|
||||
# Lighthouse audit
|
||||
npx lighthouse https://your-site.com --only-categories=accessibility --view
|
||||
|
||||
# axe-core testing
|
||||
npm install --save-dev @axe-core/cli
|
||||
npx axe https://your-site.com
|
||||
|
||||
# pa11y testing
|
||||
npm install --save-dev pa11y
|
||||
npx pa11y https://your-site.com
|
||||
|
||||
# ESLint accessibility plugin (React)
|
||||
npm install --save-dev eslint-plugin-jsx-a11y
|
||||
```
|
||||
|
||||
**Manual Testing**:
|
||||
- [ ] Test with keyboard only (no mouse)
|
||||
- [ ] Test with screen reader (NVDA, JAWS, VoiceOver)
|
||||
- [ ] Test with browser zoom at 200%
|
||||
- [ ] Test in high contrast mode
|
||||
- [ ] Test with CSS disabled
|
||||
- [ ] Test on mobile devices
|
||||
|
||||
## Review Depth Implementation
|
||||
|
||||
**Quick Depth** (10-15 min):
|
||||
- Semantic HTML check
|
||||
- Alt text verification
|
||||
- Form label check
|
||||
- Keyboard navigation test
|
||||
- Automated audit (Lighthouse)
|
||||
|
||||
**Standard Depth** (30-45 min):
|
||||
- Complete WCAG AA checklist
|
||||
- ARIA usage review
|
||||
- Keyboard navigation thorough test
|
||||
- Focus management review
|
||||
- Color contrast check
|
||||
- Screen reader spot checks
|
||||
|
||||
**Deep Depth** (60-90+ min):
|
||||
- Complete WCAG AAA checklist
|
||||
- Comprehensive screen reader testing
|
||||
- Keyboard-only navigation of entire scope
|
||||
- Color blindness simulation
|
||||
- Reduced motion testing
|
||||
- High contrast mode testing
|
||||
- Mobile accessibility testing
|
||||
- Automated testing suite
|
||||
|
||||
## Output Format
|
||||
|
||||
```markdown
|
||||
# Accessibility Review: [Scope]
|
||||
|
||||
## Executive Summary
|
||||
|
||||
**Reviewed**: [What was reviewed]
|
||||
**Depth**: [Quick|Standard|Deep]
|
||||
**WCAG Level Target**: [A|AA|AAA]
|
||||
**Accessibility Rating**: [Excellent|Good|Needs Work|Poor]
|
||||
|
||||
### Overall Assessment
|
||||
**[Compliant|Partially Compliant|Non-Compliant] with WCAG [Level]**
|
||||
|
||||
[Brief explanation]
|
||||
|
||||
### Priority Actions
|
||||
1. [Critical a11y issue 1]
|
||||
2. [Critical a11y issue 2]
|
||||
|
||||
---
|
||||
|
||||
## Critical Issues 🚨
|
||||
|
||||
**[Must fix for basic accessibility]**
|
||||
|
||||
### [Issue 1 Title]
|
||||
**File**: `path/to/component.tsx:42`
|
||||
**WCAG Criterion**: [X.X.X - Criterion Name - Level A/AA/AAA]
|
||||
**Issue**: [Description of accessibility barrier]
|
||||
**Impact**: [How this affects users]
|
||||
**Affected Users**: [Screen reader users, keyboard users, low vision users, etc.]
|
||||
**Fix**:
|
||||
|
||||
```tsx
|
||||
// Current (inaccessible)
|
||||
[problematic code]
|
||||
|
||||
// Accessible implementation
|
||||
[fixed code]
|
||||
```
|
||||
|
||||
**Testing**: [How to verify the fix]
|
||||
|
||||
[Repeat for each critical issue]
|
||||
|
||||
---
|
||||
|
||||
## High Priority Issues ⚠️
|
||||
|
||||
**[Should fix for good accessibility]**
|
||||
|
||||
[Similar format for high priority issues]
|
||||
|
||||
---
|
||||
|
||||
## Medium Priority Issues ℹ️
|
||||
|
||||
**[Consider fixing for enhanced accessibility]**
|
||||
|
||||
[Similar format for medium priority issues]
|
||||
|
||||
---
|
||||
|
||||
## Low Priority Issues 💡
|
||||
|
||||
**[Nice to have for optimal accessibility]**
|
||||
|
||||
[Similar format for low priority issues]
|
||||
|
||||
---
|
||||
|
||||
## Accessibility Strengths ✅
|
||||
|
||||
- ✅ [Good practice 1 with examples]
|
||||
- ✅ [Good practice 2 with examples]
|
||||
- ✅ [Good practice 3 with examples]
|
||||
|
||||
---
|
||||
|
||||
## WCAG 2.1 Compliance Summary
|
||||
|
||||
### Level A (Minimum)
|
||||
|
||||
| Criterion | Status | Notes |
|
||||
|-----------|--------|-------|
|
||||
| 1.1.1 Non-text Content | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 1.3.1 Info and Relationships | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 1.3.2 Meaningful Sequence | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 2.1.1 Keyboard | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 2.1.2 No Keyboard Trap | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 2.4.1 Bypass Blocks | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 3.1.1 Language of Page | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 4.1.1 Parsing | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 4.1.2 Name, Role, Value | ✅ / ⚠️ / ❌ | [Details] |
|
||||
|
||||
### Level AA (Recommended)
|
||||
|
||||
| Criterion | Status | Notes |
|
||||
|-----------|--------|-------|
|
||||
| 1.4.3 Contrast (Minimum) | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 1.4.5 Images of Text | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 2.4.5 Multiple Ways | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 2.4.6 Headings and Labels | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 2.4.7 Focus Visible | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 3.1.2 Language of Parts | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 3.2.3 Consistent Navigation | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 3.3.3 Error Suggestion | ✅ / ⚠️ / ❌ | [Details] |
|
||||
| 3.3.4 Error Prevention (Legal) | ✅ / ⚠️ / ❌ | [Details] |
|
||||
|
||||
### Level AAA (Enhanced) - Optional
|
||||
|
||||
[If deep review includes AAA]
|
||||
|
||||
---
|
||||
|
||||
## Detailed Accessibility Analysis
|
||||
|
||||
### 🏗️ Semantic HTML
|
||||
|
||||
**Overall**: [Excellent|Good|Needs Work]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Well-structured areas]
|
||||
|
||||
**Issues**:
|
||||
- ⚠️ [Semantic HTML issues with file references]
|
||||
|
||||
**Heading Structure**:
|
||||
```
|
||||
h1: [Page title]
|
||||
h2: [Section 1]
|
||||
h3: [Subsection]
|
||||
h2: [Section 2]
|
||||
```
|
||||
|
||||
### 🎯 ARIA Usage
|
||||
|
||||
**Overall**: [Appropriate|Overused|Underused]
|
||||
|
||||
**Proper ARIA**:
|
||||
- ✅ [Good ARIA usage examples]
|
||||
|
||||
**ARIA Issues**:
|
||||
- ⚠️ [ARIA problems with file references]
|
||||
|
||||
### ⌨️ Keyboard Navigation
|
||||
|
||||
**Overall**: [Fully Accessible|Partially Accessible|Not Accessible]
|
||||
|
||||
**Tab Order**: [Logical|Needs Work]
|
||||
|
||||
**Keyboard Support**:
|
||||
- ✅ [Components with full keyboard support]
|
||||
- ⚠️ [Components with keyboard issues]
|
||||
|
||||
**Focus Management**: [Good|Needs Improvement]
|
||||
|
||||
### 📢 Screen Reader Compatibility
|
||||
|
||||
**Tested with**: [NVDA|JAWS|VoiceOver|Narrator]
|
||||
|
||||
**Screen Reader Experience**: [Excellent|Good|Poor]
|
||||
|
||||
**Issues Found**:
|
||||
- ⚠️ [Screen reader issues]
|
||||
|
||||
**Missing Alternatives**:
|
||||
- ⚠️ [Missing alt text, labels, etc.]
|
||||
|
||||
### 🎨 Color and Contrast
|
||||
|
||||
**Contrast Ratio Analysis**:
|
||||
|
||||
| Element | Foreground | Background | Ratio | WCAG AA | WCAG AAA |
|
||||
|---------|-----------|------------|-------|---------|----------|
|
||||
| Body text | [Color] | [Color] | [X:1] | ✅ / ❌ | ✅ / ❌ |
|
||||
| Links | [Color] | [Color] | [X:1] | ✅ / ❌ | ✅ / ❌ |
|
||||
| Buttons | [Color] | [Color] | [X:1] | ✅ / ❌ | ✅ / ❌ |
|
||||
|
||||
**Color Usage**: [Accessible|Issues Found]
|
||||
|
||||
### 📱 Responsive and Mobile
|
||||
|
||||
**Mobile Accessibility**: [Excellent|Good|Needs Work]
|
||||
|
||||
**Touch Target Sizes**: [Adequate|Too Small]
|
||||
|
||||
**Zoom Support**: [Enabled|Disabled]
|
||||
|
||||
---
|
||||
|
||||
## Testing Results
|
||||
|
||||
### Automated Testing
|
||||
|
||||
**Lighthouse Score**: [X/100]
|
||||
|
||||
**axe-core Results**:
|
||||
- Critical issues: [X]
|
||||
- Serious issues: [X]
|
||||
- Moderate issues: [X]
|
||||
- Minor issues: [X]
|
||||
|
||||
### Manual Testing
|
||||
|
||||
**Keyboard-Only Navigation**: [Pass|Fail] - [Details]
|
||||
|
||||
**Screen Reader Testing**: [Pass|Fail] - [Details]
|
||||
|
||||
**Zoom to 200%**: [Pass|Fail] - [Details]
|
||||
|
||||
**High Contrast Mode**: [Pass|Fail] - [Details]
|
||||
|
||||
---
|
||||
|
||||
## Recommendations
|
||||
|
||||
### Immediate (This Week)
|
||||
- [ ] [Critical fix 1]
|
||||
- [ ] [Critical fix 2]
|
||||
|
||||
### Short-term (This Month)
|
||||
- [ ] [High priority fix 1]
|
||||
- [ ] [High priority fix 2]
|
||||
|
||||
### Long-term (This Quarter)
|
||||
- [ ] [Strategic improvement 1]
|
||||
- [ ] [Strategic improvement 2]
|
||||
|
||||
---
|
||||
|
||||
## Resources
|
||||
|
||||
**Testing Tools**:
|
||||
- Lighthouse (Chrome DevTools)
|
||||
- axe DevTools (browser extension)
|
||||
- WAVE (browser extension)
|
||||
- Screen reader (NVDA, JAWS, VoiceOver)
|
||||
|
||||
**Guidelines**:
|
||||
- WCAG 2.1: https://www.w3.org/WAI/WCAG21/quickref/
|
||||
- ARIA Authoring Practices: https://www.w3.org/WAI/ARIA/apg/
|
||||
|
||||
---
|
||||
|
||||
## Review Metadata
|
||||
|
||||
- **Reviewer**: 10x Fullstack Engineer (Accessibility Focus)
|
||||
- **Review Date**: [Date]
|
||||
- **WCAG Level**: [A|AA|AAA]
|
||||
- **A11y Issues**: Critical: X, High: X, Medium: X, Low: X
|
||||
- **Compliance Status**: [Compliant|Partially Compliant|Non-Compliant]
|
||||
```
|
||||
|
||||
## Agent Invocation
|
||||
|
||||
This operation MUST leverage the **10x-fullstack-engineer** agent with accessibility expertise.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Semantic HTML First**: Use native elements before ARIA
|
||||
2. **Test with Real Users**: Automated tools catch ~30-40% of issues
|
||||
3. **Keyboard First**: If keyboard works, most other things will follow
|
||||
4. **Don't Assume**: Test with actual assistive technology
|
||||
5. **Progressive Enhancement**: Start accessible, add features
|
||||
6. **Inclusive Design**: Consider all users from the beginning
|
||||
693
commands/review/full.md
Normal file
693
commands/review/full.md
Normal file
@@ -0,0 +1,693 @@
|
||||
# Comprehensive Code Review
|
||||
|
||||
Performs a complete, multi-category code review covering security, performance, code quality, architecture, testing, documentation, and accessibility.
|
||||
|
||||
## Parameters
|
||||
|
||||
**Received from router**: `$ARGUMENTS` (after removing 'full' operation)
|
||||
|
||||
Expected format: `scope:"review-scope" [depth:"quick|standard|deep"]`
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Parse Parameters
|
||||
|
||||
Extract from $ARGUMENTS:
|
||||
- **scope**: What to review (required)
|
||||
- **depth**: Review thoroughness (default: "standard")
|
||||
|
||||
### 2. Gather Context
|
||||
|
||||
Before reviewing, understand the codebase:
|
||||
|
||||
**Project Structure**:
|
||||
```bash
|
||||
# Identify project type and structure
|
||||
ls -la
|
||||
cat package.json 2>/dev/null || cat requirements.txt 2>/dev/null || cat go.mod 2>/dev/null || echo "Check for other project files"
|
||||
|
||||
# Find configuration files
|
||||
find . -maxdepth 2 -name "*.config.*" -o -name ".*rc" -o -name "*.json" | grep -E "(tsconfig|eslint|prettier|jest|vite|webpack)" | head -10
|
||||
|
||||
# Check testing patterns
|
||||
find . -name "*.test.*" -o -name "*.spec.*" | head -5
|
||||
|
||||
# Review recent changes
|
||||
git log --oneline -20
|
||||
git status
|
||||
```
|
||||
|
||||
**Technology Stack Detection**:
|
||||
- Frontend: React/Vue/Angular/Svelte
|
||||
- Backend: Node.js/Python/Go/Java
|
||||
- Database: PostgreSQL/MySQL/MongoDB
|
||||
- Testing: Jest/Pytest/Go test
|
||||
- Build tools: Vite/Webpack/Rollup
|
||||
|
||||
### 3. Define Review Scope
|
||||
|
||||
Based on scope parameter, determine files to review:
|
||||
|
||||
```bash
|
||||
# If scope is a directory
|
||||
find [scope] -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" -o -name "*.py" -o -name "*.go" \) | head -20
|
||||
|
||||
# If scope is "recent changes"
|
||||
git diff --name-only HEAD~5..HEAD
|
||||
|
||||
# If scope is specific files
|
||||
# List the specified files
|
||||
```
|
||||
|
||||
### 4. Security Review
|
||||
|
||||
**Authentication & Authorization**:
|
||||
- [ ] Authentication checks on protected routes/endpoints
|
||||
- [ ] Authorization checks for resource access
|
||||
- [ ] JWT/session token handling secure
|
||||
- [ ] No hardcoded credentials or API keys
|
||||
- [ ] Password hashing with salt (bcrypt, argon2)
|
||||
- [ ] Rate limiting on auth endpoints
|
||||
|
||||
**Input Validation & Injection Prevention**:
|
||||
- [ ] All user inputs validated and sanitized
|
||||
- [ ] SQL injection prevented (parameterized queries, ORM)
|
||||
- [ ] XSS prevention (output encoding, CSP headers)
|
||||
- [ ] CSRF protection implemented
|
||||
- [ ] Command injection prevention
|
||||
- [ ] Path traversal prevention
|
||||
- [ ] File upload validation (type, size, content)
|
||||
|
||||
**Data Protection**:
|
||||
- [ ] Sensitive data encrypted at rest
|
||||
- [ ] TLS/HTTPS for data in transit
|
||||
- [ ] No sensitive data in logs or error messages
|
||||
- [ ] Secrets management (environment variables, vault)
|
||||
- [ ] PII compliance (GDPR, CCPA)
|
||||
- [ ] Secure session management
|
||||
|
||||
**Dependencies & Configuration**:
|
||||
- [ ] No known vulnerable dependencies (check with npm audit, pip-audit)
|
||||
- [ ] Dependencies up to date
|
||||
- [ ] Security headers configured (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)
|
||||
- [ ] CORS properly configured
|
||||
- [ ] Error messages don't leak stack traces or internals
|
||||
|
||||
**Common Vulnerabilities (OWASP Top 10)**:
|
||||
- [ ] A01: Broken Access Control
|
||||
- [ ] A02: Cryptographic Failures
|
||||
- [ ] A03: Injection
|
||||
- [ ] A04: Insecure Design
|
||||
- [ ] A05: Security Misconfiguration
|
||||
- [ ] A06: Vulnerable and Outdated Components
|
||||
- [ ] A07: Identification and Authentication Failures
|
||||
- [ ] A08: Software and Data Integrity Failures
|
||||
- [ ] A09: Security Logging and Monitoring Failures
|
||||
- [ ] A10: Server-Side Request Forgery (SSRF)
|
||||
|
||||
**Security Code Examples**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: SQL Injection vulnerability
|
||||
const query = `SELECT * FROM users WHERE email = '${userEmail}'`;
|
||||
|
||||
// ✅ GOOD: Parameterized query
|
||||
const query = 'SELECT * FROM users WHERE email = ?';
|
||||
const result = await db.query(query, [userEmail]);
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Hardcoded credentials
|
||||
const apiKey = "sk_live_51A2B3C4D5E6F7G8";
|
||||
|
||||
// ✅ GOOD: Environment variables
|
||||
const apiKey = process.env.STRIPE_API_KEY;
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: No authentication check
|
||||
app.get('/api/admin/users', async (req, res) => {
|
||||
const users = await getAllUsers();
|
||||
res.json(users);
|
||||
});
|
||||
|
||||
// ✅ GOOD: Authentication and authorization
|
||||
app.get('/api/admin/users', requireAuth, requireAdmin, async (req, res) => {
|
||||
const users = await getAllUsers();
|
||||
res.json(users);
|
||||
});
|
||||
```
|
||||
|
||||
### 5. Performance Review
|
||||
|
||||
**Database Performance**:
|
||||
- [ ] No N+1 query problems
|
||||
- [ ] Proper indexes on frequently queried columns
|
||||
- [ ] Connection pooling configured
|
||||
- [ ] Transactions scoped appropriately
|
||||
- [ ] Pagination for large datasets
|
||||
- [ ] Query optimization (EXPLAIN ANALYZE)
|
||||
- [ ] Caching for expensive queries
|
||||
|
||||
**Backend Performance**:
|
||||
- [ ] Efficient algorithms (avoid O(n²) where possible)
|
||||
- [ ] Async/await used properly (no blocking operations)
|
||||
- [ ] Caching strategy implemented (Redis, in-memory)
|
||||
- [ ] Rate limiting to prevent abuse
|
||||
- [ ] Batch operations where applicable
|
||||
- [ ] Stream processing for large data
|
||||
- [ ] Background jobs for heavy tasks
|
||||
|
||||
**Frontend Performance**:
|
||||
- [ ] Components memoized appropriately (React.memo, useMemo, useCallback)
|
||||
- [ ] Large lists virtualized (react-window, react-virtualized)
|
||||
- [ ] Images optimized and lazy-loaded
|
||||
- [ ] Code splitting implemented
|
||||
- [ ] Bundle size optimized (tree shaking, minification)
|
||||
- [ ] Unnecessary re-renders prevented
|
||||
- [ ] Debouncing/throttling for expensive operations
|
||||
- [ ] Web Vitals considerations (LCP, FID, CLS)
|
||||
|
||||
**Network Performance**:
|
||||
- [ ] API calls minimized (batching, GraphQL)
|
||||
- [ ] Response compression enabled (gzip, brotli)
|
||||
- [ ] CDN for static assets
|
||||
- [ ] HTTP caching headers configured
|
||||
- [ ] Prefetching/preloading for critical resources
|
||||
- [ ] Service worker for offline support
|
||||
|
||||
**Performance Code Examples**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: N+1 query problem
|
||||
const users = await User.findAll();
|
||||
for (const user of users) {
|
||||
user.posts = await Post.findAll({ where: { userId: user.id } });
|
||||
}
|
||||
|
||||
// ✅ GOOD: Eager loading
|
||||
const users = await User.findAll({
|
||||
include: [{ model: Post }]
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Unnecessary re-renders
|
||||
function UserList({ users }) {
|
||||
return users.map(user => <UserCard key={user.id} user={user} />);
|
||||
}
|
||||
|
||||
// ✅ GOOD: Memoization
|
||||
const UserCard = React.memo(({ user }) => (
|
||||
<div>{user.name}</div>
|
||||
));
|
||||
|
||||
function UserList({ users }) {
|
||||
return users.map(user => <UserCard key={user.id} user={user} />);
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Code Quality Review
|
||||
|
||||
**Code Organization**:
|
||||
- [ ] Clear, descriptive naming (variables, functions, classes)
|
||||
- [ ] Functions focused and under 50 lines
|
||||
- [ ] Single Responsibility Principle followed
|
||||
- [ ] DRY principle applied (no code duplication)
|
||||
- [ ] Proper separation of concerns
|
||||
- [ ] Consistent code style
|
||||
- [ ] Logical file structure
|
||||
|
||||
**Error Handling**:
|
||||
- [ ] All errors caught and handled properly
|
||||
- [ ] Meaningful error messages
|
||||
- [ ] Proper error logging
|
||||
- [ ] Errors don't expose sensitive information
|
||||
- [ ] Graceful degradation
|
||||
- [ ] User-friendly error messages in UI
|
||||
- [ ] Error boundaries (React) or equivalent
|
||||
|
||||
**Type Safety** (TypeScript/typed languages):
|
||||
- [ ] No `any` types (or justified exceptions)
|
||||
- [ ] Proper type definitions for functions
|
||||
- [ ] Interfaces/types for complex objects
|
||||
- [ ] Type guards for runtime validation
|
||||
- [ ] Generics used appropriately
|
||||
- [ ] Strict mode enabled
|
||||
|
||||
**Testing**:
|
||||
- [ ] Unit tests for business logic
|
||||
- [ ] Integration tests for APIs
|
||||
- [ ] Component tests for UI
|
||||
- [ ] E2E tests for critical paths
|
||||
- [ ] Tests are meaningful (not just for coverage)
|
||||
- [ ] Edge cases covered
|
||||
- [ ] Mocks/stubs used appropriately
|
||||
- [ ] Test coverage >80% for critical code
|
||||
|
||||
**Documentation**:
|
||||
- [ ] Complex logic explained with comments
|
||||
- [ ] JSDoc/docstrings for public APIs
|
||||
- [ ] README accurate and up to date
|
||||
- [ ] API documentation complete
|
||||
- [ ] Architectural decisions documented (ADRs)
|
||||
- [ ] Setup instructions clear
|
||||
|
||||
**Quality Code Examples**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Poor naming and structure
|
||||
function p(u, d) {
|
||||
if (u.r === 'a') {
|
||||
return d.filter(x => x.o === u.i);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
// ✅ GOOD: Clear naming and structure
|
||||
function filterDataByUserRole(user: User, data: DataItem[]): DataItem[] {
|
||||
if (user.role === 'admin') {
|
||||
return data.filter(item => item.ownerId === user.id);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: No error handling
|
||||
async function fetchUser(id: string) {
|
||||
const response = await fetch(`/api/users/${id}`);
|
||||
const user = await response.json();
|
||||
return user;
|
||||
}
|
||||
|
||||
// ✅ GOOD: Proper error handling
|
||||
async function fetchUser(id: string): Promise<User> {
|
||||
try {
|
||||
const response = await fetch(`/api/users/${id}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch user: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const user = await response.json();
|
||||
return user;
|
||||
} catch (error) {
|
||||
logger.error('Error fetching user', { id, error });
|
||||
throw new UserFetchError(`Unable to retrieve user ${id}`, { cause: error });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 7. Architecture Review
|
||||
|
||||
**Design Patterns**:
|
||||
- [ ] Appropriate patterns used (Factory, Strategy, Observer, etc.)
|
||||
- [ ] No anti-patterns (God Object, Spaghetti Code, etc.)
|
||||
- [ ] Consistent with existing architecture
|
||||
- [ ] SOLID principles followed
|
||||
- [ ] Dependency injection where appropriate
|
||||
|
||||
**Scalability**:
|
||||
- [ ] Design scales with increased load
|
||||
- [ ] No bottlenecks introduced
|
||||
- [ ] Stateless design where appropriate
|
||||
- [ ] Horizontal scaling possible
|
||||
- [ ] Resource usage reasonable
|
||||
- [ ] Caching strategy for scale
|
||||
|
||||
**Maintainability**:
|
||||
- [ ] Code is readable and understandable
|
||||
- [ ] Low coupling, high cohesion
|
||||
- [ ] Easy to test
|
||||
- [ ] Easy to extend
|
||||
- [ ] No technical debt introduced
|
||||
- [ ] Consistent patterns across codebase
|
||||
|
||||
**Architecture Code Examples**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Tight coupling
|
||||
class OrderService {
|
||||
processPayment(order: Order) {
|
||||
const stripe = new StripeClient(process.env.STRIPE_KEY);
|
||||
return stripe.charge(order.amount);
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ GOOD: Dependency injection
|
||||
interface PaymentGateway {
|
||||
charge(amount: number): Promise<PaymentResult>;
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
constructor(private paymentGateway: PaymentGateway) {}
|
||||
|
||||
processPayment(order: Order) {
|
||||
return this.paymentGateway.charge(order.amount);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 8. Frontend-Specific Review
|
||||
|
||||
**Accessibility (a11y)**:
|
||||
- [ ] Semantic HTML elements used
|
||||
- [ ] ARIA labels and roles where needed
|
||||
- [ ] Keyboard navigation functional
|
||||
- [ ] Screen reader compatible
|
||||
- [ ] Color contrast meets WCAG AA standards
|
||||
- [ ] Focus management proper
|
||||
- [ ] Alt text for images
|
||||
- [ ] Form labels associated with inputs
|
||||
|
||||
**User Experience**:
|
||||
- [ ] Loading states shown
|
||||
- [ ] Error states handled gracefully
|
||||
- [ ] Forms have validation feedback
|
||||
- [ ] Responsive design implemented
|
||||
- [ ] Optimistic updates where appropriate
|
||||
- [ ] Smooth animations and transitions
|
||||
- [ ] Empty states handled
|
||||
|
||||
**Browser Compatibility**:
|
||||
- [ ] Polyfills for required features
|
||||
- [ ] Tested in target browsers
|
||||
- [ ] Graceful degradation
|
||||
- [ ] Progressive enhancement
|
||||
|
||||
### 9. Testing Review
|
||||
|
||||
**Coverage Analysis**:
|
||||
```bash
|
||||
# Check test coverage
|
||||
npm test -- --coverage || pytest --cov || go test -cover ./...
|
||||
```
|
||||
|
||||
**Test Quality**:
|
||||
- [ ] Tests are readable and maintainable
|
||||
- [ ] Tests are isolated and independent
|
||||
- [ ] Tests use meaningful assertions
|
||||
- [ ] Tests cover happy path and edge cases
|
||||
- [ ] Tests avoid implementation details
|
||||
- [ ] Integration tests cover API contracts
|
||||
- [ ] E2E tests cover critical user flows
|
||||
|
||||
### 10. Documentation Review
|
||||
|
||||
**Code Documentation**:
|
||||
- [ ] Complex algorithms explained
|
||||
- [ ] Public APIs documented
|
||||
- [ ] Inline comments for unclear code
|
||||
- [ ] Type annotations present
|
||||
|
||||
**Project Documentation**:
|
||||
- [ ] README comprehensive
|
||||
- [ ] Setup instructions work
|
||||
- [ ] API documentation accurate
|
||||
- [ ] Architecture diagrams present
|
||||
- [ ] Contributing guidelines clear
|
||||
|
||||
## Review Depth Implementation
|
||||
|
||||
**Quick Depth** (5-10 min):
|
||||
- Focus only on security critical issues and obvious bugs
|
||||
- Skip detailed architecture review
|
||||
- High-level scan of each category
|
||||
- Prioritize critical and high priority findings
|
||||
|
||||
**Standard Depth** (20-30 min):
|
||||
- Review all categories with moderate detail
|
||||
- Check security, performance, and quality thoroughly
|
||||
- Review test coverage
|
||||
- Provide actionable recommendations
|
||||
|
||||
**Deep Depth** (45-60+ min):
|
||||
- Comprehensive analysis of all categories
|
||||
- Detailed architecture and design review
|
||||
- Complete security audit
|
||||
- Performance profiling recommendations
|
||||
- Test quality assessment
|
||||
- Documentation completeness check
|
||||
|
||||
## Output Format
|
||||
|
||||
Provide structured feedback:
|
||||
|
||||
```markdown
|
||||
# Comprehensive Code Review: [Scope]
|
||||
|
||||
## Executive Summary
|
||||
|
||||
**Reviewed**: [What was reviewed]
|
||||
**Depth**: [Quick|Standard|Deep]
|
||||
**Date**: [Current date]
|
||||
|
||||
### Overall Assessment
|
||||
- **Quality**: [Excellent|Good|Fair|Needs Improvement]
|
||||
- **Security**: [Secure|Minor Issues|Major Concerns]
|
||||
- **Performance**: [Optimized|Acceptable|Needs Optimization]
|
||||
- **Maintainability**: [High|Medium|Low]
|
||||
- **Test Coverage**: [%]
|
||||
|
||||
### Recommendation
|
||||
**[Approve|Approve with Comments|Request Changes]**
|
||||
|
||||
[Brief explanation of recommendation]
|
||||
|
||||
---
|
||||
|
||||
## Critical Issues (Must Fix) 🚨
|
||||
|
||||
### [Issue 1 Title]
|
||||
**File**: `path/to/file.ts:42`
|
||||
**Category**: Security|Performance|Quality
|
||||
**Issue**: [Clear description of the problem]
|
||||
**Risk**: [Why this is critical - impact on security, data, users]
|
||||
**Fix**: [Specific, actionable recommendation]
|
||||
|
||||
```typescript
|
||||
// Current code (problematic)
|
||||
[show problematic code]
|
||||
|
||||
// Suggested fix
|
||||
[show corrected code with explanation]
|
||||
```
|
||||
|
||||
[Repeat for each critical issue]
|
||||
|
||||
---
|
||||
|
||||
## High Priority Issues (Should Fix) ⚠️
|
||||
|
||||
### [Issue 1 Title]
|
||||
**File**: `path/to/file.ts:103`
|
||||
**Category**: Security|Performance|Quality
|
||||
**Issue**: [Description]
|
||||
**Impact**: [Why this should be fixed]
|
||||
**Suggestion**: [Recommendation]
|
||||
|
||||
[Code example if applicable]
|
||||
|
||||
[Repeat for each high priority issue]
|
||||
|
||||
---
|
||||
|
||||
## Medium Priority Issues (Consider Fixing) ℹ️
|
||||
|
||||
### [Issue 1 Title]
|
||||
**File**: `path/to/file.ts:205`
|
||||
**Category**: Security|Performance|Quality
|
||||
**Issue**: [Description]
|
||||
**Suggestion**: [Recommendation]
|
||||
|
||||
[Repeat for each medium priority issue]
|
||||
|
||||
---
|
||||
|
||||
## Low Priority Issues (Nice to Have) 💡
|
||||
|
||||
### [Issue 1 Title]
|
||||
**File**: `path/to/file.ts:308`
|
||||
**Suggestion**: [Recommendation for improvement]
|
||||
|
||||
[Repeat for each low priority issue]
|
||||
|
||||
---
|
||||
|
||||
## Positive Observations ✅
|
||||
|
||||
Things done well that should be maintained:
|
||||
|
||||
- ✅ [Good practice 1 with specific example]
|
||||
- ✅ [Good practice 2 with specific example]
|
||||
- ✅ [Good practice 3 with specific example]
|
||||
|
||||
---
|
||||
|
||||
## Detailed Review by Category
|
||||
|
||||
### 🔒 Security Review
|
||||
|
||||
**Summary**: [Overall security posture]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [What's done well]
|
||||
- ✅ [What's done well]
|
||||
|
||||
**Concerns**:
|
||||
- ⚠️ [What needs attention with file references]
|
||||
- ⚠️ [What needs attention with file references]
|
||||
|
||||
**OWASP Top 10 Assessment**:
|
||||
- A01 Broken Access Control: [Pass|Fail] - [Details]
|
||||
- A03 Injection: [Pass|Fail] - [Details]
|
||||
- [Other relevant items]
|
||||
|
||||
### ⚡ Performance Review
|
||||
|
||||
**Summary**: [Overall performance assessment]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Optimizations already in place]
|
||||
|
||||
**Concerns**:
|
||||
- ⚠️ [Performance issues with specific file references]
|
||||
- ⚠️ [Bottlenecks identified]
|
||||
|
||||
**Recommendations**:
|
||||
1. [Specific performance improvement]
|
||||
2. [Specific performance improvement]
|
||||
|
||||
### 📝 Code Quality Review
|
||||
|
||||
**Summary**: [Overall code quality]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Quality aspects done well]
|
||||
|
||||
**Areas for Improvement**:
|
||||
- ⚠️ [Quality issues with file references]
|
||||
|
||||
**Code Metrics**:
|
||||
- Average function length: [X lines]
|
||||
- Code duplication: [Low|Medium|High]
|
||||
- Cyclomatic complexity: [Assessment]
|
||||
|
||||
### 🧪 Testing Review
|
||||
|
||||
**Summary**: [Test coverage and quality]
|
||||
|
||||
**Coverage**: [X%]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Well-tested areas]
|
||||
|
||||
**Gaps**:
|
||||
- ⚠️ [Missing test coverage]
|
||||
- ⚠️ [Test quality issues]
|
||||
|
||||
### 📚 Documentation Review
|
||||
|
||||
**Summary**: [Documentation completeness]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Well-documented areas]
|
||||
|
||||
**Gaps**:
|
||||
- ⚠️ [Missing or incomplete documentation]
|
||||
|
||||
### 🏗️ Architecture Review
|
||||
|
||||
**Summary**: [Architectural assessment]
|
||||
|
||||
**Patterns Observed**:
|
||||
- [Design pattern 1]
|
||||
- [Design pattern 2]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Good architectural decisions]
|
||||
|
||||
**Concerns**:
|
||||
- ⚠️ [Architectural issues]
|
||||
|
||||
**Scalability Assessment**: [Can this scale?]
|
||||
|
||||
---
|
||||
|
||||
## Recommendations for Improvement
|
||||
|
||||
### Immediate Actions (This Week)
|
||||
1. [Critical fix 1]
|
||||
2. [Critical fix 2]
|
||||
|
||||
### Short-term Improvements (This Month)
|
||||
1. [High priority improvement 1]
|
||||
2. [High priority improvement 2]
|
||||
|
||||
### Long-term Enhancements (This Quarter)
|
||||
1. [Strategic improvement 1]
|
||||
2. [Strategic improvement 2]
|
||||
|
||||
---
|
||||
|
||||
## Questions for Team
|
||||
|
||||
1. [Question about design decision or requirement]
|
||||
2. [Question about trade-offs]
|
||||
3. [Question about future plans]
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [ ] Address all critical issues
|
||||
- [ ] Fix high priority issues
|
||||
- [ ] Review and discuss medium priority suggestions
|
||||
- [ ] Update tests to cover identified gaps
|
||||
- [ ] Update documentation as needed
|
||||
- [ ] Schedule follow-up review after fixes
|
||||
|
||||
---
|
||||
|
||||
## Review Metadata
|
||||
|
||||
- **Reviewer**: 10x Fullstack Engineer Agent
|
||||
- **Review Date**: [Date]
|
||||
- **Review Depth**: [Quick|Standard|Deep]
|
||||
- **Time Spent**: [Estimated time]
|
||||
- **Files Reviewed**: [Count]
|
||||
- **Issues Found**: Critical: X, High: X, Medium: X, Low: X
|
||||
```
|
||||
|
||||
## Agent Invocation
|
||||
|
||||
This operation MUST leverage the **10x-fullstack-engineer** agent for comprehensive review expertise.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Be Specific**: Always include file paths and line numbers
|
||||
2. **Be Constructive**: Frame feedback positively with clear improvements
|
||||
3. **Explain Why**: Help understand the reasoning behind each recommendation
|
||||
4. **Provide Examples**: Show both problematic and corrected code
|
||||
5. **Acknowledge Good Work**: Recognize strengths and good practices
|
||||
6. **Prioritize**: Focus on impact - security and data integrity first
|
||||
7. **Be Actionable**: Every issue should have a clear next step
|
||||
8. **Ask Questions**: When design intent is unclear, ask rather than assume
|
||||
|
||||
## Error Handling
|
||||
|
||||
**Scope Too Large**:
|
||||
- Suggest breaking into smaller focused reviews
|
||||
- Provide high-level assessment with sampling
|
||||
- Recommend incremental review approach
|
||||
|
||||
**Missing Context**:
|
||||
- Request additional information about requirements
|
||||
- Ask about design decisions
|
||||
- Clarify technical constraints
|
||||
|
||||
**Insufficient Depth Time**:
|
||||
- Recommend appropriate depth level for scope
|
||||
- Suggest focusing on specific categories
|
||||
- Provide sampling approach for large codebases
|
||||
871
commands/review/performance.md
Normal file
871
commands/review/performance.md
Normal file
@@ -0,0 +1,871 @@
|
||||
# Performance-Focused Code Review
|
||||
|
||||
Performs comprehensive performance analysis covering database optimization, backend efficiency, frontend rendering, network optimization, and scalability.
|
||||
|
||||
## Parameters
|
||||
|
||||
**Received from router**: `$ARGUMENTS` (after removing 'performance' operation)
|
||||
|
||||
Expected format: `scope:"review-scope" [depth:"quick|standard|deep"]`
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Parse Parameters
|
||||
|
||||
Extract from $ARGUMENTS:
|
||||
- **scope**: What to review (required) - API endpoints, database layer, frontend components, entire app
|
||||
- **depth**: Performance analysis thoroughness (default: "standard")
|
||||
|
||||
### 2. Gather Context
|
||||
|
||||
**Understand Performance Baseline**:
|
||||
```bash
|
||||
# Check project structure and tech stack
|
||||
ls -la
|
||||
cat package.json 2>/dev/null || cat requirements.txt 2>/dev/null
|
||||
|
||||
# Identify performance-critical files
|
||||
find . -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" | xargs grep -l "query\|fetch\|map\|filter\|useEffect\|useState" | head -20
|
||||
|
||||
# Check for existing performance monitoring
|
||||
grep -r "performance\|timing\|profil\|benchmark" --include="*.ts" --include="*.js" | head -10
|
||||
|
||||
# Look for database queries
|
||||
grep -r "SELECT\|INSERT\|UPDATE\|DELETE\|query\|execute" --include="*.ts" --include="*.js" --include="*.py" | head -15
|
||||
|
||||
# Check bundle configuration
|
||||
ls -la | grep -E "webpack|vite|rollup|esbuild"
|
||||
```
|
||||
|
||||
### 3. Database Performance Review
|
||||
|
||||
**Query Optimization**:
|
||||
- [ ] No N+1 query problems
|
||||
- [ ] Efficient joins (avoid Cartesian products)
|
||||
- [ ] Indexes on frequently queried columns
|
||||
- [ ] Covering indexes for common queries
|
||||
- [ ] Query plans analyzed (EXPLAIN ANALYZE)
|
||||
- [ ] Avoid SELECT * (select only needed columns)
|
||||
- [ ] Limit result sets appropriately
|
||||
|
||||
**Connection Management**:
|
||||
- [ ] Connection pooling configured
|
||||
- [ ] Pool size appropriate for load
|
||||
- [ ] Connections properly released
|
||||
- [ ] Connection timeouts configured
|
||||
- [ ] No connection leaks
|
||||
|
||||
**Transaction Management**:
|
||||
- [ ] Transactions scoped appropriately (not too large)
|
||||
- [ ] Read vs write transactions differentiated
|
||||
- [ ] Transaction isolation level appropriate
|
||||
- [ ] Deadlock handling implemented
|
||||
- [ ] Long-running transactions avoided
|
||||
|
||||
**Data Access Patterns**:
|
||||
- [ ] Pagination for large datasets
|
||||
- [ ] Cursor-based pagination for large tables
|
||||
- [ ] Batch operations where possible
|
||||
- [ ] Bulk inserts instead of individual
|
||||
- [ ] Proper use of indexes
|
||||
- [ ] Denormalization where appropriate for reads
|
||||
|
||||
**Caching Strategy**:
|
||||
- [ ] Query result caching for expensive queries
|
||||
- [ ] Cache invalidation strategy clear
|
||||
- [ ] Redis/Memcached for distributed caching
|
||||
- [ ] Application-level caching appropriate
|
||||
- [ ] Cache hit rate monitored
|
||||
|
||||
**Code Examples - Database Performance**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: N+1 query problem
|
||||
const users = await User.findAll();
|
||||
for (const user of users) {
|
||||
user.posts = await Post.findAll({ where: { userId: user.id } });
|
||||
user.comments = await Comment.findAll({ where: { userId: user.id } });
|
||||
}
|
||||
|
||||
// ✅ GOOD: Eager loading with includes
|
||||
const users = await User.findAll({
|
||||
include: [
|
||||
{ model: Post },
|
||||
{ model: Comment }
|
||||
]
|
||||
});
|
||||
|
||||
// ✅ BETTER: Only load what's needed
|
||||
const users = await User.findAll({
|
||||
attributes: ['id', 'name', 'email'], // Don't SELECT *
|
||||
include: [
|
||||
{
|
||||
model: Post,
|
||||
attributes: ['id', 'title', 'createdAt'],
|
||||
limit: 5 // Only recent posts
|
||||
}
|
||||
]
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Loading all records without pagination
|
||||
const allUsers = await User.findAll(); // Could be millions of records!
|
||||
|
||||
// ✅ GOOD: Pagination
|
||||
const page = parseInt(req.query.page) || 1;
|
||||
const limit = 20;
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const { rows: users, count } = await User.findAndCountAll({
|
||||
limit,
|
||||
offset,
|
||||
order: [['createdAt', 'DESC']]
|
||||
});
|
||||
|
||||
res.json({
|
||||
users,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total: count,
|
||||
pages: Math.ceil(count / limit)
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Individual inserts
|
||||
for (const item of items) {
|
||||
await Item.create(item); // Each is a separate query!
|
||||
}
|
||||
|
||||
// ✅ GOOD: Bulk insert
|
||||
await Item.bulkCreate(items);
|
||||
```
|
||||
|
||||
```sql
|
||||
-- ❌ BAD: Missing index on frequently queried column
|
||||
SELECT * FROM orders WHERE user_id = 123 AND status = 'pending';
|
||||
-- This could be slow without an index!
|
||||
|
||||
-- ✅ GOOD: Add composite index
|
||||
CREATE INDEX idx_orders_user_status ON orders(user_id, status);
|
||||
```
|
||||
|
||||
### 4. Backend Performance Review
|
||||
|
||||
**Algorithm Efficiency**:
|
||||
- [ ] Time complexity analyzed (avoid O(n²) where possible)
|
||||
- [ ] Space complexity considered
|
||||
- [ ] Efficient data structures used (Map vs Array for lookups)
|
||||
- [ ] Sorting algorithms appropriate for data size
|
||||
- [ ] Search algorithms optimized
|
||||
- [ ] Recursion depth manageable (avoid stack overflow)
|
||||
|
||||
**Async Operations**:
|
||||
- [ ] Async/await used properly
|
||||
- [ ] No blocking operations on event loop
|
||||
- [ ] Parallel execution where possible (Promise.all)
|
||||
- [ ] Proper error handling in async code
|
||||
- [ ] Timeouts on external calls
|
||||
- [ ] Avoid awaiting in loops (use Promise.all)
|
||||
|
||||
**Caching Strategy**:
|
||||
- [ ] In-memory caching for frequently accessed data
|
||||
- [ ] Distributed caching (Redis) for scalability
|
||||
- [ ] Cache TTL appropriate
|
||||
- [ ] Cache warming strategy
|
||||
- [ ] Cache invalidation correct
|
||||
- [ ] Memoization for expensive calculations
|
||||
|
||||
**Resource Management**:
|
||||
- [ ] Memory leaks prevented (event listeners cleaned up)
|
||||
- [ ] File handles closed properly
|
||||
- [ ] Streams used for large files
|
||||
- [ ] Buffer sizes appropriate
|
||||
- [ ] Garbage collection friendly code
|
||||
- [ ] Object pooling for frequently created objects
|
||||
|
||||
**Rate Limiting & Throttling**:
|
||||
- [ ] Rate limiting on API endpoints
|
||||
- [ ] Exponential backoff for retries
|
||||
- [ ] Circuit breakers for external services
|
||||
- [ ] Request queuing for overload
|
||||
- [ ] Graceful degradation under load
|
||||
|
||||
**Code Examples - Backend Performance**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: O(n²) complexity - nested loops
|
||||
function findDuplicates(users) {
|
||||
const duplicates = [];
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
for (let j = i + 1; j < users.length; j++) {
|
||||
if (users[i].email === users[j].email) {
|
||||
duplicates.push(users[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return duplicates;
|
||||
}
|
||||
|
||||
// ✅ GOOD: O(n) complexity - using Map
|
||||
function findDuplicates(users) {
|
||||
const seen = new Map();
|
||||
const duplicates = [];
|
||||
|
||||
for (const user of users) {
|
||||
if (seen.has(user.email)) {
|
||||
duplicates.push(user);
|
||||
} else {
|
||||
seen.set(user.email, user);
|
||||
}
|
||||
}
|
||||
|
||||
return duplicates;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Sequential async operations
|
||||
async function getUserData(userId) {
|
||||
const user = await fetchUser(userId);
|
||||
const posts = await fetchPosts(userId);
|
||||
const comments = await fetchComments(userId);
|
||||
return { user, posts, comments };
|
||||
}
|
||||
|
||||
// ✅ GOOD: Parallel async operations
|
||||
async function getUserData(userId) {
|
||||
const [user, posts, comments] = await Promise.all([
|
||||
fetchUser(userId),
|
||||
fetchPosts(userId),
|
||||
fetchComments(userId)
|
||||
]);
|
||||
return { user, posts, comments };
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Awaiting in loop
|
||||
async function processUsers(userIds) {
|
||||
const results = [];
|
||||
for (const id of userIds) {
|
||||
const result = await processUser(id); // Sequential!
|
||||
results.push(result);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
// ✅ GOOD: Parallel processing with Promise.all
|
||||
async function processUsers(userIds) {
|
||||
return Promise.all(userIds.map(id => processUser(id)));
|
||||
}
|
||||
|
||||
// ✅ BETTER: Parallel with concurrency limit
|
||||
async function processUsers(userIds) {
|
||||
const concurrency = 5;
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < userIds.length; i += concurrency) {
|
||||
const batch = userIds.slice(i, i + concurrency);
|
||||
const batchResults = await Promise.all(batch.map(id => processUser(id)));
|
||||
results.push(...batchResults);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: No caching for expensive operation
|
||||
function fibonacci(n) {
|
||||
if (n <= 1) return n;
|
||||
return fibonacci(n - 1) + fibonacci(n - 2); // Recalculates same values!
|
||||
}
|
||||
|
||||
// ✅ GOOD: Memoization
|
||||
const fibCache = new Map();
|
||||
function fibonacci(n) {
|
||||
if (n <= 1) return n;
|
||||
if (fibCache.has(n)) return fibCache.get(n);
|
||||
|
||||
const result = fibonacci(n - 1) + fibonacci(n - 2);
|
||||
fibCache.set(n, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ✅ BETTER: Iterative approach (faster)
|
||||
function fibonacci(n) {
|
||||
if (n <= 1) return n;
|
||||
let prev = 0, curr = 1;
|
||||
for (let i = 2; i <= n; i++) {
|
||||
[prev, curr] = [curr, prev + curr];
|
||||
}
|
||||
return curr;
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Frontend Performance Review
|
||||
|
||||
**React Component Optimization**:
|
||||
- [ ] Components memoized where appropriate (React.memo)
|
||||
- [ ] useMemo for expensive calculations
|
||||
- [ ] useCallback for function props
|
||||
- [ ] Unnecessary re-renders prevented
|
||||
- [ ] Proper dependency arrays in hooks
|
||||
- [ ] Key props correct for lists
|
||||
- [ ] Code splitting at route level
|
||||
- [ ] Lazy loading for heavy components
|
||||
|
||||
**List Rendering**:
|
||||
- [ ] Large lists virtualized (react-window, react-virtualized)
|
||||
- [ ] Pagination for very large datasets
|
||||
- [ ] Infinite scroll implemented efficiently
|
||||
- [ ] Window recycling for scrolling performance
|
||||
- [ ] Avoid rendering off-screen items
|
||||
|
||||
**Image Optimization**:
|
||||
- [ ] Images properly sized (responsive images)
|
||||
- [ ] Lazy loading implemented
|
||||
- [ ] Modern formats used (WebP, AVIF)
|
||||
- [ ] Image compression applied
|
||||
- [ ] Srcset for different screen sizes
|
||||
- [ ] Loading placeholder or skeleton
|
||||
|
||||
**Bundle Optimization**:
|
||||
- [ ] Code splitting implemented
|
||||
- [ ] Tree shaking enabled
|
||||
- [ ] Dead code eliminated
|
||||
- [ ] Dynamic imports for large libraries
|
||||
- [ ] Bundle size analyzed (webpack-bundle-analyzer)
|
||||
- [ ] Moment.js replaced with date-fns or dayjs
|
||||
- [ ] Lodash imports optimized (import specific functions)
|
||||
|
||||
**State Management**:
|
||||
- [ ] State normalized (avoid nested updates)
|
||||
- [ ] Global state minimized
|
||||
- [ ] Computed values memoized
|
||||
- [ ] State updates batched
|
||||
- [ ] Context splits prevent unnecessary re-renders
|
||||
- [ ] Use of local state preferred over global
|
||||
|
||||
**Web Vitals Optimization**:
|
||||
- [ ] Largest Contentful Paint (LCP) < 2.5s
|
||||
- [ ] First Input Delay (FID) < 100ms
|
||||
- [ ] Cumulative Layout Shift (CLS) < 0.1
|
||||
- [ ] Time to Interactive (TTI) optimized
|
||||
- [ ] First Contentful Paint (FCP) optimized
|
||||
|
||||
**Code Examples - Frontend Performance**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Unnecessary re-renders
|
||||
function UserList({ users, onDelete }) {
|
||||
return users.map(user => (
|
||||
<UserCard
|
||||
key={user.id}
|
||||
user={user}
|
||||
onDelete={() => onDelete(user.id)} // New function every render!
|
||||
/>
|
||||
));
|
||||
}
|
||||
|
||||
// ✅ GOOD: Memoized components
|
||||
const UserCard = React.memo(({ user, onDelete }) => (
|
||||
<div onClick={() => onDelete(user.id)}>
|
||||
{user.name}
|
||||
</div>
|
||||
));
|
||||
|
||||
function UserList({ users, onDelete }) {
|
||||
return users.map(user => (
|
||||
<UserCard key={user.id} user={user} onDelete={onDelete} />
|
||||
));
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Expensive calculation on every render
|
||||
function ProductList({ products }) {
|
||||
const sortedProducts = products
|
||||
.sort((a, b) => b.rating - a.rating)
|
||||
.slice(0, 10); // Recalculated every render!
|
||||
|
||||
return <div>{sortedProducts.map(p => <Product key={p.id} {...p} />)}</div>;
|
||||
}
|
||||
|
||||
// ✅ GOOD: Memoized calculation
|
||||
function ProductList({ products }) {
|
||||
const sortedProducts = useMemo(() =>
|
||||
products
|
||||
.sort((a, b) => b.rating - a.rating)
|
||||
.slice(0, 10),
|
||||
[products] // Only recalculate when products change
|
||||
);
|
||||
|
||||
return <div>{sortedProducts.map(p => <Product key={p.id} {...p} />)}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: No virtualization for large list
|
||||
function MessageList({ messages }) {
|
||||
return (
|
||||
<div>
|
||||
{messages.map(msg => (
|
||||
<MessageItem key={msg.id} message={msg} />
|
||||
))}
|
||||
</div>
|
||||
); // Renders ALL messages, even off-screen!
|
||||
}
|
||||
|
||||
// ✅ GOOD: Virtualized list
|
||||
import { FixedSizeList } from 'react-window';
|
||||
|
||||
function MessageList({ messages }) {
|
||||
const Row = ({ index, style }) => (
|
||||
<div style={style}>
|
||||
<MessageItem message={messages[index]} />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<FixedSizeList
|
||||
height={600}
|
||||
itemCount={messages.length}
|
||||
itemSize={80}
|
||||
width="100%"
|
||||
>
|
||||
{Row}
|
||||
</FixedSizeList>
|
||||
); // Only renders visible items!
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Entire library imported
|
||||
import moment from 'moment'; // Imports entire 70KB library!
|
||||
|
||||
// ✅ GOOD: Lightweight alternative
|
||||
import { format } from 'date-fns'; // Tree-shakeable, smaller
|
||||
|
||||
// ❌ BAD: Lodash imported entirely
|
||||
import _ from 'lodash';
|
||||
|
||||
// ✅ GOOD: Specific imports
|
||||
import debounce from 'lodash/debounce';
|
||||
import throttle from 'lodash/throttle';
|
||||
```
|
||||
|
||||
### 6. Network Performance Review
|
||||
|
||||
**API Optimization**:
|
||||
- [ ] API calls minimized
|
||||
- [ ] GraphQL for flexible data fetching
|
||||
- [ ] Batch API requests where possible
|
||||
- [ ] Debouncing for search/autocomplete
|
||||
- [ ] Prefetching for predictable navigation
|
||||
- [ ] Optimistic updates for better UX
|
||||
- [ ] Request deduplication
|
||||
|
||||
**Caching & CDN**:
|
||||
- [ ] HTTP caching headers configured
|
||||
- [ ] Cache-Control directives appropriate
|
||||
- [ ] ETag for conditional requests
|
||||
- [ ] Service Worker for offline caching
|
||||
- [ ] CDN for static assets
|
||||
- [ ] Edge caching where applicable
|
||||
|
||||
**Compression**:
|
||||
- [ ] Gzip or Brotli compression enabled
|
||||
- [ ] Appropriate compression levels
|
||||
- [ ] Assets minified
|
||||
- [ ] JSON responses compressed
|
||||
|
||||
**Resource Loading**:
|
||||
- [ ] Critical CSS inlined
|
||||
- [ ] Non-critical CSS loaded async
|
||||
- [ ] JavaScript loaded with async/defer
|
||||
- [ ] DNS prefetch for external domains
|
||||
- [ ] Preload for critical resources
|
||||
- [ ] Preconnect for required origins
|
||||
|
||||
**Code Examples - Network Performance**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: No debouncing for search
|
||||
function SearchBox() {
|
||||
const [query, setQuery] = useState('');
|
||||
|
||||
const handleChange = async (e) => {
|
||||
setQuery(e.target.value);
|
||||
await fetchResults(e.target.value); // API call on every keystroke!
|
||||
};
|
||||
|
||||
return <input value={query} onChange={handleChange} />;
|
||||
}
|
||||
|
||||
// ✅ GOOD: Debounced search
|
||||
import { debounce } from 'lodash';
|
||||
|
||||
function SearchBox() {
|
||||
const [query, setQuery] = useState('');
|
||||
|
||||
const fetchResultsDebounced = useMemo(
|
||||
() => debounce((q) => fetchResults(q), 300),
|
||||
[]
|
||||
);
|
||||
|
||||
const handleChange = (e) => {
|
||||
setQuery(e.target.value);
|
||||
fetchResultsDebounced(e.target.value);
|
||||
};
|
||||
|
||||
return <input value={query} onChange={handleChange} />;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Multiple API calls
|
||||
const user = await fetch('/api/user/123').then(r => r.json());
|
||||
const posts = await fetch('/api/user/123/posts').then(r => r.json());
|
||||
const followers = await fetch('/api/user/123/followers').then(r => r.json());
|
||||
|
||||
// ✅ GOOD: Single API call with all data
|
||||
const userData = await fetch('/api/user/123?include=posts,followers')
|
||||
.then(r => r.json());
|
||||
|
||||
// ✅ BETTER: GraphQL for flexible data fetching
|
||||
const userData = await graphqlClient.query({
|
||||
query: gql`
|
||||
query GetUser($id: ID!) {
|
||||
user(id: $id) {
|
||||
name
|
||||
email
|
||||
posts(limit: 10) { title }
|
||||
followers(limit: 5) { name }
|
||||
}
|
||||
}
|
||||
`,
|
||||
variables: { id: '123' }
|
||||
});
|
||||
```
|
||||
|
||||
### 7. Performance Monitoring & Profiling
|
||||
|
||||
**Monitoring Tools**:
|
||||
```bash
|
||||
# Check bundle size
|
||||
npm run build
|
||||
ls -lh dist/ # Check output sizes
|
||||
|
||||
# Analyze bundle composition
|
||||
npm install --save-dev webpack-bundle-analyzer
|
||||
# Add to webpack config and analyze
|
||||
|
||||
# Run Lighthouse audit
|
||||
npx lighthouse https://your-site.com --view
|
||||
|
||||
# Check Core Web Vitals
|
||||
# Use Chrome DevTools -> Performance
|
||||
# Use Lighthouse or WebPageTest
|
||||
```
|
||||
|
||||
**Performance Metrics**:
|
||||
- [ ] Response time monitoring
|
||||
- [ ] Database query times logged
|
||||
- [ ] API endpoint performance tracked
|
||||
- [ ] Error rates monitored
|
||||
- [ ] Memory usage tracked
|
||||
- [ ] CPU usage monitored
|
||||
|
||||
**Profiling**:
|
||||
- [ ] Node.js profiling for CPU hotspots
|
||||
- [ ] Memory profiling for leaks
|
||||
- [ ] Chrome DevTools performance profiling
|
||||
- [ ] React DevTools Profiler used
|
||||
|
||||
### 8. Scalability Review
|
||||
|
||||
**Horizontal Scalability**:
|
||||
- [ ] Stateless application design
|
||||
- [ ] Session data in external store (Redis)
|
||||
- [ ] No local file system dependencies
|
||||
- [ ] Load balancer compatible
|
||||
- [ ] Health check endpoints
|
||||
|
||||
**Vertical Scalability**:
|
||||
- [ ] Memory usage efficient
|
||||
- [ ] CPU usage optimized
|
||||
- [ ] Can handle increased load per instance
|
||||
|
||||
**Database Scalability**:
|
||||
- [ ] Read replicas for read-heavy loads
|
||||
- [ ] Write scaling strategy (sharding, partitioning)
|
||||
- [ ] Connection pooling configured
|
||||
- [ ] Query performance at scale considered
|
||||
|
||||
**Caching for Scale**:
|
||||
- [ ] Distributed caching (Redis cluster)
|
||||
- [ ] Cache warming strategy
|
||||
- [ ] Cache hit rate optimization
|
||||
- [ ] Cache invalidation across instances
|
||||
|
||||
## Review Depth Implementation
|
||||
|
||||
**Quick Depth** (10-15 min):
|
||||
- Focus on obvious performance issues
|
||||
- Check for N+1 queries
|
||||
- Review large data fetching without pagination
|
||||
- Check bundle size
|
||||
- Identify blocking operations
|
||||
|
||||
**Standard Depth** (30-40 min):
|
||||
- All performance categories reviewed
|
||||
- Database query analysis
|
||||
- Frontend rendering optimization
|
||||
- Network request analysis
|
||||
- Caching strategy review
|
||||
- Basic profiling recommendations
|
||||
|
||||
**Deep Depth** (60-90+ min):
|
||||
- Comprehensive performance audit
|
||||
- Detailed query plan analysis
|
||||
- Algorithm complexity review
|
||||
- Memory profiling
|
||||
- Complete bundle analysis
|
||||
- Load testing recommendations
|
||||
- Scalability assessment
|
||||
- Performance monitoring setup
|
||||
|
||||
## Output Format
|
||||
|
||||
```markdown
|
||||
# Performance Review: [Scope]
|
||||
|
||||
## Executive Summary
|
||||
|
||||
**Reviewed**: [What was reviewed]
|
||||
**Depth**: [Quick|Standard|Deep]
|
||||
**Performance Rating**: [Excellent|Good|Needs Optimization|Critical Issues]
|
||||
|
||||
### Overall Performance Assessment
|
||||
**[Optimized|Acceptable|Needs Improvement|Poor]**
|
||||
|
||||
[Brief explanation]
|
||||
|
||||
### Key Performance Metrics
|
||||
- **Average Response Time**: [Xms]
|
||||
- **Database Query Time**: [Xms]
|
||||
- **Bundle Size**: [XKB]
|
||||
- **Largest Contentful Paint**: [Xs]
|
||||
- **Time to Interactive**: [Xs]
|
||||
|
||||
### Priority Actions
|
||||
1. [Critical performance fix 1]
|
||||
2. [Critical performance fix 2]
|
||||
|
||||
---
|
||||
|
||||
## Critical Performance Issues 🚨
|
||||
|
||||
### [Issue 1 Title]
|
||||
**File**: `path/to/file.ts:42`
|
||||
**Category**: Database|Backend|Frontend|Network
|
||||
**Impact**: [Severe slowdown, timeout, memory leak, etc.]
|
||||
**Current Performance**: [Xms, XKB, etc.]
|
||||
**Expected Performance**: [Target]
|
||||
**Root Cause**: [Why this is slow]
|
||||
**Optimization**: [Specific fix]
|
||||
|
||||
```typescript
|
||||
// Current code (slow)
|
||||
[slow code]
|
||||
|
||||
// Optimized implementation
|
||||
[fast code]
|
||||
|
||||
// Performance improvement: [X% faster, XKB smaller, etc.]
|
||||
```
|
||||
|
||||
[Repeat for each critical issue]
|
||||
|
||||
---
|
||||
|
||||
## High Impact Optimizations ⚠️
|
||||
|
||||
[Similar format for high impact issues]
|
||||
|
||||
---
|
||||
|
||||
## Medium Impact Optimizations ℹ️
|
||||
|
||||
[Similar format for medium impact issues]
|
||||
|
||||
---
|
||||
|
||||
## Low Impact Optimizations 💡
|
||||
|
||||
[Similar format for low impact issues]
|
||||
|
||||
---
|
||||
|
||||
## Performance Strengths ✅
|
||||
|
||||
- ✅ [Optimization already in place]
|
||||
- ✅ [Good performance practice]
|
||||
|
||||
---
|
||||
|
||||
## Detailed Performance Analysis
|
||||
|
||||
### 🗄️ Database Performance
|
||||
|
||||
**Query Performance**:
|
||||
- Average query time: [Xms]
|
||||
- Slowest queries: [List with times]
|
||||
- N+1 queries found: [Count and locations]
|
||||
- Missing indexes: [List]
|
||||
|
||||
**Optimization Recommendations**:
|
||||
1. [Specific database optimization]
|
||||
2. [Specific database optimization]
|
||||
|
||||
### ⚙️ Backend Performance
|
||||
|
||||
**Algorithm Complexity**:
|
||||
- O(n²) operations found: [Count and locations]
|
||||
- Memory-intensive operations: [List]
|
||||
|
||||
**Async Performance**:
|
||||
- Sequential operations that could be parallel: [Count]
|
||||
- Blocking operations: [List]
|
||||
|
||||
**Optimization Recommendations**:
|
||||
1. [Specific backend optimization]
|
||||
2. [Specific backend optimization]
|
||||
|
||||
### 🎨 Frontend Performance
|
||||
|
||||
**Bundle Analysis**:
|
||||
- Total bundle size: [XKB]
|
||||
- Largest dependencies: [List with sizes]
|
||||
- Code splitting: [Enabled/Not enabled]
|
||||
- Tree shaking: [Effective/Ineffective]
|
||||
|
||||
**Rendering Performance**:
|
||||
- Unnecessary re-renders: [Count and components]
|
||||
- Large lists without virtualization: [List]
|
||||
- Unoptimized images: [Count]
|
||||
|
||||
**Web Vitals**:
|
||||
| Metric | Current | Target | Status |
|
||||
|--------|---------|--------|--------|
|
||||
| LCP | [Xs] | < 2.5s | ✅ / ⚠️ / ❌ |
|
||||
| FID | [Xms] | < 100ms | ✅ / ⚠️ / ❌ |
|
||||
| CLS | [X] | < 0.1 | ✅ / ⚠️ / ❌ |
|
||||
| TTI | [Xs] | < 3.8s | ✅ / ⚠️ / ❌ |
|
||||
|
||||
**Optimization Recommendations**:
|
||||
1. [Specific frontend optimization]
|
||||
2. [Specific frontend optimization]
|
||||
|
||||
### 🌐 Network Performance
|
||||
|
||||
**API Performance**:
|
||||
- Average API response time: [Xms]
|
||||
- Slowest endpoints: [List with times]
|
||||
- API calls that could be batched: [Count]
|
||||
- Missing caching: [List]
|
||||
|
||||
**Resource Loading**:
|
||||
- Total page size: [XMB]
|
||||
- Number of requests: [X]
|
||||
- Compression enabled: [Yes/No]
|
||||
- CDN usage: [Yes/No/Partial]
|
||||
|
||||
**Optimization Recommendations**:
|
||||
1. [Specific network optimization]
|
||||
2. [Specific network optimization]
|
||||
|
||||
---
|
||||
|
||||
## Scalability Assessment
|
||||
|
||||
**Current Load Capacity**: [X requests/second]
|
||||
**Bottlenecks for Scaling**:
|
||||
1. [Bottleneck 1]
|
||||
2. [Bottleneck 2]
|
||||
|
||||
**Horizontal Scaling**: [Ready|Needs Work|Not Possible]
|
||||
**Vertical Scaling**: [Efficient|Acceptable|Memory/CPU intensive]
|
||||
|
||||
**Recommendations for Scale**:
|
||||
1. [Scaling recommendation 1]
|
||||
2. [Scaling recommendation 2]
|
||||
|
||||
---
|
||||
|
||||
## Performance Optimization Roadmap
|
||||
|
||||
### Immediate (This Week) - Quick Wins
|
||||
- [ ] [Quick optimization 1 - estimated Xms improvement]
|
||||
- [ ] [Quick optimization 2 - estimated XKB reduction]
|
||||
|
||||
### Short-term (This Month) - High Impact
|
||||
- [ ] [Optimization 1 - estimated impact]
|
||||
- [ ] [Optimization 2 - estimated impact]
|
||||
|
||||
### Long-term (This Quarter) - Strategic
|
||||
- [ ] [Strategic improvement 1]
|
||||
- [ ] [Strategic improvement 2]
|
||||
|
||||
**Expected Overall Improvement**: [X% faster, XKB smaller, etc.]
|
||||
|
||||
---
|
||||
|
||||
## Performance Testing Recommendations
|
||||
|
||||
1. **Load Testing**: [Specific scenarios to test]
|
||||
2. **Stress Testing**: [Peak load scenarios]
|
||||
3. **Profiling**: [Areas to profile with tools]
|
||||
4. **Monitoring**: [Metrics to track continuously]
|
||||
|
||||
---
|
||||
|
||||
## Tools & Resources
|
||||
|
||||
**Profiling Tools**:
|
||||
- Chrome DevTools Performance tab
|
||||
- React DevTools Profiler
|
||||
- Node.js --prof for CPU profiling
|
||||
- clinic.js for Node.js diagnostics
|
||||
|
||||
**Monitoring Tools**:
|
||||
- [Recommended monitoring setup]
|
||||
- [Metrics to track]
|
||||
|
||||
---
|
||||
|
||||
## Review Metadata
|
||||
|
||||
- **Reviewer**: 10x Fullstack Engineer (Performance Focus)
|
||||
- **Review Date**: [Date]
|
||||
- **Performance Issues**: Critical: X, High: X, Medium: X, Low: X
|
||||
- **Estimated Total Performance Gain**: [X% improvement]
|
||||
```
|
||||
|
||||
## Agent Invocation
|
||||
|
||||
This operation MUST leverage the **10x-fullstack-engineer** agent with performance expertise.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Measure First**: Use profiling data, not assumptions
|
||||
2. **Optimize Hotspots**: Focus on code that runs frequently
|
||||
3. **Balance Trade-offs**: Consider readability vs performance
|
||||
4. **Think Scale**: How will this perform with 10x, 100x data?
|
||||
5. **User-Centric**: Optimize for perceived performance
|
||||
6. **Incremental Optimization**: Make measurable improvements iteratively
|
||||
519
commands/review/pr.md
Normal file
519
commands/review/pr.md
Normal file
@@ -0,0 +1,519 @@
|
||||
# Pull Request Review
|
||||
|
||||
Performs comprehensive pull request review with git integration, analyzing changes, assessing impact, and providing structured feedback for code review collaboration.
|
||||
|
||||
## Parameters
|
||||
|
||||
**Received from router**: `$ARGUMENTS` (after removing 'pr' operation)
|
||||
|
||||
Expected format: `scope:"PR #123" [depth:"quick|standard|deep"]`
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Parse Parameters
|
||||
|
||||
Extract from $ARGUMENTS:
|
||||
- **scope**: PR number or description (required) - "PR #123", "pull request 456", "current branch"
|
||||
- **depth**: Review thoroughness (default: "standard")
|
||||
|
||||
### 2. Gather PR Context
|
||||
|
||||
**Extract PR Information**:
|
||||
```bash
|
||||
# Get PR details if PR number provided
|
||||
# Example: scope:"PR #123" → extract "123"
|
||||
PR_NUMBER=$(echo "$SCOPE" | grep -oP '#?\K\d+' || echo "")
|
||||
|
||||
if [ -n "$PR_NUMBER" ]; then
|
||||
# Get PR info via GitHub CLI
|
||||
gh pr view $PR_NUMBER --json title,body,author,labels,assignees,reviewDecision
|
||||
|
||||
# Get PR changes
|
||||
gh pr diff $PR_NUMBER
|
||||
else
|
||||
# Review current branch changes
|
||||
git diff $(git merge-base HEAD main)..HEAD
|
||||
fi
|
||||
|
||||
# Get commit history
|
||||
git log main..HEAD --oneline
|
||||
|
||||
# Get changed files
|
||||
git diff --name-only $(git merge-base HEAD main)..HEAD
|
||||
|
||||
# Get file change stats
|
||||
git diff --stat $(git merge-base HEAD main)..HEAD
|
||||
```
|
||||
|
||||
### 3. Analyze Change Context
|
||||
|
||||
**Understand the Changes**:
|
||||
```bash
|
||||
# Categorize changed files
|
||||
git diff --name-only $(git merge-base HEAD main)..HEAD | grep -E '\.(ts|tsx|js|jsx)$' | head -20
|
||||
|
||||
# Check for new files
|
||||
git diff --name-status $(git merge-base HEAD main)..HEAD | grep "^A"
|
||||
|
||||
# Check for deleted files
|
||||
git diff --name-status $(git merge-base HEAD main)..HEAD | grep "^D"
|
||||
|
||||
# Check for renamed/moved files
|
||||
git diff --name-status $(git merge-base HEAD main)..HEAD | grep "^R"
|
||||
|
||||
# Look for test changes
|
||||
git diff --name-only $(git merge-base HEAD main)..HEAD | grep -E '\.(test|spec)\.'
|
||||
|
||||
# Check for documentation changes
|
||||
git diff --name-only $(git merge-base HEAD main)..HEAD | grep -E '\.(md|txt)$'
|
||||
```
|
||||
|
||||
### 4. PR-Specific Review Checklist
|
||||
|
||||
**PR Metadata Review**:
|
||||
- [ ] PR title is clear and descriptive
|
||||
- [ ] PR description explains what and why
|
||||
- [ ] PR size is manageable (< 400 lines changed)
|
||||
- [ ] PR has appropriate labels
|
||||
- [ ] PR is linked to issue/ticket
|
||||
- [ ] PR has reviewers assigned
|
||||
- [ ] PR targets correct branch
|
||||
|
||||
**Change Scope Assessment**:
|
||||
- [ ] Changes align with PR description
|
||||
- [ ] No unrelated changes included
|
||||
- [ ] Scope creep avoided
|
||||
- [ ] Breaking changes clearly documented
|
||||
- [ ] Migration path provided for breaking changes
|
||||
|
||||
**Commit Quality**:
|
||||
- [ ] Commit messages are meaningful
|
||||
- [ ] Commits are logically organized
|
||||
- [ ] No "fix typo" or "wip" commits in history
|
||||
- [ ] Commits could be atomic (optional: suggest squash)
|
||||
- [ ] No merge commits (if using rebase workflow)
|
||||
|
||||
**Branch Strategy**:
|
||||
- [ ] Branch name follows conventions
|
||||
- [ ] Branch is up to date with base branch
|
||||
- [ ] No conflicts with base branch
|
||||
- [ ] Branch focused on single feature/fix
|
||||
|
||||
### 5. Impact Analysis
|
||||
|
||||
**Risk Assessment**:
|
||||
```bash
|
||||
# Check if changes affect critical files
|
||||
git diff --name-only $(git merge-base HEAD main)..HEAD | grep -E '(auth|payment|security|config)'
|
||||
|
||||
# Check for database changes
|
||||
git diff $(git merge-base HEAD main)..HEAD | grep -E '(migration|schema|ALTER|CREATE TABLE)'
|
||||
|
||||
# Check for dependency changes
|
||||
git diff $(git merge-base HEAD main)..HEAD -- package.json requirements.txt go.mod
|
||||
|
||||
# Check for configuration changes
|
||||
git diff $(git merge-base HEAD main)..HEAD -- '*.config.*' '.env.example'
|
||||
```
|
||||
|
||||
**Impact Categories**:
|
||||
- [ ] **Critical**: Auth, payment, data integrity, security
|
||||
- [ ] **High**: Core business logic, public APIs, database schema
|
||||
- [ ] **Medium**: Feature additions, UI changes, internal APIs
|
||||
- [ ] **Low**: Documentation, tests, minor refactors
|
||||
|
||||
**Backward Compatibility**:
|
||||
- [ ] API changes are backward compatible
|
||||
- [ ] Database migrations are reversible
|
||||
- [ ] Feature flags used for risky changes
|
||||
- [ ] Deprecation warnings for removed features
|
||||
|
||||
### 6. Code Review Categories
|
||||
|
||||
**Security Review** (Critical for all PRs):
|
||||
- [ ] No hardcoded secrets or credentials
|
||||
- [ ] Input validation for user data
|
||||
- [ ] Authentication/authorization checks
|
||||
- [ ] SQL injection prevention
|
||||
- [ ] XSS prevention
|
||||
- [ ] CSRF protection where needed
|
||||
- [ ] Dependency vulnerabilities checked
|
||||
|
||||
**Performance Review**:
|
||||
- [ ] No obvious performance regressions
|
||||
- [ ] Database queries optimized
|
||||
- [ ] No N+1 query problems introduced
|
||||
- [ ] Caching strategy appropriate
|
||||
- [ ] Bundle size impact considered
|
||||
|
||||
**Code Quality Review**:
|
||||
- [ ] Code follows project conventions
|
||||
- [ ] Functions are focused and manageable
|
||||
- [ ] Naming is clear and consistent
|
||||
- [ ] No code duplication
|
||||
- [ ] Error handling appropriate
|
||||
- [ ] Type safety maintained
|
||||
|
||||
**Testing Review**:
|
||||
- [ ] New features have tests
|
||||
- [ ] Bug fixes have regression tests
|
||||
- [ ] Tests are meaningful
|
||||
- [ ] Test coverage maintained or improved
|
||||
- [ ] Tests pass locally
|
||||
|
||||
**Documentation Review**:
|
||||
- [ ] Public APIs documented
|
||||
- [ ] Complex logic explained
|
||||
- [ ] README updated if needed
|
||||
- [ ] CHANGELOG updated
|
||||
- [ ] Migration guide for breaking changes
|
||||
|
||||
### 7. Test Coverage Analysis
|
||||
|
||||
**Check Test Changes**:
|
||||
```bash
|
||||
# Find test files in PR
|
||||
git diff --name-only $(git merge-base HEAD main)..HEAD | grep -E '\.(test|spec)\.'
|
||||
|
||||
# Check test coverage (if available)
|
||||
npm test -- --coverage --changedSince=main 2>/dev/null || echo "Run tests to check coverage"
|
||||
|
||||
# Look for untested code
|
||||
# (Manual review of changed files vs test files)
|
||||
```
|
||||
|
||||
**Test Quality Questions**:
|
||||
- Are tests testing behavior or implementation?
|
||||
- Are edge cases covered?
|
||||
- Are error paths tested?
|
||||
- Are tests isolated and independent?
|
||||
- Are test names descriptive?
|
||||
|
||||
### 8. Review Changed Files
|
||||
|
||||
**For Each Changed File**:
|
||||
1. Understand the purpose of changes
|
||||
2. Check for security issues
|
||||
3. Check for performance issues
|
||||
4. Check for quality issues
|
||||
5. Verify tests exist
|
||||
6. Look for potential bugs
|
||||
|
||||
**Focus Areas by File Type**:
|
||||
- **Backend code**: Auth, validation, queries, error handling
|
||||
- **Frontend code**: Rendering, state management, accessibility
|
||||
- **Database migrations**: Reversibility, data safety, indexes
|
||||
- **Configuration**: Security, environment-specific values
|
||||
- **Dependencies**: Vulnerability check, license compatibility
|
||||
|
||||
### 9. PR Review Template
|
||||
|
||||
Structure feedback for GitHub PR review:
|
||||
|
||||
```markdown
|
||||
## Summary
|
||||
|
||||
[High-level assessment of the PR]
|
||||
|
||||
**Overall Assessment**: ✅ Approve | 💬 Approve with Comments | 🔄 Request Changes
|
||||
|
||||
**Change Type**: [Feature | Bug Fix | Refactor | Documentation | Performance]
|
||||
**Risk Level**: [Low | Medium | High | Critical]
|
||||
**Estimated Review Time**: [X minutes]
|
||||
|
||||
---
|
||||
|
||||
## Critical Issues 🚨
|
||||
|
||||
**[Must be fixed before merge]**
|
||||
|
||||
### Security Issue: [Title]
|
||||
**File**: `path/to/file.ts` (line X)
|
||||
**Issue**: [Description]
|
||||
**Risk**: [Why this is critical]
|
||||
**Suggestion**:
|
||||
```typescript
|
||||
// Current
|
||||
[problematic code]
|
||||
|
||||
// Suggested
|
||||
[fixed code]
|
||||
```
|
||||
|
||||
[Repeat for each critical issue]
|
||||
|
||||
---
|
||||
|
||||
## High Priority Comments ⚠️
|
||||
|
||||
**[Should be addressed before merge]**
|
||||
|
||||
### [Issue Title]
|
||||
**File**: `path/to/file.ts` (line X)
|
||||
**Comment**: [Description and suggestion]
|
||||
|
||||
[Repeat for each high priority issue]
|
||||
|
||||
---
|
||||
|
||||
## Medium Priority Suggestions 💡
|
||||
|
||||
**[Consider addressing]**
|
||||
|
||||
### [Suggestion Title]
|
||||
**File**: `path/to/file.ts` (line X)
|
||||
**Suggestion**: [Description]
|
||||
|
||||
[Repeat for each medium priority suggestion]
|
||||
|
||||
---
|
||||
|
||||
## Low Priority / Nits 📝
|
||||
|
||||
**[Optional improvements]**
|
||||
|
||||
- [File]: [Minor suggestion]
|
||||
- [File]: [Style nit]
|
||||
|
||||
---
|
||||
|
||||
## Positive Observations ✅
|
||||
|
||||
Things done well in this PR:
|
||||
|
||||
- ✅ [Good practice 1]
|
||||
- ✅ [Good practice 2]
|
||||
- ✅ [Good practice 3]
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
**Test Coverage**: [Adequate | Needs Improvement | Insufficient]
|
||||
|
||||
- [✅ | ❌] Unit tests for new/changed logic
|
||||
- [✅ | ❌] Integration tests for API changes
|
||||
- [✅ | ❌] Component tests for UI changes
|
||||
- [✅ | ❌] E2E tests for critical paths
|
||||
|
||||
**Missing Tests**:
|
||||
- [Area 1 that needs tests]
|
||||
- [Area 2 that needs tests]
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
- [✅ | ❌] Code is well-commented
|
||||
- [✅ | ❌] Public APIs documented
|
||||
- [✅ | ❌] README updated
|
||||
- [✅ | ❌] CHANGELOG updated
|
||||
- [✅ | ❌] Migration guide (if breaking changes)
|
||||
|
||||
---
|
||||
|
||||
## Questions for Author
|
||||
|
||||
1. [Question 1 about design decision]
|
||||
2. [Question 2 about implementation choice]
|
||||
3. [Question 3 about future plans]
|
||||
|
||||
---
|
||||
|
||||
## Review Checklist
|
||||
|
||||
- [✅ | ❌] PR title and description clear
|
||||
- [✅ | ❌] Changes align with description
|
||||
- [✅ | ❌] No unrelated changes
|
||||
- [✅ | ❌] Tests added/updated
|
||||
- [✅ | ❌] Documentation updated
|
||||
- [✅ | ❌] No security issues
|
||||
- [✅ | ❌] No performance regressions
|
||||
- [✅ | ❌] Code quality maintained
|
||||
- [✅ | ❌] Branch up to date with base
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
**For Author**:
|
||||
- [ ] Address critical issues
|
||||
- [ ] Respond to comments
|
||||
- [ ] Add missing tests
|
||||
- [ ] Update documentation
|
||||
- [ ] Request re-review
|
||||
|
||||
**For Reviewers**:
|
||||
- [ ] Additional reviewers needed?
|
||||
- [ ] Security review needed?
|
||||
- [ ] Performance testing needed?
|
||||
|
||||
---
|
||||
|
||||
## Approval Status
|
||||
|
||||
**Recommendation**: [Approve | Request Changes | Needs More Info]
|
||||
|
||||
[Explanation of recommendation]
|
||||
```
|
||||
|
||||
### 10. PR Size Considerations
|
||||
|
||||
**PR Too Large** (>400 lines):
|
||||
- Suggest breaking into smaller PRs
|
||||
- Review in phases (architecture first, then details)
|
||||
- Focus on high-risk areas
|
||||
- Note areas that need detailed review later
|
||||
|
||||
**PR Too Small** (<10 lines):
|
||||
- Quick review appropriate
|
||||
- Still check for edge cases
|
||||
- Verify tests exist
|
||||
|
||||
### 11. Special PR Types
|
||||
|
||||
**Bug Fix PRs**:
|
||||
- [ ] Root cause identified and documented
|
||||
- [ ] Regression test added
|
||||
- [ ] Fix is minimal and focused
|
||||
- [ ] No unrelated refactoring
|
||||
- [ ] Backward compatible
|
||||
|
||||
**Refactoring PRs**:
|
||||
- [ ] Behavior unchanged (tests prove this)
|
||||
- [ ] Motivation clear
|
||||
- [ ] Refactoring scope reasonable
|
||||
- [ ] No functional changes mixed in
|
||||
|
||||
**Feature PRs**:
|
||||
- [ ] Feature complete (no half-done work)
|
||||
- [ ] Feature flag used if risky
|
||||
- [ ] Tests comprehensive
|
||||
- [ ] Documentation complete
|
||||
- [ ] Backward compatible
|
||||
|
||||
**Hotfix PRs**:
|
||||
- [ ] Minimal changes only
|
||||
- [ ] High test coverage
|
||||
- [ ] Rollback plan documented
|
||||
- [ ] Can be deployed independently
|
||||
|
||||
## Review Depth Implementation
|
||||
|
||||
**Quick Depth** (5-10 min):
|
||||
- PR metadata and description review
|
||||
- Security critical issues only
|
||||
- Obvious bugs
|
||||
- Test presence check
|
||||
- High-level change assessment
|
||||
|
||||
**Standard Depth** (20-30 min):
|
||||
- Complete PR review
|
||||
- All categories covered (security, performance, quality)
|
||||
- Test coverage reviewed
|
||||
- Documentation checked
|
||||
- Detailed inline comments
|
||||
|
||||
**Deep Depth** (45-60+ min):
|
||||
- Comprehensive PR analysis
|
||||
- Architecture implications
|
||||
- Performance impact analysis
|
||||
- Complete test review
|
||||
- Documentation thoroughness
|
||||
- Deployment considerations
|
||||
- Backward compatibility analysis
|
||||
|
||||
## Output Format
|
||||
|
||||
Provide a GitHub-compatible PR review following the template above, formatted for posting as PR comments.
|
||||
|
||||
## Code Examples - Common PR Issues
|
||||
|
||||
```typescript
|
||||
// ❌ COMMON PR ISSUE: Unrelated changes
|
||||
// PR says "Fix login bug" but also includes:
|
||||
function LoginForm() {
|
||||
// Login fix
|
||||
validateCredentials(email, password);
|
||||
|
||||
// UNRELATED: Random formatting change in different feature
|
||||
const userProfile = formatUserProfile(user);
|
||||
return <div>{userProfile}</div>;
|
||||
}
|
||||
|
||||
// ✅ GOOD: Focused changes only
|
||||
// PR says "Fix login bug" and only includes:
|
||||
function LoginForm() {
|
||||
// Only the login validation fix
|
||||
validateCredentials(email, password);
|
||||
return <div>...</div>;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ COMMON PR ISSUE: No tests for new feature
|
||||
// PR adds new feature without tests
|
||||
export function calculateDiscount(price: number, code: string): number {
|
||||
if (code === 'SAVE10') return price * 0.9;
|
||||
if (code === 'SAVE20') return price * 0.8;
|
||||
return price;
|
||||
}
|
||||
|
||||
// ✅ GOOD: New feature with tests
|
||||
export function calculateDiscount(price: number, code: string): number {
|
||||
if (code === 'SAVE10') return price * 0.9;
|
||||
if (code === 'SAVE20') return price * 0.8;
|
||||
return price;
|
||||
}
|
||||
|
||||
// In test file:
|
||||
describe('calculateDiscount', () => {
|
||||
it('should apply 10% discount for SAVE10 code', () => {
|
||||
expect(calculateDiscount(100, 'SAVE10')).toBe(90);
|
||||
});
|
||||
|
||||
it('should apply 20% discount for SAVE20 code', () => {
|
||||
expect(calculateDiscount(100, 'SAVE20')).toBe(80);
|
||||
});
|
||||
|
||||
it('should return original price for invalid code', () => {
|
||||
expect(calculateDiscount(100, 'INVALID')).toBe(100);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ COMMON PR ISSUE: Breaking change without migration
|
||||
// Removes field without deprecation period
|
||||
export interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
// 'email' field removed - BREAKING!
|
||||
}
|
||||
|
||||
// ✅ GOOD: Deprecation with migration guide
|
||||
export interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
/**
|
||||
* @deprecated Use primaryEmail instead. Will be removed in v2.0.0
|
||||
*/
|
||||
email?: string;
|
||||
primaryEmail: string; // New field
|
||||
}
|
||||
```
|
||||
|
||||
## Agent Invocation
|
||||
|
||||
This operation MUST leverage the **10x-fullstack-engineer** agent for comprehensive PR review expertise.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Be Timely**: Review PRs promptly to unblock teammates
|
||||
2. **Be Thorough**: But don't let perfect be enemy of good
|
||||
3. **Be Constructive**: Suggest solutions, not just problems
|
||||
4. **Ask Questions**: Understand intent before criticizing
|
||||
5. **Acknowledge Good Work**: Positive feedback matters
|
||||
6. **Focus on Impact**: Prioritize issues by importance
|
||||
7. **Be Specific**: Reference exact files and lines
|
||||
8. **Consider Context**: Understand constraints and trade-offs
|
||||
808
commands/review/quality.md
Normal file
808
commands/review/quality.md
Normal file
@@ -0,0 +1,808 @@
|
||||
# Code Quality Review
|
||||
|
||||
Performs comprehensive code quality analysis focusing on organization, maintainability, testing, documentation, and software craftsmanship best practices.
|
||||
|
||||
## Parameters
|
||||
|
||||
**Received from router**: `$ARGUMENTS` (after removing 'quality' operation)
|
||||
|
||||
Expected format: `scope:"review-scope" [depth:"quick|standard|deep"]`
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Parse Parameters
|
||||
|
||||
Extract from $ARGUMENTS:
|
||||
- **scope**: What to review (required) - files, modules, features
|
||||
- **depth**: Quality analysis thoroughness (default: "standard")
|
||||
|
||||
### 2. Gather Context
|
||||
|
||||
**Understand Code Structure**:
|
||||
```bash
|
||||
# Check project structure
|
||||
ls -la
|
||||
cat package.json 2>/dev/null || cat requirements.txt 2>/dev/null
|
||||
|
||||
# Find test files
|
||||
find . -name "*.test.*" -o -name "*.spec.*" -o -name "*_test.*" | head -20
|
||||
|
||||
# Check for linting configuration
|
||||
ls -la | grep -E "eslint|prettier|pylint|flake8|golangci"
|
||||
|
||||
# Analyze code metrics (if tools available)
|
||||
npx cloc . --exclude-dir=node_modules,dist,build 2>/dev/null || echo "Code analysis"
|
||||
|
||||
# Check for documentation
|
||||
find . -name "README*" -o -name "*.md" | head -10
|
||||
```
|
||||
|
||||
### 3. Code Organization Review
|
||||
|
||||
**Naming Conventions**:
|
||||
- [ ] Variables have clear, descriptive names
|
||||
- [ ] Functions/methods have verb-based names
|
||||
- [ ] Classes have noun-based names
|
||||
- [ ] Constants are UPPER_SNAKE_CASE
|
||||
- [ ] Boolean variables use is/has/should prefix
|
||||
- [ ] Names reveal intent (no cryptic abbreviations)
|
||||
|
||||
**Function Structure**:
|
||||
- [ ] Functions focused on single responsibility
|
||||
- [ ] Functions under 50 lines (ideally under 30)
|
||||
- [ ] Function parameters limited (ideally 3 or fewer)
|
||||
- [ ] Deep nesting avoided (max 3 levels)
|
||||
- [ ] Early returns for guard clauses
|
||||
- [ ] Pure functions where possible
|
||||
|
||||
**File Organization**:
|
||||
- [ ] Related code grouped together
|
||||
- [ ] Clear separation of concerns
|
||||
- [ ] Logical folder structure
|
||||
- [ ] Consistent file naming
|
||||
- [ ] Import statements organized
|
||||
- [ ] File length manageable (under 300 lines)
|
||||
|
||||
**Code Duplication**:
|
||||
- [ ] DRY principle followed
|
||||
- [ ] Repeated patterns extracted to functions
|
||||
- [ ] Common utilities in shared modules
|
||||
- [ ] Magic numbers replaced with named constants
|
||||
- [ ] Similar code refactored to reusable components
|
||||
|
||||
**Code Examples - Organization**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Poor naming and structure
|
||||
function p(u, d) {
|
||||
if (u.r === 'a') {
|
||||
let result = [];
|
||||
for (let i = 0; i < d.length; i++) {
|
||||
if (d[i].o === u.i) {
|
||||
result.push(d[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
// ✅ GOOD: Clear naming and structure
|
||||
function filterDataByUserRole(user: User, data: DataItem[]): DataItem[] {
|
||||
if (user.role === 'admin') {
|
||||
return data.filter(item => item.ownerId === user.id);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Long function with multiple responsibilities
|
||||
function processOrder(order) {
|
||||
// Validate order (20 lines)
|
||||
// Calculate totals (15 lines)
|
||||
// Apply discounts (25 lines)
|
||||
// Process payment (30 lines)
|
||||
// Send notifications (20 lines)
|
||||
// Update inventory (15 lines)
|
||||
// Log analytics (10 lines)
|
||||
// 135 lines total!
|
||||
}
|
||||
|
||||
// ✅ GOOD: Decomposed into focused functions
|
||||
function processOrder(order: Order): OrderResult {
|
||||
validateOrder(order);
|
||||
const totals = calculateOrderTotals(order);
|
||||
const finalPrice = applyDiscounts(totals, order.discountCode);
|
||||
const payment = processPayment(finalPrice, order.paymentMethod);
|
||||
sendOrderNotifications(order, payment);
|
||||
updateInventory(order.items);
|
||||
logOrderAnalytics(order, payment);
|
||||
|
||||
return { order, payment, totals };
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Code duplication
|
||||
function formatUserName(user) {
|
||||
return user.firstName + ' ' + user.lastName;
|
||||
}
|
||||
|
||||
function formatAuthorName(author) {
|
||||
return author.firstName + ' ' + author.lastName;
|
||||
}
|
||||
|
||||
function formatCustomerName(customer) {
|
||||
return customer.firstName + ' ' + customer.lastName;
|
||||
}
|
||||
|
||||
// ✅ GOOD: Extracted common logic
|
||||
interface Person {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
}
|
||||
|
||||
function formatFullName(person: Person): string {
|
||||
return `${person.firstName} ${person.lastName}`;
|
||||
}
|
||||
|
||||
// Use for all person types
|
||||
const userName = formatFullName(user);
|
||||
const authorName = formatFullName(author);
|
||||
const customerName = formatFullName(customer);
|
||||
```
|
||||
|
||||
### 4. Error Handling Review
|
||||
|
||||
**Error Handling Patterns**:
|
||||
- [ ] All errors caught and handled
|
||||
- [ ] Error messages are meaningful
|
||||
- [ ] Errors logged with context
|
||||
- [ ] Errors don't expose sensitive data
|
||||
- [ ] Graceful degradation implemented
|
||||
- [ ] User-friendly error messages in UI
|
||||
- [ ] Error boundaries in React (or equivalent)
|
||||
|
||||
**Validation**:
|
||||
- [ ] Input validation at boundaries
|
||||
- [ ] Type checking for dynamic data
|
||||
- [ ] Null/undefined checks where needed
|
||||
- [ ] Range and boundary checks
|
||||
- [ ] Business rule validation
|
||||
- [ ] Validation errors clearly communicated
|
||||
|
||||
**Code Examples - Error Handling**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Silent failure
|
||||
async function fetchUser(id: string) {
|
||||
try {
|
||||
const response = await fetch(`/api/users/${id}`);
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
return null; // Silent failure!
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ GOOD: Proper error handling
|
||||
async function fetchUser(id: string): Promise<User> {
|
||||
try {
|
||||
const response = await fetch(`/api/users/${id}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch user: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
logger.error('Error fetching user', { id, error });
|
||||
throw new UserFetchError(`Unable to retrieve user ${id}`, { cause: error });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: No validation
|
||||
function calculateDiscount(price, discountPercent) {
|
||||
return price * (discountPercent / 100);
|
||||
}
|
||||
|
||||
// ✅ GOOD: Input validation
|
||||
function calculateDiscount(price: number, discountPercent: number): number {
|
||||
if (price < 0) {
|
||||
throw new Error('Price cannot be negative');
|
||||
}
|
||||
|
||||
if (discountPercent < 0 || discountPercent > 100) {
|
||||
throw new Error('Discount must be between 0 and 100');
|
||||
}
|
||||
|
||||
return price * (discountPercent / 100);
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Type Safety Review (TypeScript/Typed Languages)
|
||||
|
||||
**Type Usage**:
|
||||
- [ ] No `any` types (or justified with comments)
|
||||
- [ ] Explicit return types on functions
|
||||
- [ ] Interface/type definitions for objects
|
||||
- [ ] Enums for fixed sets of values
|
||||
- [ ] Union types for multiple possibilities
|
||||
- [ ] Type guards for runtime validation
|
||||
- [ ] Generics used appropriately
|
||||
|
||||
**Type Quality**:
|
||||
- [ ] Types are precise (not overly broad)
|
||||
- [ ] Types are DRY (shared interfaces)
|
||||
- [ ] Complex types have descriptive names
|
||||
- [ ] Type assertions justified and minimal
|
||||
- [ ] Non-null assertions avoided
|
||||
|
||||
**Code Examples - Type Safety**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Using any
|
||||
function processData(data: any) {
|
||||
return data.map((item: any) => item.value);
|
||||
}
|
||||
|
||||
// ✅ GOOD: Proper types
|
||||
interface DataItem {
|
||||
id: string;
|
||||
value: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function processData(data: DataItem[]): number[] {
|
||||
return data.map(item => item.value);
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Overly broad type
|
||||
function getConfig(): object {
|
||||
return { apiUrl: 'https://api.example.com', timeout: 5000 };
|
||||
}
|
||||
|
||||
// ✅ GOOD: Specific type
|
||||
interface AppConfig {
|
||||
apiUrl: string;
|
||||
timeout: number;
|
||||
retries?: number;
|
||||
}
|
||||
|
||||
function getConfig(): AppConfig {
|
||||
return { apiUrl: 'https://api.example.com', timeout: 5000 };
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Testing Review
|
||||
|
||||
**Test Coverage**:
|
||||
- [ ] Unit tests for business logic
|
||||
- [ ] Integration tests for APIs
|
||||
- [ ] Component tests for UI
|
||||
- [ ] E2E tests for critical paths
|
||||
- [ ] Coverage >80% for critical code
|
||||
- [ ] Edge cases tested
|
||||
- [ ] Error paths tested
|
||||
|
||||
**Test Quality**:
|
||||
- [ ] Tests are readable and maintainable
|
||||
- [ ] Tests are isolated (no interdependencies)
|
||||
- [ ] Tests use meaningful assertions
|
||||
- [ ] Tests focus on behavior, not implementation
|
||||
- [ ] Test names describe what they test
|
||||
- [ ] Mocks/stubs used appropriately
|
||||
- [ ] Test data is clear and minimal
|
||||
|
||||
**Test Organization**:
|
||||
- [ ] Tests colocated with source (or parallel structure)
|
||||
- [ ] Test setup/teardown handled properly
|
||||
- [ ] Shared test utilities extracted
|
||||
- [ ] Test factories for complex objects
|
||||
- [ ] Consistent test patterns across codebase
|
||||
|
||||
**Code Examples - Testing**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Testing implementation details
|
||||
it('should update state', () => {
|
||||
const component = mount(<Counter />);
|
||||
component.instance().incrementCount(); // Implementation detail!
|
||||
expect(component.state('count')).toBe(1);
|
||||
});
|
||||
|
||||
// ✅ GOOD: Testing behavior
|
||||
it('should increment counter when button is clicked', () => {
|
||||
render(<Counter />);
|
||||
const button = screen.getByRole('button', { name: /increment/i });
|
||||
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(screen.getByText('Count: 1')).toBeInTheDocument();
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Unclear test name and setup
|
||||
it('works', async () => {
|
||||
const result = await func(123, true, 'test', null, undefined);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
// ✅ GOOD: Descriptive name and clear test
|
||||
it('should return true when user is authenticated and has admin role', async () => {
|
||||
const user = createTestUser({ role: 'admin', isAuthenticated: true });
|
||||
|
||||
const result = await canAccessAdminPanel(user);
|
||||
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
```
|
||||
|
||||
### 7. Documentation Review
|
||||
|
||||
**Code Documentation**:
|
||||
- [ ] Complex logic explained with comments
|
||||
- [ ] JSDoc/docstrings for public APIs
|
||||
- [ ] "Why" comments, not "what" comments
|
||||
- [ ] TODO/FIXME comments tracked
|
||||
- [ ] Outdated comments removed
|
||||
- [ ] Type definitions documented
|
||||
|
||||
**Project Documentation**:
|
||||
- [ ] README comprehensive and up to date
|
||||
- [ ] Setup instructions accurate
|
||||
- [ ] API documentation complete
|
||||
- [ ] Architecture documented (ADRs)
|
||||
- [ ] Contributing guidelines present
|
||||
- [ ] Changelog maintained
|
||||
|
||||
**Code Examples - Documentation**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Obvious comment
|
||||
// Increment the counter
|
||||
count++;
|
||||
|
||||
// ❌ BAD: Outdated comment
|
||||
// TODO: Add validation (already done!)
|
||||
function saveUser(user: User) {
|
||||
validateUser(user);
|
||||
return db.users.save(user);
|
||||
}
|
||||
|
||||
// ✅ GOOD: Explains why
|
||||
// Using exponential backoff to handle rate limiting from external API
|
||||
await retryWithBackoff(() => externalApi.call());
|
||||
|
||||
// ✅ GOOD: JSDoc for public API
|
||||
/**
|
||||
* Calculates the total price including discounts and taxes.
|
||||
*
|
||||
* @param items - Array of cart items
|
||||
* @param discountCode - Optional discount code to apply
|
||||
* @returns Total price with applied discounts and taxes
|
||||
* @throws {InvalidDiscountError} If discount code is invalid
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const total = calculateTotal(cartItems, 'SAVE10');
|
||||
* ```
|
||||
*/
|
||||
function calculateTotal(items: CartItem[], discountCode?: string): number {
|
||||
// Implementation
|
||||
}
|
||||
```
|
||||
|
||||
### 8. SOLID Principles Review
|
||||
|
||||
**Single Responsibility Principle**:
|
||||
- [ ] Each class/function has one reason to change
|
||||
- [ ] Responsibilities clearly defined
|
||||
- [ ] Cohesion is high
|
||||
|
||||
**Open/Closed Principle**:
|
||||
- [ ] Open for extension, closed for modification
|
||||
- [ ] New features don't require changing existing code
|
||||
- [ ] Abstractions used appropriately
|
||||
|
||||
**Liskov Substitution Principle**:
|
||||
- [ ] Subtypes can replace base types
|
||||
- [ ] Inheritance used correctly
|
||||
- [ ] No broken hierarchies
|
||||
|
||||
**Interface Segregation Principle**:
|
||||
- [ ] Interfaces are focused
|
||||
- [ ] Clients don't depend on unused methods
|
||||
- [ ] Small, cohesive interfaces
|
||||
|
||||
**Dependency Inversion Principle**:
|
||||
- [ ] Depend on abstractions, not concretions
|
||||
- [ ] Dependency injection used
|
||||
- [ ] High-level modules independent of low-level
|
||||
|
||||
**Code Examples - SOLID**:
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Violates Single Responsibility
|
||||
class User {
|
||||
saveToDatabase() { /* ... */ }
|
||||
sendEmail() { /* ... */ }
|
||||
generateReport() { /* ... */ }
|
||||
validateData() { /* ... */ }
|
||||
}
|
||||
|
||||
// ✅ GOOD: Single Responsibility
|
||||
class User {
|
||||
constructor(public name: string, public email: string) {}
|
||||
}
|
||||
|
||||
class UserRepository {
|
||||
save(user: User) { /* ... */ }
|
||||
}
|
||||
|
||||
class EmailService {
|
||||
sendWelcomeEmail(user: User) { /* ... */ }
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ BAD: Violates Dependency Inversion
|
||||
class OrderService {
|
||||
processOrder(order: Order) {
|
||||
const stripe = new StripePayment(); // Tight coupling!
|
||||
stripe.charge(order.amount);
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ GOOD: Dependency Inversion
|
||||
interface PaymentGateway {
|
||||
charge(amount: number): Promise<PaymentResult>;
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
constructor(private paymentGateway: PaymentGateway) {}
|
||||
|
||||
processOrder(order: Order) {
|
||||
return this.paymentGateway.charge(order.amount);
|
||||
}
|
||||
}
|
||||
|
||||
// Can now use any payment gateway
|
||||
const orderService = new OrderService(new StripePayment());
|
||||
// or
|
||||
const orderService = new OrderService(new PayPalPayment());
|
||||
```
|
||||
|
||||
### 9. Design Patterns Review
|
||||
|
||||
**Appropriate Patterns**:
|
||||
- [ ] Patterns used where beneficial
|
||||
- [ ] Patterns not overused
|
||||
- [ ] Patterns implemented correctly
|
||||
- [ ] Patterns consistent with codebase
|
||||
|
||||
**Common Patterns to Look For**:
|
||||
- Factory Pattern: Object creation
|
||||
- Strategy Pattern: Algorithm selection
|
||||
- Observer Pattern: Event handling
|
||||
- Decorator Pattern: Adding functionality
|
||||
- Singleton Pattern: Single instance (use sparingly)
|
||||
- Repository Pattern: Data access
|
||||
- Dependency Injection: Loose coupling
|
||||
|
||||
**Anti-Patterns to Avoid**:
|
||||
- [ ] God Object (class doing too much)
|
||||
- [ ] Spaghetti Code (tangled logic)
|
||||
- [ ] Copy-Paste Programming
|
||||
- [ ] Golden Hammer (overusing one solution)
|
||||
- [ ] Premature Optimization
|
||||
- [ ] Magic Numbers/Strings
|
||||
|
||||
### 10. Code Metrics Analysis
|
||||
|
||||
**Complexity Metrics**:
|
||||
```bash
|
||||
# Cyclomatic complexity (if tools available)
|
||||
npx eslint . --ext .ts,.tsx --format json | grep complexity
|
||||
|
||||
# Lines of code per file
|
||||
find . -name "*.ts" -exec wc -l {} \; | sort -rn | head -10
|
||||
|
||||
# Function length analysis
|
||||
# (Manual review of longest functions)
|
||||
```
|
||||
|
||||
**Quality Indicators**:
|
||||
- [ ] Low cyclomatic complexity (< 10)
|
||||
- [ ] Limited function parameters (< 4)
|
||||
- [ ] Reasonable file length (< 300 lines)
|
||||
- [ ] Low code duplication
|
||||
- [ ] High cohesion, low coupling
|
||||
|
||||
## Review Depth Implementation
|
||||
|
||||
**Quick Depth** (10-15 min):
|
||||
- Focus on obvious quality issues
|
||||
- Check function length and complexity
|
||||
- Review naming conventions
|
||||
- Check for code duplication
|
||||
- Verify basic error handling
|
||||
|
||||
**Standard Depth** (30-40 min):
|
||||
- All quality categories reviewed
|
||||
- Test coverage analysis
|
||||
- Documentation review
|
||||
- SOLID principles check
|
||||
- Design pattern review
|
||||
- Code organization assessment
|
||||
|
||||
**Deep Depth** (60-90+ min):
|
||||
- Comprehensive quality audit
|
||||
- Detailed metrics analysis
|
||||
- Complete test quality review
|
||||
- Architecture pattern review
|
||||
- Refactoring recommendations
|
||||
- Technical debt assessment
|
||||
- Maintainability scoring
|
||||
|
||||
## Output Format
|
||||
|
||||
```markdown
|
||||
# Code Quality Review: [Scope]
|
||||
|
||||
## Executive Summary
|
||||
|
||||
**Reviewed**: [What was reviewed]
|
||||
**Depth**: [Quick|Standard|Deep]
|
||||
**Quality Rating**: [Excellent|Good|Fair|Needs Improvement]
|
||||
|
||||
### Overall Quality Assessment
|
||||
**[High|Medium|Low] Maintainability**
|
||||
|
||||
[Brief explanation]
|
||||
|
||||
### Code Metrics
|
||||
- **Total Lines**: [X]
|
||||
- **Average Function Length**: [X lines]
|
||||
- **Cyclomatic Complexity**: [Average: X]
|
||||
- **Test Coverage**: [X%]
|
||||
- **Code Duplication**: [Low|Medium|High]
|
||||
|
||||
### Priority Actions
|
||||
1. [Critical quality issue 1]
|
||||
2. [Critical quality issue 2]
|
||||
|
||||
---
|
||||
|
||||
## Critical Quality Issues 🚨
|
||||
|
||||
### [Issue 1 Title]
|
||||
**File**: `path/to/file.ts:42`
|
||||
**Category**: Organization|Error Handling|Type Safety|Testing|Documentation
|
||||
**Issue**: [Description of quality problem]
|
||||
**Impact**: [Why this matters for maintainability]
|
||||
**Refactoring**: [Specific improvement]
|
||||
|
||||
```typescript
|
||||
// Current code
|
||||
[problematic code]
|
||||
|
||||
// Refactored code
|
||||
[improved code]
|
||||
```
|
||||
|
||||
[Repeat for each critical issue]
|
||||
|
||||
---
|
||||
|
||||
## High Priority Issues ⚠️
|
||||
|
||||
[Similar format for high priority issues]
|
||||
|
||||
---
|
||||
|
||||
## Medium Priority Issues ℹ️
|
||||
|
||||
[Similar format for medium priority issues]
|
||||
|
||||
---
|
||||
|
||||
## Low Priority Issues 💡
|
||||
|
||||
[Similar format for low priority issues]
|
||||
|
||||
---
|
||||
|
||||
## Quality Strengths ✅
|
||||
|
||||
- ✅ [Good practice 1 with examples]
|
||||
- ✅ [Good practice 2 with examples]
|
||||
- ✅ [Good practice 3 with examples]
|
||||
|
||||
---
|
||||
|
||||
## Detailed Quality Analysis
|
||||
|
||||
### 📂 Code Organization
|
||||
|
||||
**Structure**: [Assessment]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Well-organized aspects]
|
||||
|
||||
**Improvements Needed**:
|
||||
- ⚠️ [Organization issues with file references]
|
||||
|
||||
**Naming Quality**: [Excellent|Good|Needs Improvement]
|
||||
**Function Size**: Average [X] lines (Target: <30)
|
||||
**File Size**: Average [X] lines (Target: <300)
|
||||
|
||||
### 🛡️ Error Handling
|
||||
|
||||
**Coverage**: [Comprehensive|Partial|Insufficient]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Good error handling practices]
|
||||
|
||||
**Improvements Needed**:
|
||||
- ⚠️ [Missing or poor error handling with file references]
|
||||
|
||||
### 🔷 Type Safety (TypeScript)
|
||||
|
||||
**Type Coverage**: [X%]
|
||||
**Any Types Found**: [Count and locations]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Good type usage]
|
||||
|
||||
**Improvements Needed**:
|
||||
- ⚠️ [Type safety issues with file references]
|
||||
|
||||
### 🧪 Testing
|
||||
|
||||
**Test Coverage**: [X%]
|
||||
|
||||
**Coverage by Type**:
|
||||
- Unit Tests: [X%]
|
||||
- Integration Tests: [X%]
|
||||
- E2E Tests: [X%]
|
||||
|
||||
**Test Quality**: [High|Medium|Low]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Well-tested areas]
|
||||
|
||||
**Gaps**:
|
||||
- ⚠️ [Missing test coverage]
|
||||
- ⚠️ [Test quality issues]
|
||||
|
||||
**Untested Code**:
|
||||
- [File/function 1 - why important]
|
||||
- [File/function 2 - why important]
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
**Documentation Level**: [Comprehensive|Adequate|Insufficient]
|
||||
|
||||
**Strengths**:
|
||||
- ✅ [Well-documented areas]
|
||||
|
||||
**Gaps**:
|
||||
- ⚠️ [Missing or inadequate documentation]
|
||||
|
||||
**README Quality**: [Excellent|Good|Needs Work]
|
||||
**API Documentation**: [Complete|Partial|Missing]
|
||||
**Code Comments**: [Appropriate|Excessive|Insufficient]
|
||||
|
||||
### 🏗️ SOLID Principles
|
||||
|
||||
| Principle | Adherence | Issues |
|
||||
|-----------|-----------|--------|
|
||||
| Single Responsibility | ✅ Good / ⚠️ Some Issues / ❌ Violated | [Details] |
|
||||
| Open/Closed | ✅ Good / ⚠️ Some Issues / ❌ Violated | [Details] |
|
||||
| Liskov Substitution | ✅ Good / ⚠️ Some Issues / ❌ Violated | [Details] |
|
||||
| Interface Segregation | ✅ Good / ⚠️ Some Issues / ❌ Violated | [Details] |
|
||||
| Dependency Inversion | ✅ Good / ⚠️ Some Issues / ❌ Violated | [Details] |
|
||||
|
||||
### 🎨 Design Patterns
|
||||
|
||||
**Patterns Identified**:
|
||||
- [Pattern 1]: [Where used, appropriateness]
|
||||
- [Pattern 2]: [Where used, appropriateness]
|
||||
|
||||
**Anti-Patterns Found**:
|
||||
- ⚠️ [Anti-pattern 1 with location]
|
||||
- ⚠️ [Anti-pattern 2 with location]
|
||||
|
||||
### 📊 Code Metrics
|
||||
|
||||
| Metric | Value | Target | Status |
|
||||
|--------|-------|--------|--------|
|
||||
| Avg Function Length | [X] lines | <30 | ✅ / ⚠️ / ❌ |
|
||||
| Max Function Length | [X] lines | <50 | ✅ / ⚠️ / ❌ |
|
||||
| Avg Cyclomatic Complexity | [X] | <10 | ✅ / ⚠️ / ❌ |
|
||||
| Max Cyclomatic Complexity | [X] | <15 | ✅ / ⚠️ / ❌ |
|
||||
| Test Coverage | [X%] | >80% | ✅ / ⚠️ / ❌ |
|
||||
| Code Duplication | [Low/Med/High] | Low | ✅ / ⚠️ / ❌ |
|
||||
|
||||
---
|
||||
|
||||
## Refactoring Recommendations
|
||||
|
||||
### Immediate (This Week)
|
||||
1. [Refactoring 1 - estimated effort, impact]
|
||||
2. [Refactoring 2 - estimated effort, impact]
|
||||
|
||||
### Short-term (This Month)
|
||||
1. [Refactoring 1 - estimated effort, impact]
|
||||
2. [Refactoring 2 - estimated effort, impact]
|
||||
|
||||
### Long-term (This Quarter)
|
||||
1. [Strategic improvement 1]
|
||||
2. [Strategic improvement 2]
|
||||
|
||||
---
|
||||
|
||||
## Technical Debt Assessment
|
||||
|
||||
**Debt Level**: [Low|Medium|High]
|
||||
|
||||
**Key Debt Items**:
|
||||
1. [Debt item 1 - why it exists, impact, remediation]
|
||||
2. [Debt item 2 - why it exists, impact, remediation]
|
||||
|
||||
**Debt Payoff Strategy**: [Recommendation]
|
||||
|
||||
---
|
||||
|
||||
## Maintainability Score
|
||||
|
||||
**Overall Score**: [X/10]
|
||||
|
||||
**Component Scores**:
|
||||
- Organization: [X/10]
|
||||
- Error Handling: [X/10]
|
||||
- Type Safety: [X/10]
|
||||
- Testing: [X/10]
|
||||
- Documentation: [X/10]
|
||||
- Design: [X/10]
|
||||
|
||||
---
|
||||
|
||||
## Best Practices Compliance
|
||||
|
||||
**Followed**:
|
||||
- ✅ [Practice 1]
|
||||
- ✅ [Practice 2]
|
||||
|
||||
**Not Followed**:
|
||||
- ❌ [Practice 1 with remediation]
|
||||
- ❌ [Practice 2 with remediation]
|
||||
|
||||
---
|
||||
|
||||
## Review Metadata
|
||||
|
||||
- **Reviewer**: 10x Fullstack Engineer (Quality Focus)
|
||||
- **Review Date**: [Date]
|
||||
- **Quality Issues**: Critical: X, High: X, Medium: X, Low: X
|
||||
- **Maintainability**: [High|Medium|Low]
|
||||
```
|
||||
|
||||
## Agent Invocation
|
||||
|
||||
This operation MUST leverage the **10x-fullstack-engineer** agent with code quality expertise.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Readability First**: Code is read more than written
|
||||
2. **Consistency**: Follow established patterns
|
||||
3. **Simplicity**: Simple code is maintainable code
|
||||
4. **Test Coverage**: Tests document and protect behavior
|
||||
5. **Meaningful Names**: Names should reveal intent
|
||||
6. **Small Functions**: Functions should do one thing well
|
||||
704
commands/review/security.md
Normal file
704
commands/review/security.md
Normal file
@@ -0,0 +1,704 @@
|
||||
# Security-Focused Code Review
|
||||
|
||||
Performs a comprehensive security audit focusing on authentication, authorization, input validation, data protection, and OWASP Top 10 vulnerabilities.
|
||||
|
||||
## Parameters
|
||||
|
||||
**Received from router**: `$ARGUMENTS` (after removing 'security' operation)
|
||||
|
||||
Expected format: `scope:"review-scope" [depth:"quick|standard|deep"]`
|
||||
|
||||
## Workflow
|
||||
|
||||
### 1. Parse Parameters
|
||||
|
||||
Extract from $ARGUMENTS:
|
||||
- **scope**: What to review (required) - payment module, auth system, API endpoints, etc.
|
||||
- **depth**: Security audit thoroughness (default: "deep" for security reviews)
|
||||
|
||||
### 2. Gather Context
|
||||
|
||||
**Understand the Security Surface**:
|
||||
```bash
|
||||
# Identify entry points
|
||||
find . -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.go" | xargs grep -l "router\|app\.\(get\|post\|put\|delete\)\|@app\.route\|http\.HandleFunc" | head -20
|
||||
|
||||
# Check for authentication middleware
|
||||
grep -r "auth\|jwt\|session" --include="*.ts" --include="*.js" --include="*.py" | head -20
|
||||
|
||||
# Find environment variable usage
|
||||
grep -r "process\.env\|os\.getenv\|os\.environ" --include="*.ts" --include="*.js" --include="*.py" | head -15
|
||||
|
||||
# Check dependencies for known vulnerabilities
|
||||
npm audit || pip-audit || go list -m all | nancy sleuth || echo "Check package security"
|
||||
|
||||
# Look for database queries
|
||||
grep -r "query\|execute\|SELECT\|INSERT\|UPDATE\|DELETE" --include="*.ts" --include="*.js" --include="*.py" | head -20
|
||||
```
|
||||
|
||||
### 3. Authentication & Authorization Security
|
||||
|
||||
**Authentication Checks**:
|
||||
- [ ] All protected endpoints have authentication middleware
|
||||
- [ ] Authentication tokens are validated properly
|
||||
- [ ] Token expiration is enforced
|
||||
- [ ] Refresh tokens implemented securely
|
||||
- [ ] Multi-factor authentication available for sensitive operations
|
||||
- [ ] Account lockout after failed login attempts
|
||||
- [ ] Password complexity requirements enforced
|
||||
- [ ] Rate limiting on authentication endpoints
|
||||
|
||||
**Authorization Checks**:
|
||||
- [ ] Role-based access control (RBAC) implemented
|
||||
- [ ] Permission checks on every protected resource
|
||||
- [ ] Users can only access their own data (unless admin)
|
||||
- [ ] Horizontal privilege escalation prevented
|
||||
- [ ] Vertical privilege escalation prevented
|
||||
- [ ] Authorization checks on backend (never trust client)
|
||||
|
||||
**Session Management**:
|
||||
- [ ] Secure session configuration (HttpOnly, Secure, SameSite flags)
|
||||
- [ ] Session timeout configured appropriately
|
||||
- [ ] Session invalidation on logout
|
||||
- [ ] No session fixation vulnerabilities
|
||||
- [ ] Session tokens are cryptographically random
|
||||
|
||||
**Code Examples - Authentication**:
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: No authentication check
|
||||
app.get('/api/user/:id/profile', async (req, res) => {
|
||||
const user = await User.findById(req.params.id);
|
||||
res.json(user);
|
||||
});
|
||||
|
||||
// ✅ GOOD: Authentication required
|
||||
app.get('/api/user/:id/profile', requireAuth, async (req, res) => {
|
||||
const user = await User.findById(req.params.id);
|
||||
res.json(user);
|
||||
});
|
||||
|
||||
// ✅ BETTER: Authentication + authorization
|
||||
app.get('/api/user/:id/profile', requireAuth, async (req, res) => {
|
||||
// User can only access their own profile (unless admin)
|
||||
if (req.user.id !== req.params.id && req.user.role !== 'admin') {
|
||||
return res.status(403).json({ error: 'Forbidden' });
|
||||
}
|
||||
|
||||
const user = await User.findById(req.params.id);
|
||||
res.json(user);
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: Weak JWT verification
|
||||
const decoded = jwt.decode(token); // No verification!
|
||||
req.user = decoded;
|
||||
|
||||
// ✅ GOOD: Proper JWT verification with secret
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET, {
|
||||
algorithms: ['HS256'],
|
||||
maxAge: '1h'
|
||||
});
|
||||
req.user = decoded;
|
||||
```
|
||||
|
||||
### 4. Input Validation & Injection Prevention
|
||||
|
||||
**Input Validation**:
|
||||
- [ ] All user inputs validated on backend
|
||||
- [ ] Whitelist validation used (not blacklist)
|
||||
- [ ] Input length limits enforced
|
||||
- [ ] Data types validated
|
||||
- [ ] File uploads validated (type, size, content)
|
||||
- [ ] Email addresses validated properly
|
||||
- [ ] URLs validated and sanitized
|
||||
|
||||
**SQL Injection Prevention**:
|
||||
- [ ] Parameterized queries used (never string concatenation)
|
||||
- [ ] ORM used correctly (no raw queries with user input)
|
||||
- [ ] Stored procedures with parameterization
|
||||
- [ ] Input sanitization for database queries
|
||||
- [ ] Principle of least privilege for database users
|
||||
|
||||
**XSS Prevention**:
|
||||
- [ ] Output encoding for all user-generated content
|
||||
- [ ] Content Security Policy (CSP) headers configured
|
||||
- [ ] HTML sanitization for rich text input
|
||||
- [ ] No innerHTML with user data (use textContent)
|
||||
- [ ] Template engines auto-escape by default
|
||||
- [ ] React JSX auto-escapes (but check dangerouslySetInnerHTML)
|
||||
|
||||
**Command Injection Prevention**:
|
||||
- [ ] No shell command execution with user input
|
||||
- [ ] If shell commands necessary, use safe APIs
|
||||
- [ ] Input validation for any system calls
|
||||
- [ ] Whitelist allowed commands
|
||||
|
||||
**Path Traversal Prevention**:
|
||||
- [ ] No file system access with user-controlled paths
|
||||
- [ ] Path validation and sanitization
|
||||
- [ ] Use safe path joining methods
|
||||
- [ ] Restrict file access to specific directories
|
||||
|
||||
**Code Examples - Injection Prevention**:
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: SQL Injection vulnerability
|
||||
const email = req.body.email;
|
||||
const query = `SELECT * FROM users WHERE email = '${email}'`;
|
||||
const users = await db.query(query);
|
||||
|
||||
// ✅ GOOD: Parameterized query
|
||||
const email = req.body.email;
|
||||
const query = 'SELECT * FROM users WHERE email = ?';
|
||||
const users = await db.query(query, [email]);
|
||||
|
||||
// ✅ BETTER: Using ORM with validation
|
||||
const email = validateEmail(req.body.email); // Throws if invalid
|
||||
const users = await User.findAll({ where: { email } });
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: XSS vulnerability
|
||||
const username = req.query.name;
|
||||
res.send(`<h1>Welcome ${username}</h1>`);
|
||||
|
||||
// ✅ GOOD: Proper escaping
|
||||
const username = escapeHtml(req.query.name);
|
||||
res.send(`<h1>Welcome ${username}</h1>`);
|
||||
|
||||
// ✅ BETTER: Use template engine with auto-escaping
|
||||
res.render('welcome', { username: req.query.name }); // Template auto-escapes
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: Command injection
|
||||
const filename = req.body.filename;
|
||||
exec(`cat ${filename}`, (err, stdout) => {
|
||||
res.send(stdout);
|
||||
});
|
||||
|
||||
// ✅ GOOD: Use safe file reading
|
||||
const filename = path.basename(req.body.filename); // Remove path traversal
|
||||
const safePath = path.join('/safe/directory', filename);
|
||||
const content = await fs.readFile(safePath, 'utf8');
|
||||
res.send(content);
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: Path traversal vulnerability
|
||||
const file = req.query.file;
|
||||
res.sendFile(`/public/${file}`);
|
||||
|
||||
// ✅ GOOD: Validated and restricted path
|
||||
const file = path.basename(req.query.file); // Remove directory traversal
|
||||
const safePath = path.join(__dirname, 'public', file);
|
||||
|
||||
// Ensure path is within allowed directory
|
||||
if (!safePath.startsWith(path.join(__dirname, 'public'))) {
|
||||
return res.status(400).send('Invalid file path');
|
||||
}
|
||||
|
||||
res.sendFile(safePath);
|
||||
```
|
||||
|
||||
### 5. Data Protection & Cryptography
|
||||
|
||||
**Data at Rest**:
|
||||
- [ ] Sensitive data encrypted in database
|
||||
- [ ] Proper encryption algorithm (AES-256)
|
||||
- [ ] Encryption keys stored securely (not in code)
|
||||
- [ ] Key rotation strategy implemented
|
||||
- [ ] PII data identified and protected
|
||||
|
||||
**Data in Transit**:
|
||||
- [ ] HTTPS/TLS enforced for all connections
|
||||
- [ ] TLS 1.2+ required (TLS 1.0/1.1 disabled)
|
||||
- [ ] Strong cipher suites configured
|
||||
- [ ] HTTP Strict Transport Security (HSTS) enabled
|
||||
- [ ] Certificate validation proper
|
||||
|
||||
**Password Security**:
|
||||
- [ ] Passwords hashed with strong algorithm (bcrypt, argon2, scrypt)
|
||||
- [ ] Salt used for each password
|
||||
- [ ] No password length maximum (only minimum)
|
||||
- [ ] Passwords never logged or stored in plain text
|
||||
- [ ] Password reset tokens are cryptographically secure
|
||||
- [ ] Password reset tokens expire
|
||||
|
||||
**Secrets Management**:
|
||||
- [ ] No hardcoded secrets in code
|
||||
- [ ] API keys in environment variables or secret manager
|
||||
- [ ] Database credentials not in version control
|
||||
- [ ] .env files in .gitignore
|
||||
- [ ] Secrets rotation process exists
|
||||
|
||||
**Sensitive Data Handling**:
|
||||
- [ ] Credit card numbers handled per PCI DSS
|
||||
- [ ] PII minimized and protected
|
||||
- [ ] No sensitive data in logs
|
||||
- [ ] No sensitive data in URLs or query parameters
|
||||
- [ ] Sensitive data masked in UI when appropriate
|
||||
|
||||
**Code Examples - Data Protection**:
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: Hardcoded API key (example only - not a real key)
|
||||
const apiKey = "sk_live_EXAMPLE_KEY_DO_NOT_HARDCODE_SECRETS";
|
||||
|
||||
// ✅ GOOD: Environment variable
|
||||
const apiKey = process.env.STRIPE_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error('STRIPE_API_KEY not configured');
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: Weak password hashing
|
||||
const hashedPassword = md5(password); // MD5 is broken!
|
||||
|
||||
// ❌ BAD: SHA-256 without salt
|
||||
const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
|
||||
|
||||
// ✅ GOOD: bcrypt with salt
|
||||
const hashedPassword = await bcrypt.hash(password, 12); // Cost factor 12
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: Sensitive data in logs
|
||||
logger.info('User login', { email, password, creditCard });
|
||||
|
||||
// ✅ GOOD: No sensitive data
|
||||
logger.info('User login', { email, userId });
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: Weak random token
|
||||
const resetToken = Math.random().toString(36);
|
||||
|
||||
// ✅ GOOD: Cryptographically secure random token
|
||||
const resetToken = crypto.randomBytes(32).toString('hex');
|
||||
```
|
||||
|
||||
### 6. CSRF & CORS Security
|
||||
|
||||
**CSRF Protection**:
|
||||
- [ ] CSRF tokens implemented for state-changing operations
|
||||
- [ ] SameSite cookie attribute set
|
||||
- [ ] Double-submit cookie pattern used
|
||||
- [ ] Custom headers required for AJAX requests
|
||||
- [ ] Origin/Referer validation
|
||||
|
||||
**CORS Configuration**:
|
||||
- [ ] CORS whitelist configured (not wildcard in production)
|
||||
- [ ] Credentials allowed only for trusted origins
|
||||
- [ ] Preflight requests handled correctly
|
||||
- [ ] Access-Control-Max-Age set appropriately
|
||||
|
||||
**Code Examples - CSRF/CORS**:
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: CORS allows all origins
|
||||
app.use(cors({ origin: '*', credentials: true }));
|
||||
|
||||
// ✅ GOOD: CORS whitelist
|
||||
const allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];
|
||||
app.use(cors({
|
||||
origin: (origin, callback) => {
|
||||
if (!origin || allowedOrigins.includes(origin)) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
callback(new Error('Not allowed by CORS'));
|
||||
}
|
||||
},
|
||||
credentials: true
|
||||
}));
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: No CSRF protection
|
||||
app.post('/api/transfer-money', async (req, res) => {
|
||||
await transferMoney(req.body);
|
||||
res.json({ success: true });
|
||||
});
|
||||
|
||||
// ✅ GOOD: CSRF token validation
|
||||
app.post('/api/transfer-money', csrfProtection, async (req, res) => {
|
||||
await transferMoney(req.body);
|
||||
res.json({ success: true });
|
||||
});
|
||||
```
|
||||
|
||||
### 7. Security Headers
|
||||
|
||||
**Required Security Headers**:
|
||||
- [ ] Content-Security-Policy (CSP)
|
||||
- [ ] X-Content-Type-Options: nosniff
|
||||
- [ ] X-Frame-Options: DENY or SAMEORIGIN
|
||||
- [ ] X-XSS-Protection: 1; mode=block
|
||||
- [ ] Strict-Transport-Security (HSTS)
|
||||
- [ ] Referrer-Policy: strict-origin-when-cross-origin
|
||||
- [ ] Permissions-Policy (formerly Feature-Policy)
|
||||
|
||||
**Code Example - Security Headers**:
|
||||
|
||||
```typescript
|
||||
// ✅ GOOD: Security headers configured
|
||||
app.use(helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
styleSrc: ["'self'", "'unsafe-inline'"],
|
||||
scriptSrc: ["'self'"],
|
||||
imgSrc: ["'self'", "data:", "https:"],
|
||||
},
|
||||
},
|
||||
hsts: {
|
||||
maxAge: 31536000,
|
||||
includeSubDomains: true,
|
||||
preload: true
|
||||
},
|
||||
frameguard: {
|
||||
action: 'deny'
|
||||
}
|
||||
}));
|
||||
```
|
||||
|
||||
### 8. Dependency Security
|
||||
|
||||
**Vulnerability Scanning**:
|
||||
```bash
|
||||
# Node.js
|
||||
npm audit
|
||||
npm audit fix
|
||||
|
||||
# Python
|
||||
pip-audit
|
||||
safety check
|
||||
|
||||
# Go
|
||||
go list -m all | nancy sleuth
|
||||
|
||||
# Check for outdated packages
|
||||
npm outdated
|
||||
pip list --outdated
|
||||
```
|
||||
|
||||
**Dependencies Review**:
|
||||
- [ ] No known critical vulnerabilities
|
||||
- [ ] Dependencies up to date
|
||||
- [ ] Unnecessary dependencies removed
|
||||
- [ ] Development dependencies separate from production
|
||||
- [ ] Lock files committed (package-lock.json, poetry.lock, go.sum)
|
||||
- [ ] Automated dependency updates configured (Dependabot, Renovate)
|
||||
|
||||
### 9. Error Handling & Information Disclosure
|
||||
|
||||
**Secure Error Handling**:
|
||||
- [ ] Error messages don't leak sensitive information
|
||||
- [ ] Stack traces not shown to users in production
|
||||
- [ ] Database errors sanitized
|
||||
- [ ] Generic error messages for authentication failures
|
||||
- [ ] Detailed errors logged server-side only
|
||||
- [ ] No verbose debug output in production
|
||||
|
||||
**Code Examples - Error Handling**:
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: Information disclosure
|
||||
app.get('/api/user/:id', async (req, res) => {
|
||||
try {
|
||||
const user = await User.findById(req.params.id);
|
||||
res.json(user);
|
||||
} catch (error) {
|
||||
// Exposes database details and stack trace!
|
||||
res.status(500).json({ error: error.message, stack: error.stack });
|
||||
}
|
||||
});
|
||||
|
||||
// ✅ GOOD: Generic error, detailed logging
|
||||
app.get('/api/user/:id', async (req, res) => {
|
||||
try {
|
||||
const user = await User.findById(req.params.id);
|
||||
res.json(user);
|
||||
} catch (error) {
|
||||
logger.error('Error fetching user', { userId: req.params.id, error });
|
||||
res.status(500).json({ error: 'An error occurred processing your request' });
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// ❌ CRITICAL: Authentication error reveals if user exists
|
||||
if (!user) {
|
||||
return res.status(401).json({ error: 'User not found' });
|
||||
}
|
||||
if (!await bcrypt.compare(password, user.password)) {
|
||||
return res.status(401).json({ error: 'Invalid password' });
|
||||
}
|
||||
|
||||
// ✅ GOOD: Generic authentication error
|
||||
const user = await User.findByEmail(email);
|
||||
const isValidPassword = user && await bcrypt.compare(password, user.password);
|
||||
|
||||
if (!user || !isValidPassword) {
|
||||
return res.status(401).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
```
|
||||
|
||||
### 10. OWASP Top 10 Comprehensive Check
|
||||
|
||||
**A01: Broken Access Control**
|
||||
- [ ] Authorization checks on all protected resources
|
||||
- [ ] Users cannot access other users' data
|
||||
- [ ] Insecure direct object references prevented
|
||||
- [ ] API rate limiting implemented
|
||||
|
||||
**A02: Cryptographic Failures**
|
||||
- [ ] Sensitive data encrypted at rest and in transit
|
||||
- [ ] Strong encryption algorithms used
|
||||
- [ ] No hardcoded encryption keys
|
||||
- [ ] TLS/HTTPS enforced
|
||||
|
||||
**A03: Injection**
|
||||
- [ ] Parameterized queries for SQL
|
||||
- [ ] Input validation and sanitization
|
||||
- [ ] NoSQL injection prevented
|
||||
- [ ] Command injection prevented
|
||||
- [ ] LDAP/XML injection prevented
|
||||
|
||||
**A04: Insecure Design**
|
||||
- [ ] Threat modeling performed
|
||||
- [ ] Security requirements defined
|
||||
- [ ] Secure design patterns used
|
||||
- [ ] Separation of concerns enforced
|
||||
|
||||
**A05: Security Misconfiguration**
|
||||
- [ ] Security headers configured
|
||||
- [ ] Default passwords changed
|
||||
- [ ] Unnecessary features disabled
|
||||
- [ ] Error messages don't leak information
|
||||
- [ ] Security patches applied
|
||||
|
||||
**A06: Vulnerable and Outdated Components**
|
||||
- [ ] Dependencies up to date
|
||||
- [ ] No known vulnerable packages
|
||||
- [ ] Unused dependencies removed
|
||||
- [ ] Automated vulnerability scanning
|
||||
|
||||
**A07: Identification and Authentication Failures**
|
||||
- [ ] Strong password policy
|
||||
- [ ] MFA available
|
||||
- [ ] Account lockout implemented
|
||||
- [ ] Session management secure
|
||||
- [ ] Credential stuffing prevented
|
||||
|
||||
**A08: Software and Data Integrity Failures**
|
||||
- [ ] Digital signatures verified
|
||||
- [ ] CI/CD pipeline secured
|
||||
- [ ] Untrusted deserialization prevented
|
||||
- [ ] Supply chain security considered
|
||||
|
||||
**A09: Security Logging and Monitoring Failures**
|
||||
- [ ] Security events logged
|
||||
- [ ] Failed login attempts logged
|
||||
- [ ] Logs protected from tampering
|
||||
- [ ] Alerting configured for anomalies
|
||||
- [ ] Audit trail maintained
|
||||
|
||||
**A10: Server-Side Request Forgery (SSRF)**
|
||||
- [ ] URLs validated before fetching
|
||||
- [ ] Whitelist of allowed domains
|
||||
- [ ] No access to internal networks
|
||||
- [ ] DNS rebinding prevented
|
||||
|
||||
## Review Depth Implementation
|
||||
|
||||
**Quick Depth** (10-15 min):
|
||||
- Focus only on critical vulnerabilities
|
||||
- Check for common security mistakes
|
||||
- Review authentication and authorization
|
||||
- Check for SQL injection and XSS
|
||||
|
||||
**Standard Depth** (30-40 min):
|
||||
- All OWASP Top 10 categories
|
||||
- Review security headers
|
||||
- Check dependency vulnerabilities
|
||||
- Review error handling
|
||||
- Validate input sanitization
|
||||
|
||||
**Deep Depth** (60-90+ min):
|
||||
- Comprehensive security audit
|
||||
- Threat modeling for reviewed scope
|
||||
- Architecture security review
|
||||
- Complete OWASP Top 10 assessment
|
||||
- Penetration testing recommendations
|
||||
- Security test coverage review
|
||||
- Compliance considerations (GDPR, PCI DSS)
|
||||
|
||||
## Output Format
|
||||
|
||||
```markdown
|
||||
# Security Review: [Scope]
|
||||
|
||||
## Executive Summary
|
||||
|
||||
**Reviewed**: [What was reviewed]
|
||||
**Depth**: [Quick|Standard|Deep]
|
||||
**Security Risk**: [Low|Medium|High|Critical]
|
||||
|
||||
### Overall Security Posture
|
||||
**[Secure|Minor Issues|Significant Concerns|Critical Vulnerabilities]**
|
||||
|
||||
[Brief explanation]
|
||||
|
||||
### Immediate Actions Required
|
||||
1. [Critical issue 1]
|
||||
2. [Critical issue 2]
|
||||
|
||||
---
|
||||
|
||||
## Critical Security Issues 🚨
|
||||
|
||||
### [Issue 1 Title]
|
||||
**File**: `path/to/file.ts:42`
|
||||
**Vulnerability Type**: [SQL Injection|XSS|Authentication Bypass|etc.]
|
||||
**OWASP Category**: [A01-A10]
|
||||
**Risk Level**: Critical
|
||||
**Attack Vector**: [How this could be exploited]
|
||||
**Impact**: [Data breach, unauthorized access, etc.]
|
||||
**Remediation**: [Specific fix]
|
||||
|
||||
```typescript
|
||||
// Current code (vulnerable)
|
||||
[vulnerable code]
|
||||
|
||||
// Secure implementation
|
||||
[secure code]
|
||||
```
|
||||
|
||||
**Testing**: [How to verify the fix]
|
||||
|
||||
[Repeat for each critical issue]
|
||||
|
||||
---
|
||||
|
||||
## High Risk Issues ⚠️
|
||||
|
||||
[Similar format for high risk issues]
|
||||
|
||||
---
|
||||
|
||||
## Medium Risk Issues ℹ️
|
||||
|
||||
[Similar format for medium risk issues]
|
||||
|
||||
---
|
||||
|
||||
## Low Risk Issues 💡
|
||||
|
||||
[Similar format for low risk issues]
|
||||
|
||||
---
|
||||
|
||||
## OWASP Top 10 Assessment
|
||||
|
||||
| Category | Status | Findings |
|
||||
|----------|--------|----------|
|
||||
| A01: Broken Access Control | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
| A02: Cryptographic Failures | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
| A03: Injection | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
| A04: Insecure Design | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
| A05: Security Misconfiguration | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
| A06: Vulnerable Components | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
| A07: Authentication Failures | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
| A08: Software Integrity Failures | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
| A09: Logging Failures | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
| A10: SSRF | ✅ Pass / ⚠️ Issues / ❌ Fail | [Details] |
|
||||
|
||||
---
|
||||
|
||||
## Security Strengths ✅
|
||||
|
||||
- ✅ [Security practice done well]
|
||||
- ✅ [Security practice done well]
|
||||
|
||||
---
|
||||
|
||||
## Dependency Vulnerabilities
|
||||
|
||||
**Scan Results**:
|
||||
```
|
||||
[Output from npm audit, pip-audit, etc.]
|
||||
```
|
||||
|
||||
**Critical Vulnerabilities**: [Count]
|
||||
**High Vulnerabilities**: [Count]
|
||||
**Recommendations**: [Update strategy]
|
||||
|
||||
---
|
||||
|
||||
## Security Headers Analysis
|
||||
|
||||
| Header | Configured | Recommendation |
|
||||
|--------|-----------|----------------|
|
||||
| Content-Security-Policy | ✅ / ❌ | [Details] |
|
||||
| Strict-Transport-Security | ✅ / ❌ | [Details] |
|
||||
| X-Content-Type-Options | ✅ / ❌ | [Details] |
|
||||
| X-Frame-Options | ✅ / ❌ | [Details] |
|
||||
|
||||
---
|
||||
|
||||
## Remediation Roadmap
|
||||
|
||||
### Immediate (This Week)
|
||||
- [ ] [Critical fix 1]
|
||||
- [ ] [Critical fix 2]
|
||||
|
||||
### Short-term (This Month)
|
||||
- [ ] [High priority fix 1]
|
||||
- [ ] [High priority fix 2]
|
||||
|
||||
### Long-term (This Quarter)
|
||||
- [ ] [Strategic improvement 1]
|
||||
- [ ] [Security hardening 2]
|
||||
|
||||
---
|
||||
|
||||
## Security Testing Recommendations
|
||||
|
||||
1. [Penetration testing for X]
|
||||
2. [Security automation for Y]
|
||||
3. [Ongoing monitoring for Z]
|
||||
|
||||
---
|
||||
|
||||
## Compliance Considerations
|
||||
|
||||
- **GDPR**: [Relevant considerations]
|
||||
- **PCI DSS**: [If handling payment data]
|
||||
- **HIPAA**: [If handling health data]
|
||||
- **SOC 2**: [If enterprise software]
|
||||
|
||||
---
|
||||
|
||||
## Review Metadata
|
||||
|
||||
- **Reviewer**: 10x Fullstack Engineer (Security Focus)
|
||||
- **Review Date**: [Date]
|
||||
- **Security Issues**: Critical: X, High: X, Medium: X, Low: X
|
||||
```
|
||||
|
||||
## Agent Invocation
|
||||
|
||||
This operation MUST leverage the **10x-fullstack-engineer** agent with security expertise.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Assume Breach Mindset**: Think like an attacker
|
||||
2. **Defense in Depth**: Multiple layers of security
|
||||
3. **Principle of Least Privilege**: Minimal permissions necessary
|
||||
4. **Fail Securely**: Default to denial of access
|
||||
5. **Don't Trust User Input**: Validate everything
|
||||
6. **Keep Security Simple**: Complexity is the enemy of security
|
||||
178
commands/review/skill.md
Normal file
178
commands/review/skill.md
Normal file
@@ -0,0 +1,178 @@
|
||||
---
|
||||
description: Comprehensive code review with specialized focus areas (security, performance, quality, accessibility, PRs)
|
||||
---
|
||||
|
||||
# Code Review Skill Router
|
||||
|
||||
Orchestrates comprehensive code reviews with specialized operations for different focus areas and review types.
|
||||
|
||||
## Available Operations
|
||||
|
||||
- **full** - Comprehensive review covering all categories (security, performance, quality, architecture, a11y)
|
||||
- **security** - Security-focused review (auth, validation, injection, dependencies, OWASP Top 10)
|
||||
- **performance** - Performance-focused review (database, backend, frontend, network optimization)
|
||||
- **quality** - Code quality review (organization, patterns, testing, documentation)
|
||||
- **pr** - Pull request review with git integration and change analysis
|
||||
- **accessibility** - Accessibility review (a11y, ARIA, keyboard nav, screen readers)
|
||||
|
||||
## Argument Format
|
||||
|
||||
Expected: `operation [scope:"..."] [depth:"quick|standard|deep"] [focus:"..."]`
|
||||
|
||||
Examples:
|
||||
```
|
||||
/review full scope:"src/auth module" depth:"deep"
|
||||
/review security scope:"payment processing" depth:"deep"
|
||||
/review performance scope:"dashboard component" depth:"standard"
|
||||
/review quality scope:"src/utils" depth:"quick"
|
||||
/review pr scope:"PR #123" depth:"standard"
|
||||
/review accessibility scope:"checkout flow" depth:"deep"
|
||||
```
|
||||
|
||||
## Routing Logic
|
||||
|
||||
Parse $ARGUMENTS to extract:
|
||||
1. **Operation** (first word): Determines review type
|
||||
2. **Scope**: What to review (files, modules, features, PR)
|
||||
3. **Depth**: Review thoroughness (quick/standard/deep)
|
||||
4. **Focus**: Additional focus areas (optional)
|
||||
|
||||
**Router Implementation:**
|
||||
|
||||
```
|
||||
Request: $ARGUMENTS
|
||||
Base directory: /home/danie/projects/plugins/architect/open-plugins/plugins/10x-fullstack-engineer/commands/review
|
||||
```
|
||||
|
||||
### Routing Table
|
||||
|
||||
| Operation | Instruction File | Purpose |
|
||||
|-----------|-----------------|---------|
|
||||
| full | review/full.md | Comprehensive review (all categories) |
|
||||
| security | review/security.md | Security-focused review |
|
||||
| performance | review/performance.md | Performance-focused review |
|
||||
| quality | review/quality.md | Code quality review |
|
||||
| pr | review/pr.md | Pull request review |
|
||||
| accessibility | review/accessibility.md | Accessibility review |
|
||||
|
||||
### Execution Flow
|
||||
|
||||
1. **Parse Arguments**:
|
||||
- Extract operation name (first word)
|
||||
- Extract remaining parameters (scope, depth, focus)
|
||||
- Validate operation is recognized
|
||||
|
||||
2. **Route to Operation**:
|
||||
- Read corresponding .md file from review/ directory
|
||||
- Pass remaining arguments to operation
|
||||
- Execute review workflow
|
||||
|
||||
3. **Error Handling**:
|
||||
- Unknown operation → List available operations with descriptions
|
||||
- Missing scope → Request scope specification
|
||||
- Invalid depth → Default to "standard"
|
||||
|
||||
### Example Routing
|
||||
|
||||
**Input**: `/review security scope:"auth module" depth:"deep"`
|
||||
- Operation: `security`
|
||||
- Route to: `review/security.md`
|
||||
- Parameters: `scope:"auth module" depth:"deep"`
|
||||
|
||||
**Input**: `/review pr scope:"PR #456"`
|
||||
- Operation: `pr`
|
||||
- Route to: `review/pr.md`
|
||||
- Parameters: `scope:"PR #456" depth:"standard"` (default depth)
|
||||
|
||||
**Input**: `/review unknown`
|
||||
- Error: Unknown operation
|
||||
- Response: List available operations with usage examples
|
||||
|
||||
## Review Depth Levels
|
||||
|
||||
All operations support three depth levels:
|
||||
|
||||
**Quick** (5-10 minutes):
|
||||
- High-level code scan
|
||||
- Critical issues only
|
||||
- Obvious bugs and anti-patterns
|
||||
- Major concerns in focus area
|
||||
|
||||
**Standard** (20-30 minutes):
|
||||
- Thorough review
|
||||
- All major categories covered
|
||||
- Testing and documentation check
|
||||
- Moderate depth per area
|
||||
|
||||
**Deep** (45-60+ minutes):
|
||||
- Comprehensive analysis
|
||||
- All categories in detail
|
||||
- Architecture and design patterns
|
||||
- Scalability considerations
|
||||
- Complete audit in focus area
|
||||
|
||||
## Common Parameters
|
||||
|
||||
All review operations accept:
|
||||
|
||||
- **scope**: What to review (required)
|
||||
- Examples: "PR #123", "src/auth", "payment feature", "recent changes"
|
||||
|
||||
- **depth**: Review thoroughness (optional, default: "standard")
|
||||
- Values: "quick", "standard", "deep"
|
||||
|
||||
- **focus**: Additional areas to emphasize (optional)
|
||||
- Examples: "security", "performance", "testing", "documentation"
|
||||
|
||||
## Usage Examples
|
||||
|
||||
**Comprehensive Review**:
|
||||
```bash
|
||||
/review full scope:"authentication feature" depth:"deep"
|
||||
```
|
||||
|
||||
**Security Audit**:
|
||||
```bash
|
||||
/review security scope:"payment processing module" depth:"deep"
|
||||
```
|
||||
|
||||
**Performance Analysis**:
|
||||
```bash
|
||||
/review performance scope:"dashboard rendering" depth:"standard"
|
||||
```
|
||||
|
||||
**Code Quality Check**:
|
||||
```bash
|
||||
/review quality scope:"src/utils" depth:"quick"
|
||||
```
|
||||
|
||||
**Pull Request Review**:
|
||||
```bash
|
||||
/review pr scope:"PR #789 - Add user permissions" depth:"standard"
|
||||
```
|
||||
|
||||
**Accessibility Review**:
|
||||
```bash
|
||||
/review accessibility scope:"checkout flow" depth:"deep"
|
||||
```
|
||||
|
||||
## Agent Integration
|
||||
|
||||
All review operations leverage the **10x-fullstack-engineer** agent for:
|
||||
- Cross-stack expertise
|
||||
- Pattern recognition
|
||||
- Best practices knowledge
|
||||
- Constructive feedback
|
||||
- Architectural understanding
|
||||
|
||||
## Now Execute
|
||||
|
||||
**Received Request**: `$ARGUMENTS`
|
||||
|
||||
1. Parse the operation from the first word
|
||||
2. Read the corresponding instruction file from `review/` directory
|
||||
3. Pass remaining arguments to the operation
|
||||
4. Execute the review workflow
|
||||
5. Provide structured feedback
|
||||
|
||||
If operation is unrecognized, list available operations with examples.
|
||||
Reference in New Issue
Block a user