docs(README): rewrite README with product positioning, design philosophy, and agent integration guide

This commit is contained in:
kite 2026-05-30 19:04:16 +08:00
parent d0a24c4de3
commit 103a213d77
6 changed files with 272 additions and 116 deletions

2
.gitignore vendored
View file

@ -23,6 +23,8 @@ bin/opencodereview
/opencodereview
/node_modules
# Mac OS X
.DS_Store

193
README.md
View file

@ -15,15 +15,53 @@
---
AI-powered code review CLI that reads Git diffs, sends changed files to a configurable LLM via an agent with tool-use capabilities, and generates structured review comments with line-level precision.
## What is Open Code Review?
The agent can read full file contents, search the codebase, inspect other changed files for context, and produce deep reviews — not just surface-level diff feedback.
Open Code Review is an AI-powered code review CLI tool. It originated as Alibaba Group's internal official AI code review assistant — over the past two years, it has served tens of thousands of developers and identified millions of code defects. After thorough validation at massive scale, we incubated it into an open source project for the community. Simply configure a model endpoint to get started.
![Open Benchmark](imgs/open-benchmark.png)
It reads Git diffs, sends changed files to a configurable LLM via an agent with tool-use capabilities, and generates structured review comments with line-level precision. The agent can read full file contents, search the codebase, inspect other changed files for context, and produce deep reviews — not just surface-level diff feedback.
## Install
![Highlights](imgs/highlights-en.png)
### Via NPM (Recommended)
## Why Open Code Review?
### The Problem with General-Purpose Agents
If you've used general-purpose agents like Claude Code with Skills for code review, you've likely encountered these pain points:
- **Incomplete coverage** — On larger changesets, agents tend to "cut corners," selectively reviewing only some files and missing others.
- **Position drift** — Reported issues frequently don't match the actual code location, with line numbers or file references drifting off target.
- **Unstable quality** — Natural-language-driven Skills are hard to debug, and review quality fluctuates significantly with minor prompt variations.
The root cause: a purely language-driven architecture lacks hard constraints on the review process.
### Core Design: Deterministic Engineering × Agent Hybrid
Open Code Review's core philosophy is to combine deterministic engineering with an agent, each handling what it does best.
**Deterministic Engineering — Hard Constraints**
For review steps that *must not go wrong*, engineering logic — not the language model — guarantees correctness:
- **Precise file selection** — Determines exactly which files need review and which should be filtered, ensuring no important change is missed.
- **Smart file bundling** — Groups related files into a single review unit (e.g., `message_en.properties` and `message_zh.properties` are bundled together). Each bundle runs as a sub-agent with isolated context — a divide-and-conquer strategy that stays stable on very large changesets and naturally supports concurrent review.
- **Fine-grained rule matching** — Matches review rules to each file's characteristics, keeping the model's attention sharply focused and eliminating information noise at the source. Compared to purely language-driven rule guidance, template-engine-based rule matching is more stable and predictable.
- **External positioning and reflection modules** — Independent comment-positioning and comment-reflection modules systematically improve both the location accuracy and content accuracy of AI feedback.
**Agent — Dynamic Decision-Making**
The agent's strengths are concentrated where they matter most — dynamic decisions and dynamic context retrieval:
- **Scenario-tuned prompts** — Prompt templates deeply optimized for code review, improving effectiveness while reducing token consumption.
- **Scenario-tuned toolset** — Distilled from deep analysis of tool-call traces in large-scale production data — including call frequency distributions, per-tool repetition rates, and the impact of new tools on the overall call chain — resulting in a purpose-built toolset that is more stable and predictable for code review than a generic agent toolkit.
## How to Use
### CLI
#### Install
**Via NPM (Recommended)**
```bash
npm install -g @alibaba-group/open-code-review
@ -31,7 +69,7 @@ npm install -g @alibaba-group/open-code-review
After installation, the `ocr` command is available globally.
### From GitHub Release
**From GitHub Release**
Download the latest binary from [GitHub Releases](https://github.com/alibaba/open-code-review/releases):
@ -53,7 +91,7 @@ curl -Lo ocr https://github.com/alibaba/open-code-review/releases/latest/downloa
chmod +x ocr && sudo mv ocr /usr/local/bin/ocr
```
### From Source
**From Source**
```bash
git clone https://github.com/alibaba/open-code-review.git
@ -62,9 +100,9 @@ make build
sudo cp dist/opencodereview /usr/local/bin/ocr
```
## Quick Start
#### Quick Start
### 1. Configure LLM
**1. Configure LLM**
**You must configure an LLM before reviewing code.**
@ -84,15 +122,15 @@ export OCR_USE_ANTHROPIC=true
Config is stored in `~/.opencodereview/config.json`.
The tool also falls back to Claude Code environment variables (`ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_MODEL`) and parses `~/.zshrc` / `~/.bashrc` for those exports.
It is also compatible with Claude Code environment variables (`ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_MODEL`) and parses `~/.zshrc` / `~/.bashrc` for those exports.
### 2. Test Connectivity
**2. Test Connectivity**
```bash
ocr llm test
```
### 3. Review
**3. Review**
```bash
cd your-project
@ -107,6 +145,91 @@ ocr review --from main --to feature-branch
ocr review --commit abc123
```
### Integrate with Your Coding Agent
OCR is designed to work seamlessly with coding agents. Use the `--audience agent` flag to produce structured, machine-readable output optimized for agent consumption.
#### Claude Code
OCR provides a ready-to-use [Claude Code slash command](https://docs.anthropic.com/en/docs/claude-code/slash-commands). Create the following file in your project:
`.claude/commands/open-code-review.md`:
~~~markdown
# /open-code-review
Invoke the professional code review Agent CLI tool OpenCodeReview (OCR) to review current code changes, and let the Agent autonomously decide whether to apply fixes.
## Workflow
### Step 1: Run Code Review
Run the OCR command:
```bash
ocr review --audience agent [user-args]
```
- Default (no user arguments): reviews staged, unstaged, and untracked changes (workspace mode).
- If the user provides `--commit` or `--c`: pass through as-is.
- If the user provides `--from` and `--to`: pass through as-is.
- (Optional) Provide `--background "requirement context"` to review whether the requirements are correctly implemented.
- Capture full stdout. Set a 5-minute timeout.
- If the `ocr` command is not found, install it by running `npm i -g @alibaba-group/open-code-review`.
### Step 2: Filter and Evaluate
For each comment, assess its validity and quality:
- **High**: Obvious bugs, security issues, clear mistakes, or well-founded suggestions with precise fix proposals
- **Medium**: Reasonable concerns but context-dependent, style/performance suggestions, or fixes that require manual implementation
- **Low**: Likely false positives, lacking sufficient context, nitpicks, or meaningless suggestions
Silently discard low-confidence comments. Display the remaining comments.
### Step 3: Fix
Automatically fix issues and suggestions that are worth adopting.
~~~
Then use `/open-code-review` in Claude Code to run a review. The slash command will run OCR, filter and evaluate each comment, and automatically fix issues worth adopting.
#### Cursor / Windsurf
Add the following instruction to your `.cursorrules` or `.windsurfrules` file:
```
## Code Review
When asked to review code, run the following command:
ocr review --audience agent
Parse the output and evaluate each comment by confidence level:
- High: Obvious bugs, security issues, clear mistakes — fix these automatically.
- Medium: Reasonable concerns — present to the user for decision.
- Low: Likely false positives or nitpicks — silently discard.
If the `ocr` command is not found, install it: npm i -g @alibaba-group/open-code-review
```
#### Other Coding Agents
Any coding agent that can execute shell commands can integrate with OCR:
```bash
# Machine-readable output for agent consumption
ocr review --audience agent
# With requirement context for targeted review
ocr review --audience agent --background "describe what the changes should do"
# Review specific commit or branch range
ocr review --audience agent --commit abc123
ocr review --audience agent --from main --to feature-branch
```
The `--audience agent` flag suppresses progress UI and outputs a concise structured summary. The `--background` flag provides requirement context so OCR can verify whether the implementation matches intent.
## Commands
| Command | Alias | Description |
@ -196,20 +319,6 @@ Layers 13 share the same JSON format:
- Within each layer, rules are evaluated in declaration order — the first match wins.
- If a rule file does not exist, it is silently skipped.
## Architecture
The review agent follows a **three-phase workflow**:
1. **Plan Phase** — For changes exceeding 50 lines, the agent performs risk analysis before reviewing. Smaller diffs skip directly to the main phase.
2. **Main Task Loop** — Each changed file gets its own goroutine. The LLM interacts with built-in tools (read files, search code, read diffs, submit comments) in a conversation loop until it calls `task_done`.
3. **Memory Compression** — When prompt context exceeds token thresholds (60% async, 80% sync), the agent uses three-zone partitioning (frozen / compress / active) to manage context window size.
### Key Design Decisions
- **Concurrent per-file processing** — Files are reviewed in parallel (default 8 workers). Timeout prevents any single file from blocking others.
- **Dual protocol support** — Both Anthropic Messages API and OpenAI Chat Completions API are supported, with automatic URL normalization.
- **Tool-use agent** — The LLM has access to domain-specific tools (`code_search`, `file_read`, `code_comment`, `file_find`, `file_read_diff`), enabling cross-referential context-aware reviews rather than isolated diff scanning.
## Configuration Reference
Config file: `~/.opencodereview/config.json`
@ -248,38 +357,6 @@ Internal defaults defined in `internal/config/template/task_template.json`:
| `PLAN_MODE_LINE_THRESHOLD` | 50 | Skip plan phase below this line count |
| `TOOL_REQUEST_WAIT_TIME_MS` | 10000 | Per-tool-request timeout |
## Built-in Tools
Tools the LLM agent can invoke during review:
| Tool | Phases | Purpose |
|------|--------|---------|
| `task_done` | main_task | Terminate the review (DONE/FAILED) |
| `code_comment` | main_task | Submit a line-level review comment |
| `file_read` | main_task | Read file content at a line range |
| `code_search` | plan + main | Search text/regex across files |
| `file_read_diff` | plan + main | View diff content for other changed files |
| `file_find` | plan + main | Find files by filename keyword |
## System Review Rules
Built-in glob-pattern-matched review checklists per file type, defined in `internal/config/rules/system_rules.json`:
| Pattern | Focus Areas |
|---------|-------------|
| `*.java` | NPE risks, dead loops, switch fallthrough, N+1 queries, thread safety |
| `*.{ts,js,tsx,jsx}` | Quality, React best practices, async norms, XSS/security |
| `*.kt` | Null safety, coroutine usage, idiomatic patterns |
| `*{go,py,ets,lua,dart,swift,groovy}` | Logic bugs, typos |
| `*{cpp,cc,hpp}` | Smart pointers, RAII, STL, const correctness |
| `*.c` | malloc/free pairing, buffer overflow |
| `pom.xml` / `build.gradle` | SNAPSHOT version prevention |
| `package.json` | Latest/wildcard versions, dependency conflicts |
| `*mapper*.xml` / `*dao*.xml` | SQL injection, performance, logic errors |
| `*.properties` | Typo detection, duplicate keys, security issues |
Override with `--rule path/to/rules.json`.
## Telemetry
OpenTelemetry integration for observability (spans, metrics). Disabled by default.

View file

@ -15,15 +15,53 @@
---
AI 驱动的代码审查 CLI 工具,读取 Git diff通过具备工具调用能力的 Agent 将变更文件发送至可配置的 LLM生成具有行级精度的结构化审查意见。
## Open Code Review 是什么?
Agent 可以读取完整文件内容、搜索代码库、检查其他变更文件以获取上下文,从而进行深度审查 —— 而非仅停留在表面的 diff 反馈
Open Code Review 是一款 AI 驱动的代码审查 CLI 工具。它的前身是阿里集团内部官方 AI 代码审查助手,过去两年在内部服务了数万开发者,识别了数百万个代码缺陷。经过大规模充分验证后,我们将其孵化为开源项目,对社区开放。只需配置一个模型端点即可使用
![Open Benchmark](imgs/open-benchmark.png)
它读取 Git diff通过具备工具调用能力的 Agent 将变更文件发送至可配置的 LLM生成具有行级精度的结构化审查意见。Agent 可以读取完整文件内容、搜索代码库、检查其他变更文件以获取上下文,从而进行深度审查——而非仅停留在表面的 diff 反馈。
## 安装
![Highlights](imgs/highlights-zh.png)
### 通过 NPM 安装(推荐)
## 为什么选择 Open Code Review
### 通用 Agent 的局限
如果你深度用过 Claude Code 等通用 Agent + Skills 方案做代码审查,可能对以下问题深有同感:
- **覆盖不全** —— 变更较大时Agent 倾向于"偷懒",选择性地审查部分文件,导致遗漏。
- **位置漂移** —— 报告的问题与实际代码位置常常对不上,出现行号或文件偏移。
- **效果不稳定** —— 基于自然语言驱动的 Skills 难以调试,审查质量因提示词的细微差异而大幅波动。
这些问题的根源在于:纯语言驱动的架构缺乏对审查流程的强约束。
### 核心设计:确定性工程 × Agent 混合驱动
Open Code Review 的核心设计理念是将确定性工程与 Agent 结合,各司其职。
**确定性工程——负责强约束**
对代码审查场景中"不能出错"的环节,由工程逻辑而非语言模型来保证:
- **精准的文件筛选** —— 明确哪些文件需要审查、哪些应当过滤,确保真正重要的改动一个不漏。
- **智能的文件打包** —— 将关联文件归并为同一审查单元(例如 `message_en.properties``message_zh.properties` 会被打包在一起)。每个包会作为 sub-agent 进行任务,它们之间的上下文是隔离的——这一分治策略在超大变更场景下表现更为稳定,同时天然支持并发审查。
- **精细化规则匹配** —— 针对不同文件的特征,匹配对应的审查规则,确保模型的注意力足够聚焦,从源头规避信息噪声的干扰。相比纯语言驱动的规则引导,基于模板引擎的规则匹配行为更稳定、结果更可预期。
- **外挂的定位与反思组件** —— 独立的评论定位模块与评论反思模块,系统性地提升 AI 反馈的位置准确性与内容准确性。
**Agent——负责动态决策**
将 Agent 的优势集中发挥在它真正擅长的地方——动态决策、动态召回上下文:
- **场景化提示词调优** —— 针对代码审查场景深度优化提示词模板,在提升效果的同时有效降低 Token 消耗。
- **场景化工具集沉淀** —— 基于对大量线上数据中工具调用轨迹的深入分析,包括不同工具的调用频率分布、单一工具的重复调用率、新增工具对整体调用链路的影响等多维度分析,从而对通用 Agent 工具集进行取舍与拆分,最终沉淀出一套在代码审查场景下效果更稳定、行为更可预期的专属工具集。
## 如何使用
### CLI
#### 安装
**通过 NPM 安装(推荐)**
```bash
npm install -g @alibaba-group/open-code-review
@ -31,7 +69,7 @@ npm install -g @alibaba-group/open-code-review
安装后,`ocr` 命令即可全局使用。
### 从 GitHub Release 下载
**从 GitHub Release 下载**
从 [GitHub Releases](https://github.com/alibaba/open-code-review/releases) 下载最新二进制文件:
@ -53,7 +91,7 @@ curl -Lo ocr https://github.com/alibaba/open-code-review/releases/latest/downloa
chmod +x ocr && sudo mv ocr /usr/local/bin/ocr
```
### 从源码构建
**从源码构建**
```bash
git clone https://github.com/alibaba/open-code-review.git
@ -62,9 +100,9 @@ make build
sudo cp dist/opencodereview /usr/local/bin/ocr
```
## 快速开始
#### 快速开始
### 1. 配置 LLM
**1. 配置 LLM**
**在审查代码之前,必须先配置 LLM。**
@ -84,15 +122,15 @@ export OCR_USE_ANTHROPIC=true
配置存储于 `~/.opencodereview/config.json`
工具也会回退使用 Claude Code 环境变量(`ANTHROPIC_BASE_URL``ANTHROPIC_AUTH_TOKEN``ANTHROPIC_MODEL`),并解析 `~/.zshrc` / `~/.bashrc` 中的相关导出。
同时兼容了 Claude Code 环境变量(`ANTHROPIC_BASE_URL``ANTHROPIC_AUTH_TOKEN``ANTHROPIC_MODEL`),并解析 `~/.zshrc` / `~/.bashrc` 中的相关导出。
### 2. 测试连通性
**2. 测试连通性**
```bash
ocr llm test
```
### 3. 开始审查
**3. 开始审查**
```bash
cd your-project
@ -107,6 +145,91 @@ ocr review --from main --to feature-branch
ocr review --commit abc123
```
### 集成到你的 Coding Agent
OCR 天然适配各类 Coding Agent。使用 `--audience agent` 标志可输出结构化的机器可读结果,方便 Agent 消费。
#### Claude Code
OCR 提供了开箱即用的 [Claude Code 斜杠命令](https://docs.anthropic.com/en/docs/claude-code/slash-commands)。在你的项目中创建以下文件:
`.claude/commands/open-code-review.md`
~~~markdown
# /open-code-review
调用专业代码审查 Agent CLI 工具 OpenCodeReview (OCR) 审查当前代码变更,并由 Agent 自主决定是否修复。
## 工作流
### 第 1 步:执行代码审查
运行 OCR 命令:
```bash
ocr review --audience agent [user-args]
```
- 默认(无用户参数):审查所有暂存、未暂存和未跟踪的变更(工作区模式)。
- 如果用户提供了 `--commit``-c`:原样传递。
- 如果用户提供了 `--from``--to`:原样传递。
- (可选)提供 `--background "需求上下文"` 以审查需求是否被正确实现。
- 捕获完整 stdout设置 5 分钟超时。
- 如果未找到 `ocr` 命令,运行 `npm i -g @alibaba-group/open-code-review` 安装。
### 第 2 步:过滤与评估
对每条评论,评估其有效性与质量:
- **高**:明显的 bug、安全问题、明确的错误或提出了精准修复方案的建议
- **中**:合理但依赖上下文的建议、风格/性能建议,或需要手动实现的修复
- **低**:大概率误报、缺乏充分上下文、吹毛求疵或无意义的建议
静默丢弃低置信度评论,展示其余评论。
### 第 3 步:修复
自动修复值得采纳的问题和建议。
~~~
然后在 Claude Code 中使用 `/open-code-review` 即可运行审查。该斜杠命令会运行 OCR、过滤评估每条评论并自动修复值得采纳的问题。
#### Cursor / Windsurf
将以下指令添加到你的 `.cursorrules``.windsurfrules` 文件中:
```
## 代码审查
当被要求审查代码时,运行以下命令:
ocr review --audience agent
解析输出并按置信度评估每条评论:
- 高:明显的 bug、安全问题、明确的错误 —— 自动修复。
- 中:合理的建议 —— 展示给用户决定。
- 低:大概率误报或吹毛求疵 —— 静默丢弃。
如果未找到 `ocr` 命令运行安装npm i -g @alibaba-group/open-code-review
```
#### 其他 Coding Agent
任何能执行 shell 命令的 Coding Agent 都可以集成 OCR
```bash
# 机器可读输出,适合 Agent 消费
ocr review --audience agent
# 带需求上下文,进行针对性审查
ocr review --audience agent --background "描述变更应该实现的功能"
# 审查特定提交或分支范围
ocr review --audience agent --commit abc123
ocr review --audience agent --from main --to feature-branch
```
`--audience agent` 标志会抑制进度 UI输出简洁的结构化摘要。`--background` 标志提供需求上下文,让 OCR 可以验证实现是否符合意图。
## 命令
| 命令 | 别名 | 描述 |
@ -196,20 +319,6 @@ OCR 通过四层优先级链解析评审规则。每层采用首次匹配原则
- 在每一层内,规则按声明顺序评估 —— 首次匹配生效。
- 如果规则文件不存在,将被静默跳过。
## 架构
审查 Agent 遵循**三阶段工作流**
1. **计划阶段** —— 对于超过 50 行的变更Agent 会在审查前进行风险分析。较小的 diff 直接跳至主阶段。
2. **主任务循环** —— 每个变更文件分配独立的 goroutine。LLM 在对话循环中与内置工具交互(读取文件、搜索代码、读取 diff、提交评论直到调用 `task_done`
3. **记忆压缩** —— 当提示上下文超过 token 阈值(异步 60%,同步 80%Agent 使用三区分区(冻结 / 压缩 / 活跃)管理上下文窗口大小。
### 关键设计决策
- **按文件并发处理** —— 文件并行审查(默认 8 个 worker。超时机制防止单个文件阻塞其他文件。
- **双协议支持** —— 同时支持 Anthropic Messages API 和 OpenAI Chat Completions API自动 URL 规范化。
- **工具调用 Agent** —— LLM 可以访问领域特定工具(`code_search``file_read``code_comment``file_find``file_read_diff`),实现跨引用的上下文感知审查,而非孤立的 diff 扫描。
## 配置参考
配置文件:`~/.opencodereview/config.json`
@ -248,38 +357,6 @@ OCR 通过四层优先级链解析评审规则。每层采用首次匹配原则
| `PLAN_MODE_LINE_THRESHOLD` | 50 | 低于此行数跳过计划阶段 |
| `TOOL_REQUEST_WAIT_TIME_MS` | 10000 | 单次工具请求超时时间 |
## 内置工具
审查过程中 LLM Agent 可调用的工具:
| 工具 | 可用阶段 | 用途 |
|------|----------|------|
| `task_done` | main_task | 终止审查DONE/FAILED |
| `code_comment` | main_task | 提交行级审查意见 |
| `file_read` | main_task | 按行范围读取文件内容 |
| `code_search` | plan + main | 跨文件搜索文本/正则表达式 |
| `file_read_diff` | plan + main | 查看其他变更文件的 diff 内容 |
| `file_find` | plan + main | 按文件名关键词查找文件 |
## 系统审查规则
按文件类型通过 glob 模式匹配的内置审查清单,定义于 `internal/config/rules/system_rules.json`
| 模式 | 关注领域 |
|------|----------|
| `*.java` | NPE 风险、死循环、switch 穿透、N+1 查询、线程安全 |
| `*.{ts,js,tsx,jsx}` | 代码质量、React 最佳实践、异步规范、XSS/安全 |
| `*.kt` | 空安全、协程使用、惯用模式 |
| `*{go,py,ets,lua,dart,swift,groovy}` | 逻辑缺陷、拼写错误 |
| `*{cpp,cc,hpp}` | 智能指针、RAII、STL、const 正确性 |
| `*.c` | malloc/free 配对、缓冲区溢出 |
| `pom.xml` / `build.gradle` | 禁止 SNAPSHOT 版本 |
| `package.json` | latest/通配符版本、依赖冲突 |
| `*mapper*.xml` / `*dao*.xml` | SQL 注入、性能、逻辑错误 |
| `*.properties` | 拼写检测、重复键、安全问题 |
可通过 `--rule path/to/rules.json` 覆盖。
## 遥测
OpenTelemetry 集成用于可观测性spans、metrics。默认关闭。

BIN
imgs/highlights-en.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 616 KiB

BIN
imgs/highlights-zh.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 613 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 MiB