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

# CodeRabbit Guide - Complete Reference

> Version: 3.2.0 Last Updated: 2026-04-11 Config: .coderabbit.yaml v2.6.0 (optimized 2026-04-11; prior baseline v2.5.0 / 2026-02-05) Status: ✅ Fully Configured

**Version:** 3.2.0\
**Last Updated:** 2026-04-11\
**Config:** `.coderabbit.yaml` v2.6.0 (optimized 2026-04-11; prior baseline v2.5.0 / 2026-02-05)\
**Status:** ✅ Fully Configured

Complete guide to CodeRabbit setup, configuration, and usage for the Encore Health OS Platform (repository: **encoreos-platform**).

**See also:** [CODERABBIT\_IMPROVEMENTS.md](../archive/development/coderabbit/CODERABBIT_IMPROVEMENTS.md) (archived; recommendations implemented in v2.5.0).

***

## What's new since config v2.5.0 (2026-02-05)

Platform `.coderabbit.yaml` refresh (2026-04-11) aligns with CodeRabbit product updates through early 2026:

* **Security tools:** Explicit enable for **OpenGrep**, **TruffleHog**, **Trivy** (IaC/containers), and **Stylelint** (CSS/SCSS), alongside existing ESLint/Biome/Semgrep/OSV/etc.
* **Secrets:** `gitleaks` continues to run; CodeRabbit now uses the **Betterleaks** backend (comment in config).
* **Slop detection:** `slop_detection.label: "ai-slop"` for PR triage when suspicious patterns are flagged.
* **Chat:** `allow_non_org_members: false` so PR chat stays with org members (healthcare-appropriate default).
* **Labels:** `core:cl`, `core:pm`, and `core:it` added to `labeling_instructions` alongside existing core/platform labels.
* **Auto-pause:** `auto_pause_after_reviewed_commits: 8` — reviews pause after eight reviewed commits; resume with `@coderabbitai review` (tune to `0` if you need every push reviewed without pause).
* **Knowledge base:** Additional `filePatterns` for `UI_CONSISTENCY_REVIEW.md` and `SPEC_COMMAND_CHEATSHEET.md`.
* **Product surface (reference):** CodeRabbit continues to ship Skills/CLI integration, finishing touches (autofix/simplify flows where enabled), issue planner, and multi-repo analysis — see [CodeRabbit changelog](https://docs.coderabbit.ai/changelog/) for the latest.

***

## Table of Contents

1. [Quick Start](#quick-start)
2. [Setup](#setup)
3. [Configuration](#configuration)
4. [CLI Commands](#cli-commands)
5. [Output Modes](#output-modes)
6. [Workflow Patterns](#workflow-patterns)
7. [Reporting](#reporting)
8. [Best Practices](#best-practices)
9. [Troubleshooting](#troubleshooting)

***

## Quick Start

### Current Setup Status ✅

* ✅ **CodeRabbit CLI:** Installed (see `coderabbit --version`)
* ✅ **Configuration:** `.coderabbit.yaml` v2.6.0+ with custom checks, path instructions, ast-grep rules, and knowledge base
* ✅ **Tools:** ESLint, Biome, OXC, Gitleaks (Betterleaks), OpenGrep, TruffleHog, Trivy, Stylelint, Semgrep, OSV Scanner, SQLFluff, markdownlint, yamllint, shellcheck, and others (see `.coderabbit.yaml`)
* ✅ **Profile:** Assertive (comprehensive reviews)
* ✅ **Knowledge Base:** Root governance files (constitution.md, AGENTS.md, .cursor/BUGBOT.md, etc.) and auto-detected .cursorrules, AGENTS.md, .cursor/rules

### Quick Commands

```bash theme={null}
# Using aliases (recommended)
cr                  # Review all changes
cr-uncommitted      # Review only uncommitted changes
cr-plain            # Detailed feedback with suggestions
cr-quick            # Minimal output (token-efficient)

# Direct commands
coderabbit                          # Review all changes
coderabbit --type uncommitted       # Uncommitted only
coderabbit --plain                  # Detailed output
coderabbit --prompt-only            # Minimal output
coderabbit auth status              # Check auth status
```

### Common Workflows

**Before Committing:**

```bash theme={null}
cr-uncommitted    # Quick review of changes
# Fix issues, then commit
git add .
git commit -m "Your message"
```

**After Feature Complete:**

```bash theme={null}
cr-review         # Comprehensive review
# Address feedback
git commit -m "Apply CodeRabbit suggestions"
```

**Generate Reports (markdown by severity):**

```bash theme={null}
cr-lovable              # Full report → reports/active/markdown/coderabbit-<timestamp>/
cr-lovable-uncommitted  # Uncommitted only
cr-lovable-show         # Same with output streamed to terminal
cr-lovable-prompt-only  # Same plus 00-PROMPT-ONLY.md (token-efficient)
```

*(Run `bash scripts/utils/setup-coderabbit-aliases.sh` once to install aliases.)*

**Plain reports (single file):**

```bash theme={null}
cr-report              # Full detailed report (saved to reports/)
cr-report-quick        # Quick prompt-only report
cr-report-uncommitted  # Uncommitted changes report
```

**See also:** [CODE\_REVIEW\_PROCESS.md](./CODE_REVIEW_PROCESS.md) for daily commands and quick start workflow

***

## Setup

### Installation (WSL recommended on Windows)

CodeRabbit CLI does not support native Windows; use **WSL** and optionally a Windows PATH wrapper.

**1. Install in WSL (one-time)**

From a WSL terminal (in or outside the repo):

```bash theme={null}
# From repo root (recommended – uses project script that also configures PATH)
bash scripts/utils/install-coderabbit-wsl.sh
source ~/.bashrc
coderabbit auth login
```

Or install globally via official installer:

```bash theme={null}
curl -fsSL https://cli.coderabbit.ai/install.sh | sh
source ~/.bashrc
coderabbit auth login
```

The install script puts the binary in `~/.coderabbit/bin` (or `~/.local/bin`) and adds it to your shell PATH in `~/.bashrc` / `~/.zshrc`.

**2. Add CodeRabbit to Windows PATH (optional)**

To run `coderabbit` from **PowerShell or CMD** (and have it run inside WSL with the current directory), use the repo wrapper:

1. Add this repo’s **`scripts/bin`** folder to your Windows user PATH:
   * **Environment Variables** → User (or System) → **Path** → Edit → New.
   * Add the full path to `scripts\bin`, e.g. `C:\Users\YourName\encoreos-platform\scripts\bin`.
   * OK and restart any open terminals.

2. From PowerShell/CMD, in your repo directory:
   ```bat theme={null}
   coderabbit --version
   coderabbit --type uncommitted
   ```

The wrapper (`scripts/bin/coderabbit.cmd`) runs `wsl coderabbit ...` with the current Windows directory converted to a WSL path. See `scripts/bin/README.md` for details.

**Verify (from WSL):**

```bash theme={null}
coderabbit --version
coderabbit auth status
./docs/development/verify-coderabbit-setup.sh
```

**If `coderabbit auth login` fails with `libsecret not available`:** See [CODERABBIT\_CLI\_WSL\_AUTH.md](../archive/development/coderabbit/CODERABBIT_CLI_WSL_AUTH.md) for the fix (install libsecret/gnome-keyring, use `dbus-run-session`).

### Git Configuration (CRITICAL)

Configure git for Windows/WSL compatibility to prevent line-ending issues:

```bash theme={null}
# In WSL terminal
git config --global core.autocrlf input
```

**Why:** Prevents line-ending conflicts between Windows (CRLF) and Linux (LF) when using git in both environments.

### Performance Optimization

#### Option A: Keep Repository in Windows (Current Setup)

* ✅ **Pros:** Works with Windows IDEs, easy file access
* ⚠️ **Cons:** Slower file I/O performance in WSL
* **Best for:** When you primarily use Windows-based tools

#### Option B: Clone to WSL Filesystem (Recommended for Performance)

* ✅ **Pros:** Much faster file operations, better WSL performance
* ⚠️ **Cons:** Need to use VS Code Remote - WSL for editing
* **Best for:** When you want optimal CodeRabbit performance

**To migrate (optional):**

```bash theme={null}
# In WSL
cd ~
mkdir -p projects
cd projects
git clone <your-repo-url> encoreos-platform
cd encoreos-platform
```

**Access from Windows:** `\\wsl$\Ubuntu\home\<user>\projects\encoreos-platform`

### VS Code Remote - WSL Integration (HIGHLY RECOMMENDED)

**Benefits:**

* Edit files in Windows VS Code UI
* Terminal runs in WSL (native performance)
* Seamless integration with CodeRabbit CLI
* Best of both worlds

**Setup Steps:**

1. **Install Extension:**
   * Open VS Code
   * Install "Remote - WSL" extension (ms-vscode-remote.remote-wsl)

2. **Open Project in WSL:**
   ```bash theme={null}
   # In WSL terminal (use your repo path)
   cd /mnt/c/Users/JeremyBloom/encoreos-platform
   code .
   ```
   This opens VS Code in WSL mode automatically.

3. **Use Integrated Terminal:**
   * VS Code terminal will be WSL by default
   * Run `coderabbit` directly (PATH already configured)

### Convenience Aliases

#### Quick Setup (Recommended)

Run the setup script to automatically add aliases to your shell config:

```bash theme={null}
bash scripts/setup-coderabbit-aliases.sh
source ~/.bashrc  # or ~/.zshrc
```

#### Manual Setup

Add to `~/.bashrc` or `~/.zshrc`:

```bash theme={null}
# CodeRabbit aliases
alias cr='coderabbit'
alias cr-review='coderabbit --type all'
alias cr-uncommitted='coderabbit --type uncommitted'
alias cr-plain='coderabbit --plain'
alias cr-quick='coderabbit --prompt-only'

# Report generation aliases (plain text)
alias cr-report='mkdir -p reports && coderabbit --plain > reports/coderabbit-$(date +%Y%m%d-%H%M%S).txt 2>&1 && echo "✅ Report saved to reports/"'
alias cr-report-quick='mkdir -p reports && coderabbit --prompt-only > reports/coderabbit-quick-$(date +%Y%m%d-%H%M%S).txt 2>&1 && echo "✅ Quick report saved"'
alias cr-report-uncommitted='mkdir -p reports && coderabbit --type uncommitted --plain > reports/coderabbit-uncommitted-$(date +%Y%m%d-%H%M%S).txt 2>&1 && echo "✅ Uncommitted report saved"'

# Markdown report generation aliases (by severity)
# Replace /path/to/project with your actual project root path
# Use git root so aliases work from any subdir (setup script uses this pattern)
alias cr-lovable='cd "$(git rev-parse --show-toplevel)" && bash scripts/utils/generate-coderabbit-report.sh'
alias cr-lovable-uncommitted='cd "$(git rev-parse --show-toplevel)" && bash scripts/utils/generate-coderabbit-report.sh --type uncommitted'
alias cr-lovable-show='cd "$(git rev-parse --show-toplevel)" && bash scripts/utils/generate-coderabbit-report.sh --show'
```

**Activate:**

```bash theme={null}
source ~/.bashrc  # or ~/.zshrc
```

### Recommended Setup for This Project

Based on your current setup, here's the **recommended configuration**:

#### Option 1: Hybrid Approach (Recommended)

* **Keep repository in Windows** (current location)
* **Use VS Code Remote - WSL** for editing
* **Run CodeRabbit from WSL terminal** (via VS Code integrated terminal)
* **Best of both worlds:** Windows file access + WSL performance

#### Option 2: Full WSL Migration (Best Performance)

* **Clone repository to `~/projects/`** in WSL (e.g. `encoreos-platform`)
* **Use VS Code Remote - WSL** exclusively
* **Maximum performance** for CodeRabbit and git operations
* **Access files from Windows:** `\\wsl$\Ubuntu\home\<user>\projects\`

### Setup Verification

Run the verification script:

```bash theme={null}
./docs/development/verify-coderabbit-setup.sh
```

Or manually verify:

```bash theme={null}
# Check installation
coderabbit --version

# Check authentication
coderabbit auth status

# Test review
coderabbit --type uncommitted
```

***

## Configuration

### Configuration File

**Location:** `.coderabbit.yaml` (repository root)

The configuration is optimized for:

* ✅ Multi-tenant healthcare platform security
* ✅ TypeScript/React/Supabase codebase
* ✅ Architecture boundary enforcement
* ✅ Security vulnerability detection

### Key Settings

**Source of truth:** `.coderabbit.yaml` (repository root). Summary of current config:

```yaml theme={null}
reviews:
  profile: "assertive"              # Comprehensive reviews
  request_changes_workflow: true
  high_level_summary: true
  high_level_summary_in_walkthrough: true
  poem: false
  in_progress_fortune: false
  collapse_walkthrough: true        # Cleaner PR view
  auto_review:
    enabled: true
    drafts: true                    # Review draft PRs too
  pre_merge_checks:                 # Quality gates before merge
    docstrings: { mode: "error", threshold: 70 }
    title: { mode: "error" }
    description: { mode: "error" }
    issue_assessment: { mode: "warning" }
    custom_checks: [ ... ]         # Core boundary, multi-tenant, RLS, PHI, code quality
  tools:                            # Static analysis
    eslint: { enabled: true }
    biome: { enabled: true }
    oxc: { enabled: true }
    gitleaks: { enabled: true }
    semgrep: { enabled: true }
    osvScanner: { enabled: true }
    sqlfluff: { enabled: true }
    markdownlint: { enabled: true }
    yamllint: { enabled: true }
    shellcheck: { enabled: true }
    actionlint: { enabled: true }
    # ... and others
  path_instructions: [ ... ]       # File-type specific reviews (SQL, edge functions, cores, etc.)
```

### Review Profile

**Current:** `assertive` (comprehensive)

**Why:**

* Enterprise healthcare platform needs thorough reviews
* Catches critical security issues
* Enforces architecture boundaries
* Multi-tenant isolation validation

**Alternatives:**

* `chill`: Too lenient for healthcare/enterprise
* `balanced`: Good for smaller projects
* `assertive`: ⭐ **Recommended** for enterprise platforms

### Configuration Breakdown

#### Language & Access

```yaml theme={null}
language: "en-US"
early_access: true   # Use stable features only for production reliability
```

* **Language**: English (US) for consistent terminology
* **Early Access**: Enabled for stable features only (per config comment)

#### Review Settings

```yaml theme={null}
reviews:
  high_level_summary: true    # Summary helps with large PRs
  review_status: true         # Status badges in PR
  collapse_walkthrough: true  # Cleaner PR view (walkthrough in collapsible section)
  auto_review:
    enabled: true             # Auto-review on PR creation
    drafts: true              # Review draft PRs too (catch issues early)
```

**Benefits:**

* High-level summary provides PR overview
* Auto-review ensures all PRs get reviewed
* Drafts are reviewed to catch issues early

#### Paths Configuration

**Included Paths:**

* ✅ Source code (`src/**`)
* ✅ Database migrations (`supabase/**`)
* ✅ Tests (`tests/**`)
* ✅ Specifications (`specs/**`)
* ✅ Documentation (`docs/**`)
* ✅ Configuration files (`*.yaml`, `*.json`, `*.ts`)

**Ignored Paths:**

* ❌ Dependencies (`node_modules/**`)
* ❌ Build artifacts (`dist/**`, `build/**`)
* ❌ Lock files (`*.lock`, `bun.lockb`)
* ❌ IDE configs (`.vscode/**`, `.idea/**`)
* ❌ Generated reports (`reports/**`)

**Why exclude these?**

* Dependencies are external code (not our responsibility)
* Build artifacts are generated (review source instead)
* Lock files are auto-generated
* Reports are CodeRabbit output (circular)

#### Knowledge Base

The configuration points CodeRabbit to key documentation:

```yaml theme={null}
knowledge_base:
  - constitution.md          # Engineering guardrails (current: see docs/VERSIONS.md)
  - AGENTS.md                # AI agent instructions
  - AI_GUIDE.md              # Contribution guidelines (current: see docs/VERSIONS.md)
  - AGENTS.md      # Quick reference (current: see docs/VERSIONS.md)
  - README.md                 # Project overview
  - docs/architecture/...    # Architecture docs
```

**Why this matters:**

* CodeRabbit understands our architecture rules
* Enforces core boundaries and import patterns
* Validates against our coding standards
* References integration patterns

#### Review Instructions

Custom instructions guide CodeRabbit to:

* ✅ Enforce core boundaries (no cross-core imports)
* ✅ Validate import paths (`@/shared/`, `@/platform/`)
* ✅ Check multi-tenancy (organization\_id, RLS)
* ✅ Flag security issues (PHI handling, RLS patterns)
* ✅ Verify performance patterns (React.lazy, QueryClient)
* ✅ Reference key documents

### Configuration Priority

1. **Branch-specific** `.coderabbit.yaml` (if exists in feature branch)
2. **Main branch** `.coderabbit.yaml` (fallback)
3. **Organization defaults** (if configured)
4. **CodeRabbit defaults** (last resort)

### Customization

#### Adjust Review Strictness

**More lenient:**

```yaml theme={null}
reviews:
  profile: "chill"
```

**More strict:**

```yaml theme={null}
reviews:
  profile: "strict"
```

#### Add More Documentation

Add to `knowledge_base.code_guidelines.filePatterns`:

```yaml theme={null}
knowledge_base:
  code_guidelines:
    filePatterns:
      - "docs/fa/FA-API-REFERENCE.md"
      - "specs/rh/RH-01-census-beds.md"
      - "**/MODULE_STANDARDS.md"
```

**Note:** File patterns are glob patterns. Root-level files apply to the whole repo; files in subdirectories apply only to their directory tree. Custom patterns supplement the auto-detected defaults (AGENTS.md, CLAUDE.md, .cursor/rules/, etc.) rather than replacing them.

#### Customize Paths

**Include additional paths:**

```yaml theme={null}
paths:
  included_paths:
    - "scripts/**"
    - "tools/**"
```

**Exclude more patterns:**

```yaml theme={null}
paths:
  ignored_paths:
    - "*.test.ts.snap"
    - "coverage/**"
```

### Tools Configuration

**ESLint:**

* Auto-detects `eslint.config.js`
* Catches linting violations
* Enforces code style

**Gitleaks:**

* Detects hardcoded secrets
* Critical for healthcare platform
* Aligns with secrets management policy

### Path-Specific Instructions

CodeRabbit applies different review criteria based on file type:

**SQL Files (`supabase/**/*.sql`):**

* RLS policies on ALL business tables
* SECURITY DEFINER functions (prevent recursion)
* Multi-tenant isolation (organization\_id, site\_id)
* No hardcoded secrets
* Proper indexes for performance

**React/TypeScript (`src/**/*.{ts,tsx}`):**

* React.lazy() for route components
* Skeleton loaders (not null)
* useCurrentUser hook usage
* Static Supabase imports
* useEffect for side effects
* No direct core-to-core imports
* No PHI/PII logging
* Zod validation for forms

**Edge Functions (`supabase/functions/**/*.ts`):**

* JWT validation when using service role key
* Organization context extraction
* Organization\_id filtering in ALL queries
* URL validation (prevent SSRF)
* CORS headers configured
* Error messages don't leak PHI/PII
* Input validation on all parameters

**Test Files (`tests/**/*.ts`):**

* RLS policy coverage
* Multi-tenant test scenarios
* No hardcoded secrets
* Proper cleanup and isolation

### What CodeRabbit Flags

**Security Issues:**

* ❌ Missing JWT validation in edge functions
* ❌ Missing organization\_id in queries
* ❌ SSRF vulnerabilities (no URL validation)
* ❌ Hardcoded secrets or API keys
* ❌ PHI/PII in logs or error messages

**Architecture Violations:**

* ❌ Direct imports between cores
* ❌ Missing organization\_id in business tables
* ❌ RLS policies without SECURITY DEFINER functions
* ❌ Direct route imports (should use React.lazy)

**Code Quality:**

* ❌ `return null` for loading states
* ❌ Using `useState` for side effects
* ❌ Dynamic Supabase imports
* ❌ Missing error handling
* ❌ Non-null assertion operators (`!`)

***

## CLI Commands

### Command Options

| Command                         | Description                                  |
| ------------------------------- | -------------------------------------------- |
| `coderabbit`                    | Review all changes (committed + uncommitted) |
| `coderabbit --type uncommitted` | Review only uncommitted changes              |
| `coderabbit --type committed`   | Review only committed changes                |
| `coderabbit --plain`            | Detailed output with suggestions             |
| `coderabbit --prompt-only`      | Minimal output (token-efficient)             |
| `coderabbit --base <branch>`    | Compare against specific branch              |
| `coderabbit auth status`        | Check authentication status                  |
| `coderabbit auth login`         | Authenticate with GitHub                     |

### Review Types

* **`--type uncommitted`**: Quick feedback on work-in-progress
* **`--type committed`**: Review staged/committed changes
* **`--type all`**: Comprehensive review (slower, more thorough)

### Workflow Integration

#### Pre-Commit Reviews

```bash theme={null}
# Review before committing
coderabbit --type uncommitted

# If satisfied, commit
git add .
git commit -m "Your message"
```

#### Post-Commit Reviews

```bash theme={null}
# Review committed changes
coderabbit --type committed

# Review against specific branch
coderabbit --base develop --type committed
```

***

## Output Modes

### `--prompt-only` (Minimal, Token-Efficient)

**Command:** `cr-quick` or `coderabbit --prompt-only`

**Output:**

* ✅ Minimal prompts for AI assistants
* ✅ Token-efficient (saves API costs)
* ✅ Quick summaries
* ❌ No detailed explanations
* ❌ No code snippets
* ❌ No context/background

**Best for:**

* AI coding assistants (Cursor, GitHub Copilot)
* Quick checks during development
* When you need minimal output

**Example output:**

```text theme={null}
Prompt for AI Agent:
File.tsx around line 10: fix the type error by adding proper typing.
```

### `--plain` (Detailed Feedback)

**Command:** `coderabbit --plain` or `cr-plain`

**Output:**

* ✅ Detailed explanations
* ✅ Code snippets and examples
* ✅ Context and background
* ✅ Actionable suggestions
* ✅ More comprehensive
* ❌ Larger output (more tokens)

**Best for:**

* Manual code reviews
* Understanding issues deeply
* Learning from feedback
* Comprehensive analysis

**Example output:**

````text theme={null}
File: src/components/Button.tsx
Line: 10-15
Type: potential_issue
Severity: medium

Issue: Missing error handling in async function

The function `handleClick` performs an async operation but doesn't handle
potential errors. This could lead to unhandled promise rejections.

Current code:
```typescript
const handleClick = async () => {
  await submitForm();
  // No error handling
};
````

Suggested fix:

```typescript theme={null}
const handleClick = async () => {
  try {
    await submitForm();
  } catch (error) {
    console.error('Form submission failed:', error);
    // Handle error appropriately
  }
};
```

Why this matters:

* Unhandled promise rejections can crash the application
* Users won't see error feedback
* Debugging becomes difficult

````text theme={null}

### UI Reviews (Most Comprehensive)

**What you see in:** GitHub/GitLab PR reviews

**Output:**
- ✅ Most detailed explanations
- ✅ Interactive code review
- ✅ Inline comments on PR
- ✅ Rich formatting
- ✅ Code diffs with context
- ✅ Team collaboration features
- ✅ Review summaries
- ✅ Categorized findings

**Best for:**
- Team code reviews
- PR collaboration
- Comprehensive analysis
- Documentation and learning

### When to Use Each Mode

**Use `--prompt-only` (`cr-quick`) When:**
- ✅ Working with AI assistants
- ✅ Need quick feedback
- ✅ Want to save tokens/API costs
- ✅ Iterating quickly on code

**Use `--plain` (`cr-plain` or `cr-report`) When:**
- ✅ Manual code review
- ✅ Need detailed explanations
- ✅ Learning from feedback
- ✅ Comprehensive analysis
- ✅ Want to understand issues deeply

**Use UI Reviews When:**
- ✅ Creating pull requests
- ✅ Team collaboration
- ✅ Need interactive review
- ✅ Want inline comments
- ✅ Comprehensive documentation

### Recommended Workflow

**During Development:**
```bash
# Quick check (minimal output)
cr-quick

# If issues found, get details
cr-plain
````

**Before Committing:**

```bash theme={null}
# Detailed review
cr-plain

# Or generate report
cr-report
```

**For PRs:**

* CodeRabbit automatically reviews PRs in UI
* Most comprehensive feedback
* Team collaboration

***

## Workflow Patterns

### CodeRabbit + Lovable Workflow

This workflow uses CodeRabbit reports with Lovable for automated code improvements.

#### Local Report Generation (cr-lovable)

Reports are generated **locally** via the `cr-lovable` aliases. No GitHub workflow is used.

**Setup:** Run once from the repo root to add aliases to your shell config:

```bash theme={null}
bash scripts/utils/setup-coderabbit-aliases.sh
source ~/.bashrc   # or ~/.zshrc
```

**Aliases (all produce markdown by severity in `reports/active/markdown/coderabbit-<timestamp>/`):**

| Alias                    | Command                                       | Description                                               |
| ------------------------ | --------------------------------------------- | --------------------------------------------------------- |
| `cr-lovable`             | `scripts/utils/generate-coderabbit-report.sh` | Full report, all changes, markdown by severity            |
| `cr-lovable-uncommitted` | `... --type uncommitted`                      | Report for uncommitted changes only                       |
| `cr-lovable-show`        | `... --show`                                  | Same as above but stream output to terminal               |
| `cr-lovable-prompt-only` | `... --prompt-only`                           | Also writes `00-PROMPT-ONLY.md` (token-efficient prompts) |

**Output directory:** `reports/active/markdown/coderabbit-<timestamp>/`

* `00-SUMMARY.md` — Overview, severity counts, top impacted files, priority actions
* `01-CRITICAL.md` — Critical issues (security, architecture, data integrity)
* `02-MAJOR.md` — Major issues
* `03-MINOR.md` — Minor issues
* `04-TRIVIAL.md` — Trivial suggestions
* `05-OUTSIDE-DIFF.md` — Findings outside the diff (if any)
* `00-PROMPT-ONLY.md` — Present only when run with `--prompt-only`; token-efficient prompts for AI agents

**Use with Lovable:** Copy the summary or severity files and paste into Lovable for fixes.

#### Manual Workflow (Alternative)

**Workflow Overview:**

```text theme={null}
1. Make code changes
2. Generate CodeRabbit report (detailed)
3. Feed report to Lovable
4. Lovable reviews and applies fixes
5. Iterate until satisfied
```

#### Step-by-Step Process

##### 1. Generate Detailed Report

**Recommended (markdown by severity):**

```bash theme={null}
cr-lovable              # All changes, output in reports/active/markdown/coderabbit-<timestamp>/
cr-lovable-uncommitted   # Uncommitted changes only
cr-lovable-prompt-only   # Same plus 00-PROMPT-ONLY.md for token-efficient prompts
```

**Or plain report only:**

```bash theme={null}
cr-report
# or
coderabbit --plain > reports/coderabbit-report-$(date +%Y%m%d-%H%M%S).txt
```

**What cr-lovable does:**

* Runs CodeRabbit and parses output by severity
* Writes `00-SUMMARY.md`, `01-CRITICAL.md` through `05-OUTSIDE-DIFF.md` in `reports/active/markdown/coderabbit-<timestamp>/`
* Optionally adds `00-PROMPT-ONLY.md` when using `--prompt-only`
* Includes code snippets, explanations, and AI prompts in each severity file

##### 2. Review the Report

```bash theme={null}
# List report runs (markdown by severity)
ls -lt reports/active/markdown/

# Open latest report dir in VS Code
code reports/active/markdown/coderabbit-<timestamp>/
# Or find latest: code $(ls -td reports/active/markdown/coderabbit-* | head -1)

# View summary
cat reports/active/markdown/coderabbit-<timestamp>/00-SUMMARY.md
```

##### 3. Feed to Lovable

###### Option A: Copy Report Content

1. Open the report file
2. Copy the entire content
3. Paste into Lovable chat with prompt:
   ```text theme={null}
   Please review this CodeRabbit report and apply the suggested fixes:

   [paste report content]
   ```

###### Option B: Reference the File

1. Upload the report file to Lovable
2. Use prompt:
   ```text theme={null}
   Review the CodeRabbit report in coderabbit-report-YYYYMMDD-HHMMSS.txt
   and apply all suggested fixes to the codebase.
   ```

##### 4. Lovable Applies Fixes

Lovable will:

* ✅ Read the CodeRabbit report
* ✅ Understand the issues
* ✅ Apply suggested fixes
* ✅ Update code accordingly
* ✅ Maintain code quality

##### 5. Iterate

After Lovable applies fixes:

1. **Regenerate report** to verify fixes:
   ```bash theme={null}
   cr-report
   ```
2. **Check for remaining issues**
3. **Repeat** if needed

### Example Lovable Prompts

#### Basic Prompt

```text theme={null}
Review the CodeRabbit report in reports/coderabbit-report-YYYYMMDD-HHMMSS.txt
and apply all suggested fixes. Focus on:
- Critical security issues
- Architecture violations
- Performance problems
- Code quality improvements
```

#### Detailed Prompt

```text theme={null}
I've generated a CodeRabbit review report. Please:

1. Read the report: reports/coderabbit-report-YYYYMMDD-HHMMSS.txt
2. Review all findings
3. Apply fixes for:
   - Architecture violations (core boundaries, import paths)
   - Security issues (RLS, PHI handling)
   - Performance problems (React.lazy, QueryClient)
   - Code quality (type safety, error handling)
4. Maintain existing functionality
5. Follow our coding standards (constitution.md, AGENTS.md)

Report the changes you make.
```

### Integration with Development Workflow

**Daily Development:**

```bash theme={null}
# 1. Make changes
# [edit code]

# 2. Generate report
cr-report

# 3. Feed to Lovable
# [paste report to Lovable]

# 4. Lovable applies fixes
# [Lovable works]

# 5. Verify
cr-report

# 6. Commit if clean
git add .
git commit -m "Apply CodeRabbit suggestions"
```

**Feature Completion:**

```bash theme={null}
# 1. Complete feature
# [implement feature]

# 2. Comprehensive review
cr-report

# 3. Feed to Lovable for fixes
# [Lovable reviews and fixes]

# 4. Final verification
cr-report

# 5. Create PR
git push
# CodeRabbit auto-reviews in UI
```

### When to Run Reviews

✅ **Good times:**

* Before committing significant changes
* After implementing a feature
* Before creating a pull request
* When refactoring code

❌ **Skip reviews for:**

* Documentation-only changes
* Simple formatting fixes
* Generated files

***

## Reporting

### Quick Methods

#### Method 1: Simple Output Redirection

Save review output to a file:

```bash theme={null}
# Review all changes and save to file
coderabbit --plain > coderabbit-report.txt

# Review uncommitted changes and save
coderabbit --type uncommitted --plain > coderabbit-report.txt

# Review with timestamp in filename
coderabbit --plain > "coderabbit-report-$(date +%Y%m%d-%H%M%S).txt"
```

#### Method 2: Save Both Output and Errors

Capture both standard output and errors:

```bash theme={null}
coderabbit --plain > coderabbit-report.txt 2>&1
```

#### Method 3: View and Save Simultaneously

Use `tee` to see output while saving:

```bash theme={null}
coderabbit --plain | tee coderabbit-report.txt
```

### Parse AI prompts from an existing PR

To extract CodeRabbit comments and **AI prompts** from a pull request on GitHub (e.g. to work through review feedback in Cursor/Copilot), use one of the PR-based parsers. Both fetch comments from the GitHub API and write markdown by severity; each also produces a **consolidated AI prompt** file you can copy-paste into another AI to fix all listed issues.

**Which script to use:**

| Goal                                                | Script      | Command                                                | Consolidated prompt file                                                              |
| --------------------------------------------------- | ----------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------- |
| CodeRabbit comments only, best AI-prompt extraction | Node parser | `npm run parse-pr-coderabbit -- <PR>`                  | `reports/active/pr-<PR>-parsed/06-AI-PROMPT-CONSOLIDATED.md`                          |
| All review comment authors (CodeRabbit + humans)    | Bash script | `bash scripts/utils/generate-pr-review-report.sh <PR>` | `reports/active/markdown/PR-<PR>-coderabbit-<timestamp>/05-AI-PROMPT-CONSOLIDATED.md` |

**Requirements:**

* **Node parser:** `GITHUB_TOKEN` with `repo` (or `public_repo` for public repos). For local runs, add `GITHUB_TOKEN=ghp_...` to `.env.local` (gitignored); the npm script loads it automatically.
* **Bash script:** GitHub CLI (`gh`) authenticated (`gh auth login`).

**Commands (example: PR 346):**

```bash theme={null}
# CodeRabbit-only, with consolidated prompt (Node)
npm run parse-pr-coderabbit -- 346
# Output: reports/active/pr-346-parsed/ (includes 06-AI-PROMPT-CONSOLIDATED.md)

# All reviewers, with consolidated prompt (Bash)
bash scripts/utils/generate-pr-review-report.sh 346
# Output: reports/active/markdown/PR-346-coderabbit-<timestamp>/ (includes 05-AI-PROMPT-CONSOLIDATED.md)
```

**Other examples:**

```bash theme={null}
# With GITHUB_TOKEN in .env.local (Node)
npm run parse-pr-coderabbit -- 282
npm run parse-pr-coderabbit -- 282 reports/active/pr-282

# Or pass token inline (Node)
GITHUB_TOKEN=ghp_xxxx npm run parse-pr-coderabbit -- 282
```

**Direct script (without npm):** use `node --env-file=.env.local scripts/utils/parse-pr-coderabbit-comments.js <PR> [output-dir]` or set `GITHUB_TOKEN` in your shell.

**Output (Node):** `00-SUMMARY.md`, `01-CRITICAL.md` through `05-UNCLASSIFIED.md`, and **`06-AI-PROMPT-CONSOLIDATED.md`**. The consolidated file contains one copy-paste block; paste it into Cursor, Copilot, or another AI to fix all listed issues. Individual findings also include **Problem**, **Proposed Fix**, and **AI Agent Prompt** in the severity files.

**Output (Bash):** `00-SUMMARY.md`, `01-CRITICAL.md` through `04-TRIVIAL.md`, and **`05-AI-PROMPT-CONSOLIDATED.md`**. Same use: copy the consolidated prompt into your AI assistant to address all comments.

### Report Types

#### Quick Report (`--prompt-only`)

**Command:** `cr-quick` or `coderabbit --prompt-only`

**Characteristics:**

* ✅ Minimal output (token-efficient)
* ✅ Quick to generate
* ✅ Designed for AI assistants
* ❌ No detailed explanations
* ❌ No code snippets
* ❌ Limited context

**File Size:** \~5-10 KB (small)

**Best For:**

* Quick checks during development
* AI assistant integration
* When you need minimal output

#### Detailed Report (`--plain`)

**Command:** `cr-report` or `coderabbit --plain`

**Characteristics:**

* ✅ Detailed explanations
* ✅ Code snippets included
* ✅ Context provided
* ✅ Actionable suggestions
* ✅ Issue categorization
* ❌ Larger file size
* ❌ Takes longer to generate

**File Size:** \~50-200 KB (larger)

**Best For:**

* Manual code reviews
* Feeding to Lovable
* Understanding issues deeply
* Comprehensive analysis

### Report Comparison

| Feature             | Quick (`--prompt-only`) | Detailed (`--plain`)   |
| ------------------- | ----------------------- | ---------------------- |
| **Output Size**     | Small (\~5-10 KB)       | Large (\~50-200 KB)    |
| **Generation Time** | Fast (\~30 seconds)     | Slower (\~1-2 minutes) |
| **Explanations**    | Minimal                 | Detailed               |
| **Code Snippets**   | No                      | Yes                    |
| **Context**         | Limited                 | Full                   |
| **Best For**        | Quick checks, AI        | Manual review, Lovable |
| **Token Usage**     | Low                     | High                   |

### For Lovable Workflow

#### ✅ Use Detailed Report

**Why:**

* Lovable needs context to understand issues
* Code snippets help Lovable see the problem
* Detailed explanations guide fixes
* Better results with more information

**Command:**

```bash theme={null}
cr-report          # Generate detailed report
```

#### ❌ Don't Use Quick Report

**Why:**

* Too minimal for Lovable
* Lacks context
* No code snippets
* Harder for Lovable to understand

### Report Organization

#### Recommended Directory Structure

```
reports/
├── coderabbit-report-20250110-143022.txt
├── coderabbit-report-20250110-150145.txt
└── README.md
```

#### Using Aliases for Reports

The aliases configured in setup automatically:

* Create `reports/` directory if needed
* Generate timestamped filenames
* Save both output and errors
* Provide confirmation message

**Usage:**

```bash theme={null}
# Plain text reports
cr-report              # Generate plain text report in reports/ directory
cr-report-uncommitted  # Plain text report for uncommitted only
cr-report-quick        # Quick prompt-only report

# Markdown reports (organized by severity)
cr-lovable             # Generate markdown report by severity (all changes)
cr-lovable-uncommitted # Markdown report for uncommitted changes
cr-lovable-show        # Generate markdown report and show output
```

**Markdown Report Output:**
The `cr-lovable` aliases generate markdown files organized by severity in `reports/active/markdown/coderabbit-<timestamp>/`:

* `00-SUMMARY.md` - Overview with counts and top impacted files
* `01-CRITICAL.md` - Critical issues (security, data integrity)
* `02-MAJOR.md` - Major issues (architecture, multi-tenancy)
* `03-MINOR.md` - Minor issues (code quality, best practices)
* `04-TRIVIAL.md` - Trivial issues (refactoring suggestions)
* `05-OUTSIDE-DIFF.md` - Issues outside the diff (if any)

### Best Practices

#### 1. Use Timestamps

Always include timestamps in filenames:

```bash theme={null}
coderabbit --plain > "report-$(date +%Y%m%d-%H%M%S).txt"
```

#### 2. Organize Reports

Create a dedicated directory:

```bash theme={null}
mkdir -p reports
coderabbit --plain > reports/coderabbit-report.txt
```

#### 3. Include Context

Add metadata to reports:

```bash theme={null}
{
    echo "CodeRabbit Review Report"
    echo "Generated: $(date)"
    echo "Repository: $(basename $(git rev-parse --show-toplevel))"
    echo "Branch: $(git branch --show-current)"
    echo "Commit: $(git rev-parse --short HEAD)"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    coderabbit --plain
} > reports/coderabbit-report.txt
```

#### 4. Review Type Selection

* **`--type uncommitted`**: For work-in-progress reviews
* **`--type committed`**: For reviewing staged changes
* **`--type all`**: For comprehensive reviews

#### 5. Output Format

* **`--plain`**: Always use for reports (removes interactive formatting)
* **`--prompt-only`**: For minimal output (AI assistant integration)

### Example Workflows

**Daily Development Report:**

```bash theme={null}
# Morning: Review yesterday's work
coderabbit --type committed --plain > reports/daily-$(date +%Y%m%d).txt

# Before commit: Quick review
coderabbit --type uncommitted --plain > reports/pre-commit-$(date +%Y%m%d-%H%M%S).txt
```

**Feature Completion Report:**

```bash theme={null}
# Comprehensive review before PR
coderabbit --type all --plain > reports/feature-review-$(date +%Y%m%d).txt
```

***

## Best Practices

### 1. Review Before Committing

```bash theme={null}
# Quick check before commit
cr-uncommitted
# Fix issues, then commit
```

### 2. Use Appropriate Output Mode

* **Development:** `cr-plain` (detailed feedback)
* **AI Assistants:** `cr-quick` (token-efficient)
* **CI/CD:** `cr-report` (save to file)

### 3. Address Security Issues First

CodeRabbit prioritizes:

1. Security vulnerabilities (SSRF, JWT validation, etc.)
2. Multi-tenant isolation violations
3. Architecture boundary violations
4. Code quality issues

### 4. Review Reports Regularly

Check `reports/` directory for saved reviews:

* Full reports for comprehensive analysis
* Quick reports for AI assistant context
* Uncommitted reports for pre-commit checks

### 5. Keep Configuration Updated

When architecture changes:

* Update `.coderabbit.yaml`
* Add new docs to knowledge base
* Update review instructions

### 6. Integrate with Workflow

* Run reviews before committing
* Use reports for documentation
* Share findings with team

### 7. Learnings and Quarterly Review

CodeRabbit stores **learnings** from PR feedback (scope set in `.coderabbit.yaml` under `knowledge_base.learnings.scope`). To keep reviews consistent:

* **Quarterly:** In the CodeRabbit app, go to Learnings and review/remove outdated or conflicting learnings. Filter by date or topic; delete learnings that reference deprecated patterns or old file layouts.
* **Scope:** Use `global` if all org repos share the same standards; use `local` if you have repos with different tech stacks to avoid cross-contamination.
* **Reinforcement:** If learnings seem ignored, add a path instruction that says: "Before responding, review all Learnings to ensure none are ignored."

**Related:** [CodeRabbit Learnings](https://docs.coderabbit.ai/guides/learnings)

***

## Troubleshooting

### Issue: CodeRabbit Not Found

**Solution:**

```bash theme={null}
# Check if installed
which coderabbit

# If not found, reinstall
curl -fsSL https://cli.coderabbit.ai/install.sh | sh
source ~/.bashrc
```

### Issue: Authentication Required

**Solution:**

```bash theme={null}
coderabbit auth login
# Follow prompts to authenticate with GitHub
```

### Issue: Authentication Failed (libsecret not available)

**Symptoms:** OAuth completes but CLI reports `Error [ERR_SECRETS_PLATFORM_ERROR]: libsecret not available`

**Solution:** See **[CODERABBIT\_CLI\_WSL\_AUTH.md](../archive/development/coderabbit/CODERABBIT_CLI_WSL_AUTH.md)**. In short: install `libsecret-1-0`, `gnome-keyring`, `dbus-x11`; run `coderabbit auth login` inside `dbus-run-session`.

### Issue: Slow Performance (Windows Filesystem)

**Symptoms:** CodeRabbit runs slowly when repository is on Windows filesystem (`/mnt/c/...`)

**Solutions:**

1. **Use VS Code Remote - WSL:**
   * Install "Remote - WSL" extension
   * Open project in WSL mode: `code .` (from WSL terminal)

2. **Move Repository to WSL Filesystem (Optional):**
   ```bash theme={null}
   cd ~
   mkdir -p projects
   cd projects
   git clone <repo-url> encoreos-platform
   ```

### Issue: Line Ending Conflicts

**Solution:**

```bash theme={null}
git config --global core.autocrlf input
```

### Issue: Reports Directory Not Found

**Solution:**

```bash theme={null}
mkdir -p reports
# Reports will be saved here automatically
```

### Issue: Report File is Empty

**Problem:** Report file created but empty

**Solutions:**

1. Check if CodeRabbit found any changes:
   ```bash theme={null}
   git status
   ```

2. Try with explicit type:
   ```bash theme={null}
   coderabbit --type all --plain > report.txt
   ```

3. Check for errors:
   ```bash theme={null}
   coderabbit --plain > report.txt 2>&1
   cat report.txt
   ```

### Issue: Report Too Large

**Problem:** Report file is very large

**Solutions:**

1. Review specific files only (if CodeRabbit supports it)
2. Use `--prompt-only` for summary
3. Filter output:
   ```bash theme={null}
   coderabbit --plain | grep -E "(CRITICAL|HIGH|MEDIUM)" > report-critical.txt
   ```

### Issue: CodeRabbit Not Using Configuration

**Problem:** CodeRabbit ignores `.coderabbit.yaml`

**Solutions:**

1. Verify file is in repository root
2. Check YAML syntax (use validator)
3. Ensure file is committed to branch
4. Check CodeRabbit app is installed

### Issue: Knowledge Base Not Working

**Problem:** CodeRabbit doesn't reference documentation

**Solutions:**

1. Verify file paths are correct (relative to repo root)
2. Ensure files exist and are committed
3. Check file sizes (very large files may be skipped)
4. Use absolute paths if needed

### Issue: Too Many/Few Reviews

**Problem:** Reviews are too strict or lenient

**Solutions:**

1. Adjust `profile: "assertive"` → `"chill"` or `"strict"`
2. Modify `review_instructions` to be more/less specific
3. Update `paths.ignored_paths` to exclude more files

***

## Recent Improvements (2025-12-10)

### Added Tools

* ✅ ESLint integration
* ✅ Gitleaks secret detection

### Enhanced Path Instructions

* ✅ Edge function security patterns
* ✅ PHI/PII logging detection
* ✅ Config file review instructions
* ✅ Enhanced React/TypeScript patterns

### Expanded Security Patterns

* ✅ SSRF prevention
* ✅ JWT validation requirements
* ✅ Error message security
* ✅ Input validation checks

***

## Additional Resources

* **CodeRabbit Docs:** [https://docs.coderabbit.ai](https://docs.coderabbit.ai)
* **Configuration Schema:** [https://coderabbit.ai/integrations/schema.v2.json](https://coderabbit.ai/integrations/schema.v2.json)
* **Project Constitution:** `constitution.md`
* **AI Guide:** `AI_GUIDE.md`
* **Quick Reference:** [CODE\_REVIEW\_PROCESS.md](./CODE_REVIEW_PROCESS.md) - Daily commands section

***

## Quick Reference Card

```bash theme={null}
# Daily Commands
cr-uncommitted      # Quick pre-commit review
cr-review           # Full review
cr-quick            # AI-friendly output

# Reports
cr-report           # Save full report
cr-report-quick     # Save quick report

# Status
coderabbit auth status    # Check auth
coderabbit --version      # Check version
```

***

**Maintained By:** Development Team\
**Questions?** See troubleshooting section, [CODE\_REVIEW\_PROCESS.md](./CODE_REVIEW_PROCESS.md) for daily commands, or check CodeRabbit documentation.
