Skip to content

Auto-generated English stub on 2025-09-20. Replace with a proper translation.


title: "🚀 AIエージェント本番運用実装ガイド2025年8月 - エンタープライズ対応実践アーキテクチャ" description: "Claude Code・GitHub Actions・cron統合による企業レベルAIエージェント自動化システムの完全実装ガイド。自動承認・エラーハンドリング・監視まで網羅した本番運用ノウハウ" tags: - Claude Code - AIエージェント - 本番運用 - 自動化 - エンタープライズ - GitHub Actions - cron - 監視 - DevOps category: AI開発・自動化


🚀 AIエージェント本番運用実装ガイド2025年8月

📋 目次

  1. 本番運用アーキテクチャ設計
  2. Claude Code自動承認設定
  3. GitHub Actions CI/CD統合
  4. cron自動実行システム
  5. エラーハンドリング・監視
  6. セキュリティ・権限管理
  7. スケーリング・パフォーマンス最適化
  8. トラブルシューティング

🏗️ 本番運用アーキテクチャ設計

システム全体図

graph TD
    A[GitHub Repository] --> B[GitHub Actions]
    B --> C[Claude Code Agent]
    C --> D[自動承認システム]
    D --> E[実行監視]
    E --> F[Slack/Teams通知]

    G[cron] --> H[定期実行トリガー]
    H --> C

    I[エラーログ] --> J[監視ダッシュボード]
    J --> K[アラート通知]

🎯 設計原則

エンタープライズ対応原則

  • フェイルセーフ: すべての処理に自動復旧機能を実装
  • 監査証跡: 全実行ログの永続化・検索可能化
  • 権限分離: 最小権限の原則による secure by design
  • スケーラビリティ: 水平スケーリング対応アーキテクチャ

⚡ Claude Code自動承認設定

1. 基本自動承認設定

# Claude Code設定ディレクトリ作成
mkdir -p ~/.claude
cd ~/.claude

# 自動承認設定ファイル作成
cat > auto_approval_config.json << 'EOF'
{
  "auto_approval": {
    "enabled": true,
    "rules": {
      "file_operations": {
        "read": true,
        "write": true,
        "create": true
      },
      "bash_commands": {
        "safe_commands": true,
        "package_management": true,
        "git_operations": true
      },
      "web_requests": {
        "api_calls": true,
        "documentation_fetch": true
      }
    },
    "restrictions": {
      "system_files": false,
      "sensitive_directories": ["/etc", "/root", "/home/*/.ssh"],
      "dangerous_commands": ["rm -rf", "format", "dd"]
    }
  }
}
EOF

# 権限設定
chmod 600 auto_approval_config.json

2. 環境別設定管理

# 本番環境設定
cat > ~/.claude/production_config.json << 'EOF'
{
  "environment": "production",
  "auto_approval": {
    "enabled": true,
    "audit_mode": true,
    "restrictions": {
      "require_confirmation": [
        "database_operations",
        "external_api_calls",
        "file_deletions"
      ]
    }
  },
  "logging": {
    "level": "INFO",
    "audit_trail": true,
    "retention_days": 90
  }
}
EOF

# 開発環境設定
cat > ~/.claude/development_config.json << 'EOF'
{
  "environment": "development",
  "auto_approval": {
    "enabled": true,
    "audit_mode": false
  },
  "logging": {
    "level": "DEBUG",
    "retention_days": 30
  }
}
EOF

3. セキュリティホワイトリスト

# 許可コマンドリスト
cat > ~/.claude/whitelist_commands.txt << 'EOF'
# Git操作
git status
git add
git commit
git push
git pull

# パッケージ管理
npm install
npm run
pip install
yarn install

# ファイル操作
ls
cat
grep
find
mkdir
cp
mv

# システム監視
ps
top
df
du
netstat
EOF

🔄 GitHub Actions CI/CD統合

1. Claude Code実行ワークフロー

# .github/workflows/claude-agent-automation.yml
name: Claude Code Agent Automation

on:
  schedule:
    - cron: '0 6 * * *'  # 毎日6時実行
  workflow_dispatch:
    inputs:
      task_description:
        description: 'Agent task description'
        required: true
        default: 'Daily maintenance and optimization'
      environment:
        description: 'Target environment'
        required: true
        default: 'production'
        type: choice
        options:
        - production
        - staging
        - development

jobs:
  claude-agent-execution:
    runs-on: ubuntu-latest
    environment: ${{ github.event.inputs.environment || 'production' }}

    steps:
    - name: Checkout Repository
      uses: actions/checkout@v4
      with:
        token: ${{ secrets.GITHUB_TOKEN }}
        fetch-depth: 0

    - name: Setup Claude Code
      run: |
        # Claude Code インストール
        curl -fsSL https://claude.ai/install.sh | sh
        echo "Claude Code installed successfully"

        # 設定ファイル配置
        mkdir -p ~/.claude
        echo "${{ secrets.CLAUDE_CONFIG }}" > ~/.claude/config.json

        # 認証設定
        echo "${{ secrets.ANTHROPIC_API_KEY }}" > ~/.claude/api_key
        chmod 600 ~/.claude/api_key

    - name: Execute Claude Agent Task
      id: claude_execution
      run: |
        # タスク実行ログの初期化
        echo "🚀 Starting Claude Agent execution at $(date)" > execution.log

        # Claude Code実行
        claude --auto-approve \
          --task "${{ github.event.inputs.task_description || 'Daily maintenance and optimization' }}" \
          --environment "${{ github.event.inputs.environment || 'production' }}" \
          --output-format json \
          2>&1 | tee -a execution.log

        # 実行結果の評価
        if [ $? -eq 0 ]; then
          echo "execution_status=success" >> $GITHUB_OUTPUT
          echo "✅ Claude Agent execution completed successfully" >> execution.log
        else
          echo "execution_status=failed" >> $GITHUB_OUTPUT
          echo "❌ Claude Agent execution failed" >> execution.log
          exit 1
        fi

    - name: Process Execution Results
      if: always()
      run: |
        # 実行ログの構造化
        echo "## 📊 Execution Summary" > summary.md
        echo "- **Status**: ${{ steps.claude_execution.outputs.execution_status }}" >> summary.md
        echo "- **Environment**: ${{ github.event.inputs.environment || 'production' }}" >> summary.md
        echo "- **Timestamp**: $(date -u)" >> summary.md
        echo "- **Commit**: ${{ github.sha }}" >> summary.md

        # ログファイルをアーティファクトとして保存
        mkdir -p artifacts
        cp execution.log artifacts/
        cp summary.md artifacts/

    - name: Upload Execution Artifacts
      if: always()
      uses: actions/upload-artifact@v4
      with:
        name: claude-execution-logs-${{ github.run_number }}
        path: artifacts/
        retention-days: 30

    - name: Commit Changes
      if: steps.claude_execution.outputs.execution_status == 'success'
      run: |
        git config --local user.email "claude-agent@example.com"
        git config --local user.name "Claude Agent"

        # 変更があるかチェック
        if [[ $(git status --porcelain) ]]; then
          git add .
          git commit -m "🤖 Claude Agent automation - ${{ github.event.inputs.task_description || 'Daily maintenance' }}

          Environment: ${{ github.event.inputs.environment || 'production' }}
          Execution ID: ${{ github.run_number }}
          Timestamp: $(date -u)

          🛠️ Generated with [Claude Code](https://claude.ai/code)

          Co-Authored-By: Claude <noreply@anthropic.com>"

          git push
          echo "✅ Changes committed and pushed successfully"
        else
          echo "ℹ️ No changes to commit"
        fi

    - name: Notify Results
      if: always()
      uses: 8398a7/action-slack@v3
      with:
        status: ${{ job.status }}
        channel: '#claude-automation'
        webhook_url: ${{ secrets.SLACK_WEBHOOK }}
        fields: repo,message,commit,author,action,eventName,ref,workflow
        custom_payload: |
          {
            "blocks": [
              {
                "type": "section",
                "text": {
                  "type": "mrkdwn",
                  "text": "🤖 Claude Agent Execution ${{ steps.claude_execution.outputs.execution_status == 'success' && '✅ Completed' || '❌ Failed' }}\n*Environment:* ${{ github.event.inputs.environment || 'production' }}\n*Task:* ${{ github.event.inputs.task_description || 'Daily maintenance' }}"
                }
              }
            ]
          }

2. 環境別デプロイメント

# .github/workflows/environment-specific-deployment.yml
name: Environment-Specific Claude Deployment

on:
  push:
    branches: [main, develop, staging]

jobs:
  determine-environment:
    runs-on: ubuntu-latest
    outputs:
      environment: ${{ steps.env.outputs.environment }}
    steps:
    - id: env
      run: |
        if [[ "${{ github.ref }}" == "refs/heads/main" ]]; then
          echo "environment=production" >> $GITHUB_OUTPUT
        elif [[ "${{ github.ref }}" == "refs/heads/staging" ]]; then
          echo "environment=staging" >> $GITHUB_OUTPUT
        else
          echo "environment=development" >> $GITHUB_OUTPUT
        fi

  deploy-claude-agent:
    needs: determine-environment
    runs-on: ubuntu-latest
    environment: ${{ needs.determine-environment.outputs.environment }}

    steps:
    - uses: actions/checkout@v4

    - name: Deploy to ${{ needs.determine-environment.outputs.environment }}
      run: |
        echo "Deploying Claude Agent to ${{ needs.determine-environment.outputs.environment }}"

        # 環境別設定の適用
        case "${{ needs.determine-environment.outputs.environment }}" in
          production)
            echo "Applying production configuration"
            ;;
          staging)
            echo "Applying staging configuration"
            ;;
          development)
            echo "Applying development configuration"
            ;;
        esac

⏰ cron自動実行システム

1. システムcron設定

# cron設定スクリプト
cat > /etc/cron.d/claude-agent << 'EOF'
# Claude Agent 自動実行スケジュール
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin

# 毎日6時: 日次メンテナンス
0 6 * * * claude /opt/claude-agent/scripts/daily-maintenance.sh >> /var/log/claude-agent/daily.log 2>&1

# 毎時: ヘルスチェック
0 * * * * claude /opt/claude-agent/scripts/health-check.sh >> /var/log/claude-agent/health.log 2>&1

# 毎週月曜日1時: 週次レポート生成
0 1 * * 1 claude /opt/claude-agent/scripts/weekly-report.sh >> /var/log/claude-agent/weekly.log 2>&1

# 毎月1日2時: 月次最適化
0 2 1 * * claude /opt/claude-agent/scripts/monthly-optimization.sh >> /var/log/claude-agent/monthly.log 2>&1
EOF

# 権限設定
chmod 644 /etc/cron.d/claude-agent

2. 実行スクリプト群

# 日次メンテナンススクリプト
cat > /opt/claude-agent/scripts/daily-maintenance.sh << 'EOF'
#!/bin/bash
set -euo pipefail

# ログ設定
LOG_FILE="/var/log/claude-agent/daily-$(date +%Y%m%d).log"
exec 1> >(tee -a "$LOG_FILE")
exec 2>&1

echo "🚀 Starting daily maintenance at $(date)"

# Claude Code実行前チェック
if ! command -v claude &> /dev/null; then
    echo "❌ Claude Code not found"
    exit 1
fi

# 認証確認
if ! claude auth status &> /dev/null; then
    echo "❌ Claude authentication failed"
    exit 1
fi

# メンテナンスタスク実行
claude --auto-approve \
    --task "Daily system maintenance: 
    1. Check system health and performance
    2. Update dependencies and packages
    3. Clean temporary files and logs
    4. Generate system status report
    5. Optimize database and cache" \
    --timeout 3600 \
    --retry 3

echo "✅ Daily maintenance completed at $(date)"
EOF

# ヘルスチェックスクリプト
cat > /opt/claude-agent/scripts/health-check.sh << 'EOF'
#!/bin/bash
set -euo pipefail

LOG_FILE="/var/log/claude-agent/health-$(date +%Y%m%d).log"
exec 1> >(tee -a "$LOG_FILE")
exec 2>&1

echo "🔍 Starting health check at $(date)"

# システムリソースチェック
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print $2+$4}' | cut -d'%' -f1)
MEMORY_USAGE=$(free | grep Mem | awk '{printf("%.1f", $3/$2 * 100.0)}')
DISK_USAGE=$(df -h / | awk 'NR==2{print $5}' | sed 's/%//')

echo "📊 System Resources:"
echo "  CPU Usage: ${CPU_USAGE}%"
echo "  Memory Usage: ${MEMORY_USAGE}%"
echo "  Disk Usage: ${DISK_USAGE}%"

# アラート閾値チェック
if (( $(echo "$CPU_USAGE > 80" | bc -l) )); then
    echo "⚠️ High CPU usage detected: ${CPU_USAGE}%"
fi

if (( $(echo "$MEMORY_USAGE > 85" | bc -l) )); then
    echo "⚠️ High memory usage detected: ${MEMORY_USAGE}%"
fi

if [ "$DISK_USAGE" -gt 90 ]; then
    echo "⚠️ High disk usage detected: ${DISK_USAGE}%"
fi

echo "✅ Health check completed at $(date)"
EOF

# 実行権限付与
chmod +x /opt/claude-agent/scripts/*.sh

# ログディレクトリ作成
mkdir -p /var/log/claude-agent
chown claude:claude /var/log/claude-agent

3. 高度なスケジューリング

# systemd timer設定(より高度なスケジューリング)
cat > /etc/systemd/system/claude-agent-daily.service << 'EOF'
[Unit]
Description=Claude Agent Daily Maintenance
After=network.target

[Service]
Type=oneshot
User=claude
ExecStart=/opt/claude-agent/scripts/daily-maintenance.sh
StandardOutput=journal
StandardError=journal
EOF

cat > /etc/systemd/system/claude-agent-daily.timer << 'EOF'
[Unit]
Description=Run Claude Agent Daily Maintenance
Requires=claude-agent-daily.service

[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=300

[Install]
WantedBy=timers.target
EOF

# Timer有効化
systemctl enable claude-agent-daily.timer
systemctl start claude-agent-daily.timer

🛡️ エラーハンドリング・監視

1. エラーハンドリング仕組み

# エラーハンドリング共通関数
cat > /opt/claude-agent/lib/error-handling.sh << 'EOF'
#!/bin/bash

# エラーハンドリング設定
set -euo pipefail
IFS=$'\n\t'

# ログ関数
log_error() {
    echo "❌ [ERROR] $(date): $1" >&2
    logger -t claude-agent "ERROR: $1"
}

log_warn() {
    echo "⚠️ [WARN] $(date): $1" >&2
    logger -t claude-agent "WARN: $1"
}

log_info() {
    echo "ℹ️ [INFO] $(date): $1"
    logger -t claude-agent "INFO: $1"
}

# リトライ機能
retry_command() {
    local max_attempts=$1
    local delay=$2
    local command="${@:3}"
    local attempt=1

    while [ $attempt -le $max_attempts ]; do
        log_info "Attempt $attempt/$max_attempts: $command"

        if eval "$command"; then
            log_info "Command succeeded on attempt $attempt"
            return 0
        else
            log_warn "Command failed on attempt $attempt"
            if [ $attempt -lt $max_attempts ]; then
                log_info "Retrying in $delay seconds..."
                sleep $delay
            fi
        fi

        ((attempt++))
    done

    log_error "Command failed after $max_attempts attempts: $command"
    return 1
}

# 緊急停止機能
emergency_stop() {
    log_error "Emergency stop triggered: $1"

    # 実行中のClaude Codeプロセスを停止
    pkill -f "claude" || true

    # アラート送信
    send_alert "EMERGENCY" "Claude Agent emergency stop: $1"

    exit 1
}

# アラート送信
send_alert() {
    local severity=$1
    local message=$2

    # Slack通知
    if [ -n "${SLACK_WEBHOOK:-}" ]; then
        curl -X POST -H 'Content-type: application/json' \
            --data "{\"text\":\"[$severity] Claude Agent: $message\"}" \
            "$SLACK_WEBHOOK" || true
    fi

    # メール通知
    if [ -n "${ALERT_EMAIL:-}" ]; then
        echo "$message" | mail -s "[$severity] Claude Agent Alert" "$ALERT_EMAIL" || true
    fi
}

# トラップ設定
trap 'log_error "Script interrupted"; exit 130' INT TERM
trap 'log_error "Script failed on line $LINENO"' ERR
EOF

2. 監視ダッシュボード

# monitoring/dashboard.py
import json
import datetime
from pathlib import Path
import streamlit as st
import pandas as pd
import plotly.express as px

class ClaudeAgentMonitoring:
    def __init__(self):
        self.log_dir = Path("/var/log/claude-agent")

    def load_execution_logs(self):
        """実行ログの読み込み"""
        logs = []
        for log_file in self.log_dir.glob("*.log"):
            try:
                with open(log_file, 'r') as f:
                    for line in f:
                        if "Starting" in line or "completed" in line:
                            logs.append({
                                'timestamp': self.extract_timestamp(line),
                                'type': self.extract_type(line),
                                'status': self.extract_status(line),
                                'file': log_file.name
                            })
            except Exception as e:
                st.error(f"ログファイル読み込みエラー: {e}")

        return pd.DataFrame(logs)

    def extract_timestamp(self, line):
        """ログからタイムスタンプ抽出"""
        # 実装: 正規表現でタイムスタンプ抽出
        pass

    def create_dashboard(self):
        """Streamlitダッシュボード作成"""
        st.title("🤖 Claude Agent 監視ダッシュボード")

        # メトリクス表示
        col1, col2, col3, col4 = st.columns(4)

        with col1:
            st.metric("今日の実行回数", "12", "2")

        with col2:
            st.metric("成功率", "95%", "3%")

        with col3:
            st.metric("平均実行時間", "2m 34s", "-15s")

        with col4:
            st.metric("エラー率", "5%", "-2%")

        # 実行履歴グラフ
        df = self.load_execution_logs()
        if not df.empty:
            fig = px.line(df, x='timestamp', y='status', 
                         title='Claude Agent 実行状況')
            st.plotly_chart(fig, use_container_width=True)

        # 最新ログ表示
        st.subheader("📋 最新実行ログ")
        if not df.empty:
            st.dataframe(df.tail(10), use_container_width=True)

if __name__ == "__main__":
    monitor = ClaudeAgentMonitoring()
    monitor.create_dashboard()

3. アラート設定

# monitoring/alerting-rules.yml
groups:
- name: claude-agent-alerts
  rules:
  - alert: ClaudeAgentExecutionFailed
    expr: claude_agent_execution_success_rate < 0.9
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "Claude Agent実行成功率が低下"
      description: "過去5分間のClaude Agent実行成功率が90%を下回りました"

  - alert: ClaudeAgentHighMemoryUsage
    expr: claude_agent_memory_usage > 0.85
    for: 10m
    labels:
      severity: critical
    annotations:
      summary: "Claude Agentメモリ使用率が高い"
      description: "Claude Agentのメモリ使用率が85%を超えています"

  - alert: ClaudeAgentNotResponding
    expr: up{job="claude-agent"} == 0
    for: 1m
    labels:
      severity: critical
    annotations:
      summary: "Claude Agentが応答していません"
      description: "Claude Agentプロセスが1分間応答していません"

🔐 セキュリティ・権限管理

1. IAM設定

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ClaudeAgentMinimalPermissions",
      "Effect": "Allow",
      "Principal": {
        "User": "arn:aws:iam::ACCOUNT:user/claude-agent"
      },
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:ListBucket",
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "cloudwatch:PutMetricData"
      ],
      "Resource": [
        "arn:aws:s3:::claude-agent-bucket/*",
        "arn:aws:logs:*:ACCOUNT:*:claude-agent*",
        "arn:aws:cloudwatch:*:ACCOUNT:metric/ClaudeAgent/*"
      ]
    },
    {
      "Sid": "DenyDangerousOperations",
      "Effect": "Deny",
      "Action": [
        "iam:*",
        "ec2:TerminateInstances",
        "rds:DeleteDBInstance",
        "s3:DeleteBucket"
      ],
      "Resource": "*"
    }
  ]
}

2. セキュリティ監査

# security/audit-script.sh
#!/bin/bash

echo "🔍 Claude Agent セキュリティ監査開始"

# API キー保護確認
echo "📋 API キー保護状況:"
if [ -f ~/.claude/api_key ]; then
    PERMISSIONS=$(stat -c "%a" ~/.claude/api_key)
    if [ "$PERMISSIONS" = "600" ]; then
        echo "✅ API キーの権限設定は適切です (600)"
    else
        echo "❌ API キーの権限設定が不適切です ($PERMISSIONS)"
        echo "修正: chmod 600 ~/.claude/api_key"
    fi
else
    echo "⚠️ API キーファイルが見つかりません"
fi

# 設定ファイル権限確認
echo "📋 設定ファイル権限:"
find ~/.claude -type f -name "*.json" | while read file; do
    PERMISSIONS=$(stat -c "%a" "$file")
    if [ "$PERMISSIONS" = "600" ] || [ "$PERMISSIONS" = "644" ]; then
        echo "✅ $file ($PERMISSIONS)"
    else
        echo "❌ $file ($PERMISSIONS) - 権限を修正してください"
    fi
done

# ログファイル権限確認
echo "📋 ログファイル権限:"
if [ -d /var/log/claude-agent ]; then
    OWNER=$(stat -c "%U:%G" /var/log/claude-agent)
    echo "ログディレクトリ所有者: $OWNER"

    find /var/log/claude-agent -type f | head -5 | while read logfile; do
        PERMISSIONS=$(stat -c "%a" "$logfile")
        echo "📄 $(basename $logfile): $PERMISSIONS"
    done
fi

echo "✅ セキュリティ監査完了"

📈 スケーリング・パフォーマンス最適化

1. 水平スケーリング設定

# k8s/claude-agent-deployment.yml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: claude-agent
  namespace: ai-automation
spec:
  replicas: 3
  selector:
    matchLabels:
      app: claude-agent
  template:
    metadata:
      labels:
        app: claude-agent
    spec:
      containers:
      - name: claude-agent
        image: claude-agent:latest
        resources:
          requests:
            memory: "512Mi"
            cpu: "250m"
          limits:
            memory: "1Gi"
            cpu: "500m"
        env:
        - name: ANTHROPIC_API_KEY
          valueFrom:
            secretKeyRef:
              name: claude-secrets
              key: api-key
        - name: ENVIRONMENT
          value: "production"
        volumeMounts:
        - name: config
          mountPath: /app/config
        - name: logs
          mountPath: /app/logs
      volumes:
      - name: config
        configMap:
          name: claude-agent-config
      - name: logs
        persistentVolumeClaim:
          claimName: claude-agent-logs

---
apiVersion: v1
kind: Service
metadata:
  name: claude-agent-service
spec:
  selector:
    app: claude-agent
  ports:
  - port: 8080
    targetPort: 8080
  type: ClusterIP

---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: claude-agent-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: claude-agent
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80

2. パフォーマンス最適化

# optimization/performance-tuner.py
import asyncio
import aiohttp
import time
from concurrent.futures import ThreadPoolExecutor
import logging

class ClaudeAgentOptimizer:
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.executor = ThreadPoolExecutor(max_workers=4)

    async def optimize_execution(self, tasks):
        """タスクの並列実行最適化"""

        # タスクの優先度別分類
        high_priority = [t for t in tasks if t.get('priority') == 'high']
        normal_priority = [t for t in tasks if t.get('priority') == 'normal']
        low_priority = [t for t in tasks if t.get('priority') == 'low']

        # 高優先度タスクを最初に実行
        results = []

        if high_priority:
            high_results = await self.execute_batch(high_priority, max_concurrent=2)
            results.extend(high_results)

        # 通常優先度タスクを並列実行
        if normal_priority:
            normal_results = await self.execute_batch(normal_priority, max_concurrent=4)
            results.extend(normal_results)

        # 低優先度タスクをバックグラウンドで実行
        if low_priority:
            asyncio.create_task(self.execute_batch(low_priority, max_concurrent=2))

        return results

    async def execute_batch(self, tasks, max_concurrent=3):
        """バッチ実行"""
        semaphore = asyncio.Semaphore(max_concurrent)

        async def execute_single(task):
            async with semaphore:
                start_time = time.time()
                try:
                    result = await self.execute_claude_task(task)
                    execution_time = time.time() - start_time

                    self.logger.info(f"Task {task['id']} completed in {execution_time:.2f}s")
                    return {
                        'task_id': task['id'],
                        'result': result,
                        'execution_time': execution_time,
                        'status': 'success'
                    }
                except Exception as e:
                    execution_time = time.time() - start_time
                    self.logger.error(f"Task {task['id']} failed: {e}")
                    return {
                        'task_id': task['id'],
                        'error': str(e),
                        'execution_time': execution_time,
                        'status': 'failed'
                    }

        # 全タスクを並列実行
        results = await asyncio.gather(*[execute_single(task) for task in tasks])
        return results

    async def execute_claude_task(self, task):
        """Claude Code タスク実行"""
        # 実装: Claude Code API呼び出し
        await asyncio.sleep(1)  # 模擬実行時間
        return f"Task {task['id']} completed"

# パフォーマンス監視
class PerformanceMonitor:
    def __init__(self):
        self.metrics = {
            'execution_times': [],
            'success_rate': 0,
            'throughput': 0
        }

    def record_execution(self, execution_time, success):
        """実行メトリクスの記録"""
        self.metrics['execution_times'].append(execution_time)

        # 成功率計算
        total_executions = len(self.metrics['execution_times'])
        if total_executions > 0:
            success_count = sum(1 for _ in self.metrics['execution_times'] if success)
            self.metrics['success_rate'] = success_count / total_executions

    def get_performance_summary(self):
        """パフォーマンス要約"""
        if not self.metrics['execution_times']:
            return "No execution data available"

        avg_time = sum(self.metrics['execution_times']) / len(self.metrics['execution_times'])

        return {
            'average_execution_time': avg_time,
            'success_rate': self.metrics['success_rate'],
            'total_executions': len(self.metrics['execution_times']),
            'throughput_per_minute': 60 / avg_time if avg_time > 0 else 0
        }

🔧 トラブルシューティング

よくある問題と解決方法

認証エラー

症状: Authentication failed エラー

解決方法:

# API キー再設定
claude auth login

# 権限確認
claude auth status

# 設定ファイル確認
cat ~/.claude/config.json

自動承認が動作しない

症状: 毎回手動承認が求められる

解決方法:

# 自動承認設定確認
claude config get auto_approval

# 設定有効化
claude config set auto_approval.enabled true

# 権限確認
claude config set auto_approval.rules.file_operations.write true

cron実行でエラー

症状: cron経由でのClaude Code実行が失敗

解決方法:

# 環境変数設定
export PATH="/usr/local/bin:$PATH"
export ANTHROPIC_API_KEY="your-api-key"

# cron用ラッパースクリプト作成
cat > /opt/claude-agent/cron-wrapper.sh << 'EOF'
#!/bin/bash
source /etc/environment
source ~/.bashrc
exec /usr/local/bin/claude "$@"
EOF

デバッグ情報収集

# debug/collect-info.sh
#!/bin/bash

echo "🔍 Claude Agent デバッグ情報収集"

DEBUG_DIR="/tmp/claude-debug-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$DEBUG_DIR"

# システム情報
echo "📋 システム情報収集中..."
{
    echo "=== System Information ==="
    uname -a
    echo ""

    echo "=== Claude Code Version ==="
    claude --version
    echo ""

    echo "=== Authentication Status ==="
    claude auth status
    echo ""

    echo "=== Configuration ==="
    claude config list
    echo ""

    echo "=== Environment Variables ==="
    env | grep -i claude
    echo ""

    echo "=== Process Information ==="
    ps aux | grep claude
    echo ""

    echo "=== Recent Logs ==="
    tail -100 /var/log/claude-agent/*.log 2>/dev/null || echo "No logs found"

} > "$DEBUG_DIR/system-info.txt"

# 設定ファイル収集
echo "📋 設定ファイル収集中..."
cp -r ~/.claude "$DEBUG_DIR/config" 2>/dev/null || echo "Config not found"

# ログファイル収集
echo "📋 ログファイル収集中..."
cp -r /var/log/claude-agent "$DEBUG_DIR/logs" 2>/dev/null || echo "Logs not found"

# アーカイブ作成
tar -czf "${DEBUG_DIR}.tar.gz" -C "/tmp" "$(basename $DEBUG_DIR)"

echo "✅ デバッグ情報を収集しました: ${DEBUG_DIR}.tar.gz"
echo "このファイルをサポートチームに送信してください"

📊 成功指標とKPI

運用成功指標

指標目標値測定方法
実行成功率> 95%GitHub Actions成功率
平均実行時間< 5分ログ分析
システム稼働率> 99.5%監視ダッシュボード
エラー検出時間< 1分アラート応答時間
復旧時間< 10分インシデント管理

業務効率改善

  • 自動化前: 手動作業 8時間/日
  • 自動化後: 監視作業 30分/日
  • 効率化率: 93.75%

🔗 関連記事


実装完了チェックリスト

  • 自動承認設定の完了
  • GitHub Actions CI/CD統合
  • cron自動実行設定
  • エラーハンドリング実装
  • 監視ダッシュボード構築
  • セキュリティ監査実施
  • パフォーマンス最適化
  • 本番運用開始

このガイドを完全実装することで、エンタープライズレベルのAIエージェント自動化システムを構築できます。 🚀