Performs systematic code review with universal best practices and repo-specific standards. Auto-activates after significant code changes. Use when reviewing code, auditing files, checking PRs, examining staged changes, or when asked to "review", "check", "audit", or "examine" code. Enforces design principles (SOLID, DRY, KISS), security (OWASP), performance, concurrency safety, cross-platform compatibility, and codebase patterns.
Systematic code review skill based on industry best practices from Google Engineering, OWASP, and modern development standards. Designed to catch issues that casual review misses through structured, checklist-driven analysis.
Core Principle (Google): Approve code that improves overall code health, even if not perfect. Seek continuous improvement, not perfection. But NEVER approve code that degrades code health.
When to Use This Skill
Auto-activation triggers:
After completing significant implementation tasks
Before committing changes
When reviewing PRs or staged files
Explicit activation triggers:
User asks to "review", "check", "audit", or "examine" code
User mentions "code review", "PR review", "look at this code"
User asks about code quality or standards compliance
Interactive Review Scoping
Use AskUserQuestion to determine review depth and risk profile when not specified:
# Check if config exists
ls .claude/code-review.md 2>/dev/null || echo "No config, will use CLAUDE.md fallback"
# Preview what config will be loaded (via review command)
/code-quality:review --show-rules
Step 0e: Git History Analysis
Triggered by:thorough or strict profile (partial for security/performance)
Before reviewing, count the files to ensure accurate reporting:
Review Scope
Counting Command
Staged changes
git diff --staged --name-only | wc -l
PR changes
git diff --name-only main...HEAD | wc -l
Specific paths
Use Glob tool and count results
Important:
Track this count accurately - report it in Files Reviewed output
Exclude binary files (images, compiled assets) from review count
Exclude deleted files from review count (nothing to review)
For renamed files: count as 1 file (the new name)
Large Changeset Warnings:
50+ files: Consider batched review or consensus mode
100+ files: Strongly recommend breaking into smaller chunks
Step 1b: Detect Generated Content
Scan changed files for generation markers to identify files that were created by scripts/tools. Review the generator (source of truth) instead of generated output.
Detection Markers (scan first 20 + last 10 lines):
File Type
Markers
Markdown
Generated: YYYY-MM-DD, <!-- Generated by ScriptName -->
When --baseline <branch> is specified, attribute each finding as NEW or PRE-EXISTING.
Why This Matters:
This is the #1 adoption blocker for code review tools. Teams with tech debt get overwhelmed by 100+ findings when their PR only introduces 3 new issues. They give up on the tool.
Baseline Mode Workflow:
Build attribution map from git diff:
git diff <baseline>...HEAD # Three-dot for symmetric comparison
Parse diff to identify changed line ranges per file
For each finding: Check if file:line is in changed ranges
Tag findings: NEW (line added/modified) or PRE-EXISTING (unchanged)
Separate output: New issues prominent, pre-existing collapsed
Finding Attribution Rules:
Line Status
Attribution
Output Section
Added (+ in diff)
NEW
"New Issues Introduced"
Modified (in hunk, changed)
NEW
"New Issues Introduced"
Context (in hunk, unchanged)
PRE-EXISTING
"Pre-existing Issues" (collapsed)
Not in any hunk
PRE-EXISTING
"Pre-existing Issues" (collapsed)
Deleted (- in diff)
SKIP
Not reviewed (doesn't exist)
Baseline Output Format:
## Review Summary (Baseline Mode)
**Baseline**: `main`
**New Issues (this changeset)**: 2 CRITICAL, 1 MAJOR ← FOCUS HERE
**Pre-existing Issues**: 47 (collapsed)
**Assessment**: Based on NEW issues only
## New Issues Introduced
[Detailed findings with Attribution: NEW]
<details>
<summary>Pre-existing Issues (47)</summary>
[Condensed findings]
</details>
Quality Gates (CI/CD):
--fail-on-new-critical: Exit 1 if ANY new CRITICAL
--fail-on-new-major: Exit 1 if ANY new MAJOR
Pre-existing issues do NOT fail the build
Edge Cases:
Baseline doesn't exist → Error with valid branch suggestions
File renamed → Attribute based on content changes
Merge commits → Use three-dot diff for correct comparison
Complexity Thresholds
Use these concrete thresholds when evaluating code complexity:
Metric
Warning
Error
Measurement
Cyclomatic Complexity
> 10
> 20
Count decision points (if, while, for, case, &&, ||, ?)
Cognitive Complexity
> 15
> 30
SonarQube metric (nesting adds more weight)
Function Lines
> 30
> 50
Count non-blank, non-comment lines
Nesting Depth
> 3
> 5
Count nested braces/indentation levels
Parameter Count
> 4
> 7
Count function/method parameters
File Lines
> 300
> 500
Count total lines in file
When thresholds exceeded:
Warning → MINOR severity finding
Error → MAJOR severity finding
Suggested Fix Template:
### Complexity Threshold Exceeded
**File**: `src/services/order.ts:processOrder()`
**Severity**: MAJOR
**Metric**: Cyclomatic Complexity = 23 (threshold: 15, error: 20)
**Problem**: Function has 23 independent paths through the code.
**Impact**: Difficult to test (need 23+ test cases), hard to maintain, high bug risk.
**Fix**: Extract methods for logical branches. Consider:
- Extract validation logic → `validateOrder()`
- Extract pricing logic → `calculatePrice()`
- Extract notification logic → `notifyCustomer()`
Progressive Loading (Token Optimization)
This skill uses tiered progressive disclosure to optimize token usage. Only load what's relevant to the files being reviewed.
Tier 0 (MANDATORY - Always First): Research Phase (~2,000 tokens)
ALWAYS load BEFORE analysis: references/tier-0/research-phase.md
Tier 4 (Repository-Specific): Load when repo config or CLAUDE.md exists
Context
Load Reference
.claude/code-review.md exists
references/tier-4/repo-config.md
CLAUDE.md exists (always)
references/tier-4/claude-md-core.md
*.md files
references/tier-4/documentation-rules.md
Duplication indicators
references/tier-4/anti-duplication-rules.md
Path patterns detected
references/tier-4/path-rules.md
*-{platform}.md files
references/tier-4/platform-rules.md
.claude/skills/**
references/tier-4/skill-rules.md
.claude/memory/**
references/tier-4/memory-rules.md
.claude/temp/**
references/tier-4/temp-file-rules.md
Profile thorough/strict
references/tier-4/pattern-compliance.md
Tier 4b (Claude Code Components): Delegate to specialized auditors when CC files detected
File Pattern
Component Type
Auditor Agent
.claude/agents/**/*.md, agents/*.md
Agent
claude-ecosystem:agent-auditor
.claude/commands/**/*.md, commands/*.md
Command
claude-ecosystem:command-auditor
.claude/hooks/**, hooks.json
Hook
claude-ecosystem:hook-auditor
.claude/skills/**
Skill
claude-ecosystem:skill-auditor
CLAUDE.md, .claude/memory/**
Memory
claude-ecosystem:memory-component-auditor
output-styles/*.md
Output Style
claude-ecosystem:output-style-auditor
.mcp.json, mcp.json
MCP Config
claude-ecosystem:mcp-auditor
settings.json, .claude/settings.json
Settings
claude-ecosystem:settings-auditor
plugin.json, .claude-plugin/**
Plugin
claude-ecosystem:plugin-component-auditor
Status line scripts
Status Line
claude-ecosystem:statusline-auditor
Load the reference for complete detection and delegation patterns: references/tier-4/claude-code-components.md
Note: Tier 4b requires the claude-ecosystem plugin to be installed. If not installed, log a warning and skip CC-specific validation (continue with standard review).
Auditor Agent Verification: Agent names may change between plugin releases. Run /claude-ecosystem:list-skills
to verify current auditor agent names if delegation fails. The table above reflects known agents as of this file's last update.
Tier 5 (Generated Content & MCP Validation Details): Load based on changeset characteristics
Trigger
Load Reference
Large changeset (50+ files)
references/tier-5/generated-content-detection.md
Generation markers found
references/tier-5/generated-content-detection.md
Need advanced MCP query patterns
references/tier-5/mcp-validation.md
Complex technology stack
references/tier-5/mcp-validation.md
Security patterns require OWASP validation
references/tier-5/mcp-validation.md
Note: Primary MCP validation happens in Tier 0 (Research Phase) which is MANDATORY. Tier 5 mcp-validation.md provides additional query templates and advanced patterns for complex scenarios.
Note: Token budgets increased by ~2,000 tokens due to MANDATORY Tier 0 Research Phase. This trade-off provides significantly more accurate reviews through MCP validation.
Layer 1: Universal Code Review Checklist
These checks apply to ANY codebase, ANY language.
1.1 Design and Architecture
Overall design makes sense - Interactions between components are logical
Belongs in this codebase - Not better suited for a library or different module
Integrates well - Fits with existing system architecture
Right time for this change - Not premature or addressing wrong problem
No over-engineering - Solves current problem, not speculative future needs (YAGNI)
SOLID Principles:
Single Responsibility (SRP) - Each class/function has ONE reason to change
Open-Closed (OCP) - Open for extension, closed for modification (no repeated if/else for types)
Liskov Substitution (LSP) - Derived classes substitutable for base (no explicit type casting)
Interface Segregation (ISP) - Clients depend only on methods they use
Dependency Inversion (DIP) - Depend on abstractions, not concrete implementations
1.2 Functionality and Logic
Does what it's supposed to do - Implements intended functionality
Good for users - Both end-users AND developers who'll use this code
Tests maintainable - Not overly complex, clear assertions
No flaky tests - Deterministic, not timing-dependent
Test Smell Detection:
Review test code for common test smells that reduce test quality and maintainability:
Smell
Detection
Severity
Why It Matters
Empty Test
Test method with no assertions
CRITICAL
False confidence - test always passes
Eager Test
> 5 assertions in one test
WARNING
When it fails, unclear which behavior broke
Mystery Guest
External file/network access without mock
MAJOR
Flaky, slow, environment-dependent
Assertion Roulette
Multiple asserts without descriptive messages
MINOR
Hard to identify which assertion failed
Sleep in Test
Thread.Sleep, await Task.Delay, setTimeout
MAJOR
Slow, flaky, hides timing bugs
Dead Test
Test that never fails (always passes)
WARNING
Usually tests nothing meaningful
Commented Test
Disabled test cases ([Ignore], skip, xtest)
WARNING
Technical debt, may hide real issues
Test Code Duplication
Same setup/teardown in multiple tests
MINOR
Maintenance burden, use fixtures
Example Findings:
### Test Smell: Eager Test
**File**: `tests/UserService.test.ts:45`
**Severity**: WARNING
**Confidence**: MEDIUM
**Problem**: Test "should handle user operations" has 12 assertions testing multiple behaviors.
**Impact**: When this test fails, you won't know which behavior broke without debugging.
**Suggested Fix**:
```typescript
// Before (Eager Test - 12 assertions, multiple behaviors)
test('should handle user operations', () => {
const user = createUser();
expect(user.name).toBe('John');
expect(user.email).toContain('@');
// ... 10 more assertions about different behaviors
});
// After (Focused Tests - one behavior each)
test('should create user with valid name', () => {
const user = createUser();
expect(user.name).toBe('John');
});
test('should validate email format', () => {
const user = createUser();
expect(user.email).toContain('@');
});
```markdown
### Test Smell: Sleep in Test
**File**: `tests/api.test.ts:78`
**Severity**: MAJOR
**Confidence**: HIGH
**Problem**: Test uses `await new Promise(r => setTimeout(r, 2000))` to wait for async operation.
**Impact**: Test is slow (2 seconds), flaky (timing varies), and hides real async handling bugs.
**Suggested Fix**:
```typescript
// Before (Sleep - slow and flaky)
await new Promise(r => setTimeout(r, 2000));
expect(result).toBeDefined();
// After (Proper async handling)
await waitFor(() => expect(result).toBeDefined());
// Or
await expect(asyncOperation()).resolves.toBeDefined();
### 1.8 Error Handling and Logging
- [ ] **Errors caught appropriately** - Right level of granularity
- [ ] **Error messages actionable** - Clear what went wrong and how to fix
- [ ] **Logging present** - For debugging and troubleshooting
- [ ] **No sensitive data in logs** - PII, passwords, keys excluded
- [ ] **Graceful degradation** - Partial failures don't crash entire system
### 1.9 Documentation
- [ ] **Code documented** - Public APIs, complex logic explained
- [ ] **README updated** - If behavior/setup changes
- [ ] **API docs updated** - If endpoints change
- [ ] **Inline comments where needed** - For non-obvious decisions
### 1.10 Cross-Platform Compatibility
- [ ] **No hardcoded platform paths**:
- `/mnt/c/Users/...` (WSL)
- `/c/Users/...` (Git Bash)
- `C:\Users\...` (Windows)
- `/home/username/...` (Linux)
- `/Users/username/...` (macOS)
- [ ] **Portable tool detection** - `command -v tool` not path hunting
- [ ] **Platform fallbacks** - Graceful handling when features unavailable
- [ ] **Scripts self-locate** - Use `Path(__file__).resolve()`, `$PSScriptRoot`, `${BASH_SOURCE[0]}`
### 1.11 Anti-Duplication
- [ ] **No duplicate content** - Same info in ONE place only
- [ ] **No identical files** - `diff` similar files to verify
- [ ] **Single source of truth** - Link instead of copy-paste
- [ ] **Config files distinct** - Each serves different purpose
### 1.12 Style and Consistency
- [ ] **Follows style guide** - Language/project conventions
- [ ] **Consistent with codebase** - Matches existing patterns
- [ ] **No style changes mixed with logic** - Separate formatting PRs
### 1.13 Accessibility (WCAG 2.1 AA)
- [ ] **Alt text present** - All images have descriptive alt text; decorative images use `alt=""`
- [ ] **Color contrast sufficient** - 4.5:1 for text, 3:1 for UI components
- [ ] **Keyboard navigable** - All interactive elements via Tab/Enter/Space; no keyboard traps
- [ ] **Focus visible** - Clear focus indicators on all interactive elements
- [ ] **Semantic HTML** - Proper heading hierarchy; buttons not divs; links not spans
- [ ] **ARIA correct** - Used only when semantic HTML insufficient; no conflicting roles
### 1.14 Internationalization (i18n)
- [ ] **No hardcoded strings** - All user-facing text externalized to resource files
- [ ] **Locale-aware formatting** - Dates, numbers, currency use locale APIs
- [ ] **RTL consideration** - Logical CSS properties where applicable
- [ ] **No string concatenation** - Use parameterized messages, not `"Hello " + name`
- [ ] **Pluralization handled** - Proper plural rules, not `count + " items"`
### 1.15 Observability
- [ ] **Structured logging** - JSON format with trace IDs, timestamps, context
- [ ] **Metrics present** - Latency, error rates, throughput for critical paths
- [ ] **Trace context propagated** - Distributed tracing across service boundaries
- [ ] **Health checks implemented** - Liveness/readiness probes with dependency checks
- [ ] **SLOs defined** - Measurable service level objectives for key operations
### 1.16 Data Privacy (GDPR/CCPA)
- [ ] **PII identified and protected** - Personal data encrypted, access controlled
- [ ] **Data retention enforced** - Clear policies, automated cleanup
- [ ] **Right to deletion** - Complete erasure across all systems possible
- [ ] **Consent tracked** - Explicit opt-in with audit trail
- [ ] **No PII in logs** - Redaction or hashing of personal identifiers
### 1.17 API Design
- [ ] **Versioning strategy** - Clear version in URL, header, or media type
- [ ] **Backward compatible** - New fields nullable, no removed fields
- [ ] **Deprecation documented** - Sunset dates, migration paths
- [ ] **Consistent naming** - Follows REST/GraphQL conventions
- [ ] **Error responses standardized** - Consistent error format across endpoints
### 1.18 Dependency Management
- [ ] **No known vulnerabilities** - CVE scanning in CI/CD
- [ ] **License compliance** - No GPL conflicts with proprietary code
- [ ] **Version pinned** - Lockfiles present and up-to-date
- [ ] **Transitive deps reviewed** - Indirect dependencies also secure
- [ ] **SBOM available** - Software Bill of Materials for audits
### 1.19 Database Patterns
- [ ] **N+1 queries avoided** - Eager loading or batch queries used
- [ ] **Indexes present** - For foreign keys, join columns, query patterns
- [ ] **Migrations backward compatible** - Incremental changes, no data loss
- [ ] **Schema properly normalized** - Or denormalized with clear rationale
- [ ] **Query optimization** - Explain plans reviewed for complex queries
### 1.20 Configuration Management
- [ ] **Secrets in vault** - Never hardcoded, use env vars or secrets manager
- [ ] **Feature flags used** - For gradual rollouts, A/B testing
- [ ] **12-factor compliant** - Config via environment, not files
- [ ] **Validation at startup** - Fail fast on missing/invalid config
- [ ] **Environment parity** - Same config structure across dev/staging/prod
### 1.21 Cloud/Infrastructure (12-Factor)
- [ ] **Stateless processes** - No local session storage, use external stores
- [ ] **Port binding** - Self-contained, exports HTTP via port
- [ ] **Disposability** - Fast startup, graceful SIGTERM shutdown
- [ ] **Dev/prod parity** - Minimal gap between environments
- [ ] **Container best practices** - Multi-stage builds, non-root user, resource limits
- [ ] **IaC used** - Terraform/CloudFormation for reproducibility
### 1.22 Frontend Patterns
- [ ] **Component design** - Small, reusable, composition over inheritance
- [ ] **State management** - Appropriate tool (local, context, Zustand, Redux)
- [ ] **Bundle size** - Code splitting, lazy loading, < 500KB main bundle
- [ ] **Memoization** - Strategic use of memo/useMemo/useCallback
- [ ] **Web Vitals** - LCP < 2.5s, FID < 100ms, CLS < 0.1
### 1.23 Mobile Patterns
- [ ] **Battery efficient** - WorkManager/JobScheduler, batched operations
- [ ] **Offline-first** - Local caching with sync, offline queue
- [ ] **Responsive layout** - Flexible dimensions (dp/sp), rotation handling
- [ ] **Memory efficient** - Image downsampling, lifecycle awareness
- [ ] **Network efficient** - Request batching, compression, exponential backoff
### 1.24 AI/ML Code Patterns
- [ ] **Model versioning** - MLflow/DVC for models and data
- [ ] **Reproducibility** - Random seeds, pinned dependencies, exact environments
- [ ] **Bias detection** - Fairness metrics across demographics
- [ ] **Data pipeline validated** - Schema validation, statistical tests
- [ ] **Model monitoring** - Drift detection for data and performance
### 1.25 Clean Code: Names (Robert C. Martin)
- [ ] **Intention-revealing names** - Name tells you why it exists, what it does, how it's used
- [ ] **No misleading names** - `accountList` should actually be a list; avoid false clues
- [ ] **Meaningful distinctions** - Not `data1`, `data2`, `dataInfo`, `theData`
- [ ] **Pronounceable names** - Can discuss code verbally without spelling variables
- [ ] **Searchable names** - Single-letter names only for small local scope
- [ ] **No encodings** - No Hungarian notation, no type prefixes (strName, intCount)
- [ ] **No mental mapping** - Reader shouldn't translate names to concepts they know
- [ ] **Class names are nouns** - Customer, Account, Parser (not verbs)
- [ ] **Method names are verbs** - postPayment, deletePage, save (not nouns)
### 1.26 Clean Code: Functions (Robert C. Martin)
- [ ] **Small** - 5-20 lines ideal; rarely exceed 30 lines
- [ ] **Do one thing** - Single level of abstraction; one reason to change
- [ ] **One abstraction level** - Don't mix getHtml() with .append("\n")
- [ ] **Descriptive names** - Long descriptive name better than short enigmatic one
- [ ] **Few arguments** - Zero ideal, one/two good, three questionable, never more than four
- [ ] **No flag arguments** - Split function into two instead of passing boolean
- [ ] **No side effects** - Don't modify unexpected state; function does what name says only
- [ ] **Command/Query separation** - Either do something OR answer something, never both
- [ ] **Prefer exceptions to error codes** - Don't return -1 or null for errors
- [ ] **Extract try/catch blocks** - Bodies of try/catch should be one-line function calls
### 1.27 Clean Code: Comments (Robert C. Martin)
- [ ] **Code explains itself first** - If you need a comment, try rewriting the code
- [ ] **Comments explain WHY** - Not what (code shows what) or how (code shows how)
- [ ] **Legal comments acceptable** - Copyright, license headers
- [ ] **Informative comments acceptable** - Regex explanation, return value meaning
- [ ] **TODO comments have tickets** - `// TODO: TICKET-123 - refactor after API v2`
- [ ] **No redundant comments** - `// Constructor` above a constructor is noise
- [ ] **No commented-out code** - Delete it; version control remembers
- [
…(truncated)
1---2name: code-reviewing3description: Performs systematic code review with universal best practices and repo-specific standards. Auto-activates after significant code changes. Use when reviewing code, auditing files, checking PRs, examining staged changes, or when asked to "review", "check", "audit", or "examine" code. Enforces design principles (SOLID, DRY, KISS), security (OWASP), performance, concurrency safety, cross-platform compatibility, and codebase patterns.4---56# Code Reviewing
78Systematic code review skill based on industry best practices from Google Engineering, OWASP, and modern development standards. Designed to catch issues that casual review misses through structured, checklist-driven analysis.
910**Core Principle (Google):** Approve code that improves overall code health, even if not perfect. Seek continuous improvement, not perfection. But NEVER approve code that degrades code health.
1112## When to Use This Skill
1314**Auto-activation triggers:**
1516- After completing significant implementation tasks
17- Before committing changes
18- When reviewing PRs or staged files
1920**Explicit activation triggers:**
2122- User asks to "review", "check", "audit", or "examine" code
23- User mentions "code review", "PR review", "look at this code"
24- User asks about code quality or standards compliance
2526## Interactive Review Scoping
2728Use AskUserQuestion to determine review depth and risk profile when not specified:
2930```yaml
31# Question 1: Review Depth (MCP: Google Engineering code review, OWASP)
32question: "What type of code review is needed?"
33header: "Review Type"
34options:
35 - label: "Quick Review (Recommended)"
36 description: "Surface issues, style, obvious bugs (~15 min, ~3.5K tokens)"
37 - label: "Thorough Review"
38 description: "Multi-pass: logic, design, tests (~45 min, ~14K tokens)"
39 - label: "Security Review"
40 description: "Threat-focused: auth, validation, crypto (~30 min)"
41 - label: "Architecture Review"
42 description: "Design patterns, dependencies, coupling (~60 min)"
4344# Question 2: Risk Profile (MCP: CLI best practices - scope selection)
45question: "What is the risk profile of this change?"
46header: "Risk"
47options:
48 - label: "Low Risk (Recommended)"
49 description: "Isolated fix, well-tested area, no user impact"
50 - label: "Medium Risk"
51 description: "Feature change, moderate scope, reversible"
52 - label: "High Risk"
53 description: "Critical path, security-sensitive, wide impact"
54 - label: "Unknown"
55 description: "I'm not sure - analyze and recommend"
56```
5758Use these responses to select the appropriate review profile (quick, thorough, security, strict, performance).
5960## Review Workflow
6162```text
63Code Review Progress:
64- [ ] Step 0: RESEARCH PHASE (MANDATORY - Run MCP queries for technology stack)
65- [ ] Step 0b: LOAD REPO CONFIG (Check .claude/code-review.md, fallback to CLAUDE.md)
66- [ ] Step 0e: Git History Analysis (coupling, hot spots, author context - thorough/strict only)
67- [ ] Step 1: Count files to review (accurate file counting)
68- [ ] Step 1b: Detect generated content (scan for markers, identify generators)
69- [ ] Step 2: Identify scope (files to review, excluding generated files)
70- [ ] Step 3: Load context (repo standards + MCP research results + repo config)
71- [ ] Step 4: Run Universal Checks (Layer 1) - informed by MCP research
72- [ ] Step 5: Run Repo-Specific Checks (Layer 2, applying repo config rules)
73- [ ] Step 5b: Run Claude Code Validation (Tier 4b, if CC files detected)
74- [ ] Step 6: Report ALL findings with severity, rule source, and MCP validation status
75- [ ] Step 7: Propose specific fixes with rationale and MCP-backed recommendations
76```
7778### Step 0: RESEARCH PHASE (MANDATORY)
7980**CRITICAL: This step runs BEFORE any code analysis. It is NOT optional.**
8182Query MCP servers to understand current patterns and best practices BEFORE reviewing code. This prevents making claims based on stale training data.
8384**Load Reference:** [references/tier-0/research-phase.md](references/tier-0/research-phase.md)
8586**Quick Reference:**
87881. **Detect Technology Stack** (from file extensions, imports, manifests)
892. **Query MCP Servers** (parallel queries based on detected technologies):
90 - Microsoft tech (.NET, Azure, C#) → `microsoft-learn` + `perplexity` (ALWAYS dual-validate)
91 - npm/PyPI packages → `context7` + `ref`
92 - Security patterns → `perplexity` (OWASP)
93 - Version claims → `perplexity` (ALWAYS validate)
943. **Build Current Truth Context** (store validated patterns for use during analysis)
9596**Core Rules:**
9798- **Research BEFORE analysis** - Know current best practices before making claims
99- **Perplexity ALWAYS required** - Training data is stale; always cross-validate
100- **Dual validation for Microsoft tech** - `microsoft-learn` can be stale, ALWAYS pair with `perplexity`
101- **Every finding needs a source** - No finding without authoritative validation
102103**High-Risk Technologies (Extra Perplexity Validation Required):**
104105- .NET 10, .NET Aspire, Azure AI Foundry, HybridCache, Microsoft.Extensions.AI
106107### Step 0b: Load Repository Configuration
108109**Load repo-specific rules to customize the review.**
110111**Load Reference:** [references/tier-4/repo-config.md](references/tier-4/repo-config.md)
112113**Configuration Priority Chain:**
114115```text
1161. .claude/code-review.md (PRIMARY)
117 ├── Found: Parse config, apply rules, STOP
118 └── Not found: Continue to fallback
1191202. CLAUDE.md + @imports (FALLBACK)
121 ├── Found: Read CLAUDE.md + follow @imports
122 │ └── Extract rules from ## Critical Rules, ## Conventions sections
123 └── Not found: Continue to fallback
1241253. No config found
126 ├── Interactive mode: Use AskUserQuestion
127 │ └── "No review configuration found. Review with default rules?"
128 └── Non-interactive: Apply default rules only
129```
130131**What Gets Loaded:**
132133| Source | What's Parsed |
134| --- | --- |
135| `.claude/code-review.md` | Tech Stack, Exclude Rules, Severity Overrides, Custom Checks |
136| CLAUDE.md + @imports | Text from ## Critical Rules, ## Conventions, ## Code Review sections |
137138**Config Effects:**
139140| Config Section | Effect on Review |
141| --- | --- |
142| Tech Stack | Override auto-detection, improve MCP query accuracy |
143| Exclude Rules | Skip these rules entirely (no findings generated) |
144| Severity Overrides | Change default severity for specific rules |
145| Custom Checks | Add project-specific checks (file patterns, content rules) |
146147**Quick Reference:**
148149```bash
150# Check if config exists
151ls .claude/code-review.md 2>/dev/null || echo "No config, will use CLAUDE.md fallback"
152153# Preview what config will be loaded (via review command)
154/code-quality:review --show-rules
155```
156157### Step 0e: Git History Analysis
158159**Triggered by:** `thorough` or `strict` profile (partial for `security`/`performance`)
160161**Load Reference:** [references/tier-1/git-history-context.md](references/tier-1/git-history-context.md)
162163Extract git history context to inform review priorities and catch coupling issues:
1641651. **Read Configuration** - Check `.claude/code-review.md` for history analysis settings
1662. **Coupling Analysis** - Find files that frequently change together
1673. **Hot Spot Detection** - Identify high-churn files (configurable threshold, default: 10+ changes in 3 months)
1684. **Author Context** - Extract ownership patterns (`strict` profile only)
1695. **Recent Patterns** - Detect bug fix, security, or refactoring history
170171**Quick Reference Commands:**
172173```bash
174# Coupling analysis - files that change together
175git log --name-only --pretty=format: -- <files> | sort | uniq -c | sort -rn | head -20
176177# Hot spot detection - change frequency
178git log --since="3 months ago" --name-only --pretty=format: | sort | uniq -c | sort -rn | head -20
179180# Author context - ownership
181git shortlog -sn -- <files>
182183# Recent patterns - commit messages
184git log --oneline -10 -- <files>
185```
186187**Profile Behavior:**
188189| Profile | Analysis Depth |
190| --- | --- |
191| quick | Skip entirely |
192| security | Partial (security-related commits only) |
193| thorough | Coupling + hot spots + recent patterns |
194| strict | Full analysis including author context |
195| performance | Partial (perf-related history only) |
196197### Step 1: Count Files (Accurate File Counting)
198199Before reviewing, count the files to ensure accurate reporting:
200201| Review Scope | Counting Command |
202| --- | --- |
203| Staged changes | `git diff --staged --name-only \| wc -l` |
204| PR changes | `git diff --name-only main...HEAD \| wc -l` |
205| Specific paths | Use Glob tool and count results |
206207**Important**:
208209- Track this count accurately - report it in **Files Reviewed** output
210- Exclude binary files (images, compiled assets) from review count
211- Exclude deleted files from review count (nothing to review)
212- For renamed files: count as 1 file (the new name)
213214**Large Changeset Warnings**:
215216- 50+ files: Consider batched review or consensus mode
217- 100+ files: Strongly recommend breaking into smaller chunks
218219### Step 1b: Detect Generated Content
220221Scan changed files for generation markers to identify files that were created by scripts/tools. Review the generator (source of truth) instead of generated output.
222223**Detection Markers** (scan first 20 + last 10 lines):
224225| File Type | Markers |
226| --- | --- |
227| Markdown | `Generated: YYYY-MM-DD`, `<!-- Generated by ScriptName -->` |
228| JSON | Root `"timestamp"` or `"generator"` fields |
229| Scripts | `Auto-generated from`, `DO NOT EDIT`, `Generated by` |
230| Code | `// <auto-generated>`, `@generated`, `*.g.cs`, `*.generated.ts` |
231232**Workflow**:
2332341. Scan changed files for markers
2352. If marker found: extract generator name, search for script, add to review scope
2363. Mark generated files for skip/light review
2374. Warn if only generated files changed (may indicate stale regeneration)
238239**Edge Cases**:
240241- Generator also changed → Review generator only, skip generated
242- Only generated changed → Warn: stale regeneration or manual edit
243- Generator not found → Review generated file anyway
244- Security-sensitive generated file → Still review (credentials, config)
245246Load [references/tier-5/generated-content-detection.md](references/tier-5/generated-content-detection.md) for complete detection patterns and algorithm.
247248### Step 2: Identify Scope
249250- **Explicit request**: User-specified files or changes
251- **Staged changes**: `git diff --staged` or `git status`
252- **Recent work**: Files modified in current session
253- **PR scope**: All files in a pull request
254255### Step 3: Load Context
256257Check for repo-specific standards. If found, load for Layer 2 checks.
258259### Review Profiles
260261When `--profile <name>` is specified, restrict tier loading to profile-specific subsets. This enables focused reviews for specific concerns.
262263**Available Profiles:**
264265| Profile | Tiers Loaded | Description | Use Case |
266| --- | --- | --- | --- |
267| `security` | 0, 1.3, 3-security | OWASP, secrets, auth, crypto | Fast security scan before merge |
268| `quick` | 1.1-1.6, 1.12 | Design, logic, style basics | Pre-commit fast check |
269| `thorough` | All tiers + 1.30-1.32 | Complete analysis + reference/pattern checks | PR review (default) |
270| `strict` | All thorough + deep patterns | Full analysis + architectural pattern enforcement | Library releases, major changes |
271| `performance` | 0, 1.5, 2-backend, 3-concurrency | N+1, complexity, memory, concurrency | Performance audit |
272273**Profile Tier Mappings:**
274275```text
276security:
277 - Tier 0: Research Phase (ALWAYS - detect auth/crypto libraries)
278 - Tier 1.3: Security (OWASP-Based)
279 - Tier 3: security-patterns.md (when auth/crypto patterns detected)
280 - Skip: Design, readability, testing, documentation
281282quick:
283 - Tier 1.1: Design and Architecture (basic structure)
284 - Tier 1.2: Functionality and Logic (obvious errors)
285 - Tier 1.3: Security (CRITICAL only - hardcoded secrets)
286 - Tier 1.4: Concurrency (obvious race conditions)
287 - Tier 1.5: Performance (N+1, obvious inefficiencies)
288 - Tier 1.6: Complexity (extreme violations)
289 - Tier 1.12: Style (consistency)
290 - Skip: Tier 0 MCP research, Tier 2+, Clean Code deep-dives
291292thorough:
293 - ALL tiers loaded based on file types/patterns
294 - Complete analysis (default behavior)
295 - Section 1.30: Reference Integrity (always when renames/deletions detected)
296 - Section 1.31: Breaking Changes (always for public API changes)
297 - Section 1.32: Pattern Compliance (basic pattern checks)
298 - Sections 1.33-1.36: Git History Context (coupling, hot spots, recent patterns)
299300strict:
301 - ALL 'thorough' checks
302 - Section 1.32 Pattern Compliance (full analysis):
303 - Architectural pattern deviation (CQRS, mediator, repository)
304 - DI registration consistency
305 - File organization enforcement
306 - Section 1.35: Author Context (ownership patterns, bus factor)
307 - Import/export hygiene (module boundaries, barrel pollution)
308 - Test correlation (orphaned tests detection)
309 - Dependency safety (migration verification)
310311performance:
312 - Tier 0: Research Phase (performance best practices via MCP)
313 - Tier 1.5: Performance and Efficiency
314 - Tier 2: backend-checks.md (database, API performance)
315 - Tier 3: concurrency-patterns.md (async, threading)
316 - Skip: Style, documentation, clean code deep-dives
317```
318319**Token Savings by Profile:**
320321| Profile | Est. Tokens | Savings vs Strict |
322| --- | --- | --- |
323| security | ~5,500 | 60%+ |
324| quick | ~3,500 | 75%+ |
325| thorough | ~14,000 | 15% |
326| strict | ~17,000 | 0% (baseline) |
327| performance | ~6,000 | 65%+ |
328329### Baseline Mode (Differential Analysis)
330331When `--baseline <branch>` is specified, attribute each finding as NEW or PRE-EXISTING.
332333**Why This Matters:**
334This is the #1 adoption blocker for code review tools. Teams with tech debt get overwhelmed by 100+ findings when their PR only introduces 3 new issues. They give up on the tool.
335336**Baseline Mode Workflow:**
3373381. **Build attribution map** from git diff:
339340 ```bash
341 git diff <baseline>...HEAD # Three-dot for symmetric comparison
342 ```
3433442. **Parse diff** to identify changed line ranges per file
3453. **For each finding**: Check if `file:line` is in changed ranges
3464. **Tag findings**: NEW (line added/modified) or PRE-EXISTING (unchanged)
3475. **Separate output**: New issues prominent, pre-existing collapsed
348349**Finding Attribution Rules:**
350351| Line Status | Attribution | Output Section |
352| --- | --- | --- |
353| Added (`+` in diff) | NEW | "New Issues Introduced" |
354| Modified (in hunk, changed) | NEW | "New Issues Introduced" |
355| Context (in hunk, unchanged) | PRE-EXISTING | "Pre-existing Issues" (collapsed) |
356| Not in any hunk | PRE-EXISTING | "Pre-existing Issues" (collapsed) |
357| Deleted (`-` in diff) | SKIP | Not reviewed (doesn't exist) |
358359**Baseline Output Format:**
360361```markdown
362## Review Summary (Baseline Mode)
363364**Baseline**: `main`
365**New Issues (this changeset)**: 2 CRITICAL, 1 MAJOR ← FOCUS HERE
366**Pre-existing Issues**: 47 (collapsed)
367**Assessment**: Based on NEW issues only
368369## New Issues Introduced
370[Detailed findings with Attribution: NEW]
371372<details>
373<summary>Pre-existing Issues (47)</summary>
374[Condensed findings]
375</details>
376```
377378**Quality Gates (CI/CD):**
379380- `--fail-on-new-critical`: Exit 1 if ANY new CRITICAL
381- `--fail-on-new-major`: Exit 1 if ANY new MAJOR
382- Pre-existing issues do NOT fail the build
383384**Edge Cases:**
385386- Baseline doesn't exist → Error with valid branch suggestions
387- File renamed → Attribute based on content changes
388- Merge commits → Use three-dot diff for correct comparison
389390### Complexity Thresholds
391392Use these concrete thresholds when evaluating code complexity:
393394| Metric | Warning | Error | Measurement |
395| --- | --- | --- | --- |
396| Cyclomatic Complexity | > 10 | > 20 | Count decision points (if, while, for, case, &&, \|\|, ?) |
397| Cognitive Complexity | > 15 | > 30 | SonarQube metric (nesting adds more weight) |
398| Function Lines | > 30 | > 50 | Count non-blank, non-comment lines |
399| Nesting Depth | > 3 | > 5 | Count nested braces/indentation levels |
400| Parameter Count | > 4 | > 7 | Count function/method parameters |
401| File Lines | > 300 | > 500 | Count total lines in file |
402403**When thresholds exceeded:**
404405- Warning → MINOR severity finding
406- Error → MAJOR severity finding
407408**Suggested Fix Template:**
409410```markdown
411### Complexity Threshold Exceeded
412413**File**: `src/services/order.ts:processOrder()`
414**Severity**: MAJOR
415**Metric**: Cyclomatic Complexity = 23 (threshold: 15, error: 20)
416417**Problem**: Function has 23 independent paths through the code.
418419**Impact**: Difficult to test (need 23+ test cases), hard to maintain, high bug risk.
420421**Fix**: Extract methods for logical branches. Consider:
422- Extract validation logic → `validateOrder()`
423- Extract pricing logic → `calculatePrice()`
424- Extract notification logic → `notifyCustomer()`
425```
426427### Progressive Loading (Token Optimization)
428429This skill uses **tiered progressive disclosure** to optimize token usage. Only load what's relevant to the files being reviewed.
430431**Tier 0 (MANDATORY - Always First):** Research Phase (~2,000 tokens)
432433- **ALWAYS load BEFORE analysis**: [references/tier-0/research-phase.md](references/tier-0/research-phase.md)
434- Contains: Technology detection matrix, MCP query templates, "Build Truth Context" workflow
435- Purpose: Query MCP servers to understand current patterns BEFORE making any claims
436- **This tier is NOT optional** - skip only if code is purely internal with no external dependencies
437438**Tier 1 (Always Applied):** Universal checks in this file (~4,500 tokens)
439440- Sections 1.1-1.12: Design, Logic, Security, Concurrency, Performance, Readability, Testing, Error Handling, Documentation, Cross-Platform, Anti-Duplication, Style
441- Sections 1.25-1.29: Clean Code (Names, Functions, Comments, Conditionals, Code Smells)
442- Section 1.30: Reference Integrity - [references/tier-1/reference-integrity.md](references/tier-1/reference-integrity.md) (when renames/deletions detected)
443- Section 1.31: Breaking Changes - [references/tier-1/breaking-changes.md](references/tier-1/breaking-changes.md) (for public API changes)
444- Sections 1.33-1.36: Git History Context - [references/tier-1/git-history-context.md](references/tier-1/git-history-context.md) (thorough/strict profiles, ~1,500 tokens)
445446**Tier 2 (File-Type Triggered):** Load based on file extensions
447448| Files | Load Reference |
449| --- | --- |
450| .tsx, .jsx, .vue, .svelte | [references/tier-2/frontend-checks.md](references/tier-2/frontend-checks.md) |
451| .py, .java, .cs, .go, .rb | [references/tier-2/backend-checks.md](references/tier-2/backend-checks.md) |
452| .swift, .kt, .dart | [references/tier-2/mobile-checks.md](references/tier-2/mobile-checks.md) |
453| .sql, migrations/* | [references/tier-2/database-checks.md](references/tier-2/database-checks.md) |
454| .yaml, .json, .env, .toml | [references/tier-2/config-checks.md](references/tier-2/config-checks.md) |
455| Dockerfile, *.tf, k8s/* | [references/tier-2/infrastructure-checks.md](references/tier-2/infrastructure-checks.md) |
456| .ipynb, model/*, ml/* | [references/tier-2/ai-ml-checks.md](references/tier-2/ai-ml-checks.md) |
457458**Tier 3 (Content-Pattern Triggered):** Load when code contains specific patterns
459460| Pattern Keywords | Load Reference |
461| --- | --- |
462| auth, crypto, password, secret, token, jwt | [references/tier-3/security-patterns.md](references/tier-3/security-patterns.md) |
463| async, await, thread, lock, mutex, concurrent | [references/tier-3/concurrency-patterns.md](references/tier-3/concurrency-patterns.md) |
464| route, endpoint, @app, @Get, @Post, api/ | [references/tier-3/api-patterns.md](references/tier-3/api-patterns.md) |
465| PII, email, user, customer, gdpr, consent | [references/tier-3/privacy-patterns.md](references/tier-3/privacy-patterns.md) |
466467**Clean Code Deep-Dives:** Load for detailed guidance
468469- [references/clean-code/naming-functions.md](references/clean-code/naming-functions.md) - Full naming and function principles
470- [references/clean-code/code-smells.md](references/clean-code/code-smells.md) - Complete code smell catalog
471- [references/clean-code/refactoring-patterns.md](references/clean-code/refactoring-patterns.md) - Refactoring techniques
472473**Tier 4 (Repository-Specific):** Load when repo config or CLAUDE.md exists
474475| Context | Load Reference |
476| --- | --- |
477| .claude/code-review.md exists | [references/tier-4/repo-config.md](references/tier-4/repo-config.md) |
478| CLAUDE.md exists (always) | [references/tier-4/claude-md-core.md](references/tier-4/claude-md-core.md) |
479| *.md files | [references/tier-4/documentation-rules.md](references/tier-4/documentation-rules.md) |
480| Duplication indicators | [references/tier-4/anti-duplication-rules.md](references/tier-4/anti-duplication-rules.md) |
481| Path patterns detected | [references/tier-4/path-rules.md](references/tier-4/path-rules.md) |
482| *-{platform}.md files | [references/tier-4/platform-rules.md](references/tier-4/platform-rules.md) |
483| .claude/skills/** | [references/tier-4/skill-rules.md](references/tier-4/skill-rules.md) |
484| .claude/memory/** | [references/tier-4/memory-rules.md](references/tier-4/memory-rules.md) |
485| .claude/temp/** | [references/tier-4/temp-file-rules.md](references/tier-4/temp-file-rules.md) |
486| Profile thorough/strict | [references/tier-4/pattern-compliance.md](references/tier-4/pattern-compliance.md) |
487488**Tier 4b (Claude Code Components):** Delegate to specialized auditors when CC files detected
489490| File Pattern | Component Type | Auditor Agent |
491| --- | --- | --- |
492| `.claude/agents/**/*.md`, `agents/*.md` | Agent | `claude-ecosystem:agent-auditor` |
493| `.claude/commands/**/*.md`, `commands/*.md` | Command | `claude-ecosystem:command-auditor` |
494| `.claude/hooks/**`, `hooks.json` | Hook | `claude-ecosystem:hook-auditor` |
495| `.claude/skills/**` | Skill | `claude-ecosystem:skill-auditor` |
496| `CLAUDE.md`, `.claude/memory/**` | Memory | `claude-ecosystem:memory-component-auditor` |
497| `output-styles/*.md` | Output Style | `claude-ecosystem:output-style-auditor` |
498| `.mcp.json`, `mcp.json` | MCP Config | `claude-ecosystem:mcp-auditor` |
499| `settings.json`, `.claude/settings.json` | Settings | `claude-ecosystem:settings-auditor` |
500| `plugin.json`, `.claude-plugin/**` | Plugin | `claude-ecosystem:plugin-component-auditor` |
501| Status line scripts | Status Line | `claude-ecosystem:statusline-auditor` |
502503Load the reference for complete detection and delegation patterns: [references/tier-4/claude-code-components.md](references/tier-4/claude-code-components.md)
504505**Note**: Tier 4b requires the `claude-ecosystem` plugin to be installed. If not installed, log a warning and skip CC-specific validation (continue with standard review).
506507> **Auditor Agent Verification:** Agent names may change between plugin releases. Run `/claude-ecosystem:list-skills`
508> to verify current auditor agent names if delegation fails. The table above reflects known agents as of this file's last update.
509510**Tier 5 (Generated Content & MCP Validation Details):** Load based on changeset characteristics
511512| Trigger | Load Reference |
513| --- | --- |
514| Large changeset (50+ files) | [references/tier-5/generated-content-detection.md](references/tier-5/generated-content-detection.md) |
515| Generation markers found | [references/tier-5/generated-content-detection.md](references/tier-5/generated-content-detection.md) |
516| Need advanced MCP query patterns | [references/tier-5/mcp-validation.md](references/tier-5/mcp-validation.md) |
517| Complex technology stack | [references/tier-5/mcp-validation.md](references/tier-5/mcp-validation.md) |
518| Security patterns require OWASP validation | [references/tier-5/mcp-validation.md](references/tier-5/mcp-validation.md) |
519520**Note:** Primary MCP validation happens in **Tier 0 (Research Phase)** which is MANDATORY. Tier 5 `mcp-validation.md` provides additional query templates and advanced patterns for complex scenarios.
521522**Token Budget Estimates:**
523524| Scenario | Tokens |
525| --- | --- |
526| Tier 0 Research Phase (MANDATORY) | ~2,000 (always included) |
527| Simple Python file | ~8,500 (Tier 0 + Hub + backend) |
528| React component | ~8,000 (Tier 0 + Hub + frontend) |
529| Auth service | ~10,000 (Tier 0 + Hub + backend + security) |
530| Full-stack PR | ~11,500 (Tier 0 + Hub + frontend + backend + API) |
531| Documentation file (CLAUDE.md repo) | ~8,500 (Tier 0 + Hub + core-rules + documentation-rules) |
532| Skill modification | ~8,000 (Tier 0 + Hub + core-rules + skill-rules) |
533| Memory file update | ~7,500 (Tier 0 + Hub + core-rules + memory-rules) |
534| With advanced MCP patterns | +~1,200 tokens (Tier 5 mcp-validation.md) |
535| With CC auditor delegation | +~1,500 tokens (Tier 4b reference + auditor spawn overhead) |
536| With generated content detection | +~1,200 tokens (Tier 5 generated-content-detection.md) |
537| With git history context (thorough/strict) | +~1,500 tokens (Tier 1 git-history-context.md) |
538539**Note:** Token budgets increased by ~2,000 tokens due to MANDATORY Tier 0 Research Phase. This trade-off provides significantly more accurate reviews through MCP validation.
540541## Layer 1: Universal Code Review Checklist
542543These checks apply to ANY codebase, ANY language.
544545### 1.1 Design and Architecture
546547- [ ] **Overall design makes sense** - Interactions between components are logical
548- [ ] **Belongs in this codebase** - Not better suited for a library or different module
549- [ ] **Integrates well** - Fits with existing system architecture
550- [ ] **Right time for this change** - Not premature or addressing wrong problem
551- [ ] **No over-engineering** - Solves current problem, not speculative future needs (YAGNI)
552553**SOLID Principles:**
554555- [ ] **Single Responsibility (SRP)** - Each class/function has ONE reason to change
556- [ ] **Open-Closed (OCP)** - Open for extension, closed for modification (no repeated if/else for types)
557- [ ] **Liskov Substitution (LSP)** - Derived classes substitutable for base (no explicit type casting)
558- [ ] **Interface Segregation (ISP)** - Clients depend only on methods they use
559- [ ] **Dependency Inversion (DIP)** - Depend on abstractions, not concrete implementations
560561### 1.2 Functionality and Logic
562563- [ ] **Does what it's supposed to do** - Implements intended functionality
564- [ ] **Good for users** - Both end-users AND developers who'll use this code
565- [ ] **Edge cases handled** - Boundary conditions, empty inputs, nulls
566- [ ] **Error handling robust** - Failures handled gracefully with actionable messages
567- [ ] **No logic errors** - Off-by-one, wrong operators, incorrect conditions
568569### 1.3 Security (OWASP-Based)
570571- [ ] **Input validation** - All inputs validated server-side (allowlist, not blocklist)
572- [ ] **Output encoding** - Context-appropriate encoding (HTML, JS, SQL, URL)
573- [ ] **No injection vulnerabilities** - SQL, command, XSS, path traversal
574- [ ] **Authentication correct** - Login via POST, secure session handling, MFA where appropriate
575- [ ] **Authorization enforced** - Role-based access, principle of least privilege
576- [ ] **Secrets not hardcoded** - No API keys, passwords, tokens in code
577- [ ] **Secrets not logged** - No sensitive data in logs, error messages, URLs
578- [ ] **Cryptography modern** - bcrypt/Argon2 for passwords, AES-GCM for encryption, no MD5/SHA1
579- [ ] **Dependencies secure** - No known vulnerabilities in third-party libraries
580581### 1.4 Concurrency and Thread Safety
582583- [ ] **Shared state protected** - Proper locks, mutexes, or atomics for shared data
584- [ ] **No race conditions** - Concurrent access patterns analyzed
585- [ ] **Consistent lock ordering** - Locks acquired in same order to prevent deadlocks
586- [ ] **No circular dependencies** - Between resources protected by different locks
587- [ ] **Async patterns correct** - Await used properly, exceptions propagated
588- [ ] **Thread-safe collections** - Concurrent collections used where needed
589- [ ] **No deadlock potential** - Timeout mechanisms, no indefinite waits while holding locks
590591### 1.5 Performance and Efficiency
592593- [ ] **No unnecessary operations** - Efficient algorithms, no redundant work
594- [ ] **Appropriate data structures** - Right choice for access patterns
595- [ ] **No N+1 queries** - Database queries optimized
596- [ ] **Memory efficient** - No leaks, appropriate caching
597- [ ] **I/O optimized** - Async for I/O-bound, batching where appropriate
598- [ ] **No blocking in async** - Sync operations not blocking async contexts
599600### 1.6 Complexity and Readability
601602- [ ] **Not more complex than needed** - Can be understood quickly
603- [ ] **Functions/classes reasonable size** - Single responsibility, not too long
604- [ ] **No deep nesting** - Max 3-4 levels of indentation
605- [ ] **Clear naming** - Names fully communicate purpose without being too long
606- [ ] **Comments explain WHY** - Not what (code should be self-documenting)
607- [ ] **No code duplication** - DRY principle followed
608609### 1.7 Testing
610611- [ ] **Tests included** - Unit/integration tests appropriate for change
612- [ ] **Tests are correct** - Actually test what they claim to test
613- [ ] **Tests are useful** - Will fail when code breaks
614- [ ] **Edge cases tested** - Boundary conditions, error scenarios
615- [ ] **Tests maintainable** - Not overly complex, clear assertions
616- [ ] **No flaky tests** - Deterministic, not timing-dependent
617618**Test Smell Detection:**
619620Review test code for common test smells that reduce test quality and maintainability:
621622| Smell | Detection | Severity | Why It Matters |
623| --- | --- | --- | --- |
624| **Empty Test** | Test method with no assertions | CRITICAL | False confidence - test always passes |
625| **Eager Test** | > 5 assertions in one test | WARNING | When it fails, unclear which behavior broke |
626| **Mystery Guest** | External file/network access without mock | MAJOR | Flaky, slow, environment-dependent |
627| **Assertion Roulette** | Multiple asserts without descriptive messages | MINOR | Hard to identify which assertion failed |
628| **Sleep in Test** | `Thread.Sleep`, `await Task.Delay`, `setTimeout` | MAJOR | Slow, flaky, hides timing bugs |
629| **Dead Test** | Test that never fails (always passes) | WARNING | Usually tests nothing meaningful |
630| **Commented Test** | Disabled test cases (`[Ignore]`, `skip`, `xtest`) | WARNING | Technical debt, may hide real issues |
631| **Test Code Duplication** | Same setup/teardown in multiple tests | MINOR | Maintenance burden, use fixtures |
632633**Example Findings:**
634635```markdown
636### Test Smell: Eager Test
637638**File**: `tests/UserService.test.ts:45`
639**Severity**: WARNING
640**Confidence**: MEDIUM
641642**Problem**: Test "should handle user operations" has 12 assertions testing multiple behaviors.
643644**Impact**: When this test fails, you won't know which behavior broke without debugging.
645646**Suggested Fix**:
647```typescript
648// Before (Eager Test - 12 assertions, multiple behaviors)
649test('should handle user operations', () => {
650 const user = createUser();
651 expect(user.name).toBe('John');
652 expect(user.email).toContain('@');
653 // ... 10 more assertions about different behaviors
654});
655656// After (Focused Tests - one behavior each)
657test('should create user with valid name', () => {
658 const user = createUser();
659 expect(user.name).toBe('John');
660});
661662test('should validate email format', () => {
663 const user = createUser();
664 expect(user.email).toContain('@');
665});
666```
667668```text
669670```markdown
671### Test Smell: Sleep in Test
672673**File**: `tests/api.test.ts:78`
674**Severity**: MAJOR
675**Confidence**: HIGH
676677**Problem**: Test uses `await new Promise(r => setTimeout(r, 2000))` to wait for async operation.
678679**Impact**: Test is slow (2 seconds), flaky (timing varies), and hides real async handling bugs.
680681**Suggested Fix**:
682```typescript
683// Before (Sleep - slow and flaky)
684await new Promise(r => setTimeout(r, 2000));
685expect(result).toBeDefined();
686687// After (Proper async handling)
688await waitFor(() => expect(result).toBeDefined());
689// Or
690await expect(asyncOperation()).resolves.toBeDefined();
691```
692693```text
694695### 1.8 Error Handling and Logging
696697- [ ] **Errors caught appropriately** - Right level of granularity
698- [ ] **Error messages actionable** - Clear what went wrong and how to fix
699- [ ] **Logging present** - For debugging and troubleshooting
700- [ ] **No sensitive data in logs** - PII, passwords, keys excluded
701- [ ] **Graceful degradation** - Partial failures don't crash entire system
702703### 1.9 Documentation
704705- [ ] **Code documented** - Public APIs, complex logic explained
706- [ ] **README updated** - If behavior/setup changes
707- [ ] **API docs updated** - If endpoints change
708- [ ] **Inline comments where needed** - For non-obvious decisions
709710### 1.10 Cross-Platform Compatibility
711712- [ ] **No hardcoded platform paths**:
713 - `/mnt/c/Users/...` (WSL)
714 - `/c/Users/...` (Git Bash)
715 - `C:\Users\...` (Windows)
716 - `/home/username/...` (Linux)
717 - `/Users/username/...` (macOS)
718- [ ] **Portable tool detection** - `command -v tool` not path hunting
719- [ ] **Platform fallbacks** - Graceful handling when features unavailable
720- [ ] **Scripts self-locate** - Use `Path(__file__).resolve()`, `$PSScriptRoot`, `${BASH_SOURCE[0]}`
721722### 1.11 Anti-Duplication
723724- [ ] **No duplicate content** - Same info in ONE place only
725- [ ] **No identical files** - `diff` similar files to verify
726- [ ] **Single source of truth** - Link instead of copy-paste
727- [ ] **Config files distinct** - Each serves different purpose
728729### 1.12 Style and Consistency
730731- [ ] **Follows style guide** - Language/project conventions
732- [ ] **Consistent with codebase** - Matches existing patterns
733- [ ] **No style changes mixed with logic** - Separate formatting PRs
734735### 1.13 Accessibility (WCAG 2.1 AA)
736737- [ ] **Alt text present** - All images have descriptive alt text; decorative images use `alt=""`
738- [ ] **Color contrast sufficient** - 4.5:1 for text, 3:1 for UI components
739- [ ] **Keyboard navigable** - All interactive elements via Tab/Enter/Space; no keyboard traps
740- [ ] **Focus visible** - Clear focus indicators on all interactive elements
741- [ ] **Semantic HTML** - Proper heading hierarchy; buttons not divs; links not spans
742- [ ] **ARIA correct** - Used only when semantic HTML insufficient; no conflicting roles
743744### 1.14 Internationalization (i18n)
745746- [ ] **No hardcoded strings** - All user-facing text externalized to resource files
747- [ ] **Locale-aware formatting** - Dates, numbers, currency use locale APIs
748- [ ] **RTL consideration** - Logical CSS properties where applicable
749- [ ] **No string concatenation** - Use parameterized messages, not `"Hello " + name`
750- [ ] **Pluralization handled** - Proper plural rules, not `count + " items"`
751752### 1.15 Observability
753754- [ ] **Structured logging** - JSON format with trace IDs, timestamps, context
755- [ ] **Metrics present** - Latency, error rates, throughput for critical paths
756- [ ] **Trace context propagated** - Distributed tracing across service boundaries
757- [ ] **Health checks implemented** - Liveness/readiness probes with dependency checks
758- [ ] **SLOs defined** - Measurable service level objectives for key operations
759760### 1.16 Data Privacy (GDPR/CCPA)
761762- [ ] **PII identified and protected** - Personal data encrypted, access controlled
763- [ ] **Data retention enforced** - Clear policies, automated cleanup
764- [ ] **Right to deletion** - Complete erasure across all systems possible
765- [ ] **Consent tracked** - Explicit opt-in with audit trail
766- [ ] **No PII in logs** - Redaction or hashing of personal identifiers
767768### 1.17 API Design
769770- [ ] **Versioning strategy** - Clear version in URL, header, or media type
771- [ ] **Backward compatible** - New fields nullable, no removed fields
772- [ ] **Deprecation documented** - Sunset dates, migration paths
773- [ ] **Consistent naming** - Follows REST/GraphQL conventions
774- [ ] **Error responses standardized** - Consistent error format across endpoints
775776### 1.18 Dependency Management
777778- [ ] **No known vulnerabilities** - CVE scanning in CI/CD
779- [ ] **License compliance** - No GPL conflicts with proprietary code
780- [ ] **Version pinned** - Lockfiles present and up-to-date
781- [ ] **Transitive deps reviewed** - Indirect dependencies also secure
782- [ ] **SBOM available** - Software Bill of Materials for audits
783784### 1.19 Database Patterns
785786- [ ] **N+1 queries avoided** - Eager loading or batch queries used
787- [ ] **Indexes present** - For foreign keys, join columns, query patterns
788- [ ] **Migrations backward compatible** - Incremental changes, no data loss
789- [ ] **Schema properly normalized** - Or denormalized with clear rationale
790- [ ] **Query optimization** - Explain plans reviewed for complex queries
791792### 1.20 Configuration Management
793794- [ ] **Secrets in vault** - Never hardcoded, use env vars or secrets manager
795- [ ] **Feature flags used** - For gradual rollouts, A/B testing
796- [ ] **12-factor compliant** - Config via environment, not files
797- [ ] **Validation at startup** - Fail fast on missing/invalid config
798- [ ] **Environment parity** - Same config structure across dev/staging/prod
799800### 1.21 Cloud/Infrastructure (12-Factor)
801802- [ ] **Stateless processes** - No local session storage, use external stores
803- [ ] **Port binding** - Self-contained, exports HTTP via port
804- [ ] **Disposability** - Fast startup, graceful SIGTERM shutdown
805- [ ] **Dev/prod parity** - Minimal gap between environments
806- [ ] **Container best practices** - Multi-stage builds, non-root user, resource limits
807- [ ] **IaC used** - Terraform/CloudFormation for reproducibility
808809### 1.22 Frontend Patterns
810811- [ ] **Component design** - Small, reusable, composition over inheritance
812- [ ] **State management** - Appropriate tool (local, context, Zustand, Redux)
813- [ ] **Bundle size** - Code splitting, lazy loading, < 500KB main bundle
814- [ ] **Memoization** - Strategic use of memo/useMemo/useCallback
815- [ ] **Web Vitals** - LCP < 2.5s, FID < 100ms, CLS < 0.1
816817### 1.23 Mobile Patterns
818819- [ ] **Battery efficient** - WorkManager/JobScheduler, batched operations
820- [ ] **Offline-first** - Local caching with sync, offline queue
821- [ ] **Responsive layout** - Flexible dimensions (dp/sp), rotation handling
822- [ ] **Memory efficient** - Image downsampling, lifecycle awareness
823- [ ] **Network efficient** - Request batching, compression, exponential backoff
824825### 1.24 AI/ML Code Patterns
826827- [ ] **Model versioning** - MLflow/DVC for models and data
828- [ ] **Reproducibility** - Random seeds, pinned dependencies, exact environments
829- [ ] **Bias detection** - Fairness metrics across demographics
830- [ ] **Data pipeline validated** - Schema validation, statistical tests
831- [ ] **Model monitoring** - Drift detection for data and performance
832833### 1.25 Clean Code: Names (Robert C. Martin)
834835- [ ] **Intention-revealing names** - Name tells you why it exists, what it does, how it's used
836- [ ] **No misleading names** - `accountList` should actually be a list; avoid false clues
837- [ ] **Meaningful distinctions** - Not `data1`, `data2`, `dataInfo`, `theData`
838- [ ] **Pronounceable names** - Can discuss code verbally without spelling variables
839- [ ] **Searchable names** - Single-letter names only for small local scope
840- [ ] **No encodings** - No Hungarian notation, no type prefixes (strName, intCount)
841- [ ] **No mental mapping** - Reader shouldn't translate names to concepts they know
842- [ ] **Class names are nouns** - Customer, Account, Parser (not verbs)
843- [ ] **Method names are verbs** - postPayment, deletePage, save (not nouns)
844845### 1.26 Clean Code: Functions (Robert C. Martin)
846847- [ ] **Small** - 5-20 lines ideal; rarely exceed 30 lines
848- [ ] **Do one thing** - Single level of abstraction; one reason to change
849- [ ] **One abstraction level** - Don't mix getHtml() with .append("\n")
850- [ ] **Descriptive names** - Long descriptive name better than short enigmatic one
851- [ ] **Few arguments** - Zero ideal, one/two good, three questionable, never more than four
852- [ ] **No flag arguments** - Split function into two instead of passing boolean
853- [ ] **No side effects** - Don't modify unexpected state; function does what name says only
854- [ ] **Command/Query separation** - Either do something OR answer something, never both
855- [ ] **Prefer exceptions to error codes** - Don't return -1 or null for errors
856- [ ] **Extract try/catch blocks** - Bodies of try/catch should be one-line function calls
857858### 1.27 Clean Code: Comments (Robert C. Martin)
859860- [ ] **Code explains itself first** - If you need a comment, try rewriting the code
861- [ ] **Comments explain WHY** - Not what (code shows what) or how (code shows how)
862- [ ] **Legal comments acceptable** - Copyright, license headers
863- [ ] **Informative comments acceptable** - Regex explanation, return value meaning
864- [ ] **TODO comments have tickets** - `// TODO: TICKET-123 - refactor after API v2`
865- [ ] **No redundant comments** - `// Constructor` above a constructor is noise
866- [ ] **No commented-out code** - Delete it; version control remembers
867- [
868869…(truncated)
Run npx skillmds add majiayu000/code-reviewing in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Performs systematic code review with universal best practices and repo-specific standards. Auto-activates after significant code changes. Use when reviewing code, auditing files, checking PRs, examining staged changes, or when asked to "review", "check", "audit", or "examine" code. Enforces design principles (SOLID, DRY, KISS), security (OWASP), performance, concurrency safety, cross-platform compatibility, and codebase patterns. It is listed under Security on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Capability flags: makes network calls, reads secrets. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
majiayu000 (@majiayu000) published this skill. Their other Agent Skills are listed on their SkillMD profile.