
Coderabbit
- 79 installs
- 22 repo stars
- Updated August 1, 2026
- itechmeat/llm-code
Run AI-powered code review on pull requests or local changes with CodeRabbit, configuring rules via .coderabbit.yaml and triaging findings.
About
Covers CodeRabbit AI code review via CLI and PR commands, with .coderabbit.yaml config, 40+ supported linters, and a triage workflow. A developer uses it when reviewing PRs or local changes with AI.
- CLI and @coderabbitai PR commands with 40+ linters
- Configuration via .coderabbit.yaml plus a triage-and-fix workflow
Coderabbit by the numbers
- 79 all-time installs (skills.sh)
- +1 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #491 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/itechmeat/llm-code --skill coderabbitAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 79 |
|---|---|
| repo stars | ★ 22 |
| Last updated | August 1, 2026 |
| Repository | itechmeat/llm-code ↗ |
What it does
Run AI-powered code review on pull requests or local changes with CodeRabbit, configuring rules via .coderabbit.yaml and triaging findings.
Files
CodeRabbit
AI-powered code review for pull requests and local changes.
Quick Navigation
| Task | Reference |
|---|---|
| Install & run CLI | cli-usage.md |
| Configure .coderabbit.yaml | configuration.md |
| Supported tools (40+ linters) | tools.md |
| Git platform setup | platforms.md |
| PR commands (@coderabbitai) | pr-commands.md |
| Claude/Cursor/Codex workflow | agent-integration.md |
| Triage findings | triage.md |
| Fix single issue | fix.md |
| Reporting & metrics | end-to-end-workflow.md |
| End-to-end workflow | end-to-end-workflow.md |
| Windows/WSL setup | windows-wsl.md |
Prerequisites Check (MUST RUN BEFORE REVIEW)
Before running CodeRabbit CLI, verify ALL of the following:
# 1. CLI installed?
which coderabbit || echo "MISSING: install with: curl -fsSL https://cli.coderabbit.ai/install.sh | sh"
# 2. Authenticated?
coderabbit auth status 2>&1 | grep -q "Logged in" || echo "MISSING: run coderabbit auth login"
# 3. Git repo has at least one commit? (CRITICAL — CLI crashes with GitError on empty repos)
git rev-parse HEAD >/dev/null 2>&1 || echo "MISSING: repo has no commits — make at least one commit first"
# 4. Base branch exists? (CLI defaults to 'main')
git rev-parse main >/dev/null 2>&1 || echo "WARNING: 'main' branch not found — use --base <branch>"If any check fails, fix it before running the review. Do NOT proceed with a broken state.
Authentication failure rule: If authentication check fails (step 2), the agent MUST:
1. Stop immediately — do not attempt to run the review 2. Notify the user that CodeRabbit CLI is not authenticated 3. Show the user the exact command to authenticate: coderabbit auth login 4. Wait for the user to complete authentication before retrying 5. Do NOT attempt to run coderabbit auth login on behalf of the user — it requires interactive browser redirect
Quick Start
Run Review
# AI agent workflow (most common) — note: 'review' subcommand is optional
coderabbit review --prompt-only --type uncommitted --no-color
# If base branch is not 'main' (e.g., master, develop):
coderabbit review --prompt-only --type uncommitted --base master --no-color
# Plain text output (human-readable)
coderabbit review --plain --type uncommitted --no-colorLocal Capture Script
Persist output to a file for later analysis:
# IMPORTANT: use absolute path to the skill's script directory
python3 ~/.claude/skills/coderabbit/scripts/run_coderabbit.py --output coderabbit-report.txtOptions:
--outputto choose a different file name (saved to.code-review/in repo root)--timeoutto adjust the timeout in seconds (default: 1800)--baseto specify base branch (default: auto-detect from git)
PR Commands
@coderabbitai review # Incremental review
@coderabbitai full review # Complete review
@coderabbitai simplify # Apply targeted simplifications to changed files
@coderabbitai fix merge conflict # Attempt automatic merge-conflict resolution
@coderabbitai pause # Stop auto-reviews
@coderabbitai resume # Resume auto-reviews
@coderabbitai resolve # Mark comments resolvedSeverity Matrix
| Severity | Action | Examples |
|---|---|---|
| CRITICAL | Fix immediately | Security, data loss, tenant isolation |
| HIGH | Should fix | Reliability, performance, architecture violations |
| MEDIUM | Judgment call | Maintainability, type safety (quick wins) |
| LOW | Skip | Style/formatting, subjective nits |
AI Agent Workflow Pattern
Implement [feature] and then run CodeRabbit CLI in a background terminal.
Wait for it to complete, then read the report. Fix CRITICAL/HIGH issues. Ignore nits.Step-by-step:
1. Run prerequisites check (see above) — fix any issues before proceeding 2. Detect base branch: git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null or fall back to main/master 3. Run CLI in background: coderabbit review --prompt-only --type uncommitted --base <branch> --no-color 4. Reviews take 7-30+ minutes — run in background (run_in_background=true) 5. Read output when process completes 6. Fix CRITICAL/HIGH findings, skip LOW 7. Limit to 2-3 review iterations maximum
Troubleshooting
[error] stopping cli with no details
Run with DEBUG=* to see the actual error:
DEBUG=* coderabbit review --prompt-only --type uncommitted 2>&1 | grep -E "(ERROR|error|GitError)"Check the log file:
ls -t ~/.coderabbit/logs/ | head -1 | xargs -I{} cat ~/.coderabbit/logs/{}Common errors
| Error | Cause | Fix |
|---|---|---|
GitError (no details) | No commits in repo | Make at least one commit |
Failed to get commit SHA for branch main | Base branch doesn't exist | Use --base master or --base <your-branch> |
Raw mode is not supported | Interactive mode in non-TTY | Always use --prompt-only or --plain |
[error] stopping cli after auth | Token expired | Re-run coderabbit auth login |
| CLI hangs / no output | Large changeset | Use --type uncommitted to limit scope |
Check auth status
coderabbit auth statusLinked Repositories (2026-02-18)
CodeRabbit can analyze linked repositories during PR review to catch cross-repo breakages (API/type/dependency drift).
- Configure linked repositories in Knowledge Base settings.
- As of 2026-03-11, Pro plans can link up to 2 repositories for Multi-Repo Analysis.
- Use this when changes in one repo affect contracts in another.
- Treat cross-repo findings as HIGH/CRITICAL when they indicate runtime incompatibility.
Dashboard and Reporting (2026-03-12)
- Dashboard metrics are now split between Git platform reviews and IDE/CLI reviews.
- Reporting surfaces now include Git-platform pages like Knowledge Base, Pre-merge Checks, and Reporting, plus IDE/CLI pages like Summary, Organization Trends, and Data Metrics.
- Team filters are available across dashboards; use them when review volume or findings need to be separated by team rather than repository alone.
Simplify Code (Open Beta, Pro) (2026-03-13)
@coderabbitai simplifyruns an agentic cleanup pass over the files changed in the PR.- It focuses on extracting reusable helpers, simplifying conditionals, and removing redundancy while preserving behavior.
- CodeRabbit validates the result with the repository's existing test suite and can either open a follow-up PR or commit directly to the branch.
- Not available for fork PR direct-commit mode.
Chat Access Control (GitHub Orgs) (2026-03-16)
- Use
chat.allow_non_org_members: falsein.coderabbit.yamlwhen PR comment chat must stay limited to organization members. - This affects comment-thread interaction only; automatic PR review behavior is unchanged.
- Default remains
true, so public-repo chat stays open unless you opt out.
Resolve Merge Conflicts (Open Beta, Pro) (2026-03-17)
- CodeRabbit can detect merge conflicts during PR review and offer one-click or comment-triggered resolution.
- Trigger with
@coderabbitai fix merge conflictor the Walkthrough checkbox on GitHub. - It commits a proper merge commit when successful, but declines if the resolution is ambiguous or touches security-critical logic such as auth, encryption, secrets, or access control.
- If any conflicted file is declined, the whole auto-resolution attempt is aborted and no partial commit is created.
Betterleaks (replaces Gitleaks) (2026-03-19)
- Secret scanning now uses Betterleaks (improved detection over Gitleaks).
- The
gitleaksconfig key in.coderabbit.yamlnow controls Betterleaks. - Default remains enabled; existing secret scanning continues without changes.
Slop Detection (2026-03-24)
- Automatically detects low-quality AI-generated PRs on public GitHub repositories.
- Flagged in the PR Walkthrough comment.
- Opt-in label tagging:
reviews:
slop_detection:
enabled: true # default
label: "slop" # optional labelBitbucket Data Center (2026-03-24)
- Full support for Bitbucket Data Center as a Git platform.
- OAuth 2.0, automated webhook configuration, and full PR review capabilities.
Audit Logs (2026-03-25)
- Tamper-resistant audit log for every administrative action across the workspace.
- Covers seat assignments/removals, role changes, org/repo changes, subscription events, config updates, and API key operations.
- Accessible in Settings UI or via REST API for automated export.
CLI Agent Mode (2026-03-31)
coderabbit review --agentoutputs results in structured JSON format for Skills and agent integrations.
CLI 0.4.x (2026-04-01 to 2026-04-06)
coderabbit auth logincompletes fully in the browser.--agentnow covers auth-related workflows better for agent environments.--dirreplaces--cwdfor subdirectory-scoped reviews.coderabbit statsis available for local review telemetry.
GitLab SSH Access (2026-04-02)
- Self-managed GitLab can use SSH clone credentials instead of HTTPS.
- This is useful when GitLab instances do not expose HTTPS cloning or enforce SSH-only repository access.
Codex Plugin (2026-04-14)
- CodeRabbit is available as a dedicated Codex plugin in addition to the standalone CLI.
- The plugin verifies CLI install/auth, triggers reviews from natural language or
@coderabbit, and keeps findings inside the agent loop for follow-up fixes.
Global Overrides (2026-04-16)
- Organization admins can enforce top-priority configuration overrides across every repository.
- Nested objects merge with lower layers; arrays and scalar values replace them.
Custom Finishing Touch Recipes (Early Access) (2026-02-23)
Define reusable, named "finishing touch" recipes that apply agentic code changes to your PR.
See configuration.md for a minimal example.
Minimal Configuration
# .coderabbit.yaml
language: en-US
reviews:
profile: chill
high_level_summary: true
tools:
gitleaks:
enabled: true
ruff:
enabled: trueCritical Prohibitions
- Do not introduce fallbacks, mocks, or stubs in production code
- Do not broaden scope beyond what CodeRabbit flagged
- Do not "fix" style nits handled by formatters/linters
- Do not ignore CRITICAL findings; escalate if unclear
- Stop and resolve CLI errors (auth/network) before fixing code
- Do not run CLI on a repo with no commits — it will silently crash
Links
Templates
- coderabbit.minimal.yaml — Minimal configuration
- coderabbit.full.yaml — Full example with all options
- agent-prompts.md — Ready-to-use AI agent prompts
CodeRabbit AI Agent Prompts
Ready-to-use prompts for integrating CodeRabbit with AI coding agents.
Basic Review Prompt
Run coderabbit --prompt-only --type uncommitted and fix any critical issues.Full Implementation + Review
Implement [FEATURE DESCRIPTION] and then run coderabbit --prompt-only -t uncommitted,
let it run as long as it needs (run it in the background) and fix any critical issues.
Ignore style nits.Review with Severity Filter
Run coderabbit --prompt-only and evaluate the findings:
- Fix all CRITICAL and HIGH severity issues
- Defer MEDIUM issues if not quick wins
- Skip LOW severity (style/formatting)
Provide a summary of what was fixed and what was deferred.Loop-Limited Review
Run coderabbit --prompt-only --type uncommitted. Fix critical issues only.
Then run CodeRabbit again to verify.
Only run the loop twice. If on the second run you don't find any critical issues,
ignore remaining nits and report completion with a summary.Feature Branch Review
I'm working on [FEATURE]. Run coderabbit --prompt-only --base develop
to compare against the develop branch. Focus on:
- Security vulnerabilities
- Breaking changes
- Performance regressions
Fix critical issues and document any architectural concerns.Cursor Rules Addition
Add to .cursorrules:
# CodeRabbit Integration
CodeRabbit CLI is installed. Use it to review code changes.
Commands:
- `cr -h` for help
- `coderabbit --prompt-only -t uncommitted` for AI-optimized review
Rules:
- Run CodeRabbit with --prompt-only flag
- Don't run more than 3 times per change set
- Fix CRITICAL issues immediately
- Document MEDIUM issues if deferring
- Skip LOW (style) issuesClaude.md Addition
Add to claude.md (Pro feature - CodeRabbit reads this):
## Code Review Standards
When CodeRabbit reviews my code, apply these preferences:
### Focus Areas
- Security vulnerabilities (SQL injection, XSS, auth bypass)
- Data integrity (race conditions, transaction handling)
- Error handling (uncaught exceptions, missing validations)
- Performance (N+1 queries, memory leaks)
### Ignore
- Formatting (handled by Prettier/Black)
- Import ordering (handled by isort/eslint)
- Line length warnings
### Style Preferences
- Prefer explicit error handling over silent failures
- Use typed parameters and return values
- Keep functions under 50 lines# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
# CodeRabbit Configuration - Full Example
# See full reference: https://docs.coderabbit.ai/reference/configuration
language: en-US
tone_instructions: "Be concise. Focus on bugs, security issues, and correctness."
reviews:
# Review style: chill (fewer comments) or assertive (more detailed)
profile: chill
# Summary and visualization
high_level_summary: true
sequence_diagrams: true
poem: false
# Auto-review settings
auto_review:
enabled: true
auto_incremental_review: true
drafts: false
ignore_title_keywords:
- "WIP"
- "DO NOT MERGE"
- "[skip ci]"
labels:
- "!wip" # Skip PRs with 'wip' label
base_branches:
- "main"
- "develop"
# Path filters - exclude generated/vendor files
path_filters:
- "!dist/**"
- "!build/**"
- "!node_modules/**"
- "!vendor/**"
- "!*.min.js"
- "!*.min.css"
- "!package-lock.json"
- "!yarn.lock"
- "!pnpm-lock.yaml"
# Path-specific instructions
path_instructions:
- path: "**/*.py"
instructions: "Check for type hints, proper exception handling, and PEP 8 compliance."
- path: "**/*.ts"
instructions: "Verify strict TypeScript types, avoid 'any', check null handling."
- path: "src/api/**"
instructions: "Verify authentication, authorization, input validation, and rate limiting."
- path: "**/*test*"
instructions: "Ensure tests are meaningful, cover edge cases, and use proper assertions."
- path: "**/migrations/**"
instructions: "Check for reversibility, data preservation, and index usage."
# Finishing touches (Pro feature)
finishing_touches:
docstrings:
enabled: true
unit_tests:
enabled: true
# Pre-merge checks
pre_merge_checks:
title:
mode: warning
description:
mode: warning
docstrings:
mode: warning
threshold: 80
# Tools configuration
tools:
# Security
gitleaks:
enabled: true
semgrep:
enabled: true
# Python
ruff:
enabled: true
pylint:
enabled: true
# JavaScript/TypeScript
eslint:
enabled: true
biome:
enabled: true
# Go
golangci-lint:
enabled: true
config_file: ".golangci.yml"
# Infrastructure
hadolint:
enabled: true
checkov:
enabled: true
actionlint:
enabled: true
yamllint:
enabled: true
# Documentation
markdownlint:
enabled: true
shellcheck:
enabled: true
# Code generation settings
code_generation:
docstrings:
language: en-US
unit_tests:
path_instructions:
- path: "**/*.py"
instructions: "Use pytest with fixtures. Include edge cases."
- path: "**/*.ts"
instructions: "Use Jest or Vitest. Mock external dependencies."
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
# CodeRabbit Configuration - Minimal
# See full reference: https://docs.coderabbit.ai/reference/configuration
language: en-US
reviews:
profile: chill
high_level_summary: true
AI Agent Integration
CodeRabbit CLI integrates with AI coding agents (Claude Code, Cursor, Codex) for autonomous review-fix workflows.
Core Workflow
1. Implement feature 2. Run prerequisites check (see below) 3. Run coderabbit review --prompt-only in background 4. AI agent evaluates findings 5. Fix critical issues 6. Re-run CodeRabbit to verify (max 2-3 iterations)
Prerequisites (MUST CHECK BEFORE EVERY REVIEW)
# All of these must pass:
which coderabbit # CLI installed
coderabbit auth status 2>&1 | grep -q "Logged in" # Authenticated
git rev-parse HEAD >/dev/null 2>&1 # Has at least one commit
git rev-parse main >/dev/null 2>&1 # Base branch exists (or use --base)Critical: CodeRabbit CLI silently crashes with [error] stopping cli if:
- The repo has no commits (GitError)
- The base branch doesn't exist (defaults to
main)
Claude Code Integration
Prerequisites
# Install CodeRabbit CLI
curl -fsSL https://cli.coderabbit.ai/install.sh | sh
source ~/.zshrc
# Authenticate
coderabbit auth loginRunning Reviews
# Auto-detect base branch and run review
python3 ~/.claude/skills/coderabbit/scripts/run_coderabbit.py
# Or run CLI directly (specify base branch if not 'main'):
coderabbit review --prompt-only --type uncommitted --base master --no-colorKey Components
review— subcommand (optional, it's the default)--prompt-only— AI-optimized output format (implies--plain)--no-color— strip ANSI codes for clean parsing--base <branch>— specify base branch (default:main)--type uncommitted— only review working directory changes- Background execution — reviews take 7-30+ minutes
Configuration
CodeRabbit reads claude.md for coding standards (Pro feature).
Cursor Integration
Setup
Let's verify you can run the CodeRabbit CLI.
Run the terminal command: coderabbit auth status and tell me the output.Usage Prompt
Implement phase 7.3 - adding Withings smart scale integration.
Then run coderabbit review --prompt-only --type uncommitted --no-color.
Once it completes, fix any critical issues.Cursor Rules File
Add to .cursorrules:
# Running the CodeRabbit CLI
CodeRabbit is already installed in the terminal. Run it as a way to review your code.
Run the command: cr review -h for details on commands available.
In general, I want you to run coderabbit with the `--prompt-only` flag.
To review uncommitted changes run:
`coderabbit review --prompt-only -t uncommitted --no-color`.
IMPORTANT: Before running CodeRabbit, verify the repo has at least one commit
(git rev-parse HEAD) and that the base branch exists.
Don't run CodeRabbit more than 3 times in a given set of changes.Codex Integration
CodeRabbit now has a dedicated Codex plugin in addition to the standalone CLI.
Setup flow:
1. Install Codex. 2. Install/authenticate CodeRabbit CLI. 3. Install the coderabbit plugin from the Codex plugin marketplace. 4. Trigger reviews with natural language or @coderabbit mentions.
Examples:
Review my current changes with CodeRabbit
@coderabbit Review my current changesOperational notes:
- The plugin verifies CLI installation and authentication before running.
- It summarizes the diff first, then reports findings with severity, file path, impact, and fix direction.
- Keep direct CLI usage for debugging/manual control; let the plugin drive normal Codex review loops.
Structured agent output
- Prefer
coderabbit review --agentwhen another agent needs machine-readable findings. - Consume the output line by line and branch on event
type; findings include severity, file path, and codegen guidance.
Recommended Commands
# Review uncommitted changes (most common)
coderabbit review --prompt-only -t uncommitted --no-color
# Specify base branch (if not 'main')
coderabbit review --prompt-only --base master --no-color
# Review all changes
coderabbit review --prompt-only --type all --no-colorLoop Limit Pattern
Prevent infinite iteration:
Only run the loop twice. If on the second run you don't find any critical issues,
ignore the nits and you're complete. Give me a summary of everything that was
completed and why.Severity Prioritization
Instruct agent to prioritize:
Evaluate the fixes and considerations. Fix major issues only, or fix any critical
issues and ignore the nits.Troubleshooting
[error] stopping cli with no details
1. Check git rev-parse HEAD — repo must have at least one commit 2. Check git rev-parse main — base branch must exist (use --base to override) 3. Check coderabbit auth status — must be authenticated 4. Run with debug: DEBUG=* coderabbit review --prompt-only 2>&1 | grep ERROR 5. Check logs: ls -t ~/.coderabbit/logs/ | head -1 | xargs -I{} cat ~/.coderabbit/logs/{}
Review Not Finding Issues
1. Check coderabbit auth status 2. Verify git status shows tracked changes 3. Use --type uncommitted for working directory 4. Specify --base develop if main branch differs
Agent Not Applying Fixes
1. Ensure background execution in prompt 2. Use --prompt-only mode 3. Explicitly say "fix the issues found by CodeRabbit" 4. Check if review finished: "Is CodeRabbit finished running?"
Managing Duration
- Use
--type uncommittedfor faster reviews - Work on smaller feature branches
- Break large features into reviewable chunks
CodeRabbit CLI Usage
Installation
curl -fsSL https://cli.coderabbit.ai/install.sh | shRestart shell after installation:
source ~/.zshrc # or source ~/.bashrcAuthentication
coderabbit auth login
# Short alias
cr auth loginAuthentication completes in the browser; no token copy-paste step is required in current CLI builds.
Check status:
coderabbit auth statusPrerequisites
CodeRabbit CLI requires:
1. Initialized git repo — must be run from within a git repository 2. At least one commit — the CLI uses git diff internally and will crash with GitError on repos with no commits 3. Valid base branch — defaults to main; use --base if your branch is named differently (e.g., master, develop)
Review Commands
The review subcommand is the default — coderabbit --plain and coderabbit review --plain are equivalent.
Output Modes
| Mode | Command | Use Case |
|---|---|---|
| Interactive | coderabbit review | Browsable findings, apply fixes inline |
| Plain text | coderabbit review --plain | Detailed feedback with suggestions |
| Prompt-only | coderabbit review --prompt-only | Optimized for AI agents |
| Agent JSON | coderabbit review --agent | Structured events for agent workflows |
--agent writes JSON objects to stdout (one per line). Expect event types such as review_context, status, finding, complete, and error.
Review Types
| Type | Command | Description |
|---|---|---|
| All changes | coderabbit review --type all | Both committed and uncommitted (default) |
| Uncommitted | coderabbit review --type uncommitted | Working directory only |
| Committed | coderabbit review --type committed | Committed changes only |
Base Branch
# Default assumes 'main' branch — override if needed
coderabbit review --base master
coderabbit review --base developCombined Examples
# AI agent workflow: uncommitted changes, non-interactive
coderabbit review --prompt-only --type uncommitted --base master --no-color
# Compare feature branch against develop
coderabbit review --prompt-only --base develop --no-color
# Human-readable review
coderabbit review --plain --type uncommitted --no-colorCommand Reference
| Command | Description |
|---|---|
coderabbit review | Run code review (interactive by default) |
coderabbit review --plain | Plain text output |
coderabbit review --prompt-only | Minimal AI-optimized output |
coderabbit auth login | Authenticate with CodeRabbit |
coderabbit auth status | Check authentication status |
coderabbit stats | Show local review statistics |
coderabbit update | Update CLI to latest version |
cr | Short alias for all commands |
Additional Options
| Option | Description |
|---|---|
-t, --type <type> | Review type: all, committed, uncommitted |
-c, --config <files...> | Additional instruction files (claude.md, .cursorrules) |
--base <branch> | Base branch for comparison (default: main) |
--base-commit <commit> | Base commit on current branch |
--dir <path> | Review directory path (replaces --cwd) |
--no-color | Disable colored output (recommended for agents) |
--api-key <key> | API key for authentication (usage-based billing) |
Timing Notes
- Reviews take 7-30+ minutes depending on scope
- Use
--type uncommittedfor faster feedback - Background execution recommended for AI agent workflows
- Use
--no-colorwhen capturing output programmatically
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
[error] stopping cli + GitError in logs | No commits in repo | Create at least one commit |
Failed to get commit SHA for branch main | Base branch doesn't exist | Use --base master or appropriate branch |
Raw mode is not supported | Interactive mode without TTY | Use --prompt-only or --plain |
| Silent failure, empty output | Auth expired | Re-run coderabbit auth login |
Debug mode: DEBUG=* coderabbit review --prompt-only 2>&1 Logs: ~/.coderabbit/logs/
Uninstall
# If installed via script
rm $(which coderabbit)
# If installed via Homebrew
brew remove coderabbitCodeRabbit Configuration
CodeRabbit can be configured via .coderabbit.yaml in repository root.
Configuration Priority (highest to lowest)
0. Global overrides — Organization Settings → Global Overrides 1. Local .coderabbit.yaml — repository root 2. Central configuration — dedicated coderabbit repository 3. Repository settings — Web UI per-repository 4. Organization settings — Web UI organization-wide 5. Schema defaults
Configuration is resolved through the precedence chain above, and Global overrides are applied last as the authoritative enforcement layer.
Global Overrides (2026-04-16)
- Use Global overrides when organization admins need settings that repositories cannot bypass.
- Nested objects merge with the effective lower-priority configuration.
- Arrays and scalar values replace the lower-priority value entirely.
- The PR comment shows the winning configuration source, which is useful during rollout/debugging.
Central configuration notes
- The central
coderabbitrepository must itself be installed in CodeRabbit so the config file can be read. - On GitLab, CodeRabbit can resolve the nearest
coderabbitrepository in the nested group hierarchy, which enables team-specific central configs with fallback to parent groups.
Minimal Example
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
language: en-US
tone_instructions: "Be concise and focus on critical issues only"
reviews:
profile: chill
high_level_summary: trueKey Settings
Knowledge Base: Linked Repositories (2026-02-18)
CodeRabbit can traverse linked repositories during PR review to detect cross-repo issues:
- Breaking API contract changes
- Type mismatches across repos
- Dependency drift between connected services/libraries
Operational guidance:
- Configure linked repositories in CodeRabbit Knowledge Base settings.
- Use linked repos for multi-repo systems where PRs frequently impact shared contracts.
- Keep links minimal and relevant to reduce noisy findings.
General
| Setting | Type | Default | Description |
|---|---|---|---|
language | string | en-US | Review language (ISO code) |
tone_instructions | string | "" | Custom tone (max 250 chars) |
early_access | boolean | false | Enable early-access features |
Chat
GitHub organization repositories can restrict PR comment chat to org members only:
chat:
allow_non_org_members: false- Default:
true - Effect: limits comment-thread interaction to organization members
- Does not affect automatic PR review eligibility or background review execution
Reviews
| Setting | Type | Default | Description |
|---|---|---|---|
reviews.profile | enum | chill | chill or assertive |
reviews.high_level_summary | boolean | true | Summary in PR description |
reviews.sequence_diagrams | boolean | true | Generate diagrams |
reviews.poem | boolean | true | Generate poem in walkthrough |
reviews.path_filters | array | [] | Include/exclude patterns (!dist/**) |
reviews.auto_pause_after_reviewed_commits | integer | 5 | Auto-pause reviews after N reviewed commits (set 0 to disable) |
Auto Review
reviews:
auto_review:
enabled: true
auto_incremental_review: true
drafts: false
ignore_title_keywords: ["WIP", "DO NOT MERGE"]
labels: ["!wip"] # Skip PRs with 'wip' label
base_branches: ["develop", "main"]Path Instructions
reviews:
path_instructions:
- path: "**/*.ts"
instructions: "Focus on type safety and null checks"
- path: "src/api/**"
instructions: "Verify authentication and authorization"Tools Configuration
reviews:
tools:
eslint:
enabled: true
gitleaks:
enabled: true
ruff:
enabled: true
golangci-lint:
enabled: true
config_file: ".golangci.yml"Pre-merge Checks
Override restrictions (2026-02-25):
reviews:
pre_merge_checks:
override_requested_reviewers_only: trueWhen enabled, pre-merge check overrides can be restricted to requested reviewers (excluding the PR author). Overrides include an audit trail in the Pre-Merge Checks section.
reviews:
pre_merge_checks:
title:
mode: warning # off, warning, error
description:
mode: warning
docstrings:
mode: warning
threshold: 80Finishing Touches
reviews:
finishing_touches:
docstrings:
enabled: true
unit_tests:
enabled: trueCustom Recipes (early access)
Create up to 5 named recipes under reviews.finishing_touches.custom. Each recipe has a name and freeform instructions.
Requirements:
- Set
early_access: truein.coderabbit.yaml. - GitHub only (GitLab support is not available yet).
Trigger a recipe via PR comment:
@coderabbitai run <recipe name>Minimal example:
early_access: true
reviews:
finishing_touches:
custom:
- name: "Harden error handling"
instructions: "Replace silent fallbacks with explicit errors; add typed exceptions."
- name: "Add missing tests"
instructions: "Add unit tests for edge cases; avoid snapshot-only coverage."Labeling Configuration
reviews:
suggested_labels: true
auto_apply_labels: false
labeling_instructions:
- label: "frontend"
instructions: "Apply when PR contains React component changes"
- label: "security"
instructions: "Apply for auth, encryption, or sensitive data handling"Complete Example
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
language: en-US
tone_instructions: "Be direct. Focus on bugs and security issues."
chat:
allow_non_org_members: false
reviews:
profile: chill
high_level_summary: true
sequence_diagrams: true
poem: false
auto_review:
enabled: true
drafts: false
ignore_title_keywords: ["WIP"]
path_filters:
- "!dist/**"
- "!node_modules/**"
- "!*.min.js"
path_instructions:
- path: "**/*.py"
instructions: "Check for type hints and proper exception handling"
tools:
ruff:
enabled: true
gitleaks:
enabled: true
eslint:
enabled: trueCodeRabbit End-to-End Workflow
Complete workflow from running a review to implementing fixes.
When to use
- You want a structured, pre-PR review to catch correctness/security issues early.
- You want to use CodeRabbit output as an input for a focused, minimal-fix workflow.
Inputs
- Target scope: repo root or a subfolder (e.g.
src/). - CodeRabbit output (prompt-only) for triage.
If the team is close to PR review limits, confirm whether the Usage-based add-on is enabled before assuming PR/CLI reviews will continue past the plan cap.
Process
1. Run CodeRabbit (prompt-only) for the relevant scope. 2. If the review fails (rate limit/auth/network), stop and resolve the failure first. 3. Triage findings with triage.md. 4. If the PR needs agentic cleanup, optionally trigger @coderabbitai simplify and review the produced branch/commit before touching code manually. 5. If the PR is blocked by merge conflicts, use the merge-conflict path below instead of manual triage. 6. Implement fixes with fix.md (one issue at a time). 7. Verify quality gates (project checks, tests).
Merge Conflict Resolution Path (2026-03-17)
Use this when CodeRabbit detects merge conflicts in a PR or merge request.
Trigger options:
@coderabbitai fix merge conflict- Resolve merge conflicts checkbox in the GitHub Walkthrough
Operational behavior:
- CodeRabbit simulates the merge in a sandbox, analyzes the intent of both sides, edits the repo, and validates the result.
- On success it creates a proper merge commit with two parents.
- If the branch changes during processing, the run is aborted and must be retried.
- If any file is ambiguous or security-sensitive, the entire attempt is declined and no partial commit is created.
Treat these conflict classes as manual-review territory even if CodeRabbit offers the action:
- authentication or authorization logic
- encryption, secrets handling, or access control
- mutually exclusive architectural decisions that need product judgment
Critical prohibitions
- Do not introduce fallbacks, mocks, or stubs in production code.
- Do not "fix" style nits if tooling already covers them.
- Do not broaden the scope beyond the reviewed findings.
Reporting & Metrics
Usage-based review continuity (2026-04-08)
- PR reviews and CLI-triggered reviews follow the same usage-based add-on behavior when a plan limit is exceeded.
- When enabled, only the overflow is billed; the normal usage remains on-plan.
- Treat sudden review stoppage after plan exhaustion as an account/billing configuration issue before debugging the CLI.
Dashboard Structure (2026-03-12)
CodeRabbit dashboards are now split into two top-level review surfaces:
- Git platform reviews for GitHub/GitLab/Azure DevOps/Bitbucket pull-request review metrics.
- IDE/CLI reviews for local or editor-driven reviews through extensions and the CLI.
Use the dashboard split to avoid mixing PR review trends with IDE/CLI review adoption data.
Team filters are available across the dashboards, which is useful when adoption or findings need to be compared across teams instead of across the entire organization.
Data Export (Dashboard)
Use Data Export to download per‑PR review metrics as CSV for a selected date range (last 7/30/90 days or a custom range within the last year). The export includes fields like complexity scores, review times, and comment breakdowns by severity/category.
Dashboard drill-down (2026-02-24):
- You can drill into severity/category metrics to open a Comment Details view (useful for audits and debugging false positives).
Additional Git-platform dashboard pages (2026-03-12):
- Knowledge Base: review how Learnings and MCP integrations affect review outcomes.
- Pre-merge Checks: monitor pass/fail results for built-in and custom gates.
- Reporting: track report delivery volume and channel distribution.
Additional IDE/CLI dashboard pages (2026-03-12):
- Summary: overall IDE/CLI review activity and findings.
- Organization Trends: week-over-week adoption and findings by tool/severity.
- Data Metrics: per-user IDE/CLI review breakdown.
Review Metrics API
REST API for programmatic access to review metrics. Query by date range, filter by repository or user, and retrieve results in JSON or CSV.
Related references
- CLI usage:
cli-usage.md - Triage workflow:
triage.md - Single issue fix:
fix.md
CodeRabbit Fix (Single Issue)
Implement a single CodeRabbit issue fix with minimal scope, root-cause focus, and mandatory verification.
When to use
- You have one triaged issue and you want to implement a focused fix.
- You want to avoid scope creep and keep diffs minimal.
Inputs
- One issue from triage:
file,line(optional),issue,suggestion,severity,constraints.
Process
1. Read the relevant code section (include a small context window before/after). 2. Confirm the root cause (do not blindly apply the suggestion). 3. Implement the smallest correct fix that addresses the cause. 4. Preserve existing patterns and public APIs unless the issue requires a change. 5. Add or update verification:
- Run the narrowest checks/tests first.
- Then run broader checks if needed.
Verification (minimum)
- Run the workspace checker (
code_checker) after edits. - Run the most relevant tests for the changed area (follow repo test instructions).
Fixing guidelines
- Security/correctness: prefer explicit validation and clear error handling.
- Multi-tenant systems: ensure tenant context/isolation rules are respected (if applicable).
- Async code: avoid blocking I/O and ensure timeouts for network calls.
- Types: add precise type hints when it reduces risk; avoid "Any" unless justified.
Report format
Issue: <summary>
Severity: <CRITICAL|HIGH|MEDIUM|LOW>
Decision: FIXED
Files:
- path/to/file.py
Verification:
- code_checker: PASS
- tests: <what ran>
Notes: <trade-offs, if any>Critical prohibitions
- Do not introduce silent fallbacks for required identifiers.
- Do not add mocks/stubs/fake implementations to production code.
- Do not refactor unrelated code while fixing a single issue.
Git Platform Integration
CodeRabbit integrates with major Git platforms for PR-based code reviews.
Supported Platforms
| Platform | Variants |
|---|---|
| GitHub | github.com, Enterprise Cloud, Enterprise Server |
| GitLab | gitlab.com, Self-Managed |
| Azure DevOps | Azure DevOps Services |
| Bitbucket | Cloud, Server, Data Center |
Integration Process
1. Authenticate — Log in to CodeRabbit with Git platform credentials 2. Add organizations — Connect organizations/groups/workspaces 3. Configure service account — Create dedicated CodeRabbit account (auto on GitHub.com) 4. Grant permissions — Authorize specific repositories
Platform Terminology
| Concept | GitHub | GitLab | Bitbucket |
|---|---|---|---|
| Organization | organization | group | workspace |
| Pull Request | pull request | merge request | pull request |
| Permissions | Repository access | Developer/Maintainer role | Repository access |
Permission Requirements
GitHub
- Ownership-level permissions for organizations
- Repository read/write access
GitLab
- Developer role in primary group to view repositories
- Maintainer role in primary group to enable toggle
- Self-managed GitLab works best on
16.x+.
Self-managed GitLab SSH cloning (2026-04-02)
- CodeRabbit can use SSH clone credentials instead of HTTPS for self-managed GitLab.
- SSH keys must be passphrase-free, and the public key must be registered on the GitLab account used by CodeRabbit.
- Optional
known_hostscontent helps avoid first-connect trust issues. - If SSH credentials are invalid or cannot be decrypted, CodeRabbit falls back to HTTPS.
Azure DevOps
- Project-level permissions
Bitbucket
- Workspace admin for organization setup
- Repository write access
Enterprise / Self-Hosted
For organizations with 500+ users:
- Self-hosted CodeRabbit deployment available
- Contact CodeRabbit Sales for enterprise options
Enterprise roles and permissions (2026-02-24):
- Enterprise orgs can define custom roles with per-resource access levels (No access / Read only / Read+Write) for org/repo settings, reports, team management, billing, and API access.
Issue Tracker Integration
CodeRabbit connects with issue management for ticket creation:
| Platform | Status |
|---|---|
| GitHub Issues | Supported |
| GitLab Issues | Supported |
| Jira | Supported |
| Linear | Supported |
GitHub PR Commands (@coderabbitai)
All commands use @coderabbitai mention in PR comments.
Review Control
| Command | Description |
|---|---|
@coderabbitai review | Incremental review of new changes only |
@coderabbitai full review | Complete review from scratch |
@coderabbitai pause | Stop automatic reviews |
@coderabbitai resume | Restart automatic reviews |
@coderabbitai ignore | Disable reviews (add to PR description) |
@coderabbitai resolve | Mark all CodeRabbit comments resolved |
Information Commands
| Command | Description |
|---|---|
@coderabbitai summary | Regenerate PR summary in description |
@coderabbitai generate sequence diagram | Post sequence diagram of PR history |
@coderabbitai configuration | Show current settings |
@coderabbitai help | Quick-reference guide |
Code Generation
| Command | Description |
|---|---|
@coderabbitai generate docstrings | Generate documentation for functions |
@coderabbitai generate unit tests | Generate test coverage |
Finishing Touches
| Command | Description |
|---|---|
@coderabbitai simplify | Simplify the changed files in the PR while preserving behavior |
@coderabbitai fix merge conflict | Attempt automatic merge-conflict resolution and commit a merge result |
Chat Interaction
Ask questions about code changes:
@coderabbitai Why did you suggest using a factory pattern here?@coderabbitai Can you explain the security implications of this change?Usage Notes
@coderabbitai ignoremust be in PR description (not comments)@coderabbitai resolvemarks ALL comments as resolved- CodeRabbit learns from your feedback over time
- Chat responses consider full repository context
@coderabbitai simplifyis an Open Beta Pro feature and may take up to 20 minutes on large PRs@coderabbitai fix merge conflictaborts without a commit when any conflicted file is too ambiguous or security-sensitive for safe automation
Supported Tools Reference
CodeRabbit integrates with 40+ static analysis tools, linters, and security scanners.
Configuration
Enable/disable tools in .coderabbit.yaml:
reviews:
tools:
eslint:
enabled: true
gitleaks:
enabled: trueTools by Category
JavaScript/TypeScript
| Tool | Version | Description |
|---|---|---|
| ESLint | latest | Static analysis for JavaScript |
| Biome | v2.1.2 | Fast formatter/linter for web projects |
| Oxlint | v1.28.0 | Rust-based JS/TS linter |
Stylesheets
| Tool | Version | Description |
|---|---|---|
| Stylelint | v17.2.0 | Linter for CSS, SCSS, Sass, and Less |
PowerShell
| Tool | Version | Description |
|---|---|---|
| PSScriptAnalyzer | v1.24.0 | Static code checker for PowerShell scripts/modules |
Python
| Tool | Version | Description |
|---|---|---|
| Ruff | v0.14.5 | Fast Python linter and formatter |
| Flake8 | v7.3.0 | PyFlakes + pycodestyle + McCabe |
| Pylint | v4.0.3 | Static code analysis |
Go
| Tool | Version | Description |
|---|---|---|
| golangci-lint | v2.5.0 | Fast linters runner for Go |
Ruby
| Tool | Version | Description |
|---|---|---|
| RuboCop | v1.81.7 | Static analyzer and formatter |
| Brakeman | v7.1.1 | Security scanner for Rails |
PHP
| Tool | Version | Description |
|---|---|---|
| PHPStan | v2.1.32 | Static analysis (requires config) |
| PHPMD | v2.15.0 | Mess detector |
| PHP CodeSniffer | v3.7.2 | Coding standard checker |
Rust
| Tool | Version | Description |
|---|---|---|
| Clippy | latest | Lint collection for Rust |
Kotlin/Java
| Tool | Version | Description |
|---|---|---|
| detekt | v1.23.8 | Static analysis for Kotlin |
| PMD | v7.18.0 | Multilanguage analyzer (Java focus) |
C/C++
| Tool | Version | Description |
|---|---|---|
| Clang | v14.0.6 | Static analysis |
| Cppcheck | v2.18.0 | Static analysis |
Swift
| Tool | Version | Description |
|---|---|---|
| SwiftLint | v0.57.0 | Swift linter |
Shell
| Tool | Version | Description |
|---|---|---|
| ShellCheck | v0.11.0 | Shell script analyzer |
SQL
| Tool | Version | Description |
|---|---|---|
| SQLFluff | v3.5.0 | Dialect-flexible SQL linter |
Infrastructure
| Tool | Version | Description |
|---|---|---|
| Checkov | v3.2.334 | IaC security scanner |
| Hadolint | v2.14.0 | Dockerfile linter |
| Trivy | latest | IaC security scanner (config mode) |
| TFLint | latest | Terraform linter |
| actionlint | v1.7.8 | GitHub Actions checker |
| CircleCI | v0.1.33494 | CircleCI config checker |
| YAMLlint | v1.37.1 | YAML linter |
Security
| Tool | Version | Description |
|---|---|---|
| Gitleaks | v8.29.0 | Secret scanner |
| TruffleHog | v3.92.0 | Secret scanner with verification |
| OpenGrep | v1.16.0 | Semgrep-compatible code scanning |
| Semgrep | v1.143.0 | Security vulnerability scanner |
| OSV Scanner | v2.2.4 | Package vulnerability scanner |
Documentation
| Tool | Version | Description |
|---|---|---|
| LanguageTool | latest | Grammar/style checker (30+ languages) |
| markdownlint | v0.18.1 | Markdown standards |
Other
| Tool | Version | Description |
|---|---|---|
| ast-grep | v0.40.0 | AST pattern matching |
| HTMLHint | v1.7.1 | HTML analyzer |
| Prisma Lint | v0.11.0 | Prisma schema linter |
| checkmake | v0.2.2 | Makefile linter |
| dotenv-linter | v4.0.0 | .env file checker |
| Buf | v1.60.0 | Protobuf linter |
| Regal | v0.37.0 | Rego linter |
| Luacheck | v1.2.0 | Lua linter |
| Shopify Theme Check | v3.58.2 | Liquid best practices |
| Fortitude | v0.7.5 | Fortran linter |
| Blinter | latest | Windows batch linter |
| smarty-lint | v0.3.3 | Linter for Smarty 3 templates (.tpl) |
Tools with Config File Support
Some tools accept custom configuration paths:
reviews:
tools:
golangci-lint:
enabled: true
config_file: ".golangci.yml"
detekt:
enabled: true
config_file: "detekt.yml"
semgrep:
enabled: true
config_file: ".semgrep.yml"
swiftlint:
enabled: true
config_file: ".swiftlint.yml"
pmd:
enabled: true
config_file: "ruleset.xml"PHPStan Level Configuration
reviews:
tools:
phpstan:
enabled: true
level: "max" # 0-9 or "max"LanguageTool Configuration
reviews:
tools:
languagetool:
enabled: true
level: "picky" # default or picky
enabled_rules: []
disabled_rules: []GitHub Checks Integration
reviews:
tools:
github-checks:
enabled: true
timeout_ms: 90000 # Max 900000 (15 min)CodeRabbit Triage Workflow
Turn CodeRabbit output into a severity-ranked plan: fix/defer/skip with clear rationale.
When to use
- You have CodeRabbit output (preferably
--prompt-only) and need a structured fix plan. - You want to balance pragmatism (minimal diffs) with safety (security/correctness first).
Inputs
- Full CodeRabbit output (do not paraphrase; keep exact wording where possible).
- Repository context: applicable instructions and skills (e.g., architecture, multi-tenancy, async rules).
Process
1. Extract issues into a list with: file, line (if provided), issue, suggestion. 2. Classify severity:
- CRITICAL: security, data loss/corruption, tenant isolation violations, broken error handling, missing timeouts.
- HIGH: reliability/performance regressions, transaction/session misuse, architectural violations.
- MEDIUM: type safety, refactors, maintainability improvements.
- LOW: formatting, naming preferences, pure style nits.
Cross-repo note:
- If linked-repository analysis flags contract drift across repos, default to HIGH.
- Multi-Repo Analysis can now span up to 2 linked repositories on supported plans, so check both linked repos before downgrading a cross-repo warning.
- Escalate to CRITICAL if breakage can cause production runtime failures.
3. Decide per issue:
- FIX if it materially improves safety/correctness or is a clear quick win.
- DEFER if valuable but not appropriate now (add an explicit TODO with reason).
- SKIP if subjective/outdated or handled by tooling.
4. Produce a triage report and a task plan (one task per issue).
Documentation for deferred issues
When deferring HIGH/MEDIUM issues, add a focused TODO that includes:
- Issue summary
- Reason for deferral
- Suggested follow-up
Expected output (template)
CRITICAL: N
HIGH: N
MEDIUM: N
LOW: N
Issue 1
- Severity: CRITICAL
- Decision: FIX
- Location: path/to/file.py:123
- Reason: ...
- Verification: ...
Issue 2
- Severity: MEDIUM
- Decision: DEFER
- Location: ...
- Reason: ...
- Follow-up: TODO(...)Critical prohibitions
- Do not invent issues.
- Do not broaden scope beyond what CodeRabbit flagged.
- Do not recommend adding fallbacks/mocks/stubs to production code.
Windows / WSL notes (manual)
CodeRabbit CLI may be more practical to run inside WSL on Windows.
Install WSL + Ubuntu
wsl --install -d UbuntuInstall CodeRabbit CLI in WSL
wsl -d Ubuntu -e bash -c "curl -fsSL https://cli.coderabbit.ai/install.sh | sh"Authenticate
wsl -d Ubuntu -e bash -c "~/.local/bin/coderabbit auth login"Line endings issue (CRLF vs LF)
When accessing Windows files via /mnt/..., tools can detect massive line-ending changes. A common workaround is to copy the repo into a native WSL folder and run CodeRabbit there.
Important: any commands that reset working tree state (e.g., git checkout .) must be run intentionally by a human and only on a disposable copy.
Troubleshooting
- "command not found": use
~/.local/bin/coderabbitor add$HOME/.local/bintoPATH. - Slow performance on
/mnt/...: prefer working inside WSL home (e.g.~/projects).
#!/usr/bin/env python3
import argparse
import shutil
import subprocess
import sys
from pathlib import Path
def detect_base_branch() -> str:
"""Auto-detect the base branch (main, master, or current)."""
for branch in ("main", "master"):
result = subprocess.run(
["git", "rev-parse", "--verify", branch],
capture_output=True, text=True,
)
if result.returncode == 0:
return branch
# fallback: use current branch
result = subprocess.run(
["git", "branch", "--show-current"],
capture_output=True, text=True,
)
return result.stdout.strip() or "main"
def check_prerequisites() -> list[str]:
"""Check all prerequisites and return list of errors."""
errors = []
# 1. CLI installed?
if not shutil.which("coderabbit"):
errors.append(
"coderabbit CLI not found in PATH. "
"Install: curl -fsSL https://cli.coderabbit.ai/install.sh | sh"
)
# 2. Inside a git repo?
result = subprocess.run(
["git", "rev-parse", "--git-dir"],
capture_output=True, text=True,
)
if result.returncode != 0:
errors.append("Not inside a git repository.")
return errors # no point checking further
# 3. At least one commit? (CRITICAL — CLI crashes with GitError otherwise)
result = subprocess.run(
["git", "rev-parse", "HEAD"],
capture_output=True, text=True,
)
if result.returncode != 0:
errors.append(
"Repository has no commits. "
"CodeRabbit CLI requires at least one commit to compute diffs. "
"Create an initial commit first."
)
return errors
def run_coderabbit(output_path: Path, timeout_seconds: int, base_branch: str) -> int:
coderabbit_path = shutil.which("coderabbit")
if not coderabbit_path:
raise RuntimeError("coderabbit CLI not found in PATH")
cmd = [
coderabbit_path, "review",
"--prompt-only", "--type", "uncommitted",
"--base", base_branch, "--no-color",
]
print(f"Running: {' '.join(cmd)}", file=sys.stderr)
print(f"Base branch: {base_branch}", file=sys.stderr)
print(f"Output: {output_path}", file=sys.stderr)
print(f"Timeout: {timeout_seconds}s", file=sys.stderr)
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
)
try:
stdout, _ = process.communicate(timeout=timeout_seconds)
except subprocess.TimeoutExpired:
process.kill()
stdout, _ = process.communicate()
output_path.write_text(stdout or "", encoding="utf-8")
raise RuntimeError(f"coderabbit timed out after {timeout_seconds}s")
output_path.write_text(stdout or "", encoding="utf-8")
if process.returncode != 0:
# Check for common errors in output
if stdout and "GitError" in stdout:
raise RuntimeError(
f"coderabbit GitError — check that base branch '{base_branch}' exists "
"and repo has commits."
)
if stdout and "[error] stopping cli" in stdout:
raise RuntimeError(
f"coderabbit failed with '[error] stopping cli'. "
f"Run 'DEBUG=* coderabbit review --prompt-only --type uncommitted "
f"--base {base_branch}' for details. "
f"Check ~/.coderabbit/logs/ for the full log."
)
return process.returncode
def resolve_repo_root(start_path: Path) -> Path:
for parent in [start_path, *start_path.parents]:
if (parent / ".project").exists() or (parent / ".git").exists():
return parent
raise RuntimeError("Unable to locate repo root (missing .project or .git)")
def ensure_code_review_dir(repo_root: Path) -> Path:
code_review_dir = repo_root / ".code-review"
code_review_dir.mkdir(parents=True, exist_ok=True)
gitignore_path = code_review_dir / ".gitignore"
if not gitignore_path.exists():
gitignore_path.write_text("*", encoding="utf-8")
return code_review_dir
def main() -> int:
parser = argparse.ArgumentParser(
description="Run CodeRabbit in prompt-only mode and save output to a file.",
)
parser.add_argument(
"--output",
default="coderabbit-report.txt",
help="Output file name (default: coderabbit-report.txt)",
)
parser.add_argument(
"--timeout",
type=int,
default=1800,
help="Timeout in seconds (default: 1800)",
)
parser.add_argument(
"--base",
default=None,
help="Base branch for comparison (default: auto-detect main/master)",
)
args = parser.parse_args()
# Check prerequisites
errors = check_prerequisites()
if errors:
for err in errors:
print(f"ERROR: {err}", file=sys.stderr)
return 1
# Detect base branch
base_branch = args.base or detect_base_branch()
# Verify base branch exists
result = subprocess.run(
["git", "rev-parse", "--verify", base_branch],
capture_output=True, text=True,
)
if result.returncode != 0:
print(
f"ERROR: Base branch '{base_branch}' not found. "
f"Use --base <branch> to specify a valid branch.",
file=sys.stderr,
)
return 1
repo_root = resolve_repo_root(Path.cwd())
code_review_dir = ensure_code_review_dir(repo_root)
output_name = Path(args.output).name
output_path = (code_review_dir / output_name).resolve()
exit_code = run_coderabbit(output_path, args.timeout, base_branch)
if exit_code != 0:
raise RuntimeError(f"coderabbit exited with status {exit_code}")
print(f"Review saved to: {output_path}", file=sys.stderr)
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Exception as exc: # noqa: BLE001
print(str(exc), file=sys.stderr)
sys.exit(1)