ping-rust 0.3.2

Menu-driven installer and manager for the shoes proxy server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
name: Codex Dispatch

# 仓库所有者在 issue / PR 下评论 `/codex <任务>`,由 Codex 在 GitHub Actions 里直接写代码。
#
#   PR 下评论    → 在该 PR 的 head 分支上改,结果推到同一个 PR。
#   issue 下评论 → 从 main 开始改,推到新分支并开新 PR(Closes #issue)。
#   手动触发     → workflow_dispatch,参数 prompt / pr / base;prompt 留空 = 只做自检。
#   CI 失败      → codex-ci-fix.yml 用 GITHUB_TOKEN 触发 workflow_dispatch(带 pr),派回同一个 PR。
#   定时任务     → 每 3 天自检一次,顺便让 Codex 按需刷新 token 并写回 secret。
#
# 为什么不用 `codex cloud exec`:网页上建的 Codex 云端环境,CLI 和 GitHub 的 @codex
# 目前都查不到(接口返回空列表),所以改为在 runner 上运行 `codex exec`。
#
# 两个 job:
#   codex — 持有 ChatGPT 登录凭据。Codex 在沙箱里运行(workspace-write、沙箱内无网络),
#           只产出一个 diff。diff 和 Codex 的输出都会先检查是否含有 token,再上传。
#   push  — 不接触 Codex 凭据。下载 diff,检查路径,git apply,用 CODEX_BOT_TOKEN 推送 / 开 PR。
#
# 注意:OpenAI 的指南不建议在公开仓库使用 ChatGPT 登录凭据。这里的防护:
#   1. 只接受仓库所有者本人的评论 / 手动触发,以及 codex-ci-fix.yml 带 pr 的派发;
#   2. 凭据放在只允许 main 部署的 environment 里,PR 分支上的 workflow 拿不到;
#   3. Codex 的命令在沙箱里运行(权限配置 ci):只能写工作区和 ~/.cargo、不能联网,
#      读不到 $RUNNER_TEMP(Codex 凭据、token 列表、.git 副本都在这里),运行前先实测;
#      推送用的 token 不在这个 job 的 Codex 步骤里;
#   4. Codex 的完整输出只写文件不打日志;diff 和最终总结里出现任何 token 就中止;
#   5. 用 Codex 运行前保存的 .git 副本生成 diff,不受工作区里被改动的 git 配置影响;
#   6. CODEX_BOT_TOKEN 不给 Workflows 权限,改动 .github/workflows 或 .github/actions 的 diff
#      直接拒绝;
#   7. 外部输入只经环境变量传给脚本,不做 ${{ }} 插值;
#   8. 不是仓库所有者创建的 issue,标题和正文不交给 Codex,只用所有者 /codex 评论里的要求。
# 配置步骤见 docs/CODEX_DISPATCH.md。

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:
    # Codex 在 last_refresh 超过约 8 天时才会刷新 token;每 3 天自检一次,
    # 让刷新尽量发生在这个空闲任务里。
    - 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:
    # github-actions[bot] 的手动触发只来自 codex-ci-fix.yml(CI 失败后派回同一个 PR),必须带 pr。
    # 其他 workflow 不要给 GITHUB_TOKEN `actions: write`,也不要用 pull_request_target,
    # 否则这条路径会对它们开放。
    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:
      # 同一个 issue / PR 的任务排队执行;不同 issue / PR 之间可以并行。
      group: codex-dispatch-${{ github.event.issue.number || inputs.pr || github.run_id }}
      cancel-in-progress: false
    permissions:
      contents: read
      issues: write
      # 在 PR 下贴状态评论(issues 接口)需要 pull-requests: write;只有发评论的步骤拿到 token。
      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 # v5
        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 # v4
        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
      # 更新 PR 下的状态评论同样需要 pull-requests: write。
      pull-requests: write
    steps:
      - name: Download result
        uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
        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 # v5
        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