コンテンツにスキップ

Codex CLI × GitHub Actions統合実装|PRレビュー自動化の完全ガイド

この記事は朝の記事のフォローアップです

朝の記事: Codex CLIプランモード実践ガイド

ゴール

  • PRコメントトリガーでCodex plan modeを自動実行し、実行計画をレビュアーへ提示
  • GitHub承認フロー統合で、レビュー承認後にcodex実行を自動化
  • 失敗時のロールバック戦略とエラー通知を実装し、本番運用レベルの信頼性を確保

前提条件とセキュリティ設定

必須要件

  • Codex CLI 0.45.0以降がインストール済み
  • GitHub ActionsのGITHUB_TOKEN権限: contents: write, pull-requests: write
  • Codex API keyをRepository SecretsにCODEX_API_KEYとして登録

セキュリティベストプラクティス

設定項目推奨値理由
トリガー条件if: github.event.issue.pull_request && contains(github.event.comment.body, '/codex-plan')悪意あるコメントからの実行を防止
権限スコープ最小権限(write権限はPR更新のみ)不要な操作を制限
API Key保存Secrets(Environment Secretsを推奨)ログへの漏洩を防止

基本ワークフロー実装

.github/workflows/codex-plan.yml:

name: Codex Plan Mode Auto-Review

on:
  issue_comment:
    types: [created]

jobs:
  generate-plan:
    if: ${{ github.event.issue.pull_request && contains(github.event.comment.body, '/codex-plan') }}
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write

    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.issue.pull_request.head.ref }}

      - name: Setup Codex CLI
        run: |
          curl -fsSL https://codex.cli/install.sh | sh
          echo "$HOME/.codex/bin" >> $GITHUB_PATH

      - name: Generate execution plan
        env:
          CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}
          COMMENT_BODY: ${{ github.event.comment.body }}
        run: |
          PROMPT="${COMMENT_BODY#/codex-plan }"
          codex --plan "$PROMPT" > plan_output.txt 2>&1 || echo "Plan generation failed" > plan_output.txt

      - name: Post plan as comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const plan = fs.readFileSync('plan_output.txt', 'utf8');
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: `## Codex Execution Plan\n\n\`\`\`\n${plan}\n\`\`\`\n\nレビュー承認後に \`/codex-execute\` でこの計画を実行します。`
            });

動作フロー: 1. PRコメントで /codex-plan リファクタリング実施 と入力 2. GitHub Actionsが自動起動し、plan mode実行 3. 実行計画がPRコメントとして自動投稿 4. レビュアーが計画内容を確認

承認フロー統合

.github/workflows/codex-execute.yml:

name: Codex Execute After Approval

on:
  issue_comment:
    types: [created]

jobs:
  execute-plan:
    if: ${{ github.event.issue.pull_request && contains(github.event.comment.body, '/codex-execute') }}
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write

    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.issue.pull_request.head.ref }}

      - name: Check approval status
        id: check-approval
        uses: actions/github-script@v7
        with:
          script: |
            const reviews = await github.rest.pulls.listReviews({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: context.issue.number
            });
            const approved = reviews.data.some(r => r.state === 'APPROVED');
            if (!approved) {
              core.setFailed('PRが承認されていません');
            }
            return approved;

      - name: Execute Codex
        if: steps.check-approval.outputs.result == 'true'
        env:
          CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}
        run: |
          PROMPT=$(git log -1 --grep="codex-plan" --format=%B | sed 's/\/codex-plan //g')
          codex "$PROMPT"

      - name: Commit changes
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add .
          git commit -m "chore: apply codex changes [skip ci]" || echo "No changes"
          git push

安全装置: - 承認ステータスを必須チェック(未承認なら即時失敗) - 元のプロンプトをgit logから復元(実行計画との一貫性確保) - [skip ci]でループ防止

エラーハンドリングと失敗パターン

症状原因即時対処予防策
plan生成がタイムアウト大規模コードベース解析timeout-minutes: 10設定ファイル範囲をプロンプトで限定
実行時にマージ競合他PRのマージによるベースブランチ更新git pull --rebaseを実行前に追加ブランチ保護ルールで直前のbase更新を制限
API Key認証失敗Secretsの有効期限切れ手動実行でエラーログ確認定期的なSecret更新アラート設定
実行計画と実行結果の不一致プロンプト文字列の改変プロンプトをartifactに保存して再利用PRコメント本文からの正確な抽出ロジック実装

ロールバック戦略:

- name: Create rollback point
  run: git tag "rollback-${{ github.run_id }}"

- name: Execute with rollback
  run: |
    codex "$PROMPT" || {
      git reset --hard "rollback-${{ github.run_id }}"
      exit 1
    }

ベンチマーク

手動運用 vs 自動化の時間比較(中規模リポジトリ、10ファイル変更想定):

工程手動実行自動化削減率
実行計画生成3分(ローカルセットアップ含む)1.5分50%
レビュアーへの共有5分(Slack投稿+説明)0分(自動コメント)100%
承認後実行2分(手動実行+push)1分(自動)50%
合計10分2.5分75%削減

追加メリット: - 人的ミス(プロンプト入力ミス、push忘れ)ゼロ化 - 履歴トレーサビリティ(全実行計画がPRコメントに記録)

自動化拡張案

Slack通知統合

- name: Notify Slack
  if: always()
  uses: slackapi/slack-github-action@v1
  with:
    payload: |
      {
        "text": "Codex Plan: ${{ job.status }}",
        "blocks": [
          {
            "type": "section",
            "text": {"type": "mrkdwn", "text": "PR #${{ github.event.issue.number }} の実行計画を確認してください"}
          }
        ]
      }
  env:
    SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}

マルチブランチ対応

  • matrix戦略で複数ブランチへの並列実行
  • ブランチ名によるCodex設定の動的切り替え(staging/productionで異なる承認ポリシー)

コスト監視

  • CODEX_API_KEY使用量をCloudWatchへ送信
  • 月間実行回数の閾値アラート設定

次のステップ