Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:29:07 +08:00
commit 8b4a1b1a99
75 changed files with 18583 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
---
name: grey-haven-code-quality-analysis
description: "Multi-mode code quality analysis covering security reviews (OWASP Top 10), clarity refactoring (readability rules), and synthesis analysis (cross-file issues). Use when reviewing code for security vulnerabilities, improving code readability, conducting quality audits, pre-deployment checks, or when user mentions 'code quality', 'code review', 'security review', 'refactoring', 'code smell', 'OWASP', 'code clarity', or 'quality audit'."
---
# Code Quality Analysis Skill
Multi-mode code quality specialist with security review, clarity refactoring, and synthesis analysis.
## Description
Comprehensive code quality analysis including security vulnerability detection, readability improvements, and cross-file issue synthesis.
## What's Included
- **Examples**: Security reviews, refactoring patterns, quality improvements
- **Reference**: OWASP Top 10, code smells, refactoring catalog
- **Templates**: Code review templates, security audit structures
- **Checklists**: Quality verification, security compliance
## Modes
1. **Security Review** - Find vulnerabilities (OWASP Top 10)
2. **Clarity Refactoring** - Improve readability (10 rules)
3. **Synthesis Analysis** - Cross-file issues
## Use This Skill When
- Reviewing code for security issues
- Improving code readability
- Comprehensive quality audits
- Pre-deployment checks
## Related Agents
- `code-quality-analyzer` - Automated quality analysis
- `security-analyzer` - Deep security audits
---
**Skill Version**: 1.0

View File

@@ -0,0 +1,200 @@
# Code Quality Review Checklist
Systematic code review checklist covering security, clarity, performance, and maintainability.
## Security Review
### Input Validation
- [ ] All user input validated (Zod for TS, Pydantic for Python)
- [ ] Email addresses validated with proper format
- [ ] Numeric inputs have min/max bounds
- [ ] String inputs have length limits
- [ ] Arrays have maximum size constraints
### SQL Injection Prevention
- [ ] No raw SQL string concatenation
- [ ] ORM used for all queries (Drizzle, SQLModel)
- [ ] Parameterized queries only
- [ ] No dynamic table/column names from user input
### XSS Prevention
- [ ] React JSX used for rendering (auto-escapes)
- [ ] No dangerouslySetInnerHTML without DOMPurify
- [ ] API responses don't include executable code
- [ ] User content sanitized before display
### Authentication & Authorization
- [ ] Authentication required on protected routes
- [ ] Authorization checks present
- [ ] Multi-tenant: tenant_id checked in all queries
- [ ] No privilege escalation possible
### Secret Management
- [ ] No secrets hardcoded
- [ ] Doppler used for all secrets
- [ ] No .env files committed
- [ ] Secrets not logged
## Clarity & Readability
### Naming
- [ ] Variables have descriptive names
- [ ] Functions named with verbs (getUserById, calculateTotal)
- [ ] Boolean variables prefixed (isValid, hasAccess)
- [ ] Constants in UPPER_SNAKE_CASE
- [ ] Database fields in snake_case
### Function Complexity
- [ ] Functions are < 50 lines
- [ ] Functions do one thing (Single Responsibility)
- [ ] Cyclomatic complexity < 10
- [ ] No deeply nested conditionals (max 3 levels)
- [ ] Early returns used to reduce nesting
### Comments & Documentation
- [ ] Complex logic has explanatory comments
- [ ] JSDoc/docstrings on public functions
- [ ] No commented-out code
- [ ] TODOs tracked in issue system
- [ ] README updated if public API changed
### Code Structure
- [ ] Similar code grouped together
- [ ] Related functions in same file/module
- [ ] Proper separation of concerns
- [ ] No circular dependencies
- [ ] File organization follows conventions
## Performance
### Database Queries
- [ ] No N+1 queries
- [ ] Appropriate indexes exist
- [ ] Queries limited (pagination implemented)
- [ ] Eager loading used where appropriate
- [ ] Database connection pooling configured
### Algorithms
- [ ] Appropriate data structures chosen
- [ ] Time complexity acceptable (avoid O(n²) if possible)
- [ ] No unnecessary iterations
- [ ] Efficient string operations (avoid concatenation in loops)
### Memory
- [ ] No memory leaks (event listeners removed)
- [ ] Large objects not held in memory unnecessarily
- [ ] Streams used for large files
- [ ] Caches have eviction policies
### Network
- [ ] API calls batched where possible
- [ ] Response caching implemented
- [ ] Compression enabled
- [ ] Appropriate HTTP methods used
## Maintainability
### Error Handling
- [ ] Errors caught and handled appropriately
- [ ] Error messages are helpful
- [ ] Errors logged with context
- [ ] No swallowed exceptions
- [ ] Retry logic for transient failures
### Testing
- [ ] Unit tests exist and pass
- [ ] Edge cases tested
- [ ] Error paths tested
- [ ] Integration tests for critical flows
- [ ] Test coverage > 80%
### Dependencies
- [ ] No unnecessary dependencies added
- [ ] Dependencies up to date
- [ ] No security vulnerabilities (npm audit, pip-audit)
- [ ] License compatibility checked
### Code Duplication
- [ ] No copy-pasted code
- [ ] Common logic extracted to utilities
- [ ] Shared types defined once
- [ ] No magic numbers (use constants)
## TypeScript/JavaScript Specific
### Type Safety
- [ ] No `any` types (unless Grey Haven pragmatic style)
- [ ] Proper type annotations on functions
- [ ] Interfaces/types defined for complex objects
- [ ] Discriminated unions used for variants
- [ ] Type guards implemented where needed
### React Best Practices
- [ ] Components are focused (< 250 lines)
- [ ] Props properly typed
- [ ] useEffect cleanup implemented
- [ ] Keys provided for lists
- [ ] Memoization used appropriately (useMemo, useCallback)
## Python Specific
### Type Hints
- [ ] Type hints on all functions
- [ ] Return types specified
- [ ] Complex types use typing module
- [ ] mypy passes with no errors
### Python Conventions
- [ ] PEP 8 style followed
- [ ] Docstrings on classes and functions
- [ ] Context managers used for resources
- [ ] List comprehensions used appropriately
## Deployment Readiness
### Configuration
- [ ] Environment variables documented
- [ ] Sensible defaults provided
- [ ] Different configs for dev/staging/prod
- [ ] Feature flags for risky changes
### Monitoring
- [ ] Critical operations logged
- [ ] Performance metrics tracked
- [ ] Error tracking configured
- [ ] Alerts defined for failures
### Documentation
- [ ] README updated
- [ ] API documentation current
- [ ] Migration guide if breaking changes
- [ ] Deployment notes added
## Scoring
- **90+ items checked**: Excellent - Ship it! ✅
- **75-89 items**: Good - Minor improvements needed ⚠️
- **60-74 items**: Fair - Significant work required 🔴
- **<60 items**: Poor - Not ready for review ❌
## Priority Issues
Address these first if unchecked:
1. **Security items** (SQL injection, XSS, auth)
2. **Multi-tenant isolation** (tenant_id checks)
3. **Secret management** (no hardcoded secrets)
4. **Error handling** (no swallowed exceptions)
5. **Testing** (critical paths covered)
## Related Resources
- [Security Practices](../../security-practices/SKILL.md)
- [OWASP Top 10](../../security-analysis/reference/owasp-top-10.md)
- [Code Style Guide](../../code-style/SKILL.md)
- [Performance Optimization](../../performance-optimization/SKILL.md)
---
**Total Items**: 100+ quality checks
**Critical Items**: Security, Multi-tenant, Error Handling, Testing
**Last Updated**: 2025-11-09

View File

@@ -0,0 +1,46 @@
# Code Quality Analyzer Examples
Real-world code quality analysis scenarios demonstrating security review, clarity refactoring, and synthesis analysis.
## Files in This Directory
### [security-review-example.md](security-review-example.md)
Complete security review of an authentication service, finding and fixing 12 vulnerabilities including SQL injection, XSS, weak authentication, and insecure cryptography.
**Scenario**: FastAPI authentication service with multiple security issues
**Mode**: Security Review
**Result**: 12 vulnerabilities found (3 critical, 5 high, 4 medium), security score improved from 42/100 to 95/100
### [clarity-refactoring-example.md](clarity-refactoring-example.md)
Systematic code clarity improvement using 10 refactoring rules to transform complex, nested code into readable, maintainable functions.
**Scenario**: E-commerce order processing service with high complexity
**Mode**: Clarity Refactoring
**Result**: Cyclomatic complexity reduced from 47 to 8, readability score improved from 35/100 to 92/100
### [synthesis-analysis-example.md](synthesis-analysis-example.md)
Cross-file analysis identifying architectural issues, inconsistent patterns, and hidden dependencies across a multi-module codebase.
**Scenario**: User management system with 5 modules showing inconsistent patterns
**Mode**: Synthesis Analysis
**Result**: 18 cross-file issues found, 6 architectural improvements, consistency score improved from 58/100 to 89/100
### [complete-quality-audit.md](complete-quality-audit.md)
Full codebase quality audit combining all three modes to transform a legacy codebase into a maintainable, secure system.
**Scenario**: Legacy e-commerce platform (12 files, 3,500 lines)
**Comprehensive Review**: Security + Clarity + Synthesis
**Result**: 47 total issues found and fixed, overall quality score 38/100 → 91/100, prevented 2 production incidents
## Usage
Each example includes:
- **Before**: Original problematic code with clear issues
- **Analysis**: Step-by-step identification of problems with explanations
- **After**: Improved code with specific changes highlighted
- **Metrics**: Quantitative before/after comparison
- **Lessons**: Key takeaways and patterns to recognize
---
Return to [agent documentation](../code-quality-analyzer.md)

View File

@@ -0,0 +1,75 @@
# Code Quality Analyzer Reference
Comprehensive reference guides for code quality analysis, security review, clarity refactoring, and architectural patterns.
## Files in This Directory
### [security-checklist.md](security-checklist.md)
Complete security checklist covering OWASP Top 10, input validation, authentication, cryptography, and data protection with actionable checks.
**When to use**: Security reviews, pre-deployment audits, vulnerability assessments
**Coverage**: OWASP Top 10, CWE database, common vulnerabilities
### [clarity-refactoring-rules.md](clarity-refactoring-rules.md)
10 proven refactoring rules for improving code clarity, reducing complexity, and eliminating technical debt without changing behavior.
**When to use**: Code reviews, refactoring sessions, complexity reduction
**Key topics**: Guard clauses, extract functions, explaining variables, naming conventions
### [code-quality-metrics.md](code-quality-metrics.md)
Understanding and interpreting code quality metrics including cyclomatic complexity, maintainability index, code duplication, and test coverage.
**When to use**: Quality assessments, setting standards, tracking improvements
**Metrics**: Complexity, duplication, coverage, maintainability scores
### [architecture-patterns.md](architecture-patterns.md)
Best practices for clean architecture, layering, dependency management, and preventing architectural erosion in multi-module codebases.
**When to use**: Synthesis analysis, architectural reviews, system design
**Patterns**: Layered architecture, dependency injection, circular dependency prevention
### [analysis-workflows.md](analysis-workflows.md)
Step-by-step workflows for conducting security reviews, clarity refactorings, and synthesis analysis with practical timelines and checklists.
**When to use**: Planning code quality initiatives, conducting audits
**Workflows**: Security review process, refactoring workflow, synthesis analysis
## Quick Reference
### Security Review Process
1. Run automated scanners (Bandit, Semgrep)
2. Manual code review for OWASP Top 10
3. Generate security scorecard
4. Prioritize by severity (Critical → High → Medium)
5. Fix and verify
6. Re-scan to confirm
### Clarity Refactoring Process
1. Identify complexity hotspots (complexity > 10)
2. Apply guard clauses to flatten nesting
3. Extract functions for single responsibility
4. Add explaining variables for complex logic
5. Replace magic numbers with constants
6. Measure before/after complexity
### Synthesis Analysis Process
1. Map module dependencies
2. Identify circular dependencies
3. Detect architectural violations
4. Find code duplication across files
5. Check consistency (naming, errors, patterns)
6. Enforce architectural standards
## Navigation by Use Case
**I need to**... | **Use this guide**...
---|---
Fix security vulnerabilities | [security-checklist.md](security-checklist.md)
Reduce code complexity | [clarity-refactoring-rules.md](clarity-refactoring-rules.md)
Understand quality metrics | [code-quality-metrics.md](code-quality-metrics.md)
Enforce clean architecture | [architecture-patterns.md](architecture-patterns.md)
Plan a code quality audit | [analysis-workflows.md](analysis-workflows.md)
---
Return to [agent documentation](../code-quality-analyzer.md)

View File

@@ -0,0 +1,91 @@
# Code Quality Analyzer Templates
Copy-paste report templates for security reviews, clarity refactorings, and synthesis analysis.
## Files in This Directory
### [security-report-template.md](security-report-template.md)
Comprehensive security review report template with OWASP Top 10 coverage, vulnerability classification, security scorecard, and remediation tracking.
**When to use**: After security review, for stakeholder reporting
**Format**: Markdown with tables and checklists
### [clarity-report-template.md](clarity-report-template.md)
Code clarity refactoring report template with complexity metrics, before/after comparisons, and maintainability improvements.
**When to use**: After clarity refactoring, for technical documentation
**Format**: Markdown with code examples and metrics
### [synthesis-report-template.md](synthesis-report-template.md)
Cross-file analysis report template with architectural violations, dependency issues, and consistency metrics.
**When to use**: After synthesis analysis, for architectural reviews
**Format**: Markdown with dependency graphs and issue lists
### [complete-audit-report-template.md](complete-audit-report-template.md)
Comprehensive quality audit report combining security, clarity, and synthesis analysis with executive summary and ROI metrics.
**When to use**: For complete codebase audits, executive reporting
**Format**: Markdown with executive summary and detailed findings
## Usage Instructions
1. **Copy template** to your project documentation
2. **Fill in placeholders**:
- `[Project Name]` → Your project name
- `[Date]` → Current date
- `[Version]` → Version number
- `[Analyst Name]` → Your name
3. **Complete sections** with your findings
4. **Add evidence** (code snippets, metrics, screenshots)
5. **Export** to PDF for stakeholder distribution
## Template Conventions
**Placeholders**:
- `[Project Name]` - Replace with project name
- `[Date]` - Replace with current date
- `[Analyst Name]` - Replace with reviewer name
- `[Version]` - Replace with version/commit
- `...` - Add more items as needed
**Status Indicators**:
- 🔴 Critical - Fix immediately
- 🟠 High - Fix before deployment
- 🟡 Medium - Fix soon
- 🟢 Low - Fix when convenient
- ✅ Completed
- ⏳ In Progress
- ❌ Blocked
**Severity Levels**:
- P0 (Critical): Production-blocking issues
- P1 (High): Must fix before deployment
- P2 (Medium): Should fix in next sprint
- P3 (Low): Nice to have
## Customization Tips
### For Different Stakeholders
**Executive Summary** (management):
- Focus on business impact and ROI
- Use visual indicators (✅❌)
- Include cost of inaction
- Highlight risks
**Technical Details** (developers):
- Include code examples
- Provide refactoring steps
- Link to relevant documentation
- Show metrics
**Compliance** (auditors):
- Include standards compliance
- Document all checks performed
- Provide evidence trail
- Reference frameworks (OWASP, CWE)
---
Return to [agent documentation](../code-quality-analyzer.md)