Codex CLI 非交互模式:把 AI 接入你的 CI/CD 流水线
本系列文章基于 Codex CLI 源码深度分析,本文聚焦 codex exec 命令,教你如何将 AI 编程能力接入自动化流水线。
全网唯一从 Rust 源码层面拆解 Codex CLI 的系列
零、阅读收益
读完本文你将理解:
- codex exec 的完整用法和参数体系
- 如何将 AI 编程能力接入 GitHub Actions / GitLab CI
- 非交互模式的输入输出格式(JSON/文本)
- 源码中 codex-rs/exec/ 的实现原理
一、exec 命令概览
codex exec 是 Codex CLI 的非交互模式,适合脚本化和自动化场景:
# 基本用法
codex exec "修复 src/main.rs 中的所有编译错误"
# 简写
codex e "添加单元测试"
核心参数
| PROMPT | 任务描述(位置参数) |
| –json | 以 JSON 格式输出结果 |
| –model | 指定模型 |
| –approval-policy | 覆盖审批策略 |
| –no-sandbox | 禁用沙箱(谨慎使用) |
| –cwd | 指定工作目录 |
| –max-turns | 最大 Turn 数 |
| –timeout | 超时时间(秒) |
源码结构
// 源码位置:codex-rs/exec/src/
pub struct Cli {
/// 任务描述
#[arg(value_name = "PROMPT")]
pub prompt: Option<String>,
/// 从 stdin 读取 prompt
#[arg(long = "stdin", default_value_t = false)]
pub read_prompt_from_stdin: bool,
/// JSON 格式输出
#[arg(long = "json", default_value_t = false)]
pub json_output: bool,
/// 最大 Turn 数
#[arg(long = "max-turns")]
pub max_turns: Option<usize>,
/// 超时时间
#[arg(long = "timeout")]
pub timeout_secs: Option<u64>,
}
二、实战场景
2.1 自动修复编译错误
# 将编译错误通过管道传给 Codex
cargo build 2>&1 | codex exec –stdin "修复这些编译错误"
# 或指定文件
codex exec "修复 src/main.rs 中的编译错误,不要改变功能"
2.2 自动生成单元测试
codex exec "为 src/lib.rs 中的所有公开函数生成单元测试,写入 tests/ 目录"
2.3 代码格式化与 Lint 修复
codex exec "检查 src/ 目录下的所有 Rust 文件,修复 clippy 警告"
2.4 自动生成文档
codex exec "为 src/ 目录下所有公开 API 添加 Rust doc 注释"
2.5 依赖更新
codex exec "检查 Cargo.toml 中的依赖版本,更新到最新兼容版本,确保编译通过"
三、GitHub Actions 集成
3.1 自动修复 CI 失败
# .github/workflows/ai-fix.yml
name: AI Auto Fix
on:
workflow_run:
workflows: ["CI"]
types: [completed]
jobs:
ai-fix:
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
runs-on: ubuntu–latest
steps:
– uses: actions/checkout@v4
– name: Install Codex CLI
run: |
curl -fsSL https://chatgpt.com/codex/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
– name: Get CI Error Log
run: |
# 获取 CI 失败日志
gh run view ${{ github.event.workflow_run.id }} –log > ci-error.log
– name: AI Fix
env:
CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}
run: |
cat ci-error.log | codex exec –stdin \\
–json \\
–max-turns 5 \\
–timeout 300 \\
"分析 CI 失败原因并修复代码。只修改源文件,不要修改 CI 配置。"
– name: Create PR
if: success()
run: |
git config user.name "codex-bot"
git config user.email "bot@example.com"
git checkout -b ai-fix-${{ github.run_id }}
git add .
git commit -m "🤖 AI auto-fix for CI failure"
git push origin ai-fix-${{ github.run_id }}
gh pr create –title "🤖 AI Auto Fix" –body "AI 自动修复 CI 失败"
3.2 自动 Code Review
# .github/workflows/ai-review.yml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
ai-review:
runs-on: ubuntu–latest
steps:
– uses: actions/checkout@v4
with:
fetch-depth: 0
– name: Install Codex CLI
run: |
curl -fsSL https://chatgpt.com/codex/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
– name: AI Review
env:
CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}
run: |
codex review \\
–base ${{ github.event.pull_request.base.sha }} \\
–json \\
–output review.json
– name: Post Review
run: |
# 解析 review.json 并作为 PR comment 发布
gh pr comment ${{ github.event.pull_request.number }} \\
–body "$(cat review.json | jq -r '.summary')"
3.3 自动生成 Release Notes
# .github/workflows/ai-release-notes.yml
name: AI Release Notes
on:
push:
tags:
– 'v*'
jobs:
release-notes:
runs-on: ubuntu–latest
steps:
– uses: actions/checkout@v4
with:
fetch-depth: 0
– name: Install Codex CLI
run: |
curl -fsSL https://chatgpt.com/codex/install.sh | sh
echo "$HOME/.local/bin" >> $GITHUB_PATH
– name: Generate Release Notes
env:
CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}
run: |
# 获取 git log
PREV_TAG=$(git describe –tags –abbrev=0 HEAD^ 2>/dev/null || echo "")
git log ${PREV_TAG}..HEAD –oneline > changes.txt
cat changes.txt | codex exec ––stdin \\
––json \\
"根据这些 git commits 生成 Release Notes,按 Feature/BugFix/Breaking 分类"
– name: Create Release
run: |
gh release create ${{ github.ref_name }} \\
–title "${{ github.ref_name }}" \\
–notes "$(cat release-notes.md)"
四、GitLab CI 集成
# .gitlab-ci.yml
ai-auto-fix:
stage: fix
when: on_failure
image: rust:latest
before_script:
– curl –fsSL https://chatgpt.com/codex/install.sh | sh
– export PATH="$HOME/.local/bin:$PATH"
script:
– |
# 收集错误日志
cat build.log 2>/dev/null || cargo build 2>&1 | tee build.log
# AI 修复
cat build.log | codex exec –stdin \\
–json \\
–max-turns 5 \\
"修复编译错误"
artifacts:
paths:
– "*.rs"
when: on_success
五、JSON 输出格式
codex exec –json "列出所有 TODO 注释"
输出示例:
{
"success": true,
"result": {
"summary": "找到 5 个 TODO 注释",
"files_modified": [],
"output": "1. src/main.rs:45 – TODO: handle error\\n2. src/lib.rs:120 – TODO: add tests\\n…",
"token_usage": {
"total": 1234,
"prompt": 800,
"completion": 434
}
},
"error": null
}
六、Shell 脚本集成
#!/bin/bash
# auto-fix.sh – 自动修复脚本
set -e
PROJECT_DIR="$1"
ERROR_LOG="$2"
cd "$PROJECT_DIR"
# 检查 Codex CLI 是否安装
if ! command -v codex &> /dev/null; then
echo "Installing Codex CLI…"
curl -fsSL https://chatgpt.com/codex/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
fi
# 检查认证
if ! codex login-status &> /dev/null; then
echo "Please login first: codex login"
exit 1
fi
# 执行 AI 修复
echo "Analyzing errors and fixing…"
codex exec –stdin \\
–json \\
–max-turns 5 \\
–timeout 300 \\
"修复以下错误,只修改源文件,不要引入新的问题" < "$ERROR_LOG"
# 检查修复结果
if cargo build 2>&1 | grep -q "error"; then
echo "Some errors remain, manual review needed"
exit 1
else
echo "All errors fixed!"
fi
七、安全注意事项
在 CI/CD 中使用 Codex exec 时:
# CI 环境专用配置
[approvals]
approval_policy = "never" # CI 中不需要交互审批
[sandbox]
linux = "landlock" # 始终启用沙箱
[permissions]
permission_profile = "workspace" # 限制在项目目录
allow = [
"./src",
"./tests",
"./Cargo.toml",
"/tmp",
]
deny = [
"./secrets",
"./.env",
"./.git/config",
]
[network]
# CI 环境不需要网络访问
[[network.domain_permissions]]
host = "crates.io"
action = "allow"
八、总结
codex exec 让 Codex CLI 从交互式工具变成了可编程的 AI 编程能力:
讨论:你会在 CI/CD 中使用 AI 来自动修复错误吗?你觉得最大的风险是什么?欢迎评论。
网硕互联帮助中心


评论前必须登录!
注册