# AI Code Review Automation

Automated code review with style checking, bug detection, and performance suggestions.

### Connected Apps & Services

## Why AI Code Review Matters

Code review is one of the most critical — and most bottlenecked — stages of the software development lifecycle. Studies show that the median time to merge a pull request without AI assistance hovers around **20 hours**, with many teams reporting multi-day backlogs during sprint pushes. As AI coding agents increase developer output by 25–35%, the volume of pull requests per sprint has surged, making the review bottleneck even more acute.

Manual code review struggles to scale, and the result is that bugs slip through, security issues reach production, and developers spend hours waiting for feedback instead of shipping.

**AI-augmented code review** addresses this by handling the repeatable, pattern-based aspects of review while freeing human reviewers to focus on design and architectural decisions.

## How It Works

The AI code review pipeline follows a straightforward event-driven architecture:

```plaintext
GitHub/GitLab PR Event
       │
       ▼
  Webhook POST ──────► OpenClaw Agent
       │                    │
       │              Fetch PR diff (gh pr diff)
       │              Analyze changes
       │              Check review rules
       │              Generate feedback
       │                    │
       ▼                    ▼
  PR Comments ◄──── Post inline comments
  Slack Alert ◄──── Send summary notification
  Jira Update ◄──── Link findings to tickets
```

- **Trigger**: A webhook fires when a pull request is opened, updated, or marked ready for review.
- **Fetch**: The OpenClaw agent uses the GitHub CLI to retrieve the full diff and PR status.
- **Analyze**: The agent applies your configured review rules against every changed file.
- **Report**: Findings are posted as inline PR comments with severity levels or sent as a summary to Slack, Jira, or Notion.
- **Iterate**: When the author pushes fixes, the agent re-scans only the updated changes.

## Prerequisites

| Requirement                    | Details                                                                                 |
|-------------------------------|-----------------------------------------------------------------------------------------|
| **OpenClaw instance**         | A running OpenClaw agent via [Donely](/content/site-root.html) or self-hosted               |
| **GitHub/GitLab access token**| Personal access token or GitHub App with `repo` read permissions                       |
| **Repository access**         | The agent's environment must be able to clone or fetch from target repositories         |
| **Webhook endpoint**          | Your OpenClaw instance's webhook URL                                                  |
| **Review rules document**     | A `BOOTSTRAP.md` or system prompt defining your team's review criteria                |

## Step-by-Step Setup

### Step 1: Configure GitHub Authentication

In your OpenClaw agent's terminal, authenticate the GitHub CLI:

```bash
gh auth login --with-token <<< "ghp_your_personal_access_token"
gh auth status  # verify access
```

### Step 2: Set Up the Webhook

In your GitHub repository settings, navigate to **Settings → Webhooks → Add webhook** and configure:

| Field             | Value                                           |
|-------------------|------------------------------------------------|
| **Payload URL**   | `https://your-instance.donely.cloud/hooks/agent` |
| **Content type**  | `application/json`                             |
| **Secret**        | Your webhook signing secret                    |
| **Events**        | Select "Pull requests" and "Pull request reviews" |

### Step 3: Create the Review Agent Prompt

Create a `BOOTSTRAP.md` file in your agent's workspace that defines the review personality, criteria, and output format:

```markdown
# Code Review Agent — BOOTSTRAP.md

Role

You are an expert code reviewer for our engineering team. You analyze pull
request diffs and provide constructive, actionable feedback focused on
correctness, security, performance, and maintainability.

Review Criteria

Critical (must fix before merge)

- Security vulnerabilities (SQL injection)
- Data loss risks
- Breaking API changes without versioning

High (strongly recommended)

- Logic errors and off-by-one mistakes
- Missing error handling

Medium (should address)

- Test coverage gaps for new code paths
- Inconsistent naming conventions

Low (suggestions)

- Style improvements beyond linter rules

Feedback Style

Be specific: reference exact file paths and line numbers
Be constructive: explain WHY something is an issue, not just WHAT
```

### Step 4: Configure Webhook Transform

Create a webhook transform script that parses incoming GitHub events. Place this in your OpenClaw hooks transforms directory:

```javascript
// hooks/transforms/github-pr.js
export default function transform(payload) {
  const { action, pull_request, repository } = payload;
  if (!['opened', 'synchronize', 'ready_for_review'].includes(action)) return null;
  if (pull_request.draft) return null;
  return {
    agent: 'code-reviewer',
    prompt: [
      Review PR #${pull_request.number} in ${repository.full_name}.,
      Title: ${pull_request.title},
      Branch: ${pull_request.head.ref} → ${pull_request.base.ref},
    ].join('\n'),
  };
}
```

### Step 5: Test the Pipeline

Open a test pull request and verify the full cycle:

```bash
# Create a test branch with a deliberate issue
git checkout -b test/review-automation
git push origin test/review-automation
gh pr create --title "test: review automation" --body "Testing AI review"
```

## Review Capabilities

A properly configured OpenClaw code review agent covers six key analysis dimensions:

### 1. Security Scanning

Detects hardcoded credentials, SQL injection vectors, and cross-site scripting patterns.

### 2. Bug Detection

Identifies logic errors, unhandled promise rejections, race conditions, etc.

### 3. Performance Analysis

Flags N+1 database queries and unbounded collection operations.

### 4. Style and Consistency

Enforces naming conventions, import ordering, and documentation requirements.

### 5. Test Coverage Analysis

Identifies new code paths that lack corresponding test cases.

### 6. Documentation Gaps

Flags public API changes without updated documents.

## Supported Platforms

OpenClaw's code review automation integrates with all major Git hosting platforms through particular APIs.

### Configuration Reference

#### OpenClaw Gateway Configuration

```json
{
  "hooks": {
    "token": "your-webhook-secret",
    "mappings": {
      "github-pr": {
        "transform": "github-pr.js",
        "agents": ["code-reviewer"]
      }
    }
  },
  "tools": {
    "exec": {
      "allowlist": ["gh", "git", "glab", "curl"]
    }
  }
}
```

### Review Severity Levels

| Level     | Action         | Description                              |
|-----------|----------------|------------------------------------------|
| **CRITICAL** | Block merge   | Security vulnerabilities, data loss risks |
| **HIGH**   | Request changes | Logic errors, missing error handling     |
| **MEDIUM** | Comment        | Test gaps, naming issues                 |
| **LOW**    | Suggestion     | Style preferences, refactoring ideas     |

### Best Practices

- Limit review scope to avoid processing generated files.
- Track false positive rates and maintain a log of dismissed findings.
- Use a human-in-the-loop approach where AI findings are a first pass.
