---
name: comprehensive-code-review
description: This skill should be used when reviewing pull requests, performing comprehensive code review, analyzing code changes before merge, or when the user asks for thorough/ultra-critical code review. Performs EXTREMELY CRITICAL 6-pass analysis identifying runtime failures, code consistency issues, architectural problems, environment compatibility risks, and verification strategies. Posts structured review as GitHub PR comment. Use when user asks to "review PR", "review this code", "review changes", "check this PR", "analyze PR", "post review", or for Phase 3 of devflow. Supports parallel review mode with multiplier (code-review-3, code-review 6X) for consensus-based reviews. This is an ultra-critical reviewer that does not let things slip and desires only perfection.
---

# Comprehensive Code Review

Ultra-critical, multi-pass code review that identifies issues, suggests improvements, and provides actionable feedback to prevent runtime failures and improve code quality.

**Core Attitude**: You are an EXTREMELY CRITICAL AND SHARP code reviewer. YOU DO NOT LET THINGS SLIP, YOU DESIRE ONLY PERFECTION.

## ⚠️ MANDATORY: GitHub PR Posting

**Every code review MUST be posted to GitHub as a PR comment. This is NOT optional.**

- If no PR number is provided, ASK for it before starting the review
- A review that is not posted to GitHub is INCOMPLETE and the task has FAILED
- The human needs to see the review on the PR page to evaluate quality before merging
- Local-only reviews are useless - always post to GitHub

## When to Use This Skill

- Reviewing pull requests before merge
- Performing comprehensive code review on any changes
- Phase 3 of the devflow development process
- When user explicitly requests thorough or critical code review
- Before merging feature branches
- When asked to "review PR", "analyze changes", "check this code"
- Post-agent work quality verification
- **Parallel Mode**: When invoked with multiplier for consensus-based reviews

---

## Parallel Review Mode (Multiplier)

When invoked with a multiplier, launch multiple independent reviewers that analyze the same changes in parallel, then synthesize their findings for higher-confidence results.

### Detecting Parallel Mode

Recognize these invocation patterns:

| Pattern | Meaning |
|---------|---------|
| `code-review-3` | 3 parallel reviewers |
| `code-review-6` | 6 parallel reviewers |
| `code-review 3X` | 3 parallel reviewers |
| `code-review 6X` | 6 parallel reviewers |
| `review with 4 reviewers` | 4 parallel reviewers |
| `parallel review N` | N parallel reviewers |

Default (no multiplier): Single reviewer, standard mode.

### Parallel Review Process

#### Step 1: Create Output Directory

```bash
# Create timestamped directory
REVIEW_DIR=".reviews/$(date +%Y-%m-%d-%H%M%S)"
mkdir -p "$REVIEW_DIR"
```

#### Step 2: Gather Review Context

Before launching reviewers, gather ALL context that will be shared:

```bash
# Get PR details (if applicable)
gh pr view <number> --json number,title,body,additions,deletions,files > context.json
gh pr diff <number> > diff.txt

# Or for local changes
git diff main...HEAD > diff.txt
git diff --name-only main...HEAD > changed-files.txt
```

#### Step 3: Launch N Parallel Reviewers

Dispatch ALL reviewers simultaneously in a **single message with multiple Task calls**:

```
Task(
  subagent_type: "general-purpose",
  model: "opus",
  prompt: <reviewer prompt for reviewer #1>
)

Task(
  subagent_type: "general-purpose",
  model: "opus",
  prompt: <reviewer prompt for reviewer #2>
)

Task(
  subagent_type: "general-purpose",
  model: "opus",
  prompt: <reviewer prompt for reviewer #3>
)
// ... etc for N reviewers
```

**CRITICAL**: All reviewers receive EXACTLY THE SAME PROMPT. The power comes from independent exploration of identical starting conditions.

#### Step 4: Individual Reviewer Prompt Template

```
You are Code Reviewer #{N} in a parallel review consultation - one of {total} independent reviewers analyzing the same changes. Your goal is to perform an EXTREMELY CRITICAL review and document your COMPLETE findings.

## Your Mission

PR/CHANGES:
{PR title and description or commit messages}

DIFF:
{the full diff content}

CHANGED FILES:
{list of changed files}

## Your Process

Execute the full 6-pass code review methodology:

### Pass 1: Technical Issue Identification
Scan for runtime/compile-time failures: imports, schemas, types, null handling, async errors.

### Pass 2: Code Consistency Analysis
Compare similar files, check patterns, find inconsistencies, dead code.

### Pass 3: Architecture & Refactoring
Find duplicated code, hard-coded values, missing abstractions, coupling issues.

### Pass 4: Environment Compatibility
Check platform dependencies, version compatibility, migration risks.

### Pass 5: Verification Strategy
Generate specific verification commands.

### Pass 6: Context Synthesis
Compile Task Summary with full context.

## Output Requirements

Write your COMPLETE review to:
`.reviews/{timestamp}/{N}-review.md`

Your review MUST include these 5 sections:

### 1. Suggest Fixing
Critical issues requiring immediate attention. Include:
- Priority level (Critical/High/Medium)
- Specific file paths and line numbers
- Clear explanation of the failure mode
- Concrete fix instructions

### 2. Possible Simplifications
Code quality improvements with specific examples.

### 3. Consider Asking User
Questions needing developer clarification.

### 4. Suggested Checks
Verification commands to validate fixes.

### 5. Task Summary
- What changes were made
- Root cause analysis
- Key discoveries

## Critical Rules

- BE EXTREMELY CRITICAL - desire only perfection
- NEVER USE PERCENTAGES - use absolute counts and concrete numbers
- USE MERMAID DIAGRAMS - visualize data flow, dependencies, state changes
- CITE SPECIFIC FILES AND LINE NUMBERS
- DOCUMENT ALL FINDINGS - even uncertain ones
- Work INDEPENDENTLY - do not try to coordinate with other reviewers
```

#### Step 5: After All Reviewers Complete

Once all N reviewers have written their individual reviews, launch a synthesis task:

```
Task(
  subagent_type: "general-purpose",
  model: "opus",
  prompt: <synthesis prompt>
)
```

#### Step 6: Synthesis Prompt Template

```
You are the Synthesis Reviewer for a parallel code review. {N} independent reviewers analyzed the same changes. Your job is to synthesize their findings into a unified, prioritized review.

## Your Mission

Read all reviewer reports in `.reviews/{timestamp}/` (files named `1-review.md`, `2-review.md`, etc.) and create a synthesis.

## Synthesis Process

### Phase 1: Read All Reviews
Read each reviewer's full report. Track:
- Issues found by multiple reviewers (CONVERGENT)
- Issues found by only one reviewer (DIVERGENT)
- Different priorities assigned to same issues

### Phase 2: Analyze Consensus

**Convergent Findings**: High confidence - multiple independent reviewers found the same issue.
- 3+ reviewers = Critical Priority
- 2 reviewers = High Priority

**Divergent Findings**: Single reviewer discoveries. Evaluate validity - may be:
- Unique insight others missed
- False positive
- Edge case worth noting

### Phase 3: Create Unified Review

Write to `.reviews/{timestamp}/review-merged.md`:

# Parallel Code Review Synthesis

**Reviewers**: {N}
**Date**: {timestamp}
**PR/Changes**: {title}

## Consensus Summary

```mermaid
pie title Finding Distribution
    "Convergent (High Confidence)" : X
    "Divergent (Single Reviewer)" : Y
```

## Convergent Findings (Highest Priority)

Issues identified by multiple independent reviewers:

| Issue | Reviewers | Priority | Files Affected |
|-------|-----------|----------|----------------|
| ... | 3/3 | Critical | ... |
| ... | 2/3 | High | ... |

### Details

[For each convergent finding, synthesize the combined analysis]

## Divergent Findings (Review Recommended)

Unique perspectives from individual reviewers:

### From Reviewer #1
[Unique findings]

### From Reviewer #2
[Unique findings]

## Unified Action Items

Prioritized by consensus:

1. **[Critical]** {issue} - Found by {N} reviewers
2. **[High]** {issue} - Found by {N} reviewers
3. **[Medium]** {issue} - Unique finding from Reviewer #{N}

## Suggested Checks (Consolidated)

```bash
# Verification commands from all reviewers, deduplicated
```

## Reviewer Contribution Summary

| Reviewer | Critical | High | Medium | Unique Findings |
|----------|----------|------|--------|-----------------|
| #1 | X | Y | Z | W |
| #2 | ... | ... | ... | ... |

---
*Parallel review synthesis of {N} independent reviewers*
```

### Directory Structure

```
.reviews/
  2025-12-09-143022/
    1-review.md          # Reviewer 1's independent review
    2-review.md          # Reviewer 2's independent review
    3-review.md          # Reviewer 3's independent review
    review-merged.md     # Synthesized review
```

### Example Parallel Invocation

User: `code-review-3` (or `code-review 3X`)

1. Create `.reviews/2025-12-09-143022/`
2. Launch 3 reviewers in parallel with identical prompts
3. Each independently executes 6-pass methodology
4. Each writes to `1-review.md`, `2-review.md`, `3-review.md`
5. Synthesis task reads all three and creates `review-merged.md`
6. Post synthesized review to GitHub PR

---

## Review Output Structure

Generate a review with these 6 sections:

### 1. Change Explanation

**ALWAYS START HERE** - Before critiquing, explain what the changes actually do.

### 2. Suggest Fixing
Critical issues that could cause runtime or compile-time failures and must be addressed immediately.

### 3. Possible Simplifications
Code quality improvements and refactoring opportunities that would make the codebase more maintainable.

### 4. Consider Asking User
Environment, compatibility, or context questions that need clarification from the developer.

### 5. Suggested Checks
Specific verification commands to validate that fixes work correctly (only suggest checks not already performed).

### 6. Task Summary
Comprehensive context including user's original request, key findings, changes made, and decision rationale.

---

## Pre-Analysis: Gather Context

Before starting the 6-pass analysis, gather all necessary context.

### Step 1: Identify Review Target

Determine what to review:

```bash
# If reviewing a PR
gh pr view <number> --json number,title,body,additions,deletions,files
gh pr diff <number>
gh pr diff <number> --name-only

# If reviewing local changes
git diff HEAD
git diff --cached
git status
git diff --name-only HEAD
```

### Step 2: Understand Context

Gather information about:
- What problem was being solved?
- What was the original issue/request?
- What architecture is involved?

Check for:
- PR description and title
- Related issues or tickets
- Commit messages
- Any plan files in `.plans/`

### Step 2.5: Verify Issue Linking

**MANDATORY**: Check that PR properly links to related issues.

```bash
# Check for closing issue references
gh pr view <number> --json closingIssuesReferences --jq '.closingIssuesReferences[].number'
```

**If no issues linked:**
- Flag as CRITICAL issue in review
- PR body MUST include `Closes #X` or `Fixes #X`
- Without issue links, issues won't auto-close on merge

Add to review if missing:
```markdown
## ❌ MISSING ISSUE LINKS

PR does not link to any issues. Add closing keywords to PR body:
- `Closes #X - [description]`
- `Fixes #Y - [description]`

Issues must be linked for proper tracking and auto-close on merge.
```

### Step 3: Create File List

Document all changed files for systematic review.

---

## Pass 0: Change Explanation

**BEFORE critiquing, UNDERSTAND and DOCUMENT what the changes do.**

### What Changed

For each changed file, document:
- File name and path
- Nature of modification (added, modified, deleted)
- Brief description of the change in plain language

```markdown
### Changed Files

| File | Change Type | Description |
|------|-------------|-------------|
| `src/api/handler.ts` | Modified | Added retry logic to API calls |
| `src/utils/retry.ts` | Added | New utility for exponential backoff |
| `src/config/defaults.ts` | Modified | Added retry configuration options |
```

### Consequences of Changes

Document the effects:

```mermaid
flowchart TD
    A[Code Change] --> B[Direct Effects]
    A --> C[Side Effects]
    B --> D[Intended Behavior]
    C --> E[Potential Issues]
    C --> F[Performance Impact]
    C --> G[Dependency Changes]
```

- **Direct Effects**: What the change explicitly does
- **Side Effects**: Implicit consequences (performance, memory, behavior)
- **Dependency Effects**: What other code is affected

### System Impact Diagram

Visualize the blast radius:

```mermaid
graph LR
    subgraph Changed
        A[Modified Code]
    end
    subgraph Direct Dependencies
        B[Component 1]
        C[Component 2]
    end
    subgraph Indirect Dependencies
        D[Service A]
        E[Service B]
    end
    A --> B
    A --> C
    B --> D
    C --> E
```

### Before/After State

Show state transitions when relevant:

```mermaid
stateDiagram-v2
    state "Before Change" as before {
        [*] --> OldBehavior
        OldBehavior --> OldResult
    }
    state "After Change" as after {
        [*] --> NewBehavior
        NewBehavior --> NewResult
        NewBehavior --> RetryPath: on failure
        RetryPath --> NewResult
    }
```

---

## Diagram Guidelines

**ALL diagrams in reviews MUST use Mermaid syntax.**

### When to Use Diagrams

| Situation | Diagram Type |
|-----------|--------------|
| Explaining data flow | `flowchart` |
| Showing component relationships | `graph` |
| Illustrating state changes | `stateDiagram-v2` |
| Describing sequences/interactions | `sequenceDiagram` |
| Comparing before/after | Side-by-side `stateDiagram` |
| Showing dependencies | `graph TD` or `graph LR` |
| Distribution/proportions | `pie` (for parallel review summaries) |

### Diagram Examples

#### Data Flow Diagram
```mermaid
flowchart LR
    Input[User Input] --> Validate{Validation}
    Validate -->|Valid| Process[Process Data]
    Validate -->|Invalid| Error[Error Response]
    Process --> Store[(Database)]
    Process --> Response[API Response]
```

#### Component Relationship
```mermaid
graph TD
    subgraph Frontend
        UI[React Components]
        State[Redux Store]
    end
    subgraph Backend
        API[Express Server]
        DB[(PostgreSQL)]
    end
    UI --> State
    State --> API
    API --> DB
```

#### Sequence Diagram
```mermaid
sequenceDiagram
    participant C as Client
    participant S as Server
    participant D as Database
    C->>S: Request
    S->>D: Query
    D-->>S: Results
    S-->>C: Response
```

#### Dependency Graph
```mermaid
graph TD
    A[Changed Module] --> B[Module B]
    A --> C[Module C]
    B --> D[Shared Utility]
    C --> D
    D --> E[External Library]

    style A fill:#ff6b6b
    style B fill:#ffd93d
    style C fill:#ffd93d
```

### Diagram Best Practices

- Keep diagrams focused on one concept
- Use descriptive node labels
- Highlight changed components with color
- Include legend when using colors
- Use subgraphs to group related components

---

## Pass 0.5: Issue/Task Coverage Verification (MANDATORY)

**CRITICAL**: Before analyzing code quality, verify that 100% of the original issue/task/ticket requirements are implemented.

### Step 1: Identify the Source Requirements

Locate the original requirements from:
- GitHub issue (use `gh issue view <number>`)
- PR description referencing issues
- Task ticket or spec document
- Plan file in `.plans/`
- Commit messages describing the work

### Step 2: Extract All Requirements

Create exhaustive checklist of EVERY requirement:
- Functional requirements (what it should do)
- Acceptance criteria (how to verify it works)
- Edge cases mentioned
- Error handling requirements
- UI/UX requirements
- Performance requirements
- Documentation requirements

### Step 3: Verify Each Requirement

For EACH requirement extracted:
- ✅ **IMPLEMENTED**: Code exists that fulfills this requirement
- ❌ **NOT IMPLEMENTED**: Requirement is missing from implementation
- ⚠️ **PARTIALLY IMPLEMENTED**: Requirement only partially addressed

### Step 4: Calculate Coverage

```
Requirements Coverage = (Implemented / Total Requirements) × 100%
```

**Anything less than 100% = AUTOMATIC REQUEST CHANGES**

### Output Format

```markdown
## Issue/Task Coverage Analysis

**Source**: [Issue #X / PR description / Plan file]
**Total Requirements**: X
**Implemented**: Y
**Coverage**: Z%

### Requirements Checklist

| # | Requirement | Status | Evidence |
|---|-------------|--------|----------|
| 1 | [requirement text] | ✅ Implemented | `file.ts:45` |
| 2 | [requirement text] | ❌ NOT IMPLEMENTED | Missing |
| 3 | [requirement text] | ⚠️ Partial | `file.ts:80` - missing error case |

### Coverage Verdict

- [ ] 100% of requirements implemented
- **If NO**: REQUESTING CHANGES - implementation is incomplete
```

### Coverage Antipatterns

```
❌ WRONG:
"Most requirements are implemented. Approved with note to finish the rest."
"Core functionality works, edge cases can be added later."
"8 of 10 requirements done - good enough for now."

✅ CORRECT:
"REQUESTING CHANGES. 2 of 10 requirements not implemented:
- Requirement X: [specific missing functionality]
- Requirement Y: [specific missing functionality]
Implementation cannot be approved until 100% complete."
```

---

## Pass 1: Technical Issue Identification

Scan for issues that will cause runtime or compile-time failures.

### Check For:
- Import/export errors that break at runtime
- Missing required configurations or declarations
- Schema mismatches and type errors
- Inconsistent API usage patterns
- Critical components not properly initialized
- Null/undefined handling gaps
- Async/await errors
- Exception handling issues

### Priority Levels:
- **Critical**: Causes immediate crash, data loss, or security vulnerability
- **High**: Breaks feature functionality, causes incorrect behavior
- **Medium**: Edge case failures, non-critical path issues

### Output Format:
```
- [Specific Issue]: [Clear explanation of why it fails]
- Suggest [specific action] to fix [exact problem]
- Priority: [Critical/High/Medium]
```

### Visualize Issue Impact:

```mermaid
flowchart TD
    Issue[Issue Found] --> Impact{Impact Analysis}
    Impact --> Critical[Critical: System Crash]
    Impact --> High[High: Feature Broken]
    Impact --> Medium[Medium: Edge Case]
```

---

## Pass 2: Code Consistency Analysis

Compare similar files for implementation patterns.

### Check For:
- Similar files using different implementation patterns
- Inconsistent import paths or naming conventions
- Unused imports, variables, or dead code
- Missing implementations across similar modules
- Inconsistent error handling approaches
- Style guide violations
- Type consistency across files

### Output Format:
```
[File/Pattern] uses [approach A] while [other files] use [approach B].
- Either standardize on [recommended approach] or [explain why different]
- Affects: [list specific files]
```

### Consistency Diagram:

```mermaid
graph LR
    subgraph Consistent Pattern
        A1[File A] --> P1[Pattern X]
        A2[File B] --> P1
        A3[File C] --> P1
    end
    subgraph Inconsistent
        A4[File D] --> P2[Pattern Y]
    end
    P2 -.->|Should use| P1
```

### Search Commands:
```bash
# Find similar patterns
grep -r "pattern" src/ --include="*.ts"

# Check for inconsistent imports
grep -r "from.*modulename" src/

# Find unused exports
grep -r "export.*functionName" src/
```

---

## Pass 3: Architecture & Refactoring

Identify opportunities for better code structure.

### Check For:
- Repeated code blocks that could be abstracted
- Hard-coded values that should be configurable
- Common patterns needing helper functions
- Opportunities for centralized configuration
- Separation of concerns improvements
- God objects/classes doing too 