# Ring:requesting Code Review

> Gate 4 of development cycle - dispatches 6 specialized reviewers (code, business-logic, security, test, nil-safety, consequences) in parallel for comprehensive code review feedback.

- Skill: `lerianstudio/ring-requesting-code-review` (Agent Skill)
- Install (CLI): `npx skillmds@latest add lerianstudio/ring-requesting-code-review`
- Raw SKILL.md: https://api.skillmd.com/api/skills/lerianstudio/ring-requesting-code-review/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- License: MIT
- Author: LerianStudio (https://skillmd.com/u/lerianstudio)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/lerianstudio/ring-requesting-code-review

---


# Code Review (Gate 4)

## Overview

Dispatch all six reviewer subagents in **parallel** for fast, comprehensive feedback:

1. **ring:code-reviewer** - Architecture, design patterns, code quality
2. **ring:business-logic-reviewer** - Domain correctness, business rules, edge cases
3. **ring:security-reviewer** - Vulnerabilities, authentication, OWASP risks
4. **ring:test-reviewer** - Test quality, coverage, edge cases, anti-patterns
5. **ring:nil-safety-reviewer** - Nil/null pointer safety for Go and TypeScript
6. **ring:consequences-reviewer** - Ripple effects, caller chain impact, downstream breakage

**Core principle:** All 6 reviewers run simultaneously in a single message with 6 Task tool calls.

## CRITICAL: Role Clarification

**This skill ORCHESTRATES. Reviewer Agents REVIEW.**

| Who | Responsibility |
|-----|----------------|
| **This Skill** | Dispatch reviewers, aggregate findings, track iterations |
| **Reviewer Agents** | Analyze code, report issues with severity |
| **Implementation Agent** | Fix issues found by reviewers |

---

## Step 1: Gather Context (Auto-Detect if Not Provided)

```text
This skill supports TWO modes:
1. WITH INPUTS: Called by any skill/user that provides structured inputs (unit_id, base_sha, etc.)
2. STANDALONE: Called directly without inputs - auto-detects everything from git

FOR EACH INPUT, check if provided OR auto-detect:

1. unit_id:
   IF provided → use it
   ELSE → generate: "review-" + timestamp (e.g., "review-20241222-143052")

2. base_sha:
   IF provided → use it
   ELSE → Execute: git merge-base HEAD main
   IF git fails → Execute: git rev-parse HEAD~10 (fallback to last 10 commits)

3. head_sha:
   IF provided → use it
   ELSE → Execute: git rev-parse HEAD

4. implementation_files:
   IF provided → use it
   ELSE → Execute: git diff --name-only [base_sha] [head_sha]

5. implementation_summary:
   IF provided → use it
   ELSE → Execute: git log --oneline [base_sha]..[head_sha]
   Format as: "Changes: [list of commit messages]"

6. requirements:
   IF provided → use it
   ELSE → Set to: "Infer requirements from code changes and commit messages"
   (Reviewers will analyze code to understand intent)

AFTER AUTO-DETECTION, display context:
┌─────────────────────────────────────────────────────────────────┐
│ 📋 CODE REVIEW CONTEXT                                          │
├─────────────────────────────────────────────────────────────────┤
│ Unit ID: [unit_id]                                              │
│ Base SHA: [base_sha]                                            │
│ Head SHA: [head_sha]                                            │
│ Files Changed: [count] files                                    │
│ Commits: [count] commits                                        │
│                                                                 │
│ Dispatching 6 reviewers in parallel...                          │
└─────────────────────────────────────────────────────────────────┘
```

## Step 2: Initialize Review State

```text
review_state = {
  unit_id: [from input],
  base_sha: [from input],
  head_sha: [from input],
  reviewers: {
    code_reviewer: {verdict: null, issues: []},
    business_logic_reviewer: {verdict: null, issues: []},
    security_reviewer: {verdict: null, issues: []},
    test_reviewer: {verdict: null, issues: []},
    nil_safety_reviewer: {verdict: null, issues: []},
    consequences_reviewer: {verdict: null, issues: []}
  },
  aggregated_issues: {
    critical: [],
    high: [],
    medium: [],
    low: [],
    cosmetic: []
  },
  iterations: 0,
  max_iterations: 3
}
```

## Step 2.5: Run Pre-Analysis Pipeline (MANDATORY)

**MANDATORY:** Run static analysis, AST extraction, and call graph analysis BEFORE dispatching reviewers. This provides critical context that significantly improves review quality.

**Skip Override:** The `skip_preanalysis` parameter allows bypassing this step ONLY when explicitly requested by the user. This is NOT recommended.

### Step 2.5.1: Detect Platform and Find Binary

```bash
# Detect platform
OS=$(uname -s | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case $ARCH in
  x86_64) ARCH="amd64" ;;
  aarch64|arm64) ARCH="arm64" ;;
esac

# Binary search paths (in priority order)
PLUGIN_BIN="${CLAUDE_PLUGIN_ROOT:-}/lib/codereview/bin/${OS}_${ARCH}/run-all"
LOCAL_BIN="./default/lib/codereview/bin/${OS}_${ARCH}/run-all"

# Find binary
BINARY=""
CHECKSUM_FILE=""
if [[ -x "$PLUGIN_BIN" ]]; then
    BINARY="$PLUGIN_BIN"
    CHECKSUM_FILE="${CLAUDE_PLUGIN_ROOT:-}/lib/codereview/bin/${OS}_${ARCH}/CHECKSUMS.sha256"
elif [[ -x "$LOCAL_BIN" ]]; then
    BINARY="$LOCAL_BIN"
    CHECKSUM_FILE="./default/lib/codereview/bin/${OS}_${ARCH}/CHECKSUMS.sha256"
fi
```

### Step 2.5.2: Secure Binary Execution (Security)

```bash
# Secure execution: copy to temp, verify copy, execute copy
# This prevents TOCTOU race conditions by verifying the COPY we execute
secure_execute_binary() {
    local binary="$1"
    local checksum_file="$2"
    shift 2
    local args=("$@")

    # Create secure temporary copy
    local secure_copy=$(mktemp)
    trap "rm -f '$secure_copy'" EXIT

    # Copy binary to secure location
    if ! cp "$binary" "$secure_copy"; then
        echo "✗ Failed to create secure copy"
        return 1
    fi
    chmod 700 "$secure_copy"

    # Verify the COPY (not the original - prevents TOCTOU)
    local binary_name=$(basename "$binary")

    # Check checksum file exists
    if [[ ! -f "$checksum_file" ]]; then
        echo "✗ ERROR: Checksum file required for security verification"
        echo "  Set RING_ALLOW_UNVERIFIED=true to bypass (not recommended)"
        if [[ "${RING_ALLOW_UNVERIFIED:-false}" != "true" ]]; then
            return 1
        fi
        echo "⚠️ WARNING: Running in unverified mode"
    else
        # Get expected hash using exact match (prevents partial match attacks)
        local expected_hash=$(awk -v name="$binary_name" '$2 == name {print $1}' "$checksum_file")

        if [[ -z "$expected_hash" ]]; then
            echo "✗ ERROR: Binary '$binary_name' not found in checksum file"
            return 1
        fi

        # Compute hash of the COPY (macOS and Linux compatible)
        local actual_hash
        if command -v sha256sum &> /dev/null; then
            actual_hash=$(sha256sum "$secure_copy" | awk '{print $1}')
        elif command -v shasum &> /dev/null; then
            actual_hash=$(shasum -a 256 "$secure_copy" | awk '{print $1}')
        else
            echo "✗ ERROR: No sha256sum or shasum available"
            return 1
        fi

        if [[ "$expected_hash" != "$actual_hash" ]]; then
            echo "✗ CHECKSUM MISMATCH - Binary may be corrupted or tampered"
            echo "  Expected: $expected_hash"
            echo "  Actual:   $actual_hash"
            return 1
        fi

        echo "✓ Binary integrity verified"
    fi

    # Execute the verified copy
    "$secure_copy" "${args[@]}"
    local result=$?

    rm -f "$secure_copy"
    trap - EXIT

    return $result
}
```

### Step 2.5.3: Fallback to Build from Source

```bash
build_from_source() {
    echo "Attempting to build from source..."

    # Check if Go is available
    if ! command -v go &> /dev/null; then
        echo "✗ Go not installed. Cannot build from source."
        echo "  Install Go from https://go.dev/dl/ or use pre-built binaries."
        return 1
    fi

    # Find source directory
    local source_dir=""
    if [[ -d "./scripts/codereview" ]]; then
        source_dir="./scripts/codereview"
    elif [[ -d "${CLAUDE_PLUGIN_ROOT:-}/../../scripts/codereview" ]]; then
        source_dir="${CLAUDE_PLUGIN_ROOT:-}/../../scripts/codereview"
    fi

    if [[ -z "$source_dir" || ! -d "$source_dir" ]]; then
        echo "✗ Source directory not found. Cannot build from source."
        return 1
    fi

    # Build the binary
    local output_binary="/tmp/ring-codereview-run-all"
    echo "Building run-all from $source_dir..."

    if (cd "$source_dir" && go build -o "$output_binary" ./cmd/run-all/); then
        echo "✓ Built successfully: $output_binary"
        BINARY="$output_binary"
        return 0
    else
        echo "✗ Build failed"
        return 1
    fi
}
```

### Step 2.5.4: Execute with Verification

```bash
# Main execution flow using secure_execute_binary
# This ensures atomic verify-and-execute to prevent TOCTOU attacks
if [[ -n "$BINARY" ]]; then
    if secure_execute_binary "$BINARY" "$CHECKSUM_FILE" \
        --base="$BASE_SHA" --head="$HEAD_SHA" --output="docs/codereview" --verbose; then
        echo "Pre-analysis pipeline completed successfully"
    else
        echo "⚠️ Binary verification or execution failed"
        if build_from_source; then
            # Execute the newly built binary (no checksum for local builds)
            RING_ALLOW_UNVERIFIED=true secure_execute_binary "$BINARY" "" \
                --base="$BASE_SHA" --head="$HEAD_SHA" --output="docs/codereview" --verbose
        else
            echo "⚠️ DEGRADED MODE: Proceeding without pre-analysis"
            echo "  Reviewers will work without static analysis context."
            # Skip to Step 3 (dispatch reviewers)
        fi
    fi
else
    # No binary found - try building from source
    echo "No pre-built binary found for ${OS}_${ARCH}"
    if build_from_source; then
        RING_ALLOW_UNVERIFIED=true secure_execute_binary "$BINARY" "" \
            --base="$BASE_SHA" --head="$HEAD_SHA" --output="docs/codereview" --verbose
    else
        echo "⚠️ DEGRADED MODE: Pre-analysis binary not available"
        echo "  Reviewers will proceed WITHOUT static analysis context."
        # Skip to Step 3 (dispatch reviewers)
    fi
fi
```

- Timeout: Use `preanalysis_timeout` input (default 5 minutes)
- On success: Set `preanalysis_state.success = true`
- On failure: Display warning, set `preanalysis_state.success = false`, continue to Step 3

### Step 2.5.5: Read Context Files

If pipeline succeeded, read the 6 context files:

| Reviewer | Context File |
|----------|--------------|
| `ring:code-reviewer` | `docs/codereview/context-code-reviewer.md` |
| `ring:security-reviewer` | `docs/codereview/context-security-reviewer.md` |
| `ring:business-logic-reviewer` | `docs/codereview/context-business-logic-reviewer.md` |
| `ring:test-reviewer` | `docs/codereview/context-test-reviewer.md` |
| `ring:nil-safety-reviewer` | `docs/codereview/context-nil-safety-reviewer.md` |
| `ring:consequences-reviewer` | `docs/codereview/context-consequences-reviewer.md` |

Store each file's content in `preanalysis_state.context[reviewer_name]`.

If a context file is missing or empty, log warning and continue (reviewer will work without context).

```text
preanalysis_state = {
  enabled: true,
  success: false,
  context: {
    "ring:code-reviewer": null,
    "ring:security-reviewer": null,
    "ring:business-logic-reviewer": null,
    "ring:test-reviewer": null,
    "ring:nil-safety-reviewer": null,
    "ring:consequences-reviewer": null
  }
}
```

## Step 3: Dispatch All 6 Reviewers in Parallel

**⛔ CRITICAL: All 6 reviewers MUST be dispatched in a SINGLE message with 6 Task calls.**

```yaml
# Task 1: Code Reviewer
Task:
  subagent_type: "ring:code-reviewer"
  description: "Code review for [unit_id]"
  prompt: |
    ## Code Review Request
    
    **Unit ID:** [unit_id]
    **Base SHA:** [base_sha]
    **Head SHA:** [head_sha]
    
    ## What Was Implemented
    [implementation_summary]
    
    ## Requirements
    [requirements]
    
    ## Files Changed
    [implementation_files or "Use git diff"]

    ## Pre-Analysis Context

    **Static Analysis Results:**
    The following findings were automatically extracted by the pre-analysis pipeline.
    Use these to INFORM your review, not REPLACE your analysis.

    ---

    [IF preanalysis_state.context["ring:code-reviewer"] exists AND is not empty:]
    [INSERT the content of preanalysis_state.context["ring:code-reviewer"]]
    [ELSE:]
    _No pre-analysis context available. Perform standard review based on git diff._

    ---

    ## Your Focus
    - Architecture and design patterns
    - Code quality and maintainability
    - Naming conventions
    - Error handling patterns
    - Performance concerns

    ## Required Output
    ### VERDICT: PASS / FAIL

    ### Issues Found
    | Severity | Description | File:Line | Recommendation |
    |----------|-------------|-----------|----------------|
    | [CRITICAL/HIGH/MEDIUM/LOW/COSMETIC] | [issue] | [location] | [fix] |

    ### What Was Done Well
    [positive observations]

# Task 2: Business Logic Reviewer
Task:
  subagent_type: "ring:business-logic-reviewer"
  description: "Business logic review for [unit_id]"
  prompt: |
    ## Business Logic Review Request
    
    **Unit ID:** [unit_id]
    **Base SHA:** [base_sha]
    **Head SHA:** [head_sha]
    
    ## What Was Implemented
    [implementation_summary]
    
    ## Requirements
    [requirements]

    ## Pre-Analysis Context

    **Static Analysis Results:**
    The following findings were automatically extracted by the pre-analysis pipeline.
    Use these to INFORM your review, not REPLACE your analysis.

    ---

    [IF preanalysis_state.context["ring:business-logic-reviewer"] exists AND is not empty:]
    [INSERT the content of preanalysis_state.context["ring:business-logic-reviewer"]]
    [ELSE:]
    _No pre-analysis context available. Perform standard review based on git diff._

    ---

    ## Your Focus
    - Domain correctness
    - Business rules implementation
    - Edge cases handling
    - Requirements coverage
    - Data validation

    ## Required Output
    ### VERDICT: PASS / FAIL

    ### Issues Found
    | Severity | Description | File:Line | Recommendation |
    |----------|-------------|-----------|----------------|
    | [CRITICAL/HIGH/MEDIUM/LOW/COSMETIC] | [issue] | [location] | [fix] |

    ### Requirements Traceability
    | Requirement | Status | Evidence |
    |-------------|--------|----------|
    | [req] | ✅/❌ | [file:line] |

# Task 3: Security Reviewer
Task:
  subagent_type: "ring:security-reviewer"
  description: "Security review for [unit_id]"
  prompt: |
    ## Security Review Request

    **Unit ID:** [unit_id]
    **Base SHA:** [base_sha]
    **Head SHA:** [head_sha]

    ## What Was Implemented
    [implementation_summary]

    ## Requirements
    [requirements]

    ## Pre-Analysis Context

    **Static Analysis Results:**
    The following findings were automatically extracted by the pre-analysis pipeline.
    Use these to INFORM your review, not REPLACE your analysis.

    ---

    [IF preanalysis_state.context["ring:security-reviewer"] exists AND is not empty:]
    [INSERT the content of preanalysis_state.context["ring:security-reviewer"]]
    [ELSE:]
    _No pre-analysis context available. Perform standard review based on git diff._

    ---

    ## Your Focus
    - Authentication and authorization
    - Input validation
    - SQL injection, XSS, CSRF
    - Sensitive data handling
    - OWASP Top 10 risks

    ## Required Output
    ### VERDICT: PASS / FAIL

    ### Issues Found
    | Severity | Description | File:Line | OWASP Category | Recommendation |
    |----------|-------------|-----------|----------------|----------------|
    | [CRITICAL/HIGH/MEDIUM/LOW] | [issue] | [location] | [A01-A10] | [fix] |

    ### Security Checklist
    | Check | Status |
    |-------|--------|
    | Input validation | ✅/❌ |
    | Auth checks | ✅/❌ |
    | No hardcoded secrets | ✅/❌ |

# Task 4: Test Reviewer
Task:
  subagent_type: "ring:test-reviewer"
  description: "Test quality review for [unit_id]"
  prompt: |
    ## Test Quality Review Request

    **Unit ID:** [unit_id]
    **Base SHA:** [base_sha]
    **Head SHA:** [head_sha]

    ## What Was Implemented
    [implementation_summary]

    ## Requirements
    [requirements]

    ## Pre-Analysis Context

    **Static Analysis Results:**
    The following findings were automatically extracted by the pre-analysis pipeline.
    Use these to INFORM your review, not REPLACE your analysis.

    ---

    [IF preanalysis_state.context["ring:test-reviewer"] exists AND is not empty:]
    [INSERT the content of preanalysis_state.context["ring:test-reviewer"]]
    [ELSE:]
    _No pre-analysis context available. Perform standard review based on git diff._

    ---

    ## Your Focus
    - Test coverage for business logic
    - Edge case testing (empty, null, boundary)
    - Error path coverage
    - Test independence and isolation
    - Assertion quality (not just "no error")
    - Test anti-patterns (testing mock behavior)

    ## Required Output
    ### VERDICT: PASS / FAIL

    ### Issues Found
    | Severity | Description | File:Line | Recommendation |
    |----------|-------------|-----------|----------------|
    | [CRITICAL/HIGH/MEDIUM/LOW] | [issue] | [location] | [fix] |

    ### Test Coverage Analysis
    | Test Type | Count | Coverage |
    |-----------|-------|----------|
    | Unit | [N] | [areas] |
    | Integration | [N] | [areas] |
    | E2E | [N] | [areas] |

# Task 5: Nil-Safety Reviewer
Task:
  subagent_type: "ring:nil-safety-reviewer"
  description: "Nil/null safety review for [unit_id]"
  prompt: |
    ## Nil-Safety Review Request

    **Unit ID:** [unit_id]
    **Base SHA:** [base_sha]
    **Head SHA:** [head_sha]
    **Languages:** [Go|TypeScript|both - detect from files]

    ## What Was Implemented
    [implementation_summary]

    ## Requirements
    [requirements]

    ## Pre-Analysis Context

    **Static Analysis Results:**
    The following findings were automatically extracted by the pre-analysis pipeline.
    Use these to INFORM your review, not REPLACE your analysis.

    ---

    [IF preanalysis_state.context["ring:nil-safety-reviewer"] exists AND is not empty:]
    [INSERT the content of preanalysis_state.context["ring:nil-safety-reviewer"]]
    [ELSE:]
    _No pre-analysis context available. Perform standard review based on git diff._

    ---

    ## Your Focus
    - Nil/null pointer risks in changed code
    - Missing nil guards before dereference
    - Map access without ok check (Go)
    - Type assertions without ok check (Go)
    - Optional chaining misuse (TypeScript)
    - Error-then-use patterns

    ## Required Output
    ### VERDICT: PASS / FAIL

    ### Issues Found
    | Severity | Description | File:Line | Recommendation |
    |----------|-------------|-----------|----------------|
    | [CRITICAL/HIGH/MEDIUM/LOW] | [issue] | [location] | [fix] |

    ### Nil Risk Trace
    [For each risk: Source → Propagation → Dereference point]

# Task 6: Consequences Reviewer
Task:
  subagent_type: "ring:consequences-reviewer"
  description: "Consequences review for [unit_id]"
  prompt: |
    ## Consequences Review Request

    **Unit ID:** [unit_id]
    **Base SHA:** [base_sha]
    **Head SHA:** [head_sha]

    ## What Was Implemented
    [implementation_summary]

    ## Requirements
    [requirements]

    ## Pre-Analysis Context

    **Static Analysis Results:**
    The following findings were automatically extracted by the pre-analysis pipeline.
    Use these to INFORM your review, not REPLACE your analysis.

    ---

    [IF preanalysis_state.context["ring:consequences-reviewer"] exists AND is not empty:]
    [INSERT the content of preanalysis_state.context["ring:consequences-reviewer"]]
    [ELSE:]
    _No pre-analysis context available. Perform standard review based on git diff._

    ---

    ## Your Focus
    - Caller chain impact analysis
    - Consumer contract integrity
    - Shared state consequences
    - Downstream breakage risks
    - Ripple effects across modules
    - Breaking changes to public APIs

    ## Required Output
    ### VERDICT: PASS / FAIL

    ### Issues Found
    | Severity | Description | File:Line | Recommendation |
    |----------|-------------|-----------|----------------|
    | [CRITICAL/HIGH/MEDIUM/LOW] | [issue] | [location] | [fix] |

    ### Impact Trace
    [For each risk: Changed code → Affected callers → Downstream impact]
```

## Step 4: Wait for All Reviewers and Parse Output

```text
Wait for all 6 Task calls to complete.

For each reviewer:
1. Extract VERDICT (PASS/FAIL)
2. Extract Issues Found table
3. Categorize issues by severity

review_state.reviewers.code_reviewer = {
  verdict: [PASS/FAIL],
  issues: [parsed issues]
}
// ... same for other reviewers

Aggregate all issues by severity:
review_state.aggregated_issues.critical = [all critical from all reviewers]
review_state.aggregated_issues.high = [all high from all reviewers]
// ... etc
```

## Step 5: Handle Results by Severity

```text
Count blocking issues:
blocking_count = critical.length + high.length + medium.length

IF blocking_count == 0:
  → All reviewers PASS
  → Proceed to Step 8 (Success)

IF blocking_count > 0:
  → review_state.iterations += 1
  → IF iterations >= max_iterations: Go to Step 9 (Escalate)
  → Go to Step 6 (Dispatch Fixes)
```

## Step 6: Dispatch Fixes to Implementation Agent

**⛔ CRITICAL: You are an ORCHESTRATOR. You CANNOT edit source files directly.**
**You MUST dispatch the implementation agent to fix ALL review issues.**

### Orchestrator Boundaries (HARD GATE)

**See [dev-team/skills/shared-patterns/standards-boundary-enforcement.md](../shared-patterns/standards-boundary-enforcement.md) for core enforcement rules.**

**Key prohibition:** Edit/Write/Create on source files is FORBIDDEN. Always dispatch agent.

**If you catch yourself about to use Edit/Write/Create on source files → STOP. Dispatch agent.**

### Dispatch Implementation Agent

```yaml
Task:
  subagent_type: "[implementation_agent from Gate 0]"
  description: "Fix review issues for [unit_id]"
  prompt: |
    ⛔ FIX REQUIRED - Code Review Issues Found

    ## Context
    - **Unit ID:** [unit_id]
    - **Iteration:** [iterations] of [max_iterations]

    ## Critical Issues (MUST FIX)
    [list critical issues with file:line and recommendation]

    ## High Issues (MUST FIX)
    [list high issues]

    ## Medium Issues (MUST FIX)
    [list medium issues]

    ## Requirements
    1. Fix ALL Critical, High, and Medium issues
    2. Run tests to verify fixes
    3. Commit fixes with descriptive message
    4. Return list of fixed issues with evidence

    ## For Low/Cosmetic Issues
    Add TODO/FIXME comments:
    - Low: `// TODO(review): [Issue] - [reviewer] on [date]`
    - Cosmetic: `// FIXME(nitpick): [Issue] - [reviewer] on [date]`
```

### Anti-Rationalization for Direct Editing

**See [shared-patterns/orchestrator-direct-editing-anti-rationalization.md](../shared-patterns/orchestrator-direct-editing-anti-rationalization.md) for complete anti-rationalization table.**

*Applies to: Step 6 (Fix dispatch after Ring reviewers) & Step 7.5.3 (Fix dispatch after CodeRabbit)*

## Step 7: Re-Run All Reviewers After Fixes

```text
After fixes committed:
1. Get new HEAD_SHA
2. Go back to Step 3 (dispatch all 6 reviewers again)

⛔ CRITICAL: Always re-run ALL 6 reviewers after fixes.
Do NOT cherry-pick reviewers.
```

## Step 7.5: CodeRabbit CLI Validation (Per-Subtask/Task)

**⛔ NEW APPROACH: CodeRabbit validates EACH subtask/task as it completes, accumulating findings to a file.**

### CodeRabbit Integration Overview

```text
┌─────────────────────────────────────────────────────────────────┐
│ CODERABBIT PER-UNIT VALIDATION FLOW                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│ DURING REVIEW (after each subtask/task Ring reviewers pass):   │
│   1. Run CodeRabbit for that unit's files                      │
│   2. Append findings to .coderabbit-findings.md                │
│   3. Continue to next unit                                     │
│                                                                 │
│ BEFORE COMMIT (Step 8):                                        │
│   1. Display accumulated .coderabbit-findings.md               │
│   2. User decides: fix issues OR acknowledge and proceed       │
│                                                                 │
│ BENEFITS:                                                      │
│   • Catches issues close to when code was written              │
│   • Smaller scope = faster reviews (7-30 min per unit)         │
│   • Issues isolated to specific units, easier to fix           │
│   • Accumulated file provides audit trail                      │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

### Rate Limits (Official - per developer per repository per hour)

| Limit Type | Value | Notes |
|------------|-------|-------|
| Files reviewed | 200 files/hour | Per review |
| Reviews | 3 back-to-back, then 4/hour | **7 reviews possible in first hour** |
| Conversations | 25 back-to-back, then 50/hour | For follow-up questions |

**⏱️ TIMING:** Each CodeRabbit review takes **7-30+ minutes** depending on scope.
Run in background and check periodically for completion.

### Common Commands Reference

<a id="coderabbit-install-check"></a>
**CodeRabbit Installation Check:**
```bash
which coderabbit || which cr
```
> Used in Step 7.5.1 and after installation to verify CLI availability.

---

### ⚠️ PREREQUISITES & ENVIRONMENT REQUIREMENTS

**Before attempting Step 7.5, verify your environment supports the required operations:**

| Requirement | Local Dev | CI/CD | Containerized | Remote/SSH |
|-------------|-----------|-------|---------------|------------|
| `curl \| sh` install | ✅ Yes | ⚠️ May require elevated permissions | ❌ Often blocked | ⚠️ Depends on config |
| Browser auth (`coderabbit auth login`) | ✅ Yes | ❌ No browser | ❌ No browser | ❌ No browser |
| Write to `$HOME/.coderabbit/` | ✅ Yes | ⚠️ Ephemeral | ⚠️ Ephemeral | ✅ Usually |
| Internet access to `cli.coderabbit.ai` | ✅ Yes | ⚠️ Check firewall | ⚠️ Check firewall | ⚠️ Check firewall |

**⛔ HARD STOP CONDITIONS - Skip Step 7.5 if ANY apply:**
- Running in containerized environment without persistent storage
- CI/CD pipeline without pre-installed CodeRabbit CLI
- Non-interactive environment (no TTY for browser auth)
- Network restrictions blocking `cli.coderabbit.ai`
- Read-only filesystem

### Environment-Specific Guidance

#### Local Development (RECOMMENDED)
Standard flow works: `curl | sh` install + browser authentication.

#### CI/CD Pipelines
**Option A: Pre-install in CI image**
```dockerfile
# Add to your CI Dockerfile
RUN curl -fsSL https://cli.coderabbit.ai/install.sh | sh
```

**Option B: Use API token authentication (headless)**
```bash
# Set token via environment variable (add to CI secrets)
export CODERABBIT_API_TOKEN="your-api-token"
coderabbit auth login --token "$CODERABBIT_API_TOKEN"
```

**Option C: Skip CodeRabbit in CI, run locally**
```bash
# In CI config, set env var to auto-skip
export SKIP_CODERABBIT_REVIEW=true
```

#### Containerized/Docker Environments
```bash
# Option 1: Mount credentials from host
docker run -v ~/.coderabbit:/root/.coderabbit ...

# Option 2: Pass token as env var
docker run -e CODERABBIT_API_TOKEN="..." ...

# Option 3: Pre-bake into image (not recommended for tokens)
```

#### Non-Interactive/Headless Authentication
```bash
# Generate API token at: https://app.coderabbit.ai/settings/api-tokens
# Then authenticate without browser:
coderabbit auth login --token "cr_xxxxxxxxxxxxx"
```

---

### Step 7.5 Flow Logic

```text
┌─────────────────────────────────────────────────────────────────┐
│ ✅ ALL 6 RING REVIEWERS PASSED                                  │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│ Checking CodeRabbit CLI availability...                         │
│                                                                 │
│ CodeRabbit provides additional AI-powered code review that      │
│ catches race conditions, memory leaks, security vulnerabilities,│
│ and edge cases that may complement Ring reviewers.              │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

**⛔ HARD GATE: CodeRabbit Execution Rules (NON-NEGOTIABLE)**

| Scenario | Rule | Action |
|----------|------|--------|
| **Installed & authenticated** | **MANDATORY** - CANNOT skip | Run CodeRabbit review, no prompt |
| **Not installed** | **MUST ask** user about installation | Present installation option |
| **User declines installation** | Optional - can proceed | Skip and continue to Step 8 |

**Why this distinction:**
- If CodeRabbit IS installed → User has committed to using it → MUST run
- If CodeRabbit is NOT installed → User choice to add it → MUST ask, but can decline

```text
FLOW:
1. Run CodeRabbit Installation Check
2. IF installed AND authenticated → Run CodeRabbit (MANDATORY, NO prompt, CANNOT skip)
3. IF installed BUT NOT authenticated → Guide authentication (REQUIRED before proceeding)
4. IF NOT installed → MUST ask user about installation (REQUIRED prompt)
5. IF user declines installation → Skip CodeRabbit, proceed to Step 8 (only valid skip path)
```

### Anti-Rationalization for CodeRabbit Execution

| Rationalization | Why It's WRONG | Required Action |
|-----------------|----------------|-----------------|
| "CodeRabbit is optional, I'll skip it" | If installed, it's MANDATORY. Optional only means installation is optional. | **Run CodeRabbit if installed** |
| "Ring reviewers passed, that's enough" | Different tools catch different issues. CodeRabbit complements Ring. | **Run CodeRabbit if installed** |
| "User didn't ask for CodeRabbit" | User installed it. Installation = consent to mandatory execution. | **Run CodeRabbit if installed** |
| "Takes too long, skip this time" | Time is irrelevant. Installed = mandatory. | **Run CodeRabbit if installed** |
| "I'll just proceed without asking about install" | MUST ask every user if they want to install. No silent skips. | **Ask user about installation** |

#### Step 7.5.1: Check CodeRabbit Installation

Run the [CodeRabbit Installation Check](#coderabbit-install-check) command.

**IF INSTALLED AND AUTHENTICATED → MANDATORY EXECUTION (CANNOT SKIP):**
```text
┌─────────────────────────────────────────────────────────────────┐
│ ✅ CodeRabbit CLI detected - MANDATORY EXECUTION                │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│ CodeRabbit CLI is installed and authenticated.                  │
│                                                                 │
│ ⛔ CodeRabbit review is MANDATORY when installed.               │
│    This step CANNOT be skipped. Proceeding automatically...     │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```
→ Proceed directly to Step 7.5.2 (Run CodeRabbit Review) - **NO user prompt, NO skip option**

**IF NOT INSTALLED → MUST ASK USER (REQUIRED PROMPT):**

**⛔ You MUST present this prompt to the user. Silent skips are FORBIDDEN.**

```text
┌─────────────────────────────────────────────────────────────────┐
│ ⚠️  CodeRabbit CLI not found - INSTALLATION PROMPT REQUIRED     │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│ CodeRabbit CLI is not installed on your system.                 │
│                                                                 │
│ CodeRabbit provides additional AI-powered review that catches:  │
│   • Race conditions and concurrency issues                      │
│   • Memory leaks and resource management                        │
│   • Security vulnerabilities                                    │
│   • Edge cases missed by other reviewers                        │
│                                                                 │
│ ⛔ You MUST choose one of the following options:                │
│                                                                 │
│   (a) Yes, install CodeRabbit CLI (I'll guide you)              │
│   (b) No, skip CodeRabbit and proceed to Gate 5                 │
│                                                                 │
│ ⚠️  ENVIRONMENT CHECK:                                          │
│     • Interactive terminal with browser? → Standard install     │
│     • CI/headless? → Requires API token auth                    │
│     • Container? → See Environment-Specific Guidance above      │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

**If user selects (a) Yes, install:**
→ Proceed to Installation Flow below

**If user selects (b) No, skip:**
```text
→ Record: "CodeRabbit review: SKIPPED (not installed, user declined installation)"
→ Proceed to Step 8 (Success Output)
→ This is the ONLY valid path to skip CodeRabbit
```

#### Step 7.5.1a: CodeRabbit Installation Flow

```text
┌─────────────────────────────────────────────────────────────────┐
│ 📦 INSTALLING CODERABBIT CLI                                    │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│ ⚠️  ENVIRONMENT CHECK FIRST:                                    │
│                                                                 │
│ This installation requires:                                     │
│   • curl command available                                      │
│   • Write access to $HOME or /usr/local/bin                     │
│   • Internet access to cli.coderabbit.ai                        │
│   • Non-containerized environment (or persistent storage)       │
│                                                                 │
│ If in CI/container, see "Environment-Specific Guidance" above.  │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

**Check environment before proceeding:**
```bash
# Verify prerequisites
curl --version && echo "curl: OK" || echo "curl: MISSING"
test -w "$HOME" && echo "HOME writable: OK" || echo "HOME writable: NO"
curl -sI https://cli.coderabbit.ai | head -1 | grep -q "200\|301\|302" && echo "Network: OK" || echo "Network: BLOCKED"
```

**If prerequisites pass, install:**
```text
┌─────────────────────────────────────────────────────────────────┐
│ 📦 Step 1: Installing CodeRabbit CLI...                         │
└─────────────────────────────────────────────────────────────────┘
```

```bash
# Step 1: Download and install CodeRabbit CLI
curl -fsSL https://cli.coderabbit.ai/install.sh | sh
```

**After installation, verify:** Run the [CodeRabbit Installation Check](#coderabbit-install-check) command.

**If installation successful:**
```text
┌─────────────────────────────────────────────────────────────────┐
│ ✅ CodeRabbit CLI installed successfully!                       │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│ Step 2: Authentication required                                 │
│                                                                 │
│ Choose your authentication method:                              │
│                                                                 │
│   (a) Browser login (interactive - opens browser)               │
│       → Best for: Local development with GUI                    │
│       → Command: coderabbit auth login                          │
│                                                                 │
│   (b) API token (headless - no browser needed)                  │
│       → Best for: CI/CD, containers, SSH sessions               │
│       → Get token: https://app.coderabbit.ai/settings/api-tokens│
│       → Command: coderabbit auth login --token "cr_xxx"         │
│                                                                 │
│   (c) Skip authentication and CodeRabbit review                 │
│                                                                 │
│ Note: Free tier allows 1 review/hour.                           │
│       Paid plans get enhanced reviews + higher limits.          │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

**If user selects (a) Browser login:**
```bash
# Step 2a: Authenticate with CodeRabbit (opens browser)
# ⚠️ Requires: GUI environment with default browser
coderabbit auth login
```

**If user selects (b) API token:**
```bash
# Step 2b: Authenticate with API token (headless)
# Get your token from: https://app.coderabbit.ai/settings/api-tokens
coderabbit auth login --token "cr_xxxxxxxxxxxxx"
```

**After authentication:**
```text
┌─────────────────────────────────────────────────────────────────┐
│ ✅ CodeRabbit CLI ready!                                        │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│ Installation: Complete                                          │
│ Authentication: Complete                                        │
│                                                                 │
│ Proceeding to CodeRabbit review...                              │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

→ Proceed to Step 7.5.2 (Run CodeRabbit Review)

**If installation failed:**
```text
┌─────────────────────────────────────────────────────────────────┐
│ ❌ CodeRabbit CLI installation failed                           │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│ Error: [error message from curl/sh]                             │
│                                                                 │
│ Troubleshooting:                                                │
│   • Check internet connection                                   │
│   • Try manual install: https://docs.coderabbit.ai/cli/overview │
│   • macOS/Linux only (Windows not supported yet)                │
│                                                                 │
│ Would you like to:                                              │
│   (a) Retry installation                                        │
│   (b) Skip CodeRabbit and proceed to Gate 5                     │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

#### Step 7.5.2: Run CodeRabbit Review

**⛔ GRANULAR VALIDATION: CodeRabbit MUST validate at the most granular level available.**

```text
DETERMINE VALIDATION SCOPE:
1. Check if current work has subtasks (from gate0_handoff or implementation context)
2. IF subtasks exist → Validate EACH SUBTASK separately
3. IF no subtasks → Validate the TASK as a whole

WHY GRANULAR VALIDATION:
- Subtask-level validation catches issues early
- Easier to pinpoint which subtask introduced problems
- Prevents "works for task A, breaks task B" scenarios
- Enables incremental fixes without re-running entire review
```

**Step 7.5.2a: Determine Validation Scope**

```text
validation_scope = {
  mode: null,  // "subtask" or "task"
  units: [],   // list of {id, files, commits} to validate
  current_index: 0
}

IF gate0_handoff.subtasks exists AND gate0_handoff.subtasks.length > 0:
  → validation_scope.mode = "subtask"
  → FOR EACH subtask in gate0_handoff.subtasks:
      → Get files changed by this subtask (from commits or file mapping)
      → Add to validation_scope.units: {
          id: subtask.id,
          n

…(truncated)
