codex-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

OpenAI 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.

加载方式:base.md + code-review.md
使用OpenAI的Codex CLI结合GPT-5.2-Codex进行专业代码审查——该模型专为检测bug、安全漏洞和代码质量问题训练。
参考来源: Codex CLI | GitHub | 代码审查指南

Why Codex for Code Review?

为什么选择Codex进行代码审查?

FeatureBenefit
GPT-5.2-CodexSpecialized training for code review
88% detection rateBugs, security flaws, style issues (LiveCodeBench)
Structured outputJSON schema for consistent findings
GitHub native
@codex review
in PR comments
Headless modeCI/CD automation without TUI

特性优势
GPT-5.2-Codex专为代码审查训练
88%检测率检测bug、安全漏洞、风格问题(基于LiveCodeBench)
结构化输出采用JSON格式保证结果一致性
原生支持GitHubPR评论中可使用
@codex review
触发
无头模式无需TUI即可实现CI/CD自动化

Installation

安装步骤

Prerequisites

前置要求

bash
undefined
bash
undefined

Check 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
undefined
nvm install 22 nvm use 22
undefined

Install Codex CLI

安装Codex CLI

bash
undefined
bash
undefined

Via 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
undefined
codex --version
undefined

Authentication

身份验证

Option 1: ChatGPT Subscription (Plus, Pro, Team, Edu, Enterprise)
bash
codex
选项1:ChatGPT订阅(Plus、Pro、Team、Edu、Enterprise版)
bash
codex

Follow prompts to sign in with ChatGPT account

按照提示使用ChatGPT账号登录


**Option 2: OpenAI API Key**
```bash

**选项2:OpenAI API密钥**
```bash

Set 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
undefined
codex
undefined

Shell Completions (Optional)

Shell补全(可选)

bash
undefined
bash
undefined

Bash

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
undefined
bash
undefined

Start Codex

启动Codex

codex
codex

In the TUI, type:

在TUI界面中输入:

/review
undefined
/review
undefined

Review Presets

审查预设

PresetUse Case
Review against base branchBefore opening PR - diffs against upstream
Review uncommitted changesBefore committing - staged + unstaged + untracked
Review a commitAnalyze specific SHA from history
Custom instructionse.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
undefined
bash
undefined

Simple 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"
undefined
codex exec --output-last-message review.txt "review the diff against main"
undefined

Full Automation (CI/CD)

全自动化(CI/CD)

bash
undefined
bash
undefined

Full 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"
undefined
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"
undefined

Structured Output with Schema

带Schema的结构化输出

bash
undefined
bash
undefined

Define 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"

---
codex exec
--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 review
Codex will respond with a standard GitHub code review.
在任何拉取请求中添加评论:
@codex review
Codex会回复标准的GitHub代码审查结果。

Option 2: GitHub Action

选项2:GitHub Action

yaml
undefined
yaml
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-sudo
undefined
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审查
    uses: openai/codex-action@main
    with:
      openai_api_key: ${{ secrets.OPENAI_API_KEY }}
      model: gpt-5.2-codex
      safety_strategy: drop-sudo
undefined

Option 3: Manual Headless in CI

选项3:CI中手动使用无头模式

yaml
undefined
yaml
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
undefined
yaml
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"

---
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"

---

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
undefined
toml
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:
  1. Security vulnerabilities (OWASP Top 10)
  2. Performance issues (N+1 queries, memory leaks)
  3. Error handling gaps
  4. Type safety issues """
undefined
instructions = """ 重点检查:
  1. 安全漏洞(OWASP Top 10)
  2. 性能问题(N+1查询、内存泄漏)
  3. 错误处理缺失
  4. 类型安全问题 """
undefined

Per-Project Config

项目级配置

toml
undefined
toml
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
undefined
bash
undefined

Interactive

交互式模式

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审查

AspectClaude (Built-in)Codex CLI
SetupNone (already in Claude Code)Install CLI + auth
ModelClaudeGPT-5.2-Codex (specialized)
ContextFull conversation contextFresh context per review
IntegrationNativeGitHub, GitLab, Jenkins
OutputMarkdownJSON schema support
Best forQuick reviews, in-flowCI/CD, critical PRs

维度Claude(内置)Codex CLI
设置难度无需设置(已集成到Claude Code)需要安装CLI并完成验证
模型ClaudeGPT-5.2-Codex(专为代码审查优化)
上下文继承完整对话上下文每次审查使用全新上下文
集成能力原生支持支持GitHub、GitLab、Jenkins
输出格式Markdown支持JSON Schema
最佳适用场景快速审查、流程内审查CI/CD自动化、重要PR审查

Security Considerations

安全注意事项

CI/CD Safety

CI/CD安全配置

yaml
undefined
yaml
undefined

Always 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 # 撤销高权限
undefined

API Key Protection

API密钥保护

yaml
undefined
yaml
undefined

GitHub 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

切勿在日志中输出密钥

undefined
undefined

Public Repositories

公共仓库

For public repos, use
drop-sudo
safety strategy to prevent Codex from reading its own API key during execution.

对于公共仓库,使用
drop-sudo
安全策略,防止Codex在执行过程中读取自身API密钥。

Troubleshooting

故障排查

IssueSolution
codex: command not found
Run
npm install -g @openai/codex
Node.js version error
Upgrade to Node.js 22+
Authentication failed
Re-run
codex
and sign in again
API key invalid
Check
OPENAI_API_KEY
env var
Timeout in CI
Add
--timeout 300
flag
Rate limited
Reduce frequency or upgrade plan

问题解决方案
codex: command not found
执行
npm install -g @openai/codex
重新安装
Node.js version error
升级到Node.js 22+版本
Authentication failed
重新运行
codex
并重新登录
API key invalid
检查
OPENAI_API_KEY
环境变量是否正确
CI中超时
添加
--timeout 300
参数
请求受限
降低请求频率或升级订阅计划

Anti-Patterns

反模式

  • Using
    --dangerously-bypass-approvals-and-sandbox
    casually
    - Only in isolated CI runners
  • 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
  • 随意使用
    --dangerously-bypass-approvals-and-sandbox
    - 仅在隔离的CI运行器中使用
  • 在日志中暴露API密钥 - 使用密钥管理工具
  • CI中跳过沙箱模式 - 始终使用
    --sandbox read-only
  • 忽略审查结果 - 需审查并处理结果,或记录例外情况
  • 每次提交都运行审查 - 仅在PR中运行以节省成本