codex-review
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOpenAI Codex Code Review Skill
OpenAI Codex代码审查Skill
Load with: base.md + code-review.md
Use OpenAI's Codex CLI for specialized code review with GPT-5.2-Codex - trained specifically for detecting bugs, security flaws, and code quality issues.
Why Codex for Code Review?
为什么选择Codex进行代码审查?
| Feature | Benefit |
|---|---|
| GPT-5.2-Codex | Specialized training for code review |
| 88% detection rate | Bugs, security flaws, style issues (LiveCodeBench) |
| Structured output | JSON schema for consistent findings |
| GitHub native | |
| Headless mode | CI/CD automation without TUI |
| 特性 | 优势 |
|---|---|
| GPT-5.2-Codex | 专为代码审查训练 |
| 88%检测率 | 检测bug、安全漏洞、风格问题(基于LiveCodeBench) |
| 结构化输出 | 采用JSON格式保证结果一致性 |
| 原生支持GitHub | PR评论中可使用 |
| 无头模式 | 无需TUI即可实现CI/CD自动化 |
Installation
安装步骤
Prerequisites
前置要求
bash
undefinedbash
undefinedCheck Node.js version (requires 22+)
检查Node.js版本(要求22+)
node --version
node --version
Install Node.js 22 if needed
若需要,安装Node.js 22
macOS
macOS系统
brew install node@22
brew install node@22
Or via nvm
或通过nvm安装
nvm install 22
nvm use 22
undefinednvm install 22
nvm use 22
undefinedInstall Codex CLI
安装Codex CLI
bash
undefinedbash
undefinedVia npm (recommended)
推荐通过npm安装
npm install -g @openai/codex
npm install -g @openai/codex
Via Homebrew (macOS)
macOS系统可通过Homebrew安装
brew install --cask codex
brew install --cask codex
Verify installation
验证安装
codex --version
undefinedcodex --version
undefinedAuthentication
身份验证
Option 1: ChatGPT Subscription (Plus, Pro, Team, Edu, Enterprise)
bash
codex选项1:ChatGPT订阅(Plus、Pro、Team、Edu、Enterprise版)
bash
codexFollow prompts to sign in with ChatGPT account
按照提示使用ChatGPT账号登录
**Option 2: OpenAI API Key**
```bash
**选项2:OpenAI API密钥**
```bashSet environment variable
设置环境变量
export OPENAI_API_KEY=sk-proj-...
export OPENAI_API_KEY=sk-proj-...
Or add to shell profile
或添加到shell配置文件
echo 'export OPENAI_API_KEY=sk-proj-...' >> ~/.zshrc
echo 'export OPENAI_API_KEY=sk-proj-...' >> ~/.zshrc
Run Codex
运行Codex
codex
undefinedcodex
undefinedShell Completions (Optional)
Shell补全(可选)
bash
undefinedbash
undefinedBash
Bash环境
codex completion bash >> ~/.bashrc
codex completion bash >> ~/.bashrc
Zsh
Zsh环境
codex completion zsh >> ~/.zshrc
codex completion zsh >> ~/.zshrc
Fish
Fish环境
codex completion fish > ~/.config/fish/completions/codex.fish
---codex completion fish > ~/.config/fish/completions/codex.fish
---Interactive Code Review
交互式代码审查
Launch Review Mode
启动审查模式
bash
undefinedbash
undefinedStart Codex
启动Codex
codex
codex
In the TUI, type:
在TUI界面中输入:
/review
undefined/review
undefinedReview Presets
审查预设
| Preset | Use Case |
|---|---|
| Review against base branch | Before opening PR - diffs against upstream |
| Review uncommitted changes | Before committing - staged + unstaged + untracked |
| Review a commit | Analyze specific SHA from history |
| Custom instructions | e.g., "Focus on security vulnerabilities" |
| 预设类型 | 使用场景 |
|---|---|
| 与基准分支对比审查 | 发起PR前——与上游分支对比差异 |
| 审查未提交变更 | 提交前——暂存、未暂存及未追踪文件 |
| 审查指定提交 | 分析历史中特定SHA的提交 |
| 自定义审查指令 | 例如:"重点检查安全漏洞" |
Example Session
示例会话
$ codex
> /review
Select review type:
❯ Review against a base branch
Review uncommitted changes
Review a commit
Custom review instructions
Select base branch: main
Reviewing changes...
┌─────────────────────────────────────────────────────────────┐
│ CODE REVIEW FINDINGS │
├─────────────────────────────────────────────────────────────┤
│ 🔴 CRITICAL: SQL Injection vulnerability │
│ File: src/api/users.ts:45 │
│ Issue: User input directly interpolated in query │
│ Fix: Use parameterized queries │
├─────────────────────────────────────────────────────────────┤
│ 🟠 HIGH: Missing authentication check │
│ File: src/api/admin.ts:23 │
│ Issue: Admin endpoint accessible without auth │
│ Fix: Add requireAuth middleware │
├─────────────────────────────────────────────────────────────┤
│ 🟡 MEDIUM: Inefficient database query │
│ File: src/services/orders.ts:89 │
│ Issue: N+1 query pattern in loop │
│ Fix: Use batch query or JOIN │
└─────────────────────────────────────────────────────────────┘$ codex
> /review
选择审查类型:
❯ 与基准分支对比审查
审查未提交变更
审查指定提交
自定义审查指令
选择基准分支:main
正在审查变更...
┌─────────────────────────────────────────────────────────────┐
│ 代码审查结果 │
├─────────────────────────────────────────────────────────────┤
│ 🔴 严重:SQL注入漏洞 │
│ 文件:src/api/users.ts:45 │
│ 问题:用户输入直接插入查询语句 │
│ 修复方案:使用参数化查询 │
├─────────────────────────────────────────────────────────────┤
│ 🟠 高优先级:缺少身份验证检查 │
│ 文件:src/api/admin.ts:23 │
│ 问题:管理员端点无需验证即可访问 │
│ 修复方案:添加requireAuth中间件 │
├─────────────────────────────────────────────────────────────┤
│ 🟡 中优先级:低效数据库查询 │
│ 文件:src/services/orders.ts:89 │
│ 问题:循环中存在N+1查询模式 │
│ 修复方案:使用批量查询或JOIN │
└─────────────────────────────────────────────────────────────┘Headless Mode (Automation)
无头模式(自动化)
Basic Usage
基础用法
bash
undefinedbash
undefinedSimple review
简单审查
codex exec "review the code for bugs and security issues"
codex exec "review the code for bugs and security issues"
Review with JSON output
以JSON格式输出审查结果
codex exec --json "review uncommitted changes" > review.json
codex exec --json "review uncommitted changes" > review.json
Save final message to file
将最终结果保存到文件
codex exec --output-last-message review.txt "review the diff against main"
undefinedcodex exec --output-last-message review.txt "review the diff against main"
undefinedFull Automation (CI/CD)
全自动化(CI/CD)
bash
undefinedbash
undefinedFull auto mode (use only in isolated runners!)
完全自动化模式(仅在隔离的运行器中使用!)
codex exec
--full-auto
--json
--output-last-message findings.txt
--sandbox read-only
-m gpt-5.2-codex
"Review this code for bugs, security issues, and performance problems"
--full-auto
--json
--output-last-message findings.txt
--sandbox read-only
-m gpt-5.2-codex
"Review this code for bugs, security issues, and performance problems"
undefinedcodex exec
--full-auto
--json
--output-last-message findings.txt
--sandbox read-only
-m gpt-5.2-codex
"Review this code for bugs, security issues, and performance problems"
--full-auto
--json
--output-last-message findings.txt
--sandbox read-only
-m gpt-5.2-codex
"Review this code for bugs, security issues, and performance problems"
undefinedStructured Output with Schema
带Schema的结构化输出
bash
undefinedbash
undefinedDefine output schema
定义输出Schema
cat > review-schema.json << 'EOF'
{
"type": "object",
"properties": {
"findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"severity": { "enum": ["critical", "high", "medium", "low"] },
"title": { "type": "string" },
"file": { "type": "string" },
"line": { "type": "integer" },
"description": { "type": "string" },
"suggestion": { "type": "string" }
},
"required": ["severity", "title", "file", "description"]
}
},
"summary": { "type": "string" },
"approved": { "type": "boolean" }
},
"required": ["findings", "summary", "approved"]
}
EOF
cat > review-schema.json << 'EOF'
{
"type": "object",
"properties": {
"findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"severity": { "enum": ["critical", "high", "medium", "low"] },
"title": { "type": "string" },
"file": { "type": "string" },
"line": { "type": "integer" },
"description": { "type": "string" },
"suggestion": { "type": "string" }
},
"required": ["severity", "title", "file", "description"]
}
},
"summary": { "type": "string" },
"approved": { "type": "boolean" }
},
"required": ["findings", "summary", "approved"]
}
EOF
Run with schema validation
结合Schema验证运行审查
codex exec
--output-schema review-schema.json
--output-last-message review.json
"Review the staged changes and output findings"
--output-schema review-schema.json
--output-last-message review.json
"Review the staged changes and output findings"
---codex exec
--output-schema review-schema.json
--output-last-message review.json
"Review the staged changes and output findings"
--output-schema review-schema.json
--output-last-message review.json
"Review the staged changes and output findings"
---GitHub Integration
GitHub集成
Option 1: PR Comment Trigger
选项1:PR评论触发
In any pull request, add a comment:
@codex reviewCodex will respond with a standard GitHub code review.
在任何拉取请求中添加评论:
@codex reviewCodex会回复标准的GitHub代码审查结果。
Option 2: GitHub Action
选项2:GitHub Action
yaml
undefinedyaml
undefined.github/workflows/codex-review.yml
.github/workflows/codex-review.yml
name: Codex Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Codex Review
uses: openai/codex-action@main
with:
openai_api_key: ${{ secrets.OPENAI_API_KEY }}
model: gpt-5.2-codex
safety_strategy: drop-sudoundefinedname: Codex Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Codex审查
uses: openai/codex-action@main
with:
openai_api_key: ${{ secrets.OPENAI_API_KEY }}
model: gpt-5.2-codex
safety_strategy: drop-sudoundefinedOption 3: Manual Headless in CI
选项3:CI中手动使用无头模式
yaml
undefinedyaml
undefined.github/workflows/codex-review.yml
.github/workflows/codex-review.yml
name: Codex Code Review
on:
pull_request:
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install Codex CLI
run: npm install -g @openai/codex
- name: Run Review
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
# Get diff
git diff origin/${{ github.base_ref }}...HEAD > diff.txt
# Run Codex review
codex exec \
--full-auto \
--sandbox read-only \
--output-last-message review.md \
"Review this git diff for bugs, security issues, and code quality: $(cat diff.txt)"
- name: Post Review Comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.md', 'utf8');
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `## 🤖 Codex Code Review\n\n${review}`
});
---name: Codex Code Review
on:
pull_request:
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: 安装Codex CLI
run: npm install -g @openai/codex
- name: 运行审查
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
# 获取差异内容
git diff origin/${{ github.base_ref }}...HEAD > diff.txt
# 运行Codex审查
codex exec \
--full-auto \
--sandbox read-only \
--output-last-message review.md \
"Review this git diff for bugs, security issues, and code quality: $(cat diff.txt)"
- name: 发布审查评论
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review.md', 'utf8');
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `## 🤖 Codex代码审查\n\n${review}`
});
---GitLab CI/CD
GitLab CI/CD
yaml
undefinedyaml
undefined.gitlab-ci.yml
.gitlab-ci.yml
codex-review:
image: node:22
stage: review
script:
- npm install -g @openai/codex
- |
codex exec
--full-auto
--sandbox read-only
--output-last-message review.md
"Review the merge request changes for bugs and security issues" - cat review.md artifacts: paths: - review.md rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event"
--full-auto
--sandbox read-only
--output-last-message review.md
"Review the merge request changes for bugs and security issues" - cat review.md artifacts: paths: - review.md rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event"
---codex-review:
image: node:22
stage: review
script:
- npm install -g @openai/codex
- |
codex exec
--full-auto
--sandbox read-only
--output-last-message review.md
"Review the merge request changes for bugs and security issues" - cat review.md artifacts: paths: - review.md rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event"
--full-auto
--sandbox read-only
--output-last-message review.md
"Review the merge request changes for bugs and security issues" - cat review.md artifacts: paths: - review.md rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event"
---Jenkins Pipeline
Jenkins流水线
groovy
pipeline {
agent any
environment {
OPENAI_API_KEY = credentials('openai-api-key')
}
stages {
stage('Install Codex') {
steps {
sh 'npm install -g @openai/codex'
}
}
stage('Code Review') {
steps {
sh '''
codex exec \
--full-auto \
--sandbox read-only \
--output-last-message review.md \
"Review the code changes for bugs and security issues"
'''
}
}
stage('Publish Results') {
steps {
archiveArtifacts artifacts: 'review.md'
script {
def review = readFile('review.md')
echo "Code Review Results:\n${review}"
}
}
}
}
}groovy
pipeline {
agent any
environment {
OPENAI_API_KEY = credentials('openai-api-key')
}
stages {
stage('安装Codex') {
steps {
sh 'npm install -g @openai/codex'
}
}
stage('代码审查') {
steps {
sh '''
codex exec \
--full-auto \
--sandbox read-only \
--output-last-message review.md \
"Review the code changes for bugs and security issues"
'''
}
}
stage('发布结果') {
steps {
archiveArtifacts artifacts: 'review.md'
script {
def review = readFile('review.md')
echo "代码审查结果:\n${review}"
}
}
}
}
}Configuration
配置说明
Config File
全局配置文件
toml
undefinedtoml
undefined~/.codex/config.toml
~/.codex/config.toml
[model]
default = "gpt-5.2-codex" # Best for code review
[sandbox]
default = "read-only" # Safe for reviews
[review]
[model]
default = "gpt-5.2-codex" # 最适合代码审查的模型
[sandbox]
default = "read-only" # 审查时的安全模式
[review]
Custom review instructions applied to all reviews
所有审查都会应用的自定义指令
instructions = """
Focus on:
- Security vulnerabilities (OWASP Top 10)
- Performance issues (N+1 queries, memory leaks)
- Error handling gaps
- Type safety issues """
undefinedinstructions = """
重点检查:
- 安全漏洞(OWASP Top 10)
- 性能问题(N+1查询、内存泄漏)
- 错误处理缺失
- 类型安全问题 """
undefinedPer-Project Config
项目级配置
toml
undefinedtoml
undefined.codex/config.toml (in project root)
项目根目录下的.codex/config.toml
[review]
instructions = """
This is a Python FastAPI project. Focus on:
- Async/await correctness
- Pydantic model validation
- SQL injection via SQLAlchemy
- Authentication/authorization gaps """
---[review]
instructions = """
这是一个Python FastAPI项目,重点检查:
- Async/await语法正确性
- Pydantic模型验证
- SQLAlchemy可能导致的SQL注入
- 身份验证/授权缺失 """
---CLI Quick Reference
CLI快速参考
bash
undefinedbash
undefinedInteractive
交互式模式
codex # Start TUI
/review # Open review presets
codex # 启动TUI界面
/review # 打开审查预设
Headless
无头模式
codex exec "prompt" # Non-interactive execution
codex exec --json "prompt" # JSON output
codex exec --full-auto "prompt" # No approval prompts
codex exec "prompt" # 非交互式执行
codex exec --json "prompt" # 输出JSON格式结果
codex exec --full-auto "prompt" # 无需确认直接执行
Key Flags
关键参数
--output-last-message FILE # Save response to file
--output-schema FILE # Validate against JSON schema
--sandbox read-only # Restrict file access
-m gpt-5.2-codex # Use best review model
--json # Machine-readable output
--output-last-message FILE # 将结果保存到文件
--output-schema FILE # 按照指定JSON Schema验证结果
--sandbox read-only # 限制文件访问权限
-m gpt-5.2-codex # 使用最优审查模型
--json # 输出机器可读格式
Resume
恢复会话
codex exec resume SESSION_ID # Continue previous session
---codex exec resume SESSION_ID # 继续之前的会话
---Comparison: Claude vs Codex Review
对比:Claude vs Codex审查
| Aspect | Claude (Built-in) | Codex CLI |
|---|---|---|
| Setup | None (already in Claude Code) | Install CLI + auth |
| Model | Claude | GPT-5.2-Codex (specialized) |
| Context | Full conversation context | Fresh context per review |
| Integration | Native | GitHub, GitLab, Jenkins |
| Output | Markdown | JSON schema support |
| Best for | Quick reviews, in-flow | CI/CD, critical PRs |
| 维度 | Claude(内置) | Codex CLI |
|---|---|---|
| 设置难度 | 无需设置(已集成到Claude Code) | 需要安装CLI并完成验证 |
| 模型 | Claude | GPT-5.2-Codex(专为代码审查优化) |
| 上下文 | 继承完整对话上下文 | 每次审查使用全新上下文 |
| 集成能力 | 原生支持 | 支持GitHub、GitLab、Jenkins |
| 输出格式 | Markdown | 支持JSON Schema |
| 最佳适用场景 | 快速审查、流程内审查 | CI/CD自动化、重要PR审查 |
Security Considerations
安全注意事项
CI/CD Safety
CI/CD安全配置
yaml
undefinedyaml
undefinedAlways use these flags in CI/CD:
CI/CD中务必使用以下参数:
--sandbox read-only # Prevent file modifications
--safety-strategy drop-sudo # Revoke elevated permissions
undefined--sandbox read-only # 防止文件被修改
--safety-strategy drop-sudo # 撤销高权限
undefinedAPI Key Protection
API密钥保护
yaml
undefinedyaml
undefinedGitHub Actions - use secrets
GitHub Actions中使用密钥管理
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
Never hardcode keys
切勿硬编码密钥
Never echo keys in logs
切勿在日志中输出密钥
undefinedundefinedPublic Repositories
公共仓库
For public repos, use safety strategy to prevent Codex from reading its own API key during execution.
drop-sudo对于公共仓库,使用安全策略,防止Codex在执行过程中读取自身API密钥。
drop-sudoTroubleshooting
故障排查
| Issue | Solution |
|---|---|
| Run |
| Upgrade to Node.js 22+ |
| Re-run |
| Check |
| Add |
| Reduce frequency or upgrade plan |
| 问题 | 解决方案 |
|---|---|
| 执行 |
| 升级到Node.js 22+版本 |
| 重新运行 |
| 检查 |
| 添加 |
| 降低请求频率或升级订阅计划 |
Anti-Patterns
反模式
- Using casually - Only in isolated CI runners
--dangerously-bypass-approvals-and-sandbox - Exposing API keys in logs - Use secrets management
- Skipping sandbox in CI - Always use
--sandbox read-only - Ignoring findings - Review and address or document exceptions
- Running on every commit - Use on PRs only to save costs
- 随意使用- 仅在隔离的CI运行器中使用
--dangerously-bypass-approvals-and-sandbox - 在日志中暴露API密钥 - 使用密钥管理工具
- CI中跳过沙箱模式 - 始终使用
--sandbox read-only - 忽略审查结果 - 需审查并处理结果,或记录例外情况
- 每次提交都运行审查 - 仅在PR中运行以节省成本