name: Codex Dispatch
on:
issue_comment:
types: [created]
workflow_dispatch:
inputs:
prompt:
description: 任务描述(留空 = 只做自检:Codex 登录和凭据写回)
required: false
type: string
pr:
description: 要继续修改的 PR 编号(留空则新开 PR)
required: false
type: string
base:
description: 新开 PR 时的基准分支
required: false
default: main
type: string
schedule:
- cron: '17 19 */3 * *'
permissions:
contents: read
env:
CODEX_CLI_VERSION: 0.166.0
REPO: ${{ github.repository }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
NO_COLOR: '1'
jobs:
codex:
if: >-
github.event_name == 'schedule' || (
github.event_name == 'workflow_dispatch' &&
github.actor == 'github-actions[bot]' &&
inputs.pr != ''
) || (
github.actor == github.repository_owner && (
github.event_name == 'workflow_dispatch' || (
github.event_name == 'issue_comment' &&
github.event.comment.user.login == github.repository_owner &&
github.event.comment.author_association == 'OWNER' &&
contains(github.event.comment.body, '/codex')
)
)
)
runs-on: ubuntu-latest
environment: codex
timeout-minutes: 60
concurrency:
group: codex-dispatch-${{ github.event.issue.number || inputs.pr || github.run_id }}
cancel-in-progress: false
permissions:
contents: read
issues: write
pull-requests: write
outputs:
mode: ${{ steps.req.outputs.mode }}
number: ${{ steps.req.outputs.number }}
comment_url: ${{ steps.req.outputs.comment_url }}
checkout_ref: ${{ steps.target.outputs.checkout_ref }}
push_branch: ${{ steps.target.outputs.push_branch }}
open_pr: ${{ steps.target.outputs.open_pr }}
base_sha: ${{ steps.prep.outputs.base_sha }}
status_comment_id: ${{ steps.status.outputs.id }}
has_diff: ${{ steps.collect.outputs.has_diff }}
steps:
- name: Parse request
id: req
shell: bash
env:
EVENT_NAME: ${{ github.event_name }}
IN_PROMPT: ${{ inputs.prompt }}
IN_PR: ${{ inputs.pr }}
IN_BASE: ${{ inputs.base }}
run: |
set -euo pipefail
out="$GITHUB_OUTPUT"
instr="$RUNNER_TEMP/instruction.txt"
: > "$instr"
case "$EVENT_NAME" in
schedule)
echo "mode=maintenance" >> "$out"
exit 0
;;
workflow_dispatch)
if [ -z "${IN_PROMPT//[[:space:]]/}" ]; then
echo "mode=maintenance" >> "$out"
exit 0
fi
printf '%s\n' "$IN_PROMPT" > "$instr"
if [ -n "$IN_PR" ]; then
[[ "$IN_PR" =~ ^[0-9]+$ ]] || { echo "::error::pr 必须是数字"; exit 1; }
{ echo "mode=pr"; echo "number=$IN_PR"; } >> "$out"
else
{ echo "mode=new"; echo "base=${IN_BASE:-main}"; } >> "$out"
fi
;;
issue_comment)
body_file="$RUNNER_TEMP/comment.txt"
jq -r '.comment.body' "$GITHUB_EVENT_PATH" | tr -d '\r' > "$body_file"
# 取第一行以 `/codex` 开头的行(允许前缀 `[via Claude]`),
# 该行剩余部分加上其后所有行就是任务内容;去掉末尾自动附加的
# `---` + `_Generated by ..._` 署名块和尾部空行。
awk '
!found && match($0, /^[[:space:]]*([[]via Claude[]][[:space:]]*)?[/]codex([[:space:]]|$)/) {
found = 1
rest = substr($0, RSTART + RLENGTH)
sub(/^[[:space:]]+/, "", rest)
n = 1; buf[n] = rest
next
}
found { buf[++n] = $0 }
END {
if (!found) exit 3
cut = n
for (i = n; i >= 1; i--) {
if (buf[i] ~ /^[[:space:]]*$/) continue
if (buf[i] ~ /^_Generated by /) {
for (j = i - 1; j >= 1 && buf[j] ~ /^[[:space:]]*$/; j--) {}
if (j >= 1 && buf[j] ~ /^---[[:space:]]*$/) cut = j - 1
}
break
}
while (cut >= 1 && buf[cut] ~ /^[[:space:]]*$/) cut--
for (i = 1; i <= cut; i++) print buf[i]
}
' "$body_file" > "$instr" || {
echo "评论里没有以 /codex 开头的行,跳过。"
echo "mode=skip" >> "$out"
exit 0
}
number="$(jq -r '.issue.number' "$GITHUB_EVENT_PATH")"
comment_id="$(jq -r '.comment.id' "$GITHUB_EVENT_PATH")"
comment_url="$(jq -r '.comment.html_url' "$GITHUB_EVENT_PATH")"
if jq -e '.issue.pull_request' "$GITHUB_EVENT_PATH" >/dev/null; then
echo "mode=pr" >> "$out"
else
{ echo "mode=issue"; echo "base=main"; } >> "$out"
fi
{
echo "number=$number"
echo "comment_id=$comment_id"
echo "comment_url=$comment_url"
} >> "$out"
;;
*)
echo "::error::不支持的事件 $EVENT_NAME"
exit 1
;;
esac
sed -i -e '/./,$!d' "$instr"
if [ ! -s "$instr" ] && grep -q '^mode=pr$' "$out"; then
echo "::error::/codex 后面需要写上要做什么。"
echo "empty=true" >> "$out"
fi
- name: Acknowledge comment
if: steps.req.outputs.comment_id != ''
shell: bash
env:
GH_TOKEN: ${{ github.token }}
COMMENT_ID: ${{ steps.req.outputs.comment_id }}
run: |
gh api "repos/$REPO/issues/comments/$COMMENT_ID/reactions" -f content=eyes >/dev/null || true
- name: Reject empty request
if: steps.req.outputs.empty == 'true'
shell: bash
env:
GH_TOKEN: ${{ github.token }}
NUMBER: ${{ steps.req.outputs.number }}
run: |
gh api "repos/$REPO/issues/$NUMBER/comments" \
-f body="⚠️ \`/codex\` 后面需要写上要做什么,例如:\`/codex 把 README 里的安装命令改成 xxx\`" >/dev/null
exit 1
- name: Resolve target and build prompt
id: target
if: contains(fromJSON('["pr","issue","new"]'), steps.req.outputs.mode)
shell: bash
env:
GH_TOKEN: ${{ github.token }}
OWNER: ${{ github.repository_owner }}
MODE: ${{ steps.req.outputs.mode }}
NUMBER: ${{ steps.req.outputs.number }}
BASE: ${{ steps.req.outputs.base }}
RUN_ID: ${{ github.run_id }}
run: |
set -euo pipefail
out="$GITHUB_OUTPUT"
instr="$RUNNER_TEMP/instruction.txt"
prompt="$RUNNER_TEMP/prompt.txt"
rules="$RUNNER_TEMP/rules.txt"
cat > "$rules" <<'RULES'
运行环境与约束:
- 你在 GitHub Actions 的沙箱里运行:只能修改当前仓库目录,不能联网。
- Rust 依赖已经预先下载好,可以用 `cargo build --offline`、`cargo test --offline`、
`cargo clippy --offline` 验证。
- 沙箱禁止创建 TCP/UDP socket,连 127.0.0.1 也不行:监听或连接端口的测试会失败,报错是
`Operation not permitted`(PermissionDenied)。这是沙箱的限制,不要为此修改代码或测试。
- 沙箱里没有 shoes(`PING_RUST_TEST_SHOES`、`PING_RUST_SHOES_E2E_BIN` 都没有设置):依赖
shoes 的测试有的直接返回并显示 ok(输出里有 skipped 或"未运行"),这不代表通过;有的
因为找不到 shoes 而失败。需要 root、systemd、外网或 Xray / Mihomo 的测试同样跑不了。
这些都由推送后的 CI 完整测试。
- 最终回复里分开写:实际通过的检查;因沙箱限制失败或被跳过的测试(写出测试名,标"未验证"),
不要把它们算作"通过"。
- 不要执行 git commit / git push / 新建分支,只修改文件;提交由 workflow 负责。
- 不要修改 .github/workflows/ 和 .github/actions/ 下的任何文件(这类改动会被自动拒绝)。
- 改动保持最小,只做任务要求的事。
- 任务附有所有者确认的实施方案时按方案实现;偏离方案或发现方案有误时在最终回复里说明原因。
- 先补能复现问题、在旧代码上会失败的回归测试,再改代码;不要为了通过 CI 删除、跳过或放宽
已有断言,也不要修改 tests/fixtures/yaml/compat/ 和 tests/fixtures/yaml/chain-v2/。
- 不要新建 PR 说明、报告之类的文档文件(例如 docs/PR_*.md)。任务要求写进 PR 描述的
内容(清单、例外、验证记录、终端输出等)全部写在最终回复里:新开 PR 时最终回复就是
PR 描述,在已有 PR 上继续修改时它会贴进 PR 评论。
- 最终回复用中文:第一行是一句不超过 60 个字符的提交标题(不要加引号或 Markdown),
空一行后写明改了什么、跑了哪些检查、结果如何。
RULES
case "$MODE" in
pr)
pr_json="$(gh api "repos/$REPO/pulls/$NUMBER")"
state="$(jq -r '.state' <<<"$pr_json")"
head_repo="$(jq -r '.head.repo.full_name // ""' <<<"$pr_json")"
branch="$(jq -r '.head.ref' <<<"$pr_json")"
title="$(jq -r '.title' <<<"$pr_json")"
[ "$state" = "open" ] || { echo "::error::PR #$NUMBER 不是打开状态"; exit 1; }
[ "$head_repo" = "$REPO" ] || { echo "::error::PR #$NUMBER 来自 fork,无法推送"; exit 1; }
{
# shellcheck disable=SC2016 # 反引号是给 Codex 看的 Markdown
printf '你在 %s 仓库的分支 `%s` 上工作,它对应 PR #%s「%s」。\n' "$REPO" "$branch" "$NUMBER" "$title"
printf '请在这个分支现有改动的基础上完成下面的要求:\n\n'
cat "$instr"
cat "$rules"
} > "$prompt"
{
echo "checkout_ref=$branch"
echo "push_branch=$branch"
echo "report_number=$NUMBER"
} >> "$out"
;;
issue)
issue_json="$(gh api "repos/$REPO/issues/$NUMBER")"
author="$(jq -r '.user.login // ""' <<<"$issue_json")"
association="$(jq -r '.author_association // ""' <<<"$issue_json")"
if [ "$author" = "$OWNER" ] && [ "$association" = "OWNER" ]; then
title="$(jq -r '.title' <<<"$issue_json")"
body="$(jq -r '.body // ""' <<<"$issue_json")"
{
printf '请在 %s 仓库里实现 issue #%s「%s」。\n\n' "$REPO" "$NUMBER" "$title"
printf 'issue 内容:\n%s\n' "$body"
if [ -s "$instr" ]; then
printf '\n补充要求:\n'
cat "$instr"
fi
cat "$rules"
} > "$prompt"
else
# 外部用户的标题和正文可能含提示注入,而且在所有者评论后仍可被修改;
# 这个 job 持有 Codex 凭据,所以只把所有者评论里的要求交给 Codex。
if [ ! -s "$instr" ]; then
echo "::error::issue #$NUMBER 不是仓库所有者创建的,/codex 后面需要写明要做什么"
gh api "repos/$REPO/issues/$NUMBER/comments" \
-f body="⚠️ 这个 issue 不是仓库所有者创建的,它的标题和正文不会交给 Codex。请在 \`/codex\` 后面写明要做什么,例如:\`/codex 修复 README 里的失效链接\`" >/dev/null
exit 1
fi
{
printf '请在 %s 仓库里处理 issue #%s。\n' "$REPO" "$NUMBER"
printf '这个 issue 由外部用户创建,它的标题和正文没有提供给你,也不要设法获取;只按下面的要求修改:\n\n'
cat "$instr"
cat "$rules"
} > "$prompt"
fi
{
echo "checkout_ref=$BASE"
echo "push_branch=codex/issue-$NUMBER-$RUN_ID"
echo "report_number=$NUMBER"
echo "open_pr=true"
} >> "$out"
;;
new)
{ cat "$instr"; cat "$rules"; } > "$prompt"
{
echo "checkout_ref=$BASE"
echo "push_branch=codex/task-$RUN_ID"
echo "open_pr=true"
} >> "$out"
;;
esac
- name: Post status comment
id: status
if: steps.target.outputs.report_number != ''
shell: bash
env:
GH_TOKEN: ${{ github.token }}
NUMBER: ${{ steps.target.outputs.report_number }}
BRANCH: ${{ steps.target.outputs.checkout_ref }}
run: |
set -euo pipefail
body="🤖 Codex 已开始处理(分支 \`$BRANCH\`),完成后会在这里更新结果。[运行日志]($RUN_URL)"
id="$(gh api "repos/$REPO/issues/$NUMBER/comments" -f body="$body" --jq .id)"
echo "id=$id" >> "$GITHUB_OUTPUT"
- name: Checkout target branch
if: steps.target.outcome == 'success'
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd with:
ref: ${{ steps.target.outputs.checkout_ref }}
path: work
persist-credentials: false
- name: Prepare workspace
id: prep
if: steps.target.outcome == 'success'
shell: bash
run: |
set -euo pipefail
# Codex 运行前保存一份 .git,之后用它生成 diff,不信任工作区里可能被改动的 .git。
cp -a work/.git "$RUNNER_TEMP/pristine.git"
echo "base_sha=$(git -C work rev-parse HEAD)" >> "$GITHUB_OUTPUT"
# 沙箱里不能联网,先把 Rust 依赖下载好(cargo fetch 不会执行 build script)。
if [ -f work/Cargo.toml ]; then
(cd work && cargo fetch --locked) || echo "::warning::cargo fetch 失败,Codex 将无法离线编译"
fi
- name: Install Codex CLI
if: steps.req.outputs.mode != 'skip' && steps.req.outputs.empty != 'true'
shell: bash
run: npm install -g "@openai/codex@${CODEX_CLI_VERSION}" >/dev/null && codex --version
- name: Restore Codex auth
id: auth
if: steps.req.outputs.mode != 'skip' && steps.req.outputs.empty != 'true'
shell: bash
env:
CODEX_AUTH_JSON: ${{ secrets.CODEX_AUTH_JSON }}
HAS_BOT_TOKEN: ${{ secrets.CODEX_BOT_TOKEN != '' }}
run: |
set -euo pipefail
umask 077
if [ "$HAS_BOT_TOKEN" != "true" ]; then
echo "::error::environment codex 里没有 CODEX_BOT_TOKEN,请按 docs/CODEX_DISPATCH.md 配置"
exit 1
fi
if [ -z "$CODEX_AUTH_JSON" ]; then
echo "::error::environment codex 里没有 CODEX_AUTH_JSON,请按 docs/CODEX_DISPATCH.md 配置"
exit 1
fi
home="$RUNNER_TEMP/codex-home"
mkdir -p "$home"
echo "CODEX_HOME=$home" >> "$GITHUB_ENV"
printf '%s' "$CODEX_AUTH_JSON" > "$home/auth.json"
# 权限配置 ci:在 :workspace(可写工作区和临时目录)基础上禁止读写整个 $RUNNER_TEMP
# (凭据、token 列表、.git 副本),允许写 ~/.cargo(离线编译要用),关闭网络。
# 不能再传 -s / sandbox_workspace_write,否则 Codex 会改用旧的沙箱设置、忽略这里。
{
printf 'cli_auth_credentials_store = "file"\n'
printf 'default_permissions = "ci"\n\n'
printf '[permissions.ci]\nextends = ":workspace"\n\n'
printf '[permissions.ci.filesystem]\n'
printf '"%s" = "deny"\n' "$RUNNER_TEMP"
printf '"%s" = "write"\n\n' "$HOME/.cargo"
printf '[permissions.ci.network]\nenabled = false\n'
} > "$home/config.toml"
if ! jq -e '.auth_mode == "chatgpt" and ((.tokens.refresh_token // "") != "")' "$home/auth.json" >/dev/null; then
echo "::error::CODEX_AUTH_JSON 不是有效的 ChatGPT 登录凭据,需要重新 seed(见 docs/CODEX_DISPATCH.md)"
exit 1
fi
sha256sum "$home/auth.json" | cut -d' ' -f1 > "$RUNNER_TEMP/auth.seed.sha256"
jq -r '.tokens // {} | .[] | strings | select(length >= 16)' "$home/auth.json" > "$RUNNER_TEMP/seed-tokens.txt"
while IFS= read -r t; do printf '::add-mask::%s\n' "$t"; done < "$RUNNER_TEMP/seed-tokens.txt"
echo "ok=true" >> "$GITHUB_OUTPUT"
- name: Verify sandbox hides credentials
id: sandbox
if: steps.auth.outputs.ok == 'true'
shell: bash
run: |
set -euo pipefail
# Ubuntu 24.04 默认限制非特权 user namespace,Codex 的 bubblewrap 沙箱会报
# "bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"。runner 是一次性的,放开即可。
if [ -e /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]; then
sudo sysctl -q -w kernel.apparmor_restrict_unprivileged_userns=0
fi
# 用和 Codex 相同的权限配置跑一条命令(不调用模型、不耗额度):凭据和 $RUNNER_TEMP
# 必须读不到,外网必须访问不了,工作区和 ~/.cargo 必须能写。任何一项不符合就不运行 Codex。
# 断网检查要有对照:沙箱外必须能访问 github.com;沙箱里按域名和直连 IP 都要访问不了。
# IP 只作为参数传进沙箱,不打印。
ip="$(getent ahostsv4 github.com | awk 'NR == 1 { print $1 }')"
if [ -z "$ip" ] || ! curl -sS --retry 2 --max-time 15 -o /dev/null https://github.com; then
echo "::error::沙箱外访问不了 github.com,无法检查沙箱是否断网,已停止,不运行 Codex。"
exit 1
fi
probe="$GITHUB_WORKSPACE/.codex-sandbox-probe"
rc=0
# shellcheck disable=SC2016 # 单引号里的 $1… 由沙箱内的 bash 展开
codex sandbox -P ci -C "$GITHUB_WORKSPACE" -- bash -c '
fail=0
if cat "$1" >/dev/null 2>&1; then echo "凭据文件可读"; fail=1; fi
if ls "$2" >/dev/null 2>&1; then echo "RUNNER_TEMP 可列出"; fail=1; fi
if curl -s --max-time 10 -o /dev/null https://github.com; then
echo "沙箱里能访问外网(域名)"; fail=1
fi
if curl -s --max-time 10 -o /dev/null --resolve "github.com:443:$5" https://github.com; then
echo "沙箱里能访问外网(直连 IP)"; fail=1
fi
if ! touch "$3"; then echo "工作区不可写"; fail=1; fi
if ! touch "$4/.codex-sandbox-probe"; then echo "~/.cargo 不可写"; fail=1; fi
rm -f "$3" "$4/.codex-sandbox-probe"
exit "$fail"
' probe "$CODEX_HOME/auth.json" "$RUNNER_TEMP" "$probe" "$HOME/.cargo" "$ip" || rc=$?
if [ "$rc" -ne 0 ]; then
echo "::error::Codex 沙箱没有按权限配置 ci 生效(exit $rc),已停止,不运行 Codex。"
exit 1
fi
echo "✅ 沙箱内读不到 Codex 凭据和 RUNNER_TEMP,访问不了外网;工作区和 ~/.cargo 可写。"
echo "ok=true" >> "$GITHUB_OUTPUT"
- name: Run Codex
id: run
if: steps.prep.outcome == 'success' && steps.sandbox.outputs.ok == 'true'
shell: bash
env:
CODEX_MODEL: ${{ vars.CODEX_MODEL }}
CODEX_REASONING_EFFORT: ${{ vars.CODEX_REASONING_EFFORT }}
CARGO_NET_OFFLINE: 'true'
run: |
set -uo pipefail
# 沙箱权限来自 $CODEX_HOME/config.toml 的 default_permissions = "ci"(见 Restore Codex auth)。
args=(exec -C "$GITHUB_WORKSPACE/work"
-c approval_policy='"never"'
--ignore-rules --ephemeral --json
-o "$RUNNER_TEMP/last-message.md")
[ -z "$CODEX_MODEL" ] || args+=(-m "$CODEX_MODEL")
if [ -n "$CODEX_REASONING_EFFORT" ]; then
# 值会拼进 TOML 字符串,只接受小写字母,防止注入其他配置项。
if ! [[ "$CODEX_REASONING_EFFORT" =~ ^[a-z]+$ ]]; then
echo "::error::CODEX_REASONING_EFFORT 只能是小写字母(如 high),当前值无效"
exit 1
fi
args+=(-c "model_reasoning_effort=\"$CODEX_REASONING_EFFORT\"")
fi
# codex exec --json 不输出实际使用的模型,这里记录的是请求的设置。
settings="模型:${CODEX_MODEL:-套餐默认};推理强度:${CODEX_REASONING_EFFORT:-模型默认}"
echo "Codex 设置(请求值):$settings"
echo "**Codex 设置(请求值)**:$settings" >> "$GITHUB_STEP_SUMMARY"
# 完整事件流和 stderr 只写文件,不进公开日志。
# `shell: bash` 实际是 `bash -eo pipefail`:失败时必须用 `|| rc=$?` 接住,
# 否则脚本在这里直接退出,后面的 token 遮蔽和失败原因都不会执行。
rc=0
codex "${args[@]}" - < "$RUNNER_TEMP/prompt.txt" \
> "$RUNNER_TEMP/codex-events.jsonl" 2> "$RUNNER_TEMP/codex-stderr.log" || rc=$?
# 运行中如果刷新了 token,新 token 也要遮蔽。
jq -r '.tokens // {} | .[] | strings | select(length >= 16)' "$CODEX_HOME/auth.json" > "$RUNNER_TEMP/new-tokens.txt" || true
while IFS= read -r t; do printf '::add-mask::%s\n' "$t"; done < "$RUNNER_TEMP/new-tokens.txt"
echo "codex exit code: $rc"
if [ "$rc" -ne 0 ]; then
echo "::error::Codex 运行失败"
tail -n 20 "$RUNNER_TEMP/codex-stderr.log" || true
exit "$rc"
fi
- name: Collect diff
id: collect
if: steps.run.outcome == 'success'
shell: bash
run: |
set -euo pipefail
out_dir="$RUNNER_TEMP/codex-result"
mkdir -p "$out_dir"
g=(git --git-dir="$RUNNER_TEMP/pristine.git" --work-tree="$GITHUB_WORKSPACE/work"
-c core.fsmonitor=false -c core.hooksPath=/dev/null)
"${g[@]}" add -A
"${g[@]}" diff --cached --binary > "$out_dir/task.patch"
cp "$RUNNER_TEMP/last-message.md" "$out_dir/summary.md" 2>/dev/null || : > "$out_dir/summary.md"
# 任何 token 出现在 diff 或总结里都中止(防止通过改动把凭据带出去)。
cat "$RUNNER_TEMP/seed-tokens.txt" "$RUNNER_TEMP/new-tokens.txt" 2>/dev/null | sort -u > "$RUNNER_TEMP/all-tokens.txt"
if [ -s "$RUNNER_TEMP/all-tokens.txt" ] && grep -rqF -f "$RUNNER_TEMP/all-tokens.txt" "$out_dir"; then
echo "::error::Codex 的输出里包含登录凭据,已中止。"
rm -rf "$out_dir"
exit 1
fi
if grep -qE '^(diff --git a/|--- a/|\+\+\+ b/|rename (from|to) |copy (from|to) )\.github/(workflows|actions)/' "$out_dir/task.patch"; then
echo "::error::Codex 的改动涉及 .github/workflows/ 或 .github/actions/,已拒绝。"
exit 1
fi
if [ -s "$out_dir/task.patch" ]; then
echo "has_diff=true" >> "$GITHUB_OUTPUT"
"${g[@]}" diff --cached --stat | tail -n 1
else
echo "has_diff=false" >> "$GITHUB_OUTPUT"
fi
echo '### Codex 总结' >> "$GITHUB_STEP_SUMMARY"
cat "$out_dir/summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: Upload result
if: steps.collect.outcome == 'success'
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 with:
name: codex-result
path: ${{ runner.temp }}/codex-result
retention-days: 3
if-no-files-found: error
- name: Self-check (auth and write-back)
if: steps.req.outputs.mode == 'maintenance' && steps.auth.outputs.ok == 'true'
shell: bash
run: |
set -uo pipefail
# 一次最小的调用:验证登录可用,并让 Codex 按需刷新 token。
rc=0
codex exec -s read-only --skip-git-repo-check --ephemeral \
-o "$RUNNER_TEMP/selfcheck.txt" "只回复 OK" > /dev/null 2> "$RUNNER_TEMP/selfcheck.err" || rc=$?
jq -r '.tokens // {} | .[] | strings | select(length >= 16)' "$CODEX_HOME/auth.json" \
| while IFS= read -r t; do printf '::add-mask::%s\n' "$t"; done
if [ "$rc" -ne 0 ]; then
echo "::error::Codex 登录不可用(exit $rc),可能需要重新 seed CODEX_AUTH_JSON"
tail -n 5 "$RUNNER_TEMP/selfcheck.err" || true
exit 1
fi
echo "✅ Codex 登录有效(回复:$(head -c 40 "$RUNNER_TEMP/selfcheck.txt" | tr -d '\n'))"
- name: Check write-back permission
if: steps.req.outputs.mode == 'maintenance' && steps.auth.outputs.ok == 'true'
shell: bash
env:
GH_TOKEN: ${{ secrets.CODEX_BOT_TOKEN }}
run: |
set -euo pipefail
# 真写一次 environment secret,确认 CODEX_BOT_TOKEN 有写回权限且没过期。
if ! date -u +%FT%TZ | gh secret set CODEX_WRITEBACK_CHECK --env codex --repo "$REPO"; then
echo "::error::CODEX_BOT_TOKEN 无法写 environment secret(权限不足或已过期),刷新后的凭据将无法保存。"
exit 1
fi
echo "✅ CODEX_BOT_TOKEN 可以写回 environment secret。"
- name: Persist refreshed auth
if: always() && steps.auth.outputs.ok == 'true'
shell: bash
env:
GH_TOKEN: ${{ secrets.CODEX_BOT_TOKEN }}
run: |
set -euo pipefail
file="$CODEX_HOME/auth.json"
# 只有 Codex 真的刷新过(文件变了)才写回,避免并行任务用旧文件覆盖新 token。
new_sha="$(sha256sum "$file" | cut -d' ' -f1)"
if [ "$new_sha" = "$(cat "$RUNNER_TEMP/auth.seed.sha256")" ]; then
echo "auth.json 未变化,无需写回。"
exit 0
fi
if ! jq -e '.auth_mode == "chatgpt" and ((.tokens.refresh_token // "") != "")' "$file" >/dev/null; then
echo "::error::刷新后的 auth.json 不完整,未写回;下次运行可能需要重新 seed。"
exit 1
fi
gh secret set CODEX_AUTH_JSON --env codex --repo "$REPO" < "$file"
echo "已把刷新后的 auth.json 写回 environment codex。"
- name: Remove local credentials
if: always()
shell: bash
run: rm -rf "$RUNNER_TEMP/codex-home" "$RUNNER_TEMP"/*-tokens.txt "$RUNNER_TEMP/codex-events.jsonl" "$RUNNER_TEMP/codex-stderr.log"
- name: Report (no change or failure)
if: always() && steps.status.outputs.id != '' && (failure() || steps.collect.outputs.has_diff == 'false')
shell: bash
env:
GH_TOKEN: ${{ github.token }}
COMMENT_ID: ${{ steps.status.outputs.id }}
HAS_DIFF: ${{ steps.collect.outputs.has_diff }}
run: |
set -euo pipefail
if [ "$HAS_DIFF" = "false" ]; then
result="ℹ️ Codex 完成了,但没有产生代码改动。"
if [ -s "$RUNNER_TEMP/codex-result/summary.md" ]; then
result+=$'\n\n'"$(head -c 3000 "$RUNNER_TEMP/codex-result/summary.md")"
fi
else
result="❌ 失败,详见运行日志。"
fi
body="🤖 Codex 任务结果:"$'\n\n'"$result"$'\n\n'"[运行日志]($RUN_URL)"
gh api -X PATCH "repos/$REPO/issues/comments/$COMMENT_ID" -f body="$body" >/dev/null
push:
needs: codex
if: needs.codex.outputs.has_diff == 'true'
runs-on: ubuntu-latest
environment: codex
timeout-minutes: 15
permissions:
contents: read
issues: write
pull-requests: write
steps:
- name: Download result
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c with:
name: codex-result
path: ${{ runner.temp }}/codex-result
- name: Check patch paths
shell: bash
run: |
set -euo pipefail
patch="$RUNNER_TEMP/codex-result/task.patch"
if grep -qE '^(diff --git a/|--- a/|\+\+\+ b/|rename (from|to) |copy (from|to) )\.github/(workflows|actions)/' "$patch"; then
echo "::error::改动涉及 .github/workflows/ 或 .github/actions/,已拒绝。"
exit 1
fi
- name: Checkout target branch
uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd with:
ref: ${{ needs.codex.outputs.checkout_ref }}
token: ${{ secrets.CODEX_BOT_TOKEN }}
path: work
fetch-depth: 0
- name: Apply, commit and push
id: push
shell: bash
working-directory: work
env:
GH_TOKEN: ${{ secrets.CODEX_BOT_TOKEN }}
PUSH_BRANCH: ${{ needs.codex.outputs.push_branch }}
CHECKOUT_REF: ${{ needs.codex.outputs.checkout_ref }}
BASE_SHA: ${{ needs.codex.outputs.base_sha }}
OPEN_PR: ${{ needs.codex.outputs.open_pr }}
MODE: ${{ needs.codex.outputs.mode }}
NUMBER: ${{ needs.codex.outputs.number }}
COMMENT_URL: ${{ needs.codex.outputs.comment_url }}
run: |
set -euo pipefail
result="$RUNNER_TEMP/codex-result"
patch="$result/task.patch"
git config user.name "codex-dispatch"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
if [ "$(git rev-parse HEAD)" != "$BASE_SHA" ]; then
echo "::warning::分支在 Codex 运行期间有新提交,尝试三方合并应用。"
fi
if [ "$PUSH_BRANCH" != "$CHECKOUT_REF" ]; then
git switch -c "$PUSH_BRANCH"
fi
git apply --index "$patch" || git apply --index --3way "$patch"
if git diff --cached --quiet; then
echo "nothing=true" >> "$GITHUB_OUTPUT"
exit 0
fi
stat="$(git diff --cached --shortstat | sed 's/^ *//')"
# shellcheck disable=SC2016 # 反引号是要去掉的 Markdown 字符
title="$(sed -n '/[^[:space:]]/{p;q;}' "$result/summary.md" | sed -E 's/^[#*` ]+//; s/[*`]+$//')"
title="${title:-codex: automated change}"
title="${title:0:72}"
msg="$RUNNER_TEMP/commit-msg.txt"
{
printf '%s\n\n' "$title"
printf 'Generated by Codex via %s\n' "$RUN_URL"
[ -z "$COMMENT_URL" ] || printf 'Requested-In: %s\n' "$COMMENT_URL"
} > "$msg"
git commit -q -F "$msg"
git push -q origin "HEAD:refs/heads/$PUSH_BRANCH"
{
echo "sha=$(git rev-parse --short HEAD)"
echo "stat=$stat"
} >> "$GITHUB_OUTPUT"
if [ "$OPEN_PR" = "true" ]; then
body="$RUNNER_TEMP/pr-body.md"
{
[ "$MODE" != "issue" ] || printf 'Closes #%s\n\n' "$NUMBER"
printf '由 Codex 生成([运行日志](%s))' "$RUN_URL"
[ -z "$COMMENT_URL" ] || printf ',触发评论:%s' "$COMMENT_URL"
printf '\n\n### Codex 总结\n\n'
# GitHub 的 PR 描述上限是 65536 字符;总结要承载 issue 要求的清单和记录。
head -c 60000 "$result/summary.md"
} > "$body"
pr_url="$(gh pr create --repo "$REPO" --base "$CHECKOUT_REF" --head "$PUSH_BRANCH" \
--title "$title" --body-file "$body")"
echo "pr_url=$pr_url" >> "$GITHUB_OUTPUT"
fi
- name: Report result
if: always() && needs.codex.outputs.status_comment_id != ''
shell: bash
env:
GH_TOKEN: ${{ github.token }}
COMMENT_ID: ${{ needs.codex.outputs.status_comment_id }}
NOTHING: ${{ steps.push.outputs.nothing }}
SHA: ${{ steps.push.outputs.sha }}
STAT: ${{ steps.push.outputs.stat }}
PR_URL: ${{ steps.push.outputs.pr_url }}
PUSH_BRANCH: ${{ needs.codex.outputs.push_branch }}
run: |
set -euo pipefail
if [ -n "$PR_URL" ]; then
result="✅ 已开 PR:$PR_URL($STAT)"
elif [ -n "$SHA" ]; then
result="✅ 已推送 \`$SHA\` 到 \`$PUSH_BRANCH\`($STAT)"
elif [ "$NOTHING" = "true" ]; then
result="ℹ️ 应用后没有实际改动。"
else
result="❌ 推送失败,详见运行日志。"
fi
summary="$RUNNER_TEMP/codex-result/summary.md"
body="🤖 Codex 任务结果:"$'\n\n'"$result"
if [ -s "$summary" ]; then
body+=$'\n\n<details><summary>Codex 总结</summary>\n\n'"$(head -c 60000 "$summary")"$'\n\n</details>'
fi
body+=$'\n\n'"[运行日志]($RUN_URL)"
gh api -X PATCH "repos/$REPO/issues/comments/$COMMENT_ID" -f body="$body" >/dev/null