跳到正文
GitHub·· 10 天前AI 评分62

OpticDiff 开源 code-reviewer:本地优先的 AI 代码审查工具

OpticDiff/code-reviewer

AI 导读

OpticDiff 发布开源代码审查工具 code-reviewer,采用 Apache 2.0 许可,支持 Ollama、vLLM 等本地模型以及 Vertex AI、AWS Bedrock 等 OpenAI 兼容端点,代码可完全离线运行。

正文

code-reviewer Terminal Demo


Why code-reviewer?

Most AI code review bots are closed-source SaaS solutions that demand access to your proprietary codebase, transmit code to external third parties, spam pull requests with pedantic nitpicks, and only execute after you have already pushed to CI.

code-reviewer is designed for privacy, high signal, and developer flow:

Capability code-reviewer CodeRabbit GitHub Copilot PR Review Qodo (PR-Agent)
100% Local / Offline (Ollama, vLLM) ✅ Yes ❌ No (SaaS only) ❌ No (SaaS only) 🟡 Partial (Docker)
Zero Code Sent to 3rd-Party SaaS ✅ Direct to VPC / Local ❌ Sent to vendor ❌ Sent to MS / OpenAI 🟡 Config dependent
Multi-Model Consensus Filtering ✅ Yes (Gemini + Claude) ❌ No ❌ No ❌ No
Shift-Left Local CLI (--diff) ✅ Built-in ❌ Web/PR only ❌ Web/PR only 🟡 Python CLI
Git Pre-Push Hook (hook install) ✅ Built-in ❌ No ❌ No ❌ No
Full GitHub & GitLab Parity ✅ Native comments & notes 🟡 GitHub-first ❌ GitHub only 🟡 Webhooks
Repo-Aware AST Context ✅ Pure-Go Tree-sitter 🟡 Vector DB 🟡 Proprietary 🟡 Vector / Grep
Content-Addressable Diff Cache ✅ Instant sub-second hit 🟡 Server-side ❌ No ❌ No
Safe Auto-Approve (9 Guards) ✅ SHA-pinned ❌ No ❌ No ❌ No
Security Tabs (SARIF 2.1.0 & SAST) ✅ Native 🟡 Custom 🟡 Native ❌ No
Binary Footprint ✅ Single binary (<30MB) N/A (SaaS) N/A (SaaS) Heavy Python/Docker
License ✅ Apache 2.0 Open Source ❌ Proprietary ❌ Proprietary 🟡 Open Core

How It Works

flowchart LR
    A[Git Diff / PR / MR] --> B[Tree-sitter AST Symbol Extractor]
    B --> C[Unchanged Code Usage Search]
    C --> D{Diff Cache Hit?}
    D -- Hit --> E[Cached Findings]
    D -- Miss --> F[Model Provider Engine]
    subgraph Providers [Supported Providers]
        P1[Ollama / vLLM / Local]
        P2[Vertex AI - Gemini / Claude]
        P3[AWS Bedrock via LiteLLM]
        P4[OpenAI-Compatible Endpoints]
    end
    F --> Providers
    Providers --> G[Multi-Model Consensus Filter]
    E --> H[Consolidated Results]
    G --> H
    H --> I[ANSI Terminal Output]
    H --> J[GitHub PR Inline Comments & Suggestions]
    H --> K[GitLab MR Discussions & Draft Notes]
    H --> L[SARIF 2.1.0 & GitLab SAST Security Tabs]
    H --> M[SHA-Pinned Safe Auto-Approve]

Loading


Install

# Homebrew (macOS / Linux)
brew install OpticDiff/tap/code-reviewer

# Nix Flake
nix run github:OpticDiff/code-reviewer
nix profile install github:OpticDiff/code-reviewer

# mise
mise use -g ubi:OpticDiff/code-reviewer

# Go
go install github.com/OpticDiff/code-reviewer/cmd/code-reviewer@latest

# Docker
docker pull ghcr.io/opticdiff/code-reviewer:latest
docker run --rm ghcr.io/opticdiff/code-reviewer:latest --help

# Pre-built binary from GitHub Releases
# https://github.com/OpticDiff/code-reviewer/releases

# Build from source
git clone https://github.com/OpticDiff/code-reviewer.git
cd code-reviewer && go build -o code-reviewer ./cmd/code-reviewer

Quick Start

🔧 10-Second Interactive Setup (code-reviewer init)

Bootstrap a production-ready .code-reviewer.yaml configuration tailored to your repository with a single command:

# Interactive setup: auto-detects GitHub vs GitLab, prompts for model & focus areas
code-reviewer init

# Non-interactive: generate instantly with sensible defaults
code-reviewer init --yes

# Force overwrite existing configuration
code-reviewer init --force

⚡ 30-Second Local Test Drive (Zero Cloud Setup with Ollama)

Review your current uncommitted changes against origin/HEAD completely offline:

code-reviewer --diff --api-url http://localhost:11434/v1 --model qwen3:8b

☁️ With Vertex AI (Gemini, Claude, Mistral)

export GOOGLE_CLOUD_PROJECT=my-gcp-project
gcloud auth application-default login

# Multi-model consensus: only keep findings that Gemini + Claude agree on
code-reviewer --diff --models gemini-3.8-flash,claude-sonnet-5

🛡️ Shift-Left: Block Bad Pushes with Git Pre-Push Hook

Install automatic review before code ever leaves your machine:

code-reviewer hook install

# Now every git push automatically reviews changed files
# If a HIGH/CRITICAL bug is found, push is prevented!

🛠️ Common Local CLI Recipes

# Review against a specific git ref
code-reviewer --diff HEAD~3

# Review specific files only
code-reviewer --files internal/handler.go,internal/service.go

# Security audit with custom guidelines
code-reviewer --diff --focus security --custom-prompt examples/prompts/security-audit.md

# Explain the diff in plain English
code-reviewer --diff --explain

# Automatically apply suggested fixes directly to your working tree
code-reviewer --diff --fix

# Generate structured PR description / summary from diff
code-reviewer --diff --summarize

# Output SARIF 2.1.0 for security tooling
code-reviewer --diff --sarif results.sarif

GitLab CI

Add to your .gitlab-ci.yml:

# Quick setup — uses CI_JOB_TOKEN, no PAT needed
code-review:
  stage: review
  image: gcr.io/$PROJECT/code-reviewer:latest
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  variables:
    GITLAB_TOKEN: $CI_JOB_TOKEN
    REVIEW_COMMENT_MODE: "notes"
    SARIF_OUTPUT: "results.sarif"
  script:
    - code-reviewer --ci --incremental
  allow_failure: true
  artifacts:
    reports:
      sast: results.sarif
    when: always

For inline diff-anchored comments, use a Project Access Token with api scope:

code-review:
  variables:
    GITLAB_TOKEN: $CODE_REVIEWER_TOKEN    # PAT with api scope
    REVIEW_COMMENT_MODE: "discussions"
  script:
    - code-reviewer --ci
# With auto-approve on clean reviews
code-review:
  stage: review
  image: gcr.io/$PROJECT/code-reviewer:latest
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  variables:
    GITLAB_TOKEN: $CODE_REVIEWER_TOKEN  # PAT with api scope (required for approvals)
    REVIEW_COMMENT_MODE: "discussions"
  script:
    - code-reviewer --ci --auto-approve --audit-log review.jsonl
  artifacts:
    paths:
      - review.jsonl
    when: always
# With native GitLab SAST security report (Free, Premium, and Ultimate)
code-review-sast:
  stage: review
  image: gcr.io/$PROJECT/code-reviewer:latest
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
  variables:
    GITLAB_TOKEN: $CI_JOB_TOKEN
    SAST_OUTPUT: "gl-sast-report.json"
  script:
    - code-reviewer --ci --incremental --sast gl-sast-report.json
  artifacts:
    reports:
      sast: gl-sast-report.json
    when: always

See .gitlab-ci.example.yml for the full setup.

GitHub Actions

Use the reusable action for the simplest setup:

# Self-hosted (Ollama) — zero auth, no cloud
- uses: OpticDiff/code-reviewer-action@v1
  with:
    model: qwen3:8b
    extra-args: --api-url http://ollama:11434/v1
  env:
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Vertex AI with auto-approve & incremental review
- uses: google-github-actions/auth@v2
  with:
    workload_identity_provider: ${{ secrets.WIF_PROVIDER }}
    service_account: ${{ secrets.WIF_SA }}
- uses: OpticDiff/code-reviewer-action@v1
  with:
    extra-args: --incremental --auto-approve --audit-log review.jsonl
  env:
    GOOGLE_CLOUD_PROJECT: ${{ secrets.GCP_PROJECT }}
    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

See examples/github/ for complete workflows: basic, SARIF + Code Scanning, self-hosted Ollama, multi-model consensus, AWS Bedrock.

⚡ Incremental Reviews & Commit Triggers (GitHub PRs & GitLab MRs)

When running in CI with --incremental, code-reviewer only analyzes files modified in the latest push/commit, saving LLM tokens and dramatically accelerating pipeline runtimes.

Automatic Commit & Event Inspection

  • GitLab CI: Automatically reads $CI_COMMIT_MESSAGE to inspect the latest pushed commit.
  • GitHub Actions: Automatically reads pull_request event payloads (GITHUB_EVENT_PATH / head_commit.message). When GitHub Actions checks out a synthetic merge commit (refs/pull/<PR>/merge), code-reviewer automatically inspects the secondary parent commit (HEAD^2) to retrieve the PR branch's actual commit message.

Forcing a Full Re-Review

To force a full review of all files across the entire PR or MR (bypassing incremental filtering and clearing cached findings for that review run), include a trigger string in your commit message:

git commit -m "fix: resolve rebase conflicts [re-review]"

By default, any commit message containing [re-review] or [full-review] (case-insensitive) triggers a full re-review. You can customize the trigger strings via:

  • CLI flag: --re-review-trigger="[re-review],[full-review]"
  • Environment variable: RE_REVIEW_TRIGGER="[re-review]"
  • Repository YAML: re_review_triggers: ["[re-review]", "[full-review]"] in .code-reviewer.yaml

Enterprise Platform Governance & Pod Specifics

Centrally enforce compliance rules, tenant isolation, and non-negotiable security floors across all service pods using modular multi-file configurations, globs, and monotonic severity floors:

code-reviewer --ci \
  --platform-config ".platform/rules/*.yaml" \
  --platform-review-md ".platform/guidelines/*.md"

Service pods retain full autonomy over their own .code-reviewer.yaml and REVIEW.md for domain-specific guidelines, while platform rules are guaranteed to take precedence without conflict.

👉 Read the full Platform Governance & Multi-File Architecture Guide.

Configuration

Settings are applied in priority order: CLI flags > env vars > .code-reviewer.yaml > defaults.

CLI Flags

Flag Description Default
--ci Run in CI mode (auto-detects GitHub/GitLab) —
--diff [ref] Review local git diff origin/HEAD
--files f1,f2 Review specific files —
--model Vertex AI model ID gemini-3.8-flash
--models Comma-separated models for multi-model consensus —
--consensus-threshold Min models that must agree on a finding 2 (when --models is set)
--focus Review focus (comma-separated) all
--min-severity Minimum severity to report low
--comment-mode notes or discussions notes
--chunk-strategy fail or split fail
--token-limit Context window token limit override (0 = use model default) —
--confidence-floor Minimum model confidence percent (1-100) required to report a finding 80
--context-files Directory-scoped guidance files (comma-separated, e.g. AGENTS.md) —
--extra-rules Additional prompt rules —
--custom-prompt Path to custom system prompt file —
--dry-run Analyze without posting false
--json Output results as JSON false
--sarif Write SARIF 2.1.0 output to file —
--sast Write GitLab SAST report to file —
--cache-dir Custom cache directory path ~/.cache/code-reviewer
--no-cache Disable review caching and force fresh analysis false
--no-color Disable ANSI color output false
--no-context Disable repo-aware cross-file context injection false
--max-tokens Maximum total tokens per review (0 = unlimited) 0
--max-files Maximum files before scope enforcement (0 = unlimited) 0
--scope-action Action when scope exceeded: warn or fail warn
--audit-log Write structured JSONL audit log to file —
--auto-approve Automatically approve MR/PR on clean review (CI mode only) false
--api-url OpenAI-compatible API endpoint (e.g., http://localhost:11434/v1) —
--api-key API key for HTTP provider (optional for IAM/ADC auth) —
--incremental Only review files changed in latest push (CI mode) false
--re-review-trigger Comma-separated commit message triggers that force a full PR/MR review in incremental mode [re-review],[full-review]
--proxy-url Route model calls through an LLM proxy (e.g. Candela) —
--summarize Generate structured MR summary instead of review false
--summary-update-description Update MR description with generated summary false
--intent Enable two-pass intent-aware review false (auto in CI)
--no-intent Disable intent-aware review (overrides CI default) false
--explain Explain the diff instead of reviewing it false
--fix Apply suggested fixes to the working tree false
--update-description Inject review summary into MR/PR description false
--cleanup-mode How to handle previous reviews: delete or resolve delete
--profile Review profile: platform, product, or all (default: all). See Dual-Review Architecture.
--platform-model Model override for --profile=platform (e.g. gemini-3.1-pro-preview) —
--product-model Model override for --profile=product (e.g. gemini-3.8-flash) —
--platform-visibility Platform findings visibility: public (default) or security-team-only public
--platform-config Platform rule config file, comma-separated paths, or glob —
--platform-review-md Platform review guidelines markdown file or glob —
--version Print version and exit —
init Interactively scaffold .code-reviewer.yaml (-y/--yes, -f/--force) —
hook install Install a pre-push git hook —
hook uninstall Remove the pre-push git hook —
cache stats Display cache entry count, total disk size, and oldest entry —
cache clear Purge all cached review entries —

Environment Variables

Variable Description Default
GOOGLE_CLOUD_PROJECT GCP project for Vertex AI Required
GOOGLE_CLOUD_LOCATION Vertex AI location (global, us, or a region) global
GITLAB_TOKEN GitLab API token Required in CI
GITLAB_BASE_URL GitLab API base URL https://gitlab.com
REVIEW_MODEL Model ID gemini-3.8-flash
REVIEW_MODELS Comma-separated models for consensus —
REVIEW_FOCUS Focus areas all
REVIEW_MIN_SEVERITY Min severity low
REVIEW_COMMENT_MODE Comment mode notes
REVIEW_CHUNK_STRATEGY Chunk strategy fail
REVIEW_TOKEN_LIMIT Context window token limit override —
REVIEW_CONFIDENCE_FLOOR Minimum model confidence percent (1-100) to report a finding 80
REVIEW_CONTEXT_FILES Directory-scoped guidance files, comma-separated —
REVIEW_CUSTOM_PROMPT Path to custom system prompt —
CODE_REVIEW_PLATFORM_CONFIG Platform rules YAML path, comma-separated paths, or glob —
CODE_REVIEW_PLATFORM_REVIEW_MD Platform guidelines markdown path or glob —
CODE_REVIEWER_PROFILE Review profile: platform, product, or all all
CODE_REVIEW_PLATFORM_MODEL Model override when --profile=platform —
CODE_REVIEW_PRODUCT_MODEL Model override when --profile=product —
CODE_REVIEW_PLATFORM_VISIBILITY Platform findings visibility: public or security-team-only public
REVIEW_OUTPUT_JSON Output results as JSON (true/false) false
SARIF_OUTPUT Write SARIF output to this file path —
SAST_OUTPUT Write GitLab SAST report to this file path —
INCREMENTAL Only review changed files in latest push (true/false) false
RE_REVIEW_TRIGGER Comma-separated commit message triggers forcing full PR/MR review [re-review],[full-review]
REVIEW_CACHE_DIR Custom cache directory path ~/.cache/code-reviewer
REVIEW_NO_CACHE Disable review caching (true/false) false
EXCLUDED_PATTERNS Glob patterns to skip go.sum,*.lock,vendor/*
REVIEW_MAX_TOKENS Maximum total tokens per review (0 = unlimited) 0
REVIEW_MAX_FILES Maximum files before scope enforcement (0 = unlimited) 0
REVIEW_SCOPE_ACTION Action when scope exceeded: warn or fail warn
REVIEW_AUDIT_LOG Write audit log to this file path —
REVIEW_AUTO_APPROVE Automatically approve on clean review (true/false) false
REVIEW_API_URL OpenAI-compatible API endpoint —
REVIEW_API_KEY API key for HTTP provider —
NO_COLOR Disable ANSI colors (no-color.org) —
GITHUB_TOKEN GitHub API token (auto-set in GitHub Actions) Required for GitHub
CODE_REVIEWER_UPDATE_DESCRIPTION Update MR/PR description with summary false
CODE_REVIEWER_CLEANUP_MODE Previous review cleanup mode delete

Per-Repo Config

Create .code-reviewer.yaml in your repo root:

model: gemini-3.8-flash
token_limit: 1000000     # Optional: explicit context window token limit override
confidence_floor: 80     # Optional: minimum model confidence percent (1-100) to report a finding
focus: [bugs, security]
context_files: [AGENTS.md]   # Optional: include the nearest AGENTS.md for each changed directory
min_severity: low
comment_mode: discussions
custom_prompt: prompts/team-rules.md
excluded_patterns:
  - "*.pb.go"
  - "generated/*"
extra_rules: |
  Always flag raw SQL string concatenation.
  Check that zerolog is used instead of log/fmt.
re_review_triggers:      # Force full re-review when commit message matches trigger
  - "[re-review]"
  - "[full-review]"
cache_dir: ~/.cache/code-reviewer # Optional: cache directory
no_cache: false                   # Optional: set true to disable caching
sast_output: gl-sast-report.json  # Optional: export native GitLab SAST report
max_tokens: 50000  # Optional: cap total tokens per review
api_url: http://localhost:11434/v1  # Optional: use a self-hosted model
update_description: false  # Inject summary into MR/PR description
cleanup_mode: delete       # delete or resolve
auto_approve: false     # Auto-approve MR/PR when zero findings (CI mode)
audit_log: review.jsonl # Write audit trail
max_files: 30           # Scope enforcement: warn when MR exceeds 30 files
scope_action: warn      # warn or fail

See .code-reviewer.example.yaml for all options.

Self-Hosted Models

Use --api-url to point at any OpenAI-compatible endpoint. No GCP project required.

# Ollama (local)
code-reviewer --diff --api-url http://localhost:11434/v1 --model qwen3:32b

# Gemma on Cloud Run
code-reviewer --diff --api-url https://gemma-review-xyz.run.app/v1 --model gemma-3-27b

# vLLM
code-reviewer --diff --api-url http://gpu-server:8000/v1 --model meta-llama/Llama-4-Scout-17B-16E

# With Candela proxy (observability + routing)
code-reviewer --diff --api-url http://candela:8080/v1 --model gemini-3.8-flash

Auto-Approve

When enabled, the tool automatically approves the MR/PR via the platform API if the review finds zero issues. Opt-in only.

code-reviewer --ci --auto-approve

All safety guards must pass:

Guard What it checks
Zero findings Review found no issues (pre-severity-filter)
Files reviewed > 0 Model actually reviewed something
No skipped files Token budget didn't trim any files
Budget not exceeded Runtime token limit wasn't hit mid-review
Scope not oversized MR doesn't exceed --max-files limit
Not truncated Model response wasn't cut short
Not draft MR/PR is not in draft/WIP state
CI mode, not dry-run Running in real CI pipeline
SHA pinned Approval targets the exact reviewed commit

If any guard fails, the reason is printed and approval is skipped.

Approval failures (e.g. missing token permissions) exit non-zero:

GitHub: ensure 'pull-requests: write' permission
GitLab: ensure token has 'api' scope

REVIEW.md

Create a REVIEW.md in your repo root to inject team-specific review instructions. Its contents are treated as the highest priority instruction in the system prompt — above the built-in rules, focus overlays, and extra rules.

## Our Review Standards

- All exported functions MUST have doc comments.
- Never use `fmt.Errorf` without `%w` for wrapping.
- Prefer table-driven tests over sequential assertions.
- Flag any use of `context.TODO()` — replace with a real context.

The file is discovered by walking up from the working directory, the same way .code-reviewer.yaml is found. Presence is logged at startup (review_md=true).

Directory Context Files

Set context_files: [AGENTS.md] (or --context-files, REVIEW_CONTEXT_FILES) to feed per-directory conventions to the model. For each changed directory, the nearest matching file is included, walking up to the repository root. A file shared by several changed directories is included once, and the combined content is capped at 16 KiB (excess is truncated).

The content is placed after the YAML rules in a delimited block labelled as untrusted guidance; it cannot override the rules or the output format. In CI mode the files are read from the base ref (like REVIEW.md), so a merge request cannot add or edit instructions for its own review. Locally, the working tree is used. Entries must be plain file names (no path separators). The option is off by default.

Repo-Aware Context

By default, code-reviewer uses Tree-sitter (pure-Go, no CGo) to extract symbols defined or modified in the diff, then searches the rest of the repo for usages of those symbols in unchanged files. The matched snippets are injected into the prompt as Related Unchanged Code, giving the model cross-file awareness without sending the entire repo.

Supported languages: Go, Kotlin, Java, Python, TypeScript.

Noise mitigation is built in:

  • Symbol names shorter than 4 characters are skipped.
  • If a symbol appears in more than 20 files, it is treated as too common and excluded.
  • Import statements and comments are filtered out.

Disable with --no-context or the disable_context: true config field.

Auto-Summary

Use --summarize to generate a structured MR description from the diff instead of a code review. The model analyzes the changes and produces:

  • Classification — feat, fix, refactor, chore, docs, test, security, config, perf
  • Intent — What the developer is trying to accomplish
  • Risk level — low, medium, high based on scope, complexity, and sensitivity
  • Scope areas — Which parts of the codebase are affected (e.g. auth, api, database)
  • Breaking changes — Any backward-incompatible changes
# Local: summarize your branch diff
code-reviewer --summarize --diff

# CI: post summary as MR comment
code-reviewer --summarize --ci

# JSON output for scripting
code-reviewer --summarize --diff --json

Pre-push Hook

Automatic code review before every push — catches issues before CI, before MR creation, before anyone sees your code.

# Install the hook (one-time setup)
code-reviewer hook install

# Now every git push triggers a review:
$ git push
🔍 code-reviewer: reviewing changes before push...

  ❌ HIGH  internal/auth/handler.go:58
           Nil pointer dereference — token is used before nil check

🚫 Push blocked: 1 HIGH severity finding. Fix or --no-verify to skip.

# Remove the hook
code-reviewer hook uninstall

Honors Git's core.hooksPath configuration. Won't overwrite foreign hooks.

Also works with the pre-commit framework:

# .pre-commit-config.yaml
- repo: https://github.com/OpticDiff/code-reviewer
  rev: v0.7.0
  hooks:
    - id: code-review
      stages: [pre-push]
      args: [--min-severity, high]

Other hook managers work too:

# lefthook.yml
pre-push:
  commands:
    code-review:
      run: code-reviewer --diff --min-severity high
# Husky (Node/JS projects)
npx husky add .husky/pre-push "code-reviewer --diff --min-severity high"

See examples/hooks/ for lefthook, Husky, and mise configurations.

Models

Model Tier Context Provider Best For
gemini-3.8-flash ⭐ Recommended 1M Vertex AI Fast CI reviews (default)
gemini-3.1-pro-preview ⭐⭐ Best 1M Vertex AI Deep analysis
claude-sonnet-5 ⭐⭐ Best 1M Vertex AI Code-focused reviews
mistral-medium-3 ⭐ Good 128k Vertex AI Alternative perspective
qwen3:32b ⭐ Good 32k Ollama / self-hosted Local, no cloud needed (32GB RAM)
qwen3:8b Demo 32k Ollama / self-hosted Quick local demo (8GB RAM)
Any model Varies Varies --api-url Any OpenAI-compatible endpoint

Gemini 3.x models are served from the global location (the default) and multi-regions, not from single regions such as us-central1.

Vertex AI models use Application Default Credentials. Self-hosted models use --api-url pointed at any OpenAI-compatible endpoint (Ollama, vLLM, Cloud Run, LiteLLM for Bedrock).

Multi-Model Consensus

Run multiple models in parallel and only keep findings that multiple models agree on — dramatically reducing false positives:

# Run Gemini + Claude, keep findings both agree on
code-reviewer --diff --models gemini-3.8-flash,claude-sonnet-5

# Require all 3 models to agree
code-reviewer --diff --models gemini-3.8-flash,gemini-3.1-pro-preview,claude-sonnet-5 --consensus-threshold 3

Findings are deduplicated by file + category + line proximity (±3 lines). The finding with the most detailed explanation is kept as the canonical result.

Custom Prompts

Replace the built-in system prompt with your own for specialized reviews:

code-reviewer --diff --custom-prompt path/to/my-prompt.md

The custom prompt replaces the built-in base prompt, but focus overlays (--focus) and extra rules (--extra-rules) are still appended automatically.

Example Prompts

Four example prompts are included in examples/prompts/:

Prompt Use Case
security-audit.md Deep security review: injection, auth, crypto, PII
strict.md Zero-tolerance review that flags everything
quick.md Fast review focused only on critical/high issues
architecture.md Architecture and design pattern review

Writing Custom Prompts

A custom prompt is a Markdown file with instructions for the AI reviewer. It should include:

  1. Persona — who the reviewer should act as
  2. Objective — what to focus on
  3. Output format — must instruct the model to return JSON matching the findings schema

See the example prompts for reference.

Auth

Vertex AI (Model)

Uses Application Default Credentials:

# Local development
gcloud auth application-default login

# CI/CD — use Workload Identity Federation or a service account key

GitLab API

Token Type Capabilities Setup
CI_JOB_TOKEN Notes API (simple comments) Automatic, zero config
Project Access Token Notes + Discussions API (inline diff) Settings → Access Tokens, api scope

GitHub API

Token Type Capabilities Setup
GITHUB_TOKEN (Actions) PR review comments, suggestions Automatic in GitHub Actions
Personal Access Token PR reviews outside CI repo scope required

Context Window Handling

Large MRs may exceed the model's context window. The --chunk-strategy flag controls behavior:

  • fail (default) — Errors with a helpful message if the diff is too large. Forces teams to scope MRs.
  • split — Auto-splits diffs into file groups, runs separate model calls, merges results.

The chunker interface is modular — custom strategies can be added.

Caching

code-reviewer caches review results per file diff, so unchanged files skip the LLM call on subsequent runs. This dramatically reduces API costs and latency on iterative PRs.

How it works:

  • Each cache key includes the file diff, model, prompt inputs, custom rules, path metadata, and schema version
  • Cache hits return findings instantly without an LLM call
  • Entries expire after 7 days by default
  • Use --no-cache to force a fresh review

Configuration:

# .code-reviewer.yaml
cache_dir: ~/.cache/code-reviewer   # Default location
no_cache: false                      # Set to true to disable
cache_max_age: 7d                    # Auto-expire entries
# CLI flags
code-reviewer --no-cache              # Skip cache for this run
code-reviewer --cache-dir /tmp/cr     # Custom cache location
code-reviewer --cache-max-age 24h     # Custom expiry

# Environment variables
export REVIEW_CACHE_DIR=/tmp/cr
export REVIEW_NO_CACHE=true

Cache management:

code-reviewer cache stats    # Show entry count, size, oldest entry
code-reviewer cache clear    # Remove all cached entries

Security

  • Input validation — Diff refs and file paths are validated to prevent command injection via git arguments.
  • SSRF protection — GitLab pagination URLs are validated against the configured base URL to prevent token exfiltration.
  • Prompt injection resistance — The system prompt includes adversarial content detection instructions.

Development

# Enter dev shell
nix develop

# Build
go build ./cmd/code-reviewer

# Test
go test ./... -race -count=1 -cover

# Lint
golangci-lint run

# Check version
./code-reviewer --version

CI runs build, test, and lint as 3 parallel jobs. CodeRabbit provides automated PR reviews on GitHub.

Releasing

Releases are automated via GoReleaser. Tag a version to publish binaries to GitHub Releases:

git tag -a v0.7.0 -m "v0.7.0"
git push origin v0.7.0
# → GitHub Actions: test → build 6 binaries → publish to Releases

Inline Suppressions

Suppress specific findings directly in your source code:

// opticdiff:ignore no-sql-injection: parameterized at the caller
query := "SELECT * FROM users WHERE id = " + id

Suppress all rules on a line:

// opticdiff:ignore all: false positive, tested extensively
password := os.Getenv("DB_PASSWORD")

Note: Platform rules deny suppression by default (allow_suppression: false in the rule YAML). Only repo-sourced rules allow inline suppression unless explicitly opted in. For full details on rule-level suppression and governance, see PLATFORM-GOVERNANCE.md.

License

Apache 2.0

来源:GitHub · github.com