---
name: grid:review
description: Headless PR/code review for CI/CD pipelines
allowed-tools:
  - Read
  - Glob
  - Grep
  - Bash
  - Task
disable-model-invocation: true
argument-hint: "[PR number | branch | files...]"
---

# /grid:review - Headless Code Review

Run automated code review suitable for CI/CD pipelines. Spawns parallel review agents for comprehensive analysis and outputs structured JSON for CI consumption.

## USAGE

```bash
# Review a PR by number
claude -p "/grid:review 123"

# Review current branch vs main
claude -p "/grid:review"

# Review specific files
claude -p "/grid:review src/auth/*.ts"

# Output JSON for CI pipelines
claude -p "/grid:review 123" --output-format json

# Output SARIF for GitHub Code Scanning
claude -p "/grid:review 123 --sarif"
```

## REVIEW PROCESS

### 1. Detect Review Target

Parse arguments to determine what to review:

```bash
# If PR number provided (numeric argument)
if [[ "$1" =~ ^[0-9]+$ ]]; then
  gh pr diff "$1" > /tmp/review_diff.patch
  REVIEW_TARGET="PR #$1"
  FILES=$(gh pr view "$1" --json files -q '.files[].path')

# If branch name or no argument (review current branch)
elif [[ -z "$1" ]] || git rev-parse --verify "$1" 2>/dev/null; then
  BASE_BRANCH="${1:-main}"
  git diff "$BASE_BRANCH"...HEAD > /tmp/review_diff.patch
  REVIEW_TARGET="Branch vs $BASE_BRANCH"
  FILES=$(git diff --name-only "$BASE_BRANCH"...HEAD)

# If file glob provided
else
  FILES=$(ls $1 2>/dev/null)
  REVIEW_TARGET="Files: $1"
fi
```

### 2. Spawn Review Agents

Spawn three parallel review agents via Task tool:

**Code Quality Reviewer** (`grid-code-reviewer`):
- Code style and formatting
- Naming conventions
- Cyclomatic complexity
- DRY violations
- Error handling patterns

**Security Reviewer** (`grid-security-reviewer`):
- Injection vulnerabilities
- Authentication/authorization
- Sensitive data exposure
- Dependency vulnerabilities

**Test Coverage Reviewer** (inline analysis):
- Check for corresponding test files
- Look for untested code paths
- Verify test assertions exist

### 3. Collect Results

Aggregate results from all reviewers into unified format:

```json
{
  "status": "pass|warn|fail",
  "summary": "Brief summary of review findings",
  "target": "PR #123 | Branch vs main | Files: src/*.ts",
  "reviewed_at": "2024-01-23T14:30:00Z",
  "issues": [
    {
      "severity": "error|warning|info",
      "category": "security|quality|testing",
      "file": "path/to/file.ts",
      "line": 42,
      "rule": "rule-name",
      "message": "Issue description",
      "suggestion": "How to fix",
      "cwe": "CWE-89"
    }
  ],
  "metrics": {
    "files_reviewed": 5,
    "lines_changed": 234,
    "issues_found": 3,
    "errors": 1,
    "warnings": 2,
    "security_issues": 0,
    "test_coverage_delta": "+5%"
  },
  "reviewers": {
    "code_quality": {"issues": 2, "status": "warn"},
    "security": {"issues": 0, "status": "pass"},
    "testing": {"issues": 1, "status": "warn"}
  }
}
```

### 4. Determine Status

```
pass:  No errors, 0-2 warnings
warn:  No errors, 3+ warnings
fail:  Any errors present
```

### 5. Return Exit Code

- Exit 0: status is "pass" or "warn"
- Exit 1: status is "fail"

## CI INTEGRATION

### GitHub Actions

```yaml
name: Grid Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Grid Review
        id: review
        run: |
          claude -p "/grid:review ${{ github.event.pull_request.number }}" \
            --output-format json > review.json

          # Extract status
          STATUS=$(jq -r '.status' review.json)
          echo "status=$STATUS" >> $GITHUB_OUTPUT

          # Post summary as PR comment
          SUMMARY=$(jq -r '.summary' review.json)
          gh pr comment ${{ github.event.pull_request.number }} \
            --body "## Grid Code Review\n\n**Status:** $STATUS\n\n$SUMMARY"
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

      - name: Fail if critical issues
        if: steps.review.outputs.status == 'fail'
        run: exit 1
```

### GitLab CI

```yaml
grid-review:
  stage: test
  script:
    - |
      claude -p "/grid:review" --output-format json > review.json
      STATUS=$(jq -r '.status' review.json)

      # Output review summary
      jq '.summary' review.json

      # Fail pipeline if critical issues
      if [ "$STATUS" = "fail" ]; then
        echo "Grid review found critical issues"
        exit 1
      fi
  artifacts:
    reports:
      codequality: review.json
```

### Jenkins Pipeline

```groovy
pipeline {
    agent any
    stages {
        stage('Grid Review') {
            steps {
                script {
                    sh '''
                        claude -p "/grid:review" \
                          --output-format json > review.json
                    '''

                    def review = readJSON file: 'review.json'

                    if (review.status == 'fail') {
                        error("Grid review failed: ${review.summary}")
                    }

                    echo "Review passed: ${review.summary}"
                }
            }
        }
    }
}
```

### Pre-commit Hook

```bash
#!/bin/bash
# .git/hooks/pre-push

# Get changed files
FILES=$(git diff --name-only origin/main...HEAD)

if [ -n "$FILES" ]; then
  echo "Running Grid review on changed files..."

  RESULT=$(claude -p "/grid:review" --output-format json 2>/dev/null)
  STATUS=$(echo "$RESULT" | jq -r '.status')

  if [ "$STATUS" = "fail" ]; then
    echo "Grid review found critical issues:"
    echo "$RESULT" | jq -r '.issues[] | "  - \(.file):\(.line) \(.message)"'
    exit 1
  fi

  echo "Grid review passed."
fi
```

## OUTPUT MODES

### Human-Readable (Default)

```
GRID CODE REVIEW
================

Target: PR #123
Files: 5 reviewed
Status: WARN (2 warnings, 0 errors)

ISSUES
------

[WARNING] src/auth/login.ts:42
  Rule: complexity
  Function has cyclomatic complexity of 15 (max: 10)
  Suggestion: Extract into smaller functions

[WARNING] src/api/users.ts:23
  Rule: no-any
  Avoid using 'any' type
  Suggestion: Define explicit interface

METRICS
-------
Files reviewed: 5
Lines changed: 234
Issues found: 2
Test coverage: +5%

End of Line.
```

### JSON Mode (`--output-format json`)

Full structured JSON as shown above, suitable for parsing with `jq`.

### SARIF Mode (`--sarif` flag)

```json
{
  "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
  "version": "2.1.0",
  "runs": [
    {
      "tool": {
        "driver": {
          "name": "Grid Code Review",
          "version": "1.7.x",
          "informationUri": "https://github.com/JamesWeatherhead/grid"
        }
      },
      "results": [
        {
          "ruleId": "complexity",
          "level": "warning",
          "message": {
            "text": "Function has cyclomatic complexity of 15 (max: 10)"
          },
          "locations": [
            {
              "physicalLocation": {
                "artifactLocation": { "uri": "src/auth/login.ts" },
                "region": { "startLine": 42 }
              }
            }
          ]
        }
      ]
    }
  ]
}
```

SARIF output integrates with GitHub Code Scanning:

```yaml
- name: Upload SARIF
  uses: github/codeql-action/upload-sarif@v2
  with:
    sarif_file: review.sarif
```

## IMPLEMENTATION

When `/grid:review` is invoked:

1. **Parse Arguments**
   ```
   $1 = PR number | branch | file glob | empty
   --sarif = output SARIF format
   ```

2. **Get Diff/Files**
   - PR: `gh pr diff $1`
   - Branch: `git diff main...HEAD`
   - Files: Read specified files directly

3. **Spawn Parallel Review Agents**
   ```
   Task(grid-code-reviewer, files + diff)
   Task(grid-security-reviewer, files + diff)
   Inline: Test coverage analysis
   ```

4. **Collect Results**
   - Wait for all agents
   - Merge issue lists
   - Deduplicate overlapping findings
   - Calculate aggregate metrics

5. **Determine Status**
   - `fail`: Any severity="error"
   - `warn`: No errors, any warnings
   - `pass`: No errors, <=2 warnings

6. **Format Output**
   - Default: Human-readable markdown
   - `--output-format json`: Structured JSON
   - `--sarif`: SARIF 2.1.0 format

7. **Return Exit Code**
   - 0: pass or warn
   - 1: fail

## CONFIGURATION

Environment variables:

```bash
# Maximum issues before failing (default: any error fails)
GRID_REVIEW_MAX_ERRORS=0
GRID_REVIEW_MAX_WARNINGS=10

# Categories to enable (default: all)
GRID_REVIEW_CATEGORIES="security,quality,testing"

# Custom rules file
GRID_REVIEW_RULES=".grid/review-rules.json"
```

## RULES

1. **Parallel execution** - Spawn all reviewers simultaneously
2. **Structured output** - Always produce parseable JSON internally
3. **Deterministic status** - Same input = same status
4. **Fast feedback** - Target < 60 seconds for typical PRs
5. **No false positives** - High confidence findings only
6. **Actionable suggestions** - Every issue includes fix guidance

End of Line.
