mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-02-13 02:41:50 +08:00
Add comprehensive code review specifications and templates
- Introduced best practices requirements specification covering code quality, performance, maintainability, error handling, and documentation standards. - Established quality standards with overall quality metrics and mandatory checks for security, code quality, performance, and maintainability. - Created security requirements specification aligned with OWASP Top 10 and CWE Top 25, detailing checks and patterns for common vulnerabilities. - Developed templates for documenting best practice findings, security findings, and generating reports, including structured markdown and JSON formats. - Updated dependencies in the project, ensuring compatibility and stability. - Added test files and README documentation for vector indexing tests.
This commit is contained in:
246
.claude/skills/code-reviewer/phases/01-code-discovery.md
Normal file
246
.claude/skills/code-reviewer/phases/01-code-discovery.md
Normal file
@@ -0,0 +1,246 @@
|
||||
# Phase 1: Code Discovery & Scoping
|
||||
|
||||
## Objective
|
||||
|
||||
Discover and categorize all code files within the specified scope, preparing them for security analysis and best practices review.
|
||||
|
||||
## Input
|
||||
|
||||
- **User Arguments**:
|
||||
- `--scope`: Directory or file patterns (default: entire project)
|
||||
- `--languages`: Specific languages to review (e.g., typescript, python, java)
|
||||
- `--exclude`: Patterns to exclude (e.g., test files, node_modules)
|
||||
|
||||
- **Configuration**: `.code-reviewer.json` (if exists)
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Load Configuration
|
||||
|
||||
```javascript
|
||||
// Check for project-level configuration
|
||||
const configPath = path.join(projectRoot, '.code-reviewer.json');
|
||||
const config = fileExists(configPath)
|
||||
? JSON.parse(readFile(configPath))
|
||||
: getDefaultConfig();
|
||||
|
||||
// Merge user arguments with config
|
||||
const scope = args.scope || config.scope.include;
|
||||
const exclude = args.exclude || config.scope.exclude;
|
||||
const languages = args.languages || config.languages || 'auto';
|
||||
```
|
||||
|
||||
### Step 2: Discover Files
|
||||
|
||||
Use MCP tools for efficient file discovery:
|
||||
|
||||
```javascript
|
||||
// Use smart_search for file discovery
|
||||
const files = await mcp__ccw_tools__smart_search({
|
||||
action: "find_files",
|
||||
pattern: scope,
|
||||
includeHidden: false
|
||||
});
|
||||
|
||||
// Apply exclusion patterns
|
||||
const filteredFiles = files.filter(file => {
|
||||
return !exclude.some(pattern => minimatch(file, pattern));
|
||||
});
|
||||
```
|
||||
|
||||
### Step 3: Categorize Files
|
||||
|
||||
Categorize files by:
|
||||
- **Language/Framework**: TypeScript, Python, Java, Go, etc.
|
||||
- **File Type**: Source, config, test, build
|
||||
- **Priority**: Critical (auth, payment), High (API), Medium (utils), Low (docs)
|
||||
|
||||
```javascript
|
||||
const inventory = {
|
||||
critical: {
|
||||
auth: ['src/auth/login.ts', 'src/auth/jwt.ts'],
|
||||
payment: ['src/payment/stripe.ts'],
|
||||
},
|
||||
high: {
|
||||
api: ['src/api/users.ts', 'src/api/orders.ts'],
|
||||
database: ['src/db/queries.ts'],
|
||||
},
|
||||
medium: {
|
||||
utils: ['src/utils/validator.ts'],
|
||||
services: ['src/services/*.ts'],
|
||||
},
|
||||
low: {
|
||||
types: ['src/types/*.ts'],
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Step 4: Extract Metadata
|
||||
|
||||
For each file, extract:
|
||||
- **Lines of Code (LOC)**
|
||||
- **Complexity Indicators**: Function count, class count
|
||||
- **Dependencies**: Import statements
|
||||
- **Framework Detection**: Express, React, Django, etc.
|
||||
|
||||
```javascript
|
||||
const metadata = files.map(file => ({
|
||||
path: file,
|
||||
language: detectLanguage(file),
|
||||
loc: countLines(file),
|
||||
complexity: estimateComplexity(file),
|
||||
framework: detectFramework(file),
|
||||
priority: categorizePriority(file)
|
||||
}));
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
### File Inventory
|
||||
|
||||
Save to `.code-review/inventory.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"scan_date": "2024-01-15T10:30:00Z",
|
||||
"total_files": 247,
|
||||
"by_language": {
|
||||
"typescript": 185,
|
||||
"python": 42,
|
||||
"javascript": 15,
|
||||
"go": 5
|
||||
},
|
||||
"by_priority": {
|
||||
"critical": 12,
|
||||
"high": 45,
|
||||
"medium": 120,
|
||||
"low": 70
|
||||
},
|
||||
"files": [
|
||||
{
|
||||
"path": "src/auth/login.ts",
|
||||
"language": "typescript",
|
||||
"loc": 245,
|
||||
"functions": 8,
|
||||
"classes": 2,
|
||||
"priority": "critical",
|
||||
"framework": "express",
|
||||
"dependencies": ["bcrypt", "jsonwebtoken", "express"]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Summary Report
|
||||
|
||||
```markdown
|
||||
## Code Discovery Summary
|
||||
|
||||
**Scope**: src/**/*
|
||||
**Total Files**: 247
|
||||
**Languages**: TypeScript (75%), Python (17%), JavaScript (6%), Go (2%)
|
||||
|
||||
### Priority Distribution
|
||||
- Critical: 12 files (authentication, payment processing)
|
||||
- High: 45 files (API endpoints, database queries)
|
||||
- Medium: 120 files (utilities, services)
|
||||
- Low: 70 files (types, configs)
|
||||
|
||||
### Key Areas Identified
|
||||
1. **Authentication Module** (src/auth/) - 12 files, 2,400 LOC
|
||||
2. **Payment Processing** (src/payment/) - 5 files, 1,200 LOC
|
||||
3. **API Layer** (src/api/) - 35 files, 5,600 LOC
|
||||
4. **Database Layer** (src/db/) - 8 files, 1,800 LOC
|
||||
|
||||
**Next Phase**: Security Analysis on Critical + High priority files
|
||||
```
|
||||
|
||||
## State Management
|
||||
|
||||
Save phase state for potential resume:
|
||||
|
||||
```json
|
||||
{
|
||||
"phase": "01-code-discovery",
|
||||
"status": "completed",
|
||||
"timestamp": "2024-01-15T10:35:00Z",
|
||||
"output": {
|
||||
"inventory_path": ".code-review/inventory.json",
|
||||
"total_files": 247,
|
||||
"critical_files": 12,
|
||||
"high_files": 45
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Agent Instructions
|
||||
|
||||
```markdown
|
||||
You are in Phase 1 of the Code Review workflow. Your task is to discover and categorize code files.
|
||||
|
||||
**Instructions**:
|
||||
1. Use mcp__ccw_tools__smart_search with action="find_files" to discover files
|
||||
2. Apply exclusion patterns from config or arguments
|
||||
3. Categorize files by language, type, and priority
|
||||
4. Extract basic metadata (LOC, complexity indicators)
|
||||
5. Save inventory to .code-review/inventory.json
|
||||
6. Generate summary report
|
||||
7. Proceed to Phase 2 with critical + high priority files
|
||||
|
||||
**Tools Available**:
|
||||
- mcp__ccw_tools__smart_search (file discovery)
|
||||
- Read (read configuration and sample files)
|
||||
- Write (save inventory and reports)
|
||||
|
||||
**Output Requirements**:
|
||||
- inventory.json with complete file list and metadata
|
||||
- Summary markdown report
|
||||
- State file for phase tracking
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### No Files Found
|
||||
|
||||
```javascript
|
||||
if (filteredFiles.length === 0) {
|
||||
throw new Error(`No files found matching scope: ${scope}
|
||||
|
||||
Suggestions:
|
||||
- Check if scope pattern is correct
|
||||
- Verify exclude patterns are not too broad
|
||||
- Ensure project has code files in specified scope
|
||||
`);
|
||||
}
|
||||
```
|
||||
|
||||
### Large Codebase
|
||||
|
||||
```javascript
|
||||
if (filteredFiles.length > 1000) {
|
||||
console.warn(`⚠️ Large codebase detected (${filteredFiles.length} files)`);
|
||||
console.log(`Consider using --scope to review in batches`);
|
||||
|
||||
// Offer to focus on critical/high priority only
|
||||
const answer = await askUser("Review critical/high priority files only?");
|
||||
if (answer === 'yes') {
|
||||
filteredFiles = filteredFiles.filter(f =>
|
||||
f.priority === 'critical' || f.priority === 'high'
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Validation
|
||||
|
||||
Before proceeding to Phase 2:
|
||||
|
||||
- ✅ Inventory file created
|
||||
- ✅ At least one file categorized as critical or high priority
|
||||
- ✅ Metadata extracted for all files
|
||||
- ✅ Summary report generated
|
||||
- ✅ State saved for resume capability
|
||||
|
||||
## Next Phase
|
||||
|
||||
**Phase 2: Security Analysis** - Analyze critical and high priority files for security vulnerabilities using OWASP Top 10 and CWE Top 25 checks.
|
||||
442
.claude/skills/code-reviewer/phases/02-security-analysis.md
Normal file
442
.claude/skills/code-reviewer/phases/02-security-analysis.md
Normal file
@@ -0,0 +1,442 @@
|
||||
# Phase 2: Security Analysis
|
||||
|
||||
## Objective
|
||||
|
||||
Analyze code files for security vulnerabilities based on OWASP Top 10, CWE Top 25, and language-specific security patterns.
|
||||
|
||||
## Input
|
||||
|
||||
- **File Inventory**: From Phase 1 (`.code-review/inventory.json`)
|
||||
- **Priority Focus**: Critical and High priority files (unless `--scope all`)
|
||||
- **User Arguments**:
|
||||
- `--focus security`: Security-only mode
|
||||
- `--severity critical,high,medium,low`: Minimum severity to report
|
||||
- `--checks`: Specific security checks to run (e.g., sql-injection, xss)
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Load Security Rules
|
||||
|
||||
```javascript
|
||||
// Load security check definitions
|
||||
const securityRules = {
|
||||
owasp_top_10: [
|
||||
'injection',
|
||||
'broken_authentication',
|
||||
'sensitive_data_exposure',
|
||||
'xxe',
|
||||
'broken_access_control',
|
||||
'security_misconfiguration',
|
||||
'xss',
|
||||
'insecure_deserialization',
|
||||
'vulnerable_components',
|
||||
'insufficient_logging'
|
||||
],
|
||||
cwe_top_25: [
|
||||
'cwe-79', // XSS
|
||||
'cwe-89', // SQL Injection
|
||||
'cwe-20', // Improper Input Validation
|
||||
'cwe-78', // OS Command Injection
|
||||
'cwe-190', // Integer Overflow
|
||||
// ... more CWE checks
|
||||
]
|
||||
};
|
||||
|
||||
// Load language-specific rules
|
||||
const languageRules = {
|
||||
typescript: require('./rules/typescript-security.json'),
|
||||
python: require('./rules/python-security.json'),
|
||||
java: require('./rules/java-security.json'),
|
||||
go: require('./rules/go-security.json'),
|
||||
};
|
||||
```
|
||||
|
||||
### Step 2: Analyze Files for Vulnerabilities
|
||||
|
||||
For each file in the inventory, perform security analysis:
|
||||
|
||||
```javascript
|
||||
const findings = [];
|
||||
|
||||
for (const file of inventory.files) {
|
||||
if (file.priority !== 'critical' && file.priority !== 'high') continue;
|
||||
|
||||
// Read file content
|
||||
const content = await Read({ file_path: file.path });
|
||||
|
||||
// Run security checks
|
||||
const fileFindings = await runSecurityChecks(content, file, {
|
||||
rules: securityRules,
|
||||
languageRules: languageRules[file.language],
|
||||
severity: args.severity || 'medium'
|
||||
});
|
||||
|
||||
findings.push(...fileFindings);
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: Security Check Patterns
|
||||
|
||||
#### A. Injection Vulnerabilities
|
||||
|
||||
**SQL Injection**:
|
||||
```javascript
|
||||
// Pattern: String concatenation in SQL queries
|
||||
const sqlInjectionPatterns = [
|
||||
/\$\{.*\}.*SELECT/, // Template literal with SELECT
|
||||
/"SELECT.*\+\s*\w+/, // String concatenation
|
||||
/execute\([`'"].*\$\{.*\}.*[`'"]\)/, // Parameterized query bypass
|
||||
/query\(.*\+.*\)/, // Query concatenation
|
||||
];
|
||||
|
||||
// Check code
|
||||
for (const pattern of sqlInjectionPatterns) {
|
||||
const matches = content.matchAll(new RegExp(pattern, 'g'));
|
||||
for (const match of matches) {
|
||||
findings.push({
|
||||
type: 'sql-injection',
|
||||
severity: 'critical',
|
||||
line: getLineNumber(content, match.index),
|
||||
code: match[0],
|
||||
file: file.path,
|
||||
message: 'Potential SQL injection vulnerability',
|
||||
recommendation: 'Use parameterized queries or ORM methods',
|
||||
cwe: 'CWE-89',
|
||||
owasp: 'A03:2021 - Injection'
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Command Injection**:
|
||||
```javascript
|
||||
// Pattern: Unsanitized input in exec/spawn
|
||||
const commandInjectionPatterns = [
|
||||
/exec\(.*\$\{.*\}/, // exec with template literal
|
||||
/spawn\(.*,\s*\[.*\$\{.*\}.*\]\)/, // spawn with unsanitized args
|
||||
/execSync\(.*\+.*\)/, // execSync with concatenation
|
||||
];
|
||||
```
|
||||
|
||||
**XSS (Cross-Site Scripting)**:
|
||||
```javascript
|
||||
// Pattern: Unsanitized user input in DOM/HTML
|
||||
const xssPatterns = [
|
||||
/innerHTML\s*=.*\$\{.*\}/, // innerHTML with template literal
|
||||
/dangerouslySetInnerHTML/, // React dangerous prop
|
||||
/document\.write\(.*\)/, // document.write
|
||||
/<\w+.*\$\{.*\}.*>/, // JSX with unsanitized data
|
||||
];
|
||||
```
|
||||
|
||||
#### B. Authentication & Authorization
|
||||
|
||||
```javascript
|
||||
// Pattern: Weak authentication
|
||||
const authPatterns = [
|
||||
/password\s*===?\s*['"]/, // Hardcoded password comparison
|
||||
/jwt\.sign\(.*,\s*['"][^'"]{1,16}['"]\)/, // Weak JWT secret
|
||||
/bcrypt\.hash\(.*,\s*[1-9]\s*\)/, // Low bcrypt rounds
|
||||
/md5\(.*password.*\)/, // MD5 for passwords
|
||||
/if\s*\(\s*user\s*\)\s*\{/, // Missing auth check
|
||||
];
|
||||
|
||||
// Check for missing authorization
|
||||
const authzPatterns = [
|
||||
/router\.(get|post|put|delete)\(.*\)\s*=>/, // No middleware
|
||||
/app\.use\([^)]*\)\s*;(?!.*auth)/, // Missing auth middleware
|
||||
];
|
||||
```
|
||||
|
||||
#### C. Sensitive Data Exposure
|
||||
|
||||
```javascript
|
||||
// Pattern: Sensitive data in logs/responses
|
||||
const sensitiveDataPatterns = [
|
||||
/(password|secret|token|key)\s*:/i, // Sensitive keys in objects
|
||||
/console\.log\(.*password.*\)/i, // Password in logs
|
||||
/res\.send\(.*user.*password.*\)/, // Password in response
|
||||
/(api_key|apikey)\s*=\s*['"]/i, // Hardcoded API keys
|
||||
];
|
||||
```
|
||||
|
||||
#### D. Security Misconfiguration
|
||||
|
||||
```javascript
|
||||
// Pattern: Insecure configurations
|
||||
const misconfigPatterns = [
|
||||
/cors\(\{.*origin:\s*['"]?\*['"]?.*\}\)/, // CORS wildcard
|
||||
/https?\s*:\s*false/, // HTTPS disabled
|
||||
/helmet\(\)/, // Missing helmet config
|
||||
/strictMode\s*:\s*false/, // Strict mode disabled
|
||||
];
|
||||
```
|
||||
|
||||
### Step 4: Language-Specific Checks
|
||||
|
||||
**TypeScript/JavaScript**:
|
||||
```javascript
|
||||
const jsFindings = [
|
||||
checkPrototypePollution(content),
|
||||
checkEvalUsage(content),
|
||||
checkUnsafeRegex(content),
|
||||
checkWeakCrypto(content),
|
||||
];
|
||||
```
|
||||
|
||||
**Python**:
|
||||
```javascript
|
||||
const pythonFindings = [
|
||||
checkPickleVulnerabilities(content),
|
||||
checkYamlUnsafeLoad(content),
|
||||
checkSqlAlchemy(content),
|
||||
checkFlaskSecurityHeaders(content),
|
||||
];
|
||||
```
|
||||
|
||||
**Java**:
|
||||
```javascript
|
||||
const javaFindings = [
|
||||
checkDeserialization(content),
|
||||
checkXXE(content),
|
||||
checkPathTraversal(content),
|
||||
checkSQLInjection(content),
|
||||
];
|
||||
```
|
||||
|
||||
**Go**:
|
||||
```javascript
|
||||
const goFindings = [
|
||||
checkRaceConditions(content),
|
||||
checkSQLInjection(content),
|
||||
checkPathTraversal(content),
|
||||
checkCryptoWeakness(content),
|
||||
];
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
### Security Findings File
|
||||
|
||||
Save to `.code-review/security-findings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"scan_date": "2024-01-15T11:00:00Z",
|
||||
"total_findings": 24,
|
||||
"by_severity": {
|
||||
"critical": 3,
|
||||
"high": 8,
|
||||
"medium": 10,
|
||||
"low": 3
|
||||
},
|
||||
"by_category": {
|
||||
"injection": 5,
|
||||
"authentication": 3,
|
||||
"data_exposure": 4,
|
||||
"misconfiguration": 6,
|
||||
"xss": 3,
|
||||
"other": 3
|
||||
},
|
||||
"findings": [
|
||||
{
|
||||
"id": "SEC-001",
|
||||
"type": "sql-injection",
|
||||
"severity": "critical",
|
||||
"file": "src/auth/user-service.ts",
|
||||
"line": 145,
|
||||
"column": 12,
|
||||
"code": "const query = `SELECT * FROM users WHERE username = '${username}'`;",
|
||||
"message": "SQL Injection vulnerability: User input directly concatenated in SQL query",
|
||||
"cwe": "CWE-89",
|
||||
"owasp": "A03:2021 - Injection",
|
||||
"recommendation": {
|
||||
"description": "Use parameterized queries to prevent SQL injection",
|
||||
"fix_example": "const query = 'SELECT * FROM users WHERE username = ?';\ndb.execute(query, [username]);"
|
||||
},
|
||||
"references": [
|
||||
"https://owasp.org/www-community/attacks/SQL_Injection",
|
||||
"https://cwe.mitre.org/data/definitions/89.html"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Security Report
|
||||
|
||||
Generate markdown report:
|
||||
|
||||
```markdown
|
||||
# Security Analysis Report
|
||||
|
||||
**Scan Date**: 2024-01-15 11:00:00
|
||||
**Files Analyzed**: 57 (Critical + High priority)
|
||||
**Total Findings**: 24
|
||||
|
||||
## Severity Summary
|
||||
|
||||
| Severity | Count | Percentage |
|
||||
|----------|-------|------------|
|
||||
| Critical | 3 | 12.5% |
|
||||
| High | 8 | 33.3% |
|
||||
| Medium | 10 | 41.7% |
|
||||
| Low | 3 | 12.5% |
|
||||
|
||||
## Critical Findings (Requires Immediate Action)
|
||||
|
||||
### 🔴 [SEC-001] SQL Injection in User Authentication
|
||||
|
||||
**File**: `src/auth/user-service.ts:145`
|
||||
**CWE**: CWE-89 | **OWASP**: A03:2021 - Injection
|
||||
|
||||
**Vulnerable Code**:
|
||||
\`\`\`typescript
|
||||
const query = \`SELECT * FROM users WHERE username = '\${username}'\`;
|
||||
const user = await db.execute(query);
|
||||
\`\`\`
|
||||
|
||||
**Issue**: User input (`username`) is directly concatenated into SQL query, allowing attackers to inject malicious SQL commands.
|
||||
|
||||
**Attack Example**:
|
||||
\`\`\`
|
||||
username: ' OR '1'='1' --
|
||||
Result: SELECT * FROM users WHERE username = '' OR '1'='1' --'
|
||||
Effect: Bypasses authentication, returns all users
|
||||
\`\`\`
|
||||
|
||||
**Recommended Fix**:
|
||||
\`\`\`typescript
|
||||
// Use parameterized queries
|
||||
const query = 'SELECT * FROM users WHERE username = ?';
|
||||
const user = await db.execute(query, [username]);
|
||||
|
||||
// Or use ORM
|
||||
const user = await User.findOne({ where: { username } });
|
||||
\`\`\`
|
||||
|
||||
**References**:
|
||||
- [OWASP SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection)
|
||||
- [CWE-89](https://cwe.mitre.org/data/definitions/89.html)
|
||||
|
||||
---
|
||||
|
||||
### 🔴 [SEC-002] Hardcoded JWT Secret
|
||||
|
||||
**File**: `src/auth/jwt.ts:23`
|
||||
**CWE**: CWE-798 | **OWASP**: A07:2021 - Identification and Authentication Failures
|
||||
|
||||
**Vulnerable Code**:
|
||||
\`\`\`typescript
|
||||
const token = jwt.sign(payload, 'mysecret123', { expiresIn: '1h' });
|
||||
\`\`\`
|
||||
|
||||
**Issue**: JWT secret is hardcoded and weak (only 11 characters).
|
||||
|
||||
**Recommended Fix**:
|
||||
\`\`\`typescript
|
||||
// Use environment variable with strong secret
|
||||
const token = jwt.sign(payload, process.env.JWT_SECRET, {
|
||||
expiresIn: '1h',
|
||||
algorithm: 'HS256'
|
||||
});
|
||||
|
||||
// Generate strong secret (32+ bytes):
|
||||
// node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
||||
\`\`\`
|
||||
|
||||
---
|
||||
|
||||
## High Findings
|
||||
|
||||
### 🟠 [SEC-003] Missing Input Validation
|
||||
|
||||
**File**: `src/api/users.ts:67`
|
||||
**CWE**: CWE-20 | **OWASP**: A03:2021 - Injection
|
||||
|
||||
...
|
||||
|
||||
## Medium Findings
|
||||
|
||||
...
|
||||
|
||||
## Remediation Priority
|
||||
|
||||
1. **Critical (3)**: Fix within 24 hours
|
||||
2. **High (8)**: Fix within 1 week
|
||||
3. **Medium (10)**: Fix within 1 month
|
||||
4. **Low (3)**: Fix in next release
|
||||
|
||||
## Compliance Impact
|
||||
|
||||
- **PCI DSS**: 4 findings affect compliance (SEC-001, SEC-002, SEC-008, SEC-011)
|
||||
- **HIPAA**: 2 findings affect compliance (SEC-005, SEC-009)
|
||||
- **GDPR**: 3 findings affect compliance (SEC-002, SEC-005, SEC-007)
|
||||
```
|
||||
|
||||
## State Management
|
||||
|
||||
```json
|
||||
{
|
||||
"phase": "02-security-analysis",
|
||||
"status": "completed",
|
||||
"timestamp": "2024-01-15T11:15:00Z",
|
||||
"input": {
|
||||
"inventory_path": ".code-review/inventory.json",
|
||||
"files_analyzed": 57
|
||||
},
|
||||
"output": {
|
||||
"findings_path": ".code-review/security-findings.json",
|
||||
"total_findings": 24,
|
||||
"critical_count": 3,
|
||||
"high_count": 8
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Agent Instructions
|
||||
|
||||
```markdown
|
||||
You are in Phase 2 of the Code Review workflow. Your task is to analyze code for security vulnerabilities.
|
||||
|
||||
**Instructions**:
|
||||
1. Load file inventory from Phase 1
|
||||
2. Focus on Critical + High priority files
|
||||
3. Run security checks for:
|
||||
- OWASP Top 10 vulnerabilities
|
||||
- CWE Top 25 weaknesses
|
||||
- Language-specific security patterns
|
||||
4. Use smart_search with mode="ripgrep" for pattern matching
|
||||
5. Use mcp__ace-tool__search_context for semantic security pattern discovery
|
||||
6. Classify findings by severity (Critical/High/Medium/Low)
|
||||
7. Generate security-findings.json and markdown report
|
||||
8. Proceed to Phase 3 (Best Practices Review)
|
||||
|
||||
**Tools Available**:
|
||||
- mcp__ccw_tools__smart_search (pattern search)
|
||||
- mcp__ace-tool__search_context (semantic search)
|
||||
- Read (read file content)
|
||||
- Write (save findings and reports)
|
||||
- Grep (targeted pattern matching)
|
||||
|
||||
**Output Requirements**:
|
||||
- security-findings.json with detailed findings
|
||||
- Security report in markdown format
|
||||
- Each finding must include: file, line, severity, CWE, OWASP, fix recommendation
|
||||
- State file for phase tracking
|
||||
```
|
||||
|
||||
## Validation
|
||||
|
||||
Before proceeding to Phase 3:
|
||||
|
||||
- ✅ All Critical + High priority files analyzed
|
||||
- ✅ Findings categorized by severity
|
||||
- ✅ Each finding has fix recommendation
|
||||
- ✅ CWE and OWASP mappings included
|
||||
- ✅ Security report generated
|
||||
- ✅ State saved
|
||||
|
||||
## Next Phase
|
||||
|
||||
**Phase 3: Best Practices Review** - Analyze code quality, performance, and maintainability issues.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Phase 3: Best Practices Review
|
||||
|
||||
## Objective
|
||||
|
||||
Analyze code for best practices violations including code quality, performance issues, and maintainability concerns.
|
||||
|
||||
## Input
|
||||
|
||||
- **File Inventory**: From Phase 1 (`.code-review/inventory.json`)
|
||||
- **Security Findings**: From Phase 2 (`.code-review/security-findings.json`)
|
||||
- **User Arguments**:
|
||||
- `--focus best-practices`: Best practices only mode
|
||||
- `--check quality,performance,maintainability`: Specific areas to check
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Code Quality Analysis
|
||||
|
||||
Check naming conventions, function complexity, code duplication, and dead code detection.
|
||||
|
||||
### Step 2: Performance Analysis
|
||||
|
||||
Detect N+1 queries, inefficient algorithms, and memory leaks.
|
||||
|
||||
### Step 3: Maintainability Analysis
|
||||
|
||||
Check documentation coverage, test coverage, and dependency management.
|
||||
|
||||
## Output
|
||||
|
||||
- best-practices-findings.json
|
||||
- Markdown report with recommendations
|
||||
|
||||
## Next Phase
|
||||
|
||||
**Phase 4: Report Generation**
|
||||
278
.claude/skills/code-reviewer/phases/04-report-generation.md
Normal file
278
.claude/skills/code-reviewer/phases/04-report-generation.md
Normal file
@@ -0,0 +1,278 @@
|
||||
# Phase 4: Report Generation
|
||||
|
||||
## Objective
|
||||
|
||||
Consolidate security and best practices findings into a comprehensive, actionable code review report.
|
||||
|
||||
## Input
|
||||
|
||||
- **Security Findings**: `.code-review/security-findings.json`
|
||||
- **Best Practices Findings**: `.code-review/best-practices-findings.json`
|
||||
- **File Inventory**: `.code-review/inventory.json`
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Load All Findings
|
||||
|
||||
```javascript
|
||||
const securityFindings = JSON.parse(
|
||||
await Read({ file_path: '.code-review/security-findings.json' })
|
||||
);
|
||||
const bestPracticesFindings = JSON.parse(
|
||||
await Read({ file_path: '.code-review/best-practices-findings.json' })
|
||||
);
|
||||
const inventory = JSON.parse(
|
||||
await Read({ file_path: '.code-review/inventory.json' })
|
||||
);
|
||||
```
|
||||
|
||||
### Step 2: Aggregate Statistics
|
||||
|
||||
```javascript
|
||||
const stats = {
|
||||
total_files_reviewed: inventory.total_files,
|
||||
total_findings: securityFindings.total_findings + bestPracticesFindings.total_findings,
|
||||
by_severity: {
|
||||
critical: securityFindings.by_severity.critical,
|
||||
high: securityFindings.by_severity.high + bestPracticesFindings.by_severity.high,
|
||||
medium: securityFindings.by_severity.medium + bestPracticesFindings.by_severity.medium,
|
||||
low: securityFindings.by_severity.low + bestPracticesFindings.by_severity.low,
|
||||
},
|
||||
by_category: {
|
||||
security: securityFindings.total_findings,
|
||||
code_quality: bestPracticesFindings.by_category.code_quality,
|
||||
performance: bestPracticesFindings.by_category.performance,
|
||||
maintainability: bestPracticesFindings.by_category.maintainability,
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Step 3: Generate Comprehensive Report
|
||||
|
||||
```markdown
|
||||
# Comprehensive Code Review Report
|
||||
|
||||
**Generated**: {timestamp}
|
||||
**Scope**: {scope}
|
||||
**Files Reviewed**: {total_files}
|
||||
**Total Findings**: {total_findings}
|
||||
|
||||
## Executive Summary
|
||||
|
||||
{Provide high-level overview of code health}
|
||||
|
||||
### Risk Assessment
|
||||
|
||||
{Calculate risk score based on findings}
|
||||
|
||||
### Compliance Status
|
||||
|
||||
{Map findings to compliance requirements}
|
||||
|
||||
## Detailed Findings
|
||||
|
||||
{Merge and organize security + best practices findings}
|
||||
|
||||
## Action Plan
|
||||
|
||||
{Prioritized list of fixes with effort estimates}
|
||||
|
||||
## Appendix
|
||||
|
||||
{Technical details, references, configuration}
|
||||
```
|
||||
|
||||
### Step 4: Generate Fix Tracking Checklist
|
||||
|
||||
Create actionable checklist for developers:
|
||||
|
||||
```markdown
|
||||
# Code Review Fix Checklist
|
||||
|
||||
## Critical Issues (Fix Immediately)
|
||||
|
||||
- [ ] [SEC-001] SQL Injection in src/auth/user-service.ts:145
|
||||
- [ ] [SEC-002] Hardcoded JWT Secret in src/auth/jwt.ts:23
|
||||
- [ ] [SEC-003] XSS Vulnerability in src/api/comments.ts:89
|
||||
|
||||
## High Priority Issues (Fix This Week)
|
||||
|
||||
- [ ] [SEC-004] Missing Authorization Check in src/api/admin.ts:34
|
||||
- [ ] [BP-001] N+1 Query Pattern in src/api/orders.ts:45
|
||||
...
|
||||
```
|
||||
|
||||
### Step 5: Generate Metrics Dashboard
|
||||
|
||||
```markdown
|
||||
## Code Health Metrics
|
||||
|
||||
### Security Score: 68/100
|
||||
- Critical Issues: 3 (-30 points)
|
||||
- High Issues: 8 (-2 points each)
|
||||
|
||||
### Code Quality Score: 75/100
|
||||
- High Complexity Functions: 2
|
||||
- Code Duplication: 5%
|
||||
- Dead Code: 3 instances
|
||||
|
||||
### Performance Score: 82/100
|
||||
- N+1 Queries: 3
|
||||
- Inefficient Algorithms: 2
|
||||
|
||||
### Maintainability Score: 70/100
|
||||
- Documentation Coverage: 65%
|
||||
- Test Coverage: 72%
|
||||
- Missing Tests: 5 files
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
### Main Report
|
||||
|
||||
Save to `.code-review/REPORT.md`:
|
||||
|
||||
- Executive summary
|
||||
- Detailed findings (security + best practices)
|
||||
- Action plan with priorities
|
||||
- Metrics and scores
|
||||
- References and compliance mapping
|
||||
|
||||
### Fix Checklist
|
||||
|
||||
Save to `.code-review/FIX-CHECKLIST.md`:
|
||||
|
||||
- Organized by severity
|
||||
- Checkboxes for tracking
|
||||
- File:line references
|
||||
- Effort estimates
|
||||
|
||||
### JSON Summary
|
||||
|
||||
Save to `.code-review/summary.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"report_date": "2024-01-15T12:00:00Z",
|
||||
"scope": "src/**/*",
|
||||
"statistics": {
|
||||
"total_files": 247,
|
||||
"total_findings": 69,
|
||||
"by_severity": { "critical": 3, "high": 13, "medium": 30, "low": 23 },
|
||||
"by_category": {
|
||||
"security": 24,
|
||||
"code_quality": 18,
|
||||
"performance": 12,
|
||||
"maintainability": 15
|
||||
}
|
||||
},
|
||||
"scores": {
|
||||
"security": 68,
|
||||
"code_quality": 75,
|
||||
"performance": 82,
|
||||
"maintainability": 70,
|
||||
"overall": 74
|
||||
},
|
||||
"risk_level": "MEDIUM",
|
||||
"action_required": true
|
||||
}
|
||||
```
|
||||
|
||||
## Report Template
|
||||
|
||||
Full report includes:
|
||||
|
||||
1. **Executive Summary**
|
||||
- Overall code health
|
||||
- Risk assessment
|
||||
- Key recommendations
|
||||
|
||||
2. **Security Findings** (from Phase 2)
|
||||
- Critical/High/Medium/Low
|
||||
- OWASP/CWE mappings
|
||||
- Fix recommendations with code examples
|
||||
|
||||
3. **Best Practices Findings** (from Phase 3)
|
||||
- Code quality issues
|
||||
- Performance concerns
|
||||
- Maintainability gaps
|
||||
|
||||
4. **Metrics Dashboard**
|
||||
- Security score
|
||||
- Code quality score
|
||||
- Performance score
|
||||
- Maintainability score
|
||||
|
||||
5. **Action Plan**
|
||||
- Immediate actions (critical)
|
||||
- Short-term (1 week)
|
||||
- Medium-term (1 month)
|
||||
- Long-term (3 months)
|
||||
|
||||
6. **Compliance Impact**
|
||||
- PCI DSS findings
|
||||
- HIPAA findings
|
||||
- GDPR findings
|
||||
- SOC 2 findings
|
||||
|
||||
7. **Appendix**
|
||||
- Full findings list
|
||||
- Configuration used
|
||||
- Tools and versions
|
||||
- References
|
||||
|
||||
## State Management
|
||||
|
||||
```json
|
||||
{
|
||||
"phase": "04-report-generation",
|
||||
"status": "completed",
|
||||
"timestamp": "2024-01-15T12:00:00Z",
|
||||
"input": {
|
||||
"security_findings": ".code-review/security-findings.json",
|
||||
"best_practices_findings": ".code-review/best-practices-findings.json"
|
||||
},
|
||||
"output": {
|
||||
"report": ".code-review/REPORT.md",
|
||||
"checklist": ".code-review/FIX-CHECKLIST.md",
|
||||
"summary": ".code-review/summary.json"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Agent Instructions
|
||||
|
||||
```markdown
|
||||
You are in Phase 4 (FINAL) of the Code Review workflow. Generate comprehensive report.
|
||||
|
||||
**Instructions**:
|
||||
1. Load security findings from Phase 2
|
||||
2. Load best practices findings from Phase 3
|
||||
3. Aggregate statistics and calculate scores
|
||||
4. Generate comprehensive markdown report
|
||||
5. Create fix tracking checklist
|
||||
6. Generate JSON summary
|
||||
7. Inform user of completion and output locations
|
||||
|
||||
**Tools Available**:
|
||||
- Read (load findings)
|
||||
- Write (save reports)
|
||||
|
||||
**Output Requirements**:
|
||||
- REPORT.md (comprehensive markdown report)
|
||||
- FIX-CHECKLIST.md (actionable checklist)
|
||||
- summary.json (machine-readable summary)
|
||||
- All files in .code-review/ directory
|
||||
```
|
||||
|
||||
## Validation
|
||||
|
||||
- ✅ All findings consolidated
|
||||
- ✅ Scores calculated
|
||||
- ✅ Action plan generated
|
||||
- ✅ Reports saved to .code-review/
|
||||
- ✅ User notified of completion
|
||||
|
||||
## Completion
|
||||
|
||||
Code review complete! Outputs available in `.code-review/` directory.
|
||||
Reference in New Issue
Block a user