コンテンツにスキップ
X

Level 9: Infrastructure Operator — 24/7 バックグラウンドジョブ

GitHub Actions の on.schedule や Vercel / Railway の cron 機能を使うと、Claude Code を人の操作なしに 24 時間 365 日自動実行できます。PR のレビュー・セキュリティ監査・定期レポート生成など、繰り返し発生するタスクをインフラとして設計する方法を学びます。

対象読者: 並列エージェントを使いこなしており、常時稼働する自動化システムを構築したい方。

学習時間の目安: 読了 25分 + 実践 50分


GitHub Actions でイベント駆動実行する仕組み

Section titled “GitHub Actions でイベント駆動実行する仕組み”

GitHub Actions はリポジトリで発生したイベント(PR 作成・マージ・プッシュ・デプロイ完了など)をトリガーに workflow を実行します。

on:
  pull_request:
    types: [opened, synchronize]  # PR 作成・更新時
  push:
    branches: [main]              # main へのプッシュ時
  deployment_status:              # デプロイ状態変化時
  workflow_dispatch:              # 手動実行

イベントが発生すると GitHub のインフラが自動的に jobs を起動します。Claude Code はそのジョブの中で npm install -g @anthropic-ai/claude-code でインストールして実行します。

GitHub Actions の cron スケジュール実行

Section titled “GitHub Actions の cron スケジュール実行”

on.schedule に cron 式を書くと、定期実行できます。cron 式は UTC で指定します。

on:
  schedule:
    - cron: '0 0 * * *'    # 毎日 UTC 0:00(JST 9:00)
    - cron: '0 1 * * 1'    # 毎週月曜 UTC 1:00(JST 10:00)
    - cron: '0 9 1 * *'    # 毎月1日 UTC 9:00(JST 18:00)

cron 式の書き方: 分 時 日 月 曜日* はすべて)

汎用的な PR 自動レビュー workflow

Section titled “汎用的な PR 自動レビュー workflow”

PR が作成・更新されるたびに Claude Code でレビューし、結果をコメントとして投稿します。

name: AI 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: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run AI Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          DIFF=$(git diff origin/main...HEAD)

          if [ -z "$DIFF" ]; then
            echo "レビュー対象なし"
            exit 0
          fi

          echo "$DIFF" | claude --print \
            --dangerously-skip-permissions \
            "この差分をコードレビューしてください。
            バグ・セキュリティ・パフォーマンスの観点で確認してください。
            問題があれば重要度付きで列挙し、なければ LGTM と返してください。" \
            > review_result.txt

      - name: Post Review Comment
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs')
            const review = fs.readFileSync('review_result.txt', 'utf8')
            await github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## AI コードレビュー\n\n${review}\n\n---\n*Claude Code による自動レビュー*`
            })

汎用的な日次レポート生成 workflow

Section titled “汎用的な日次レポート生成 workflow”

毎日定時にコードベースを分析し、依存パッケージのセキュリティ監査レポートを生成して Issue として起票します。

name: Daily Security Audit

on:
  schedule:
    - cron: '0 0 * * *'  # 毎日 UTC 0:00(JST 9:00)

jobs:
  audit:
    runs-on: ubuntu-latest
    permissions:
      issues: write

    steps:
      - uses: actions/checkout@v4

      - name: Install dependencies
        run: npm ci

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run Security Audit
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          AUDIT_RESULT=$(npm audit --json 2>&1 || true)

          ANALYSIS=$(echo "$AUDIT_RESULT" | claude --print --dangerously-skip-permissions "
          以下は npm audit の結果(JSON)です。
          重大な脆弱性があれば、以下の形式で報告してください:
          ## 脆弱性レポート
          - パッケージ名: 影響・修正方法
          重大な脆弱性がなければ「問題なし」と返してください。
          ")

          echo "$ANALYSIS"

          # 脆弱性が検出された場合のみ Issue を作成する
          if echo "$ANALYSIS" | grep -q "## 脆弱性レポート"; then
            gh issue create \
              --title "セキュリティ脆弱性を検出 ($(date +%Y-%m-%d))" \
              --body "$ANALYSIS" \
              --label "security,urgent"
          fi

サーバーサイドの cron(Vercel / Railway)での Node.js 実装例

Section titled “サーバーサイドの cron(Vercel / Railway)での Node.js 実装例”

GitHub Actions を使わず、Vercel の Cron Functions や Railway のスケジュール実行を使う方法もあります。

// api/cron/daily-report.js(Vercel Cron Functions の例)
// vercel.json で {"crons": [{"path": "/api/cron/daily-report", "schedule": "0 0 * * *"}]} を設定する

import Anthropic from "@anthropic-ai/sdk";

export default async function handler(req, res) {
  // Vercel Cron からのリクエストを検証する
  if (req.headers["authorization"] !== `Bearer ${process.env.CRON_SECRET}`) {
    return res.status(401).json({ error: "Unauthorized" });
  }

  const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

  // 前日のログを取得(実際の実装ではデータベースやストレージから取得する)
  const logs = await fetchYesterdayLogs();

  const message = await client.messages.create({
    model: "claude-opus-4-6",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: `以下は昨日のアクセスログです。異常なパターンがあれば報告してください。\n\n${logs}`,
      },
    ],
  });

  const report = message.content[0].text;

  // レポートを Slack や メール等で通知する
  await sendReport(report);

  res.status(200).json({ success: true, report });
}

自動化する前のチェックリスト

Section titled “自動化する前のチェックリスト”

バックグラウンドで Claude を動かす前に以下を確認します。

  • --dangerously-skip-permissions の影響範囲(操作できるファイル・コマンド)を把握しているか
  • API キーは環境変数または Secrets で管理されているか(ハードコードしていないか)
  • ジョブが失敗したときのアラート通知が設定されているか
  • 月間 API コストの上限を Anthropic コンソールで設定しているか
  • 自動生成されたコンテンツや変更は人間がレビューしてから本番適用する運用になっているか

Q. cron が実行されているか確認するには?

GitHub Actions の場合は「Actions」タブからワークフローの実行履歴を確認できます。Vercel の場合はダッシュボードの「Cron Jobs」セクションで実行ログを確認します。

Q. GitHub Actions の cron は無料枠でも使えますか?

パブリックリポジトリは無料です。プライベートリポジトリは月 2,000 分の無料枠があり、超過すると課金されます。


このレベルの実践チュートリアル →

GitHub Actions と cron を使った常時稼働の自動化システムを理解しました。次はエージェント自身がエージェントを設計・生成するスウォームアーキテクチャを学びます。

Level 10: Swarm Architect — エージェントがエージェントを構築する へ進みましょう。