> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mesa.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# CLI Code Review

> Enforce your team's rules during development with AI-powered code review.

Mesa Code Review is a local rules engine that checks code changes against your team's rules during development. You define rules as markdown files in your repo. Mesa runs them against git diffs and your codebase context and reports violations. If nothing is violated, it says nothing.

It works standalone from the CLI, or integrates with Claude Code for automatic reviews during development.

## Installing

```bash theme={null}
brew install mesa-dot-dev/homebrew-tap/code-review
```

Requires an API key from Anthropic, OpenAI, or Google. Set it in your environment or paste it during setup.

## Quickstart

<Steps>
  <Step title="Initialize Mesa in your repo">
    ```bash theme={null}
    mesa init
    ```

    This walks you through setup:

    * Creates `.mesa/config.yaml` and `.mesa/rules/`
    * Offers to generate rules from your codebase, use our starter rules, or start from scratch
    * Sets up Claude Code integration (MCP server & Claude Code slash commands and hooks)
    * Stores your API key in `.env.local` if provided
  </Step>

  <Step title="Generate rules or write your own">
    ```bash theme={null}
    mesa rules generate
    ```

    Mesa scans your codebase, detects conventions and patterns, and proposes rules. You review each one interactively and choose which to keep.

    You can also create individual rules:

    ```bash theme={null}
    mesa rules create
    ```
  </Step>

  <Step title="Run a review">
    ```bash theme={null}
    mesa review 
    ```

    Mesa diffs your current branch against the base, matches changed files to rules, and reports any violations. Use the --help flag for more options
  </Step>
</Steps>

## Rules

Rules live in `.mesa/rules/` as markdown files. Each rule defines what to check, which files it applies to, and how severe a violation is.

````markdown theme={null}
---
id: no-console-log
title: No console.log in production code
severity: warning
globs:
  - "**/*.ts"
  - "**/*.tsx"
  - "!**/*.test.ts"
---

console.log, console.warn, and console.debug should not appear in
production code. Use a structured logging library instead.

### Violations

```
console.log("Processing order", orderId, customerEmail);
```

### Compliant

```
logger.info("Processing order", { orderId });
```
````

The markdown body contains the instructions the AI uses to evaluate the rule. Optional `### Violations` and `### Compliant` sections provide code examples.

<Tip>
  Globs use repo-root-relative paths, so rules work correctly in monorepos. Scope rules to specific directories like `src/api/**/*.ts` rather than broad wildcards.
</Tip>

## Claude Code integration

`mesa init` sets up three things for Claude Code automatically.

### Stop hook

Every time Claude Code finishes writing code, Mesa reviews the uncommitted changes. If violations are found, Claude is blocked and asked to fix them before completing.

### MCP server

Mesa registers as an MCP server via `.mcp.json`. Claude Code discovers it on startup and gains access to Mesa's tools for reviewing code, creating rules, and generating rules.

### Slash commands

Available inside Claude Code after `mesa init`:

| Command               | Description                            |
| --------------------- | -------------------------------------- |
| `/mesa-review`        | Run a code review manually             |
| `/mesa-createrule`    | Create a new rule with AI assistance   |
| `/mesa-generaterules` | Auto-generate rules from your codebase |

## Background review agent

This agent runs a second AI reviewer in the background while you work. Instead of calling an LLM API directly, it shells out to whatever coding agent you already have installed (Claude Code only supported now) and uses that agent's existing subscription (Pro/Max/etc) without any setup.

<Warning title="Alpha Feature">
  **The background review agent is experimental.** It works alongside the rules engine but is a separate system under active development. Behavior and configuration may change.

  **If you run into issues, please [post on our discord](https://discord.com/invite/2vvEJFrCHV).**
</Warning>

<Info>
  **No API key needed.** The background agent uses your installed coding agent's own subscription. If you can run "claude" from your terminal, the agent works.
</Info>

### How it works

When enabled, the stop hook changes behavior:

1. After each Claude Code turn, the hook silently **queues** your changes for background review
2. On the **next** turn, the hook checks for findings from the previous review
3. If findings exist, they're injected as recommendations the agent can fix or ignore, otherwise the user sees nothing.

The background agent performs a general code review looking for bugs, security issues, regressions, and unnecessary complexity.

### Setup

Enable the daemon in `.mesa/config.yaml`:

```yaml theme={null}
daemon:
  enabled: true         # Switch stop hook from rules engine to daemon
  agent: claude           
  workers: 1            # Parallel review workers (1-2 recommended)
  idle_timeout: 1800    # Auto-shutdown after 30 min idle
```

The background agent starts automatically when the stop hook fires. You can also manage it manually:

```bash theme={null}
mesa daemon start      # Start the daemon
mesa daemon stop       # Stop the daemon
mesa daemon status     # Check if running
```

### Rules engine vs. background agent

|                      | Rules engine                                  | background agent                                   |
| -------------------- | --------------------------------------------- | -------------------------------------------------- |
| **Requires API key** | Yes                                           | No — uses your agent CLI                           |
| **What it checks**   | Your rules in `.mesa/rules/`                  | General code quality (bugs, security, regressions) |
| **Hook behavior**    | Synchronous — blocks on violations            | Async — findings arrive next turn as guidance      |
| **When to use**      | You have specific team conventions to enforce | You want a background "second pair of eyes"        |

You use one or the other via `daemon.enabled` in your config — they don't run simultaneously.

## Configuration

`.mesa/config.yaml` is created by `mesa init`:

```yaml theme={null}
# AI model for reviews
model:
  provider: anthropic       # anthropic | openai | google
  name: claude-opus-4-6

# Output settings
output:
  cursor_deeplink: true      # Print Cursor IDE links for violations

# Review tuning
review:
  max_steps: 50              # Max tool-calling steps per review batch
  files_per_batch: 2         # Files reviewed together per batch

# Claude Code stop hook
hook:
  enabled: true              # Auto-review when Claude Code finishes writing

# Background review daemon (alpha feature) 
daemon:
  enabled: false             # Enable daemon mode instead of rules engine
  agent: claude               
  workers: 1                 # Parallel review workers (1-2 max)
  idle_timeout: 1800         # Seconds before auto-shutdown (default: 30 min)
```

API keys are loaded from environment variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GOOGLE_API_KEY`) or from `.env.local` / `.env` files.

## CLI reference

### Core commands

| Command       | Description                                                              |
| ------------- | ------------------------------------------------------------------------ |
| `mesa init`   | Set up Mesa in your repo (config, rules, hooks, Claude Code integration) |
| `mesa review` | Review code changes against your rules                                   |
| `mesa stats`  | Show review history and cost analytics                                   |
| `mesa index`  | Build the import graph for richer review context                         |

### Rule management

| Command                   | Description                                                 |
| ------------------------- | ----------------------------------------------------------- |
| `mesa rules generate`     | Auto-generate rules by analyzing your codebase              |
| `mesa rules create [dir]` | Create a new rule with AI assistance, scoped to a directory |
| `mesa rules list`         | List all rules with IDs, titles, and severity               |
| `mesa rules explain <id>` | Show full details for a rule                                |
| `mesa rules validate`     | Check all rule files for correct structure                  |
| `mesa rules for <paths>`  | Show which rules match given files or directories           |
| `mesa rules delete <id>`  | Delete a rule                                               |

### `mesa review` options

```
-b, --base     Base branch to diff against                [default: "main"]
    --head     Head ref to review                         [default: "HEAD"]
-o, --output   Output format: console, json               [default: "console"]
-v, --verbose  Show detailed progress                     [default: false]
    --debug    Write debug logs to .mesa/.tmp/            [default: false]
-c, --config   Path to config file                        [default: ".mesa/config.yaml"]
    --rules    Path to rules directory                    [default: ".mesa/rules/"]
```

<Tip>
  Use `mesa stats` to see aggregated analytics from your local review history, including cost, token usage, and violation trends.
</Tip>
