統合ロードマップ

統合ロードマップ

概要

AI Course Content Generatorプロジェクトから特定された47の高価値概念を、Autonomous-Operationsに統合するための包括的なロードマップです。15の重要な概念を優先順位付けし、4つのフェーズに分けて実装を進めます。

対象読者

  • プロジェクトマネージャー
  • システムアーキテクト
  • DevOpsエンジニア
  • プロダクトオーナー

所要時間

  • 読了時間: 45分
  • フェーズ1実装: 4週間
  • フェーズ2実装: 3週間
  • フェーズ3実装: 4週間
  • フェーズ4実装: 3週間
  • 総所要時間: 14週間 (1 FTE)

前提知識


エグゼクティブサマリー

ソースプロジェクトの成果

AI Course Content Generatorプロジェクトの47概念を分析した結果、以下の実績が確認されました:

source_metrics:
  time_reduction: 83%          # 240分 → 40分
  automation_rate: 95%+        # 自動化成功率
  operation_mode: 24/7         # 完全自律運用
  specialized_agents: 6        # 専門化されたAgent
  secret_management: dynamic   # TTL 15分の動的シークレット

統合目標

integration_goals:
  phase_1:
    duration: 4週間
    focus: 基盤 (6-Agent System + 組織設計フレームワーク)

  phase_2:
    duration: 3週間
    focus: 並行実行 (DAG解決 + Task Tool最適化)

  phase_3:
    duration: 4週間
    focus: 知識永続化 (Vector DB + Postmortemシステム)

  phase_4:
    duration: 3週間
    focus: セキュリティと監視 (Vault統合 + SLA追跡)

期待される成果

expected_roi:
  efficiency_gain: 10倍
  time_reduction: 70%+
  automation_rate: 90%+
  quality_score: 85点以上 (平均)
  total_effort: 312時間 (14週間、1 FTE)

Phase 1: Foundation (4週間、96時間)

1.1 Six-Agent Type System ⭐⭐⭐

優先度: Critical 工数: 24時間 ステータス: 未着手

現状

  • Agentの概念は AGENTS.md に存在
  • 具体的な実装はまだなし

目標

6種類の特化型Agentを実装:

  1. CoordinatorAgent: タスク割り当て、競合解決、エスカレーション
  2. CodeGenAgent: コード生成、実装
  3. ReviewAgent: 品質チェック (80点基準)
  4. IssueAgent: トリアージ、ラベリング、分類
  5. PRAgent: 自動PR作成、説明文生成
  6. DeploymentAgent: CI/CD、本番デプロイ

実装例

// agents/core/BaseAgent.ts
export abstract class BaseAgent {
  abstract type: AgentType;
  abstract execute(task: Task): Promise<TaskResult>;
  abstract validate(result: TaskResult): Promise<QualityScore>;
  abstract escalate(issue: EscalationIssue): Promise<void>;

  protected async logExecution(task: Task, result: TaskResult): Promise<void> {
    // ログを .ai/logs/agents/{agent-type}-{date}.md に記録
  }
}

// agents/types/CodeGenAgent.ts
export class CodeGenAgent extends BaseAgent {
  type = AgentType.CodeGen;

  async execute(task: Task): Promise<TaskResult> {
    // Claude Code Task Toolを使用
    // タスク要件に基づいてコード生成
    // 構造化された結果を返す
  }

  async validate(result: TaskResult): Promise<QualityScore> {
    // ReviewAgentに品質チェックをトリガー
  }
}

完了基準

  • 全6種類のAgentクラス実装完了
  • 共通インターフェース (execute, validate, escalate) 実装
  • Agent専用プロンプトを .ai/prompts/agents/ に配置
  • 自動Agent起動のGitHub Actionsワークフロー作成
  • 品質スコアリングシステム実装 (ReviewAgent: 80点以上が合格)
  • エスカレーションルーティングロジック (Severity → Guardian マッピング)

検証メトリクス

validation_metrics:
  task_completion_rate: ">90%"
  average_quality_score: ">85"
  escalation_rate: "<10%"

1.2 組織設計原則 Operations Framework ⭐⭐⭐

優先度: Critical 工数: 24時間 ステータス: 未着手

組織設計とは

日本の経営理論で、明確な責任曖昧さゼロ を重視します。

5つの核心原則

core_principles:
  1_clear_responsibility:
    name: 責任の明確化
    description: 各Agentが特定の成果を所有

  2_results_oriented:
    name: 結果重視
    description: プロセスではなく結果でAgentを評価

  3_hierarchy_clarity:
    name: 階層の明確化
    description: CoordinatorAgent → Specialist Agents

  4_eliminate_ambiguity:
    name: 曖昧さの排除
    description: 責任の重複なし

  5_data_driven:
    name: データドリブン
    description: すべてに測定可能なKPI

実装例

// agents/governance/OrganizationalFramework.ts
export interface AgentResponsibility {
  agentType: AgentType;
  scope: string;              // このAgentが責任を持つ範囲
  boundaries: string[];       // このAgentが責任を持たない範囲
  kpis: KPI[];                // 測定可能な成果
  escalationCriteria: EscalationRule[];
}

export const AGENT_RESPONSIBILITIES: Record<AgentType, AgentResponsibility> = {
  [AgentType.Coordinator]: {
    scope: "タスク割り当て、競合解決、リソース配分",
    boundaries: ["コードを書かない", "PRをマージしない"],
    kpis: [
      {
        name: "タスク割り当て精度",
        target: ">95%",
        measurement: "正しいAgentへの割り当て率"
      },
      {
        name: "競合解決時間",
        target: "<5分",
        measurement: "競合検出から解決までの時間"
      }
    ],
    escalationCriteria: [
      {
        condition: "複数Agentが同じタスクを要求",
        action: "Guardianにエスカレート"
      },
      {
        condition: "予算が80%を超過",
        action: "Guardianに通知"
      }
    ]
  },
  [AgentType.CodeGen]: {
    scope: "コード実装、ユニットテスト、ドキュメント",
    boundaries: ["コード品質をレビューしない", "PRをマージしない"],
    kpis: [
      {
        name: "実装完全性",
        target: "100%",
        measurement: "受け入れ基準達成率"
      },
      {
        name: "テストカバレッジ",
        target: ">80%",
        measurement: "コードカバレッジ率"
      },
      {
        name: "ビルド成功率",
        target: "100%",
        measurement: "ビルド成功率"
      }
    ],
    escalationCriteria: [
      {
        condition: "要件が不明確",
        action: "IssueAgentに明確化を依頼"
      },
      {
        condition: "品質スコア <80",
        action: "AutoFixAgentを自動起動"
      }
    ]
  }
  // ... 他のAgent
};

完了基準

  • 全6種類のAgentの責任定義完了
  • 目標値と測定方法を持つ測定可能なKPI
  • 各Agentの明確なエスカレーション基準
  • KPI自動収集とレポート機能
  • Agent対KPIのパフォーマンスダッシュボード

検証メトリクス

validation_metrics:
  kpi_measurement_accuracy: "100%"
  responsibility_overlap_conflicts: "0"
  agent_satisfaction_survey: ">4.5/5"

1.3 Economic Circuit Breaker Enhancement ⭐⭐

優先度: High 工数: 16時間 ステータス: 部分的完了 (BUDGET.yml存在)

現状

  • BUDGET.yml で制限を定義
  • 強制メカニズムはまだなし

目標

  • Agent毎の自動予算追跡
  • リアルタイムコスト監視
  • 150%でのサーキットブレーカー自動シャットダウン
  • 80%閾値でGuardian通知

実装例

// agents/governance/EconomicGovernor.ts
export class EconomicGovernor {
  private budget: BudgetConfig;
  private currentSpend: number = 0;

  async checkBudget(
    agent: AgentType,
    estimatedCost: number
  ): Promise<BudgetCheckResult> {
    const projectedTotal = this.currentSpend + estimatedCost;
    const threshold =
      this.budget.monthly_limit *
      (this.budget.circuit_breaker_threshold / 100);

    if (projectedTotal > threshold) {
      await this.triggerCircuitBreaker();
      return { allowed: false, reason: "Circuit breaker triggered" };
    }

    if (projectedTotal > this.budget.monthly_limit * 0.8) {
      await this.notifyGuardian("80% budget threshold reached");
    }

    return { allowed: true };
  }

  async triggerCircuitBreaker(): Promise<void> {
    // 1. 実行中のAgentをすべて停止
    // 2. 緊急Issueを作成
    // 3. すべてのチャネルでGuardianに通知
    // 4. .ai/logs/circuit-breaker.md にログ
  }

  async trackCost(agent: AgentType, actualCost: number): Promise<void> {
    this.currentSpend += actualCost;
    await this.logCostAllocation(agent, actualCost);
  }
}

完了基準

  • Agent毎のリアルタイムコスト追跡
  • 150%閾値で自動シャットダウン
  • 80%閾値でGuardian通知
  • コスト配分レポート (.ai/reports/cost-allocation.json)
  • 月次予算リセットメカニズム

検証メトリクス

validation_metrics:
  circuit_breaker_activation_accuracy: "100%"
  cost_tracking_latency: "<1秒"
  guardian_notification_delivery_rate: "100%"

1.4 Agent Security Rules (Firestore-style) ⭐⭐

優先度: High 工数: 16時間 ステータス: 未着手

コンセプト

FirestoreスタイルのセキュリティルールをAgentアクションに適用:

match /files/{file} {
  allow write: if request.agent == 'CodeGenAgent'
               && request.branch.startsWith('feat/')
               && !isProtectedFile(file);
}

match /issues/{issueNumber} {
  allow close: if request.agent == 'IssueAgent'
               || request.agent == 'CoordinatorAgent'
               || request.user == 'Guardian';
}

実装例

// agents/security/AgentSecurityRules.ts
export const AGENT_SECURITY_RULES = {
  files: {
    '**/*.ts': {
      allowWrite: ['CodeGenAgent', 'AutoFixAgent'],
      requireReview: true,
      forbidden: ['AGENTS.md', 'BUDGET.yml', '.github/WORKFLOW_RULES.md']
    },
    'AGENTS.md': {
      allowWrite: ['Guardian'],
      requireApproval: true
    }
  },

  issues: {
    close: {
      allowedAgents: ['IssueAgent', 'CoordinatorAgent'],
      requireGuardianApproval: (issue) => issue.labels.includes('critical')
    },
    label: {
      allowedAgents: ['IssueAgent'],
      maxLabelsPerAction: 5
    }
  },

  pullRequests: {
    create: {
      allowedAgents: ['PRAgent', 'CodeGenAgent'],
      requireDraft: true
    },
    merge: {
      allowedAgents: ['Guardian'], // Guardianのみマージ可能
      requireChecks: ['build', 'test', 'review']
    }
  }
};

export class AgentSecurityEnforcer {
  async checkPermission(
    agent: AgentType,
    action: AgentAction,
    resource: Resource
  ): Promise<PermissionCheckResult> {
    // ルールを評価
    // すべての権限チェックを .ai/logs/security/permissions.log に記録
    // デフォルトで拒否、明示的なルールで許可
  }
}

完了基準

  • すべてのリソースタイプのセキュリティルール定義完了
  • すべてのAgentアクション前の権限チェック
  • すべての権限チェックの監査ログ
  • Guardian上書きメカニズム
  • セキュリティルールのドキュメント

検証メトリクス

validation_metrics:
  unauthorized_actions_blocked: "100%"
  permission_check_latency: "<50ms"
  audit_log_completeness: "100%"

1.5 Enhanced Logging System ⭐

優先度: High 工数: 16時間 ステータス: 部分的完了 (.ai/logs/ 存在)

現状

  • .ai/logs/YYYY-MM-DD.md に基本的なログ
  • 構造化フォーマットなし

目標

  • 機械可読性のための構造化JSONログ
  • カテゴリ別ログファイル:
    • Agent Actions: .ai/logs/agents/{agent-type}-{date}.json
    • Security Events: .ai/logs/security/{date}.json
    • Performance: .ai/logs/performance/{date}.json
    • Errors: .ai/logs/errors/{date}.json
  • 保持ポリシー: 90日間
  • 自動ログローテーション

実装例

// agents/logging/StructuredLogger.ts
export interface LogEntry {
  timestamp: string;
  level: 'debug' | 'info' | 'warn' | 'error' | 'critical';
  category: 'agent' | 'security' | 'performance' | 'error';
  agentType?: AgentType;
  action: string;
  resource?: string;
  metadata: Record<string, any>;
  duration_ms?: number;
  result: 'success' | 'failure' | 'partial';
}

export class StructuredLogger {
  async log(entry: LogEntry): Promise<void> {
    const logFile = this.getLogFile(entry.category, entry.timestamp);
    await appendFile(logFile, JSON.stringify(entry) + '\n');

    // 人間が読めるデイリーサマリーにもログ
    await this.updateDailySummary(entry);
  }

  async query(filters: LogFilters): Promise<LogEntry[]> {
    // ログのクエリをサポート
    // 例: logger.query({ agentType: 'CodeGenAgent', dateRange: [start, end] })
  }
}

完了基準

  • すべてのAgentアクションの構造化JSONログ
  • カテゴリ別のログファイル分離
  • ログローテーション (日次)
  • 保持ポリシーの強制 (90日間)
  • ログ分析用のクエリインターフェース

検証メトリクス

validation_metrics:
  log_completeness: "100%"  # Agentアクションの欠落なし
  log_query_response_time: "<500ms"
  disk_usage: "<1GB/月"

Phase 2: Parallel Execution (3週間、72時間)

2.1 DAG-Based Dependency Resolution ⭐⭐⭐

優先度: Critical 工数: 12時間 ステータス: 未着手

コンセプト

Issue本文中の #<number> 参照を解析して依存関係グラフを自動構築し、トポロジカルソートで実行順序を決定。レベルベースの並列実行をサポート。

Issue #10: "機能Xを実装 (依存: #8, #9)"
Issue #8: "データベーススキーマをセットアップ"
Issue #9: "APIエンドポイントを作成 (依存: #8)"

依存関係グラフ:
       #8
      /  \
    #9    \
      \   /
       #10

実行順序:
Level 0: [#8]           ← 単独で実行
Level 1: [#9]           ← #8の後に実行
Level 2: [#10]          ← #8と#9の後に実行

実装例

// agents/coordination/DependencyResolver.ts
export class DependencyResolver {
  async buildDAG(issues: Issue[]): Promise<TaskGraph> {
    const graph = new Map<number, number[]>(); // issueNumber → 依存関係

    for (const issue of issues) {
      const deps = this.extractDependencies(issue.body);
      graph.set(issue.number, deps);
    }

    this.detectCycles(graph); // サイクルが検出されたらエラーをスロー

    return {
      graph,
      levels: this.calculateLevels(graph),
      executionOrder: this.topologicalSort(graph)
    };
  }

  private extractDependencies(issueBody: string): number[] {
    const pattern = /#(\d+)/g;
    const matches = [];
    let match;
    while ((match = pattern.exec(issueBody)) !== null) {
      matches.push(parseInt(match[1]));
    }
    return matches;
  }

  private detectCycles(graph: Map<number, number[]>): void {
    // KahnのアルゴリズムまたはDFSベースのサイクル検出
  }

  private calculateLevels(graph: Map<number, number[]>): Map<number, number> {
    // ルートノード (依存関係のないタスク) からBFS
    // ルートにレベル0を割り当て、その依存先にレベル1、など
  }
}

完了基準

  • Issue本文からの依存関係自動抽出
  • サイクル検出を含むDAG構築
  • 実行順序のトポロジカルソート
  • レベルベースの並列実行
  • PR説明でのMermaid依存関係グラフの可視化

検証メトリクス

validation_metrics:
  cycle_detection_accuracy: "100%"
  correct_execution_order: "100%"
  level_wise_parallelism_utilization: ">80%"

2.2 Parallel Task Execution Optimization ⭐⭐⭐

優先度: Critical 工数: 16時間 ステータス: 部分的完了 (Task Toolドキュメント化済み)

現状

  • Claude Code Task Toolの使用をドキュメント化
  • 並列実行の最適化なし

目標

  • 独立したタスクの自動検出
  • 単一メッセージでの複数タスク起動
  • 競合検出 (同じファイル = 順次、異なるファイル = 並列)
  • 結果の集約

ソースからの主要な洞察

「すべてのTask toolの呼び出しは、並列処理をトリガーするために1つのメッセージで行う必要があります」

実装例

// agents/coordination/ParallelExecutor.ts
export class ParallelExecutor {
  async executeParallel(tasks: Task[]): Promise<TaskResult[]> {
    // 1. ファイル競合でタスクをグループ化
    const groups = this.groupByConflicts(tasks);

    // 2. 各グループを並列実行、グループは順次実行
    const results: TaskResult[] = [];

    for (const group of groups) {
      const groupResults = await this.executeGroup(group);
      results.push(...groupResults);
    }

    return results;
  }

  private groupByConflicts(tasks: Task[]): Task[][] {
    // 競合マトリックスを構築: tasks[i]とtasks[j]が同じファイルを変更する場合、競合
    // グラフ彩色アルゴリズムを使用して最大独立集合を見つける
    const conflictGraph = this.buildConflictGraph(tasks);
    return this.findIndependentSets(conflictGraph);
  }

  private async executeGroup(tasks: Task[]): Promise<TaskResult[]> {
    // すべてのタスクで単一のClaude Codeメッセージを生成
    const prompt = this.generateParallelPrompt(tasks);

    // これによりClaude CodeのPromise.all()が内部でトリガーされる
    const result = await claudeCode.execute(prompt);

    return this.parseResults(result);
  }

  private generateParallelPrompt(tasks: Task[]): string {
    return `
以下の${tasks.length}個のタスクを並列実行してください:

${tasks.map((t, i) => `
## タスク ${i + 1}: ${t.title}

**要件:**
${t.requirements}

**受け入れ基準:**
${t.acceptanceCriteria.map(c => `- ${c}`).join('\n')}

**返却フォーマット:**
{
  "taskId": "${t.id}",
  "success": true/false,
  "filesModified": ["path1", "path2"],
  "summary": "簡単な説明"
}
`).join('\n')}

重要: すべてのタスクの結果を含むJSON配列を返してください。
`;
  }
}

完了基準

  • 自動競合検出 (同じファイルの編集)
  • 単一メッセージの複数タスクプロンプト生成
  • 結果の解析と集約
  • 時間削減メトリクスの収集

検証メトリクス

validation_metrics:
  parallel_execution_success_rate: ">95%"
  time_reduction: ">70% vs 順次実行"
  file_conflict_rate: "<5%"

2.3 24/7 Autonomous System with tmux Dashboard ⭐⭐

優先度: High 工数: 20時間 ステータス: 未着手

コンセプト

tmux 4ペインダッシュボードを使用した完全なハンズフリー運用。ユーザーは一度だけ「parallel execution start」を入力すれば、システムは無期限で実行されます。

tmuxレイアウト

┌──────────────────────┬──────────────────────┐
│  Orchestrator Loop   │  Main Claude Agent   │
│  (30秒サイクル)      │  (監視)              │
├──────────────────────┼──────────────────────┤
│  Task Queue Monitor  │  Real-time Metrics   │
│  (GitHub Issues)     │  (JSON状態)          │
└──────────────────────┴──────────────────────┘

実装例

#!/bin/bash
# scripts/start-autonomous-system.sh

# tmuxセッションを作成
tmux new-session -d -s agentic-os

# 4つのペインに分割
tmux split-window -h -t agentic-os
tmux split-window -v -t agentic-os:0.0
tmux split-window -v -t agentic-os:0.1

# ペイン0 (左上): Orchestratorループ
tmux send-keys -t agentic-os:0.0 'npx tsx scripts/orchestrator-loop.ts' C-m

# ペイン1 (右上): メインClaude Code Agent
tmux send-keys -t agentic-os:0.1 'echo "Main Agent Ready. Monitoring orchestrator..."' C-m

# ペイン2 (左下): タスクキュー監視
tmux send-keys -t agentic-os:0.2 'watch -n 2 "gh issue list --label=status:in-progress"' C-m

# ペイン3 (右下): リアルタイムメトリクス
tmux send-keys -t agentic-os:0.3 'watch -n 2 "cat .ai/autonomous-state.json | jq"' C-m

# セッションにアタッチ
tmux attach -t agentic-os

Orchestratorループ

// scripts/orchestrator-loop.ts
async function orchestratorLoop() {
  while (true) {
    try {
      // 1. 新しいタスクを検出 (label "status:backlog"のGitHub Issue)
      const tasks = await detectNewTasks();

      // 2. 依存関係グラフを構築
      const dag = await dependencyResolver.buildDAG(tasks);

      // 3. 現在のレベルのタスクにAgentを割り当て
      await assignAgents(dag.currentLevel);

      // 4. 完了を監視
      await monitorCompletion();

      // 5. 状態を更新
      await updateAutonomousState({
        lastCycle: new Date().toISOString(),
        tasksInProgress: tasks.filter(t => t.status === 'in_progress').length,
        tasksCompleted: tasks.filter(t => t.status === 'done').length,
      });

      // 6. 30秒スリープ
      await sleep(30000);
    } catch (error) {
      logger.error('Orchestrator cycle failed', error);
      await notifyGuardian(error);
    }
  }
}

orchestratorLoop();

完了基準

  • tmux 4ペインダッシュボードスクリプト
  • Orchestrator無限ループ (30秒サイクル)
  • タスク検出と割り当て
  • リアルタイム状態の永続化 (.ai/autonomous-state.json)
  • リカバリーメカニズム (クラッシュしたAgentの再起動)

検証メトリクス

validation_metrics:
  system_uptime: ">99.9%"
  cycle_latency: "<35秒"  # 30秒スリープ + 5秒作業
  agent_crash_recovery_time: "<60秒"

Phase 3: Knowledge Persistence (4週間、64時間)

3.1 Knowledge Persistence Layer with Vector DB ⭐⭐⭐

優先度: Critical 工数: 32時間 ステータス: 未着手

コンセプト

別のGitHubリポジトリにインシデント、ポストモーテム、RFC、ソリューションを保存。コミット時に自動的にPineconeに埋め込み。Agentは実行前にクエリして履歴から学習。

アーキテクチャ

┌─────────────────────────────────────────────────┐
│  Knowledge Repo (GitHub)                        │
│  .knowledge/                                    │
│    ├── incidents/                              │
│    │   └── 2025-10-08-build-failure.md        │
│    ├── postmortems/                            │
│    │   └── 2025-10-01-deployment-issue.md     │
│    ├── rfcs/                                   │
│    │   └── rfc-001-parallel-execution.md      │
│    └── solutions/                              │
│        └── how-to-fix-typescript-error.md     │
└─────────────────────────────────────────────────┘
                    ↓ (コミット時)
         ┌─────────────────────┐
         │  GitHub Actions     │
         │  (埋め込み&アップロード) │
         └─────────────────────┘
                    ↓
         ┌─────────────────────┐
         │  Pinecone Vector DB │
         │  (埋め込み)          │
         └─────────────────────┘
                    ↑ (クエリ)
         ┌─────────────────────┐
         │  Agents             │
         │  (実行前)            │
         └─────────────────────┘

実装例

// agents/knowledge/KnowledgeRetriever.ts
export class KnowledgeRetriever {
  private pinecone: PineconeClient;

  async queryRelevantKnowledge(task: Task): Promise<Knowledge[]> {
    // 1. タスク説明を埋め込み
    const embedding = await this.embed(task.description);

    // 2. 類似する過去の経験をPineconeでクエリ
    const results = await this.pinecone.query({
      vector: embedding,
      topK: 5,
      filter: { type: ['incident', 'postmortem', 'solution'] }
    });

    // 3. 関連する知識を返す
    return results.matches.map(m => ({
      title: m.metadata.title,
      content: m.metadata.content,
      similarity: m.score,
      type: m.metadata.type,
      url: m.metadata.url
    }));
  }

  async learnFromExecution(task: Task, result: TaskResult): Promise<void> {
    if (result.status === 'failure' || result.hasInterestingPattern) {
      // インシデントレポートを作成
      await this.createIncidentReport(task, result);

      // 埋め込みワークフローをトリガー
      await this.triggerEmbedding();
    }
  }
}

// Agentの実行で使用
async function executeWithKnowledge(task: Task): Promise<TaskResult> {
  // 実行前に知識をクエリ
  const relevantKnowledge = await knowledgeRetriever.queryRelevantKnowledge(task);

  // Agentプロンプトに知識を含める
  const prompt = `
タスク: ${task.description}

関連する過去の経験:
${relevantKnowledge.map(k => `
- ${k.title} (${k.type}, 類似度: ${k.similarity})
  ${k.content.substring(0, 200)}...
  全文: ${k.url}
`).join('\n')}

これらの経験から学び、タスクを実行してください。
`;

  const result = await agent.execute(prompt);

  // 実行から学習
  await knowledgeRetriever.learnFromExecution(task, result);

  return result;
}

完了基準

  • 別の知識リポジトリを作成
  • 自動埋め込み用のGitHub Actionsワークフロー
  • Pinecone統合 (クエリ + アップロード)
  • Agent統合 (実行前クエリ)
  • インシデントレポートテンプレート
  • ポストモーテムテンプレート (5 Whys、タイムライン、アクションアイテム)

検証メトリクス

validation_metrics:
  knowledge_retrieval_relevance_score: ">0.7"  # コサイン類似度
  query_latency: "<500ms"
  agent_past_solutions_reuse_rate: ">30%"

3.2 Postmortem System ⭐⭐

優先度: High 工数: 16時間 ステータス: 未着手

コンセプト

高重要度インシデントが発生した際、テンプレート付きのポストモーテムIssueを自動作成。Agentが協力してセクションを埋める。結果は知識リポジトリに保存。

ポストモーテムテンプレート

# ポストモーテム: [インシデントタイトル]

**日付**: 2025-10-08
**重要度**: Sev.1-Critical
**期間**: 2時間15分
**影響**: 100%のデプロイメントがブロック

## タイムライン

| 時刻 | イベント |
|------|-------|
| 10:00 | インシデント検出: すべてのPRでビルド失敗 |
| 10:05 | CoordinatorAgentがCodeGenAgentに割り当て |
| 10:30 | 根本原因特定: 環境変数が不足 |
| 12:00 | 修正をデプロイ |
| 12:15 | インシデント解決 |

## 根本原因分析 (5 Whys)

1. なぜビルドが失敗したのか? → DATABASE_URL環境変数が不足
2. なぜ環境変数が不足したのか? → .env.exampleに含まれていなかった
3. なぜ.env.exampleに含まれていなかったのか? → リファクタリング中に忘れられた
4. なぜこれが検出されなかったのか? → セットアップスクリプトに検証ステップがない
5. なぜ検証がないのか? → セットアップスクリプトが新しい依存関係で更新されていない

**根本原因**: セットアップスクリプトの検証ステップが欠落

## 影響

- **影響を受けたユーザー**: すべての開発者
- **影響を受けたシステム**: CI/CDパイプライン
- **ビジネスへの影響**: デプロイメントに2時間の遅延

## 解決策

- DATABASE_URLを.env.exampleに追加
- 検証付きでセットアップスクリプトを更新
- .env完全性チェック用のpre-commitフックを追加

## アクションアイテム

- [ ] セットアップスクリプトに環境変数検証を追加 (#123)
- [ ] .env検証用のpre-commitフックを作成 (#124)
- [ ] 必要な環境変数でドキュメントを更新 (#125)
- [ ] .env.example完全性のCIチェックを追加 (#126)

## 教訓

**うまくいったこと:**
- 5分以内にインシデント検出
- 根本原因を迅速に特定
- 2時間以内に修正をデプロイ

**うまくいかなかったこと:**
- セットアップスクリプトに検証がない
- ドキュメントが不完全

**今後の改善:**
- すべてのセットアップスクリプトに検証を追加
- .env.exampleをコードと同期させる

---

Agentic OSによる自動生成

実装例

// agents/knowledge/PostmortemGenerator.ts
export class PostmortemGenerator {
  async generatePostmortem(incident: Incident): Promise<Postmortem> {
    // 1. ポストモーテムIssueを作成
    const issue = await github.issues.create({
      title: `[POSTMORTEM] ${incident.title}`,
      body: this.getPostmortemTemplate(incident),
      labels: ['postmortem', 'knowledge']
    });

    // 2. セクションを埋めるためにAgentを割り当て
    await this.assignPostmortemTasks(issue, incident);

    // 3. 完了を待つ
    await this.waitForCompletion(issue);

    // 4. 知識リポジトリに保存
    await this.storeInKnowledgeRepo(issue);

    return issue;
  }

  private async assignPostmortemTasks(
    issue: Issue,
    incident: Incident
  ): Promise<void> {
    // 各セクションのサブタスクを作成
    await this.createSubTask(issue, 'Fill in Timeline', 'IssueAgent');
    await this.createSubTask(issue, 'Perform 5 Whys Analysis', 'ReviewAgent');
    await this.createSubTask(issue, 'Create Action Items', 'CoordinatorAgent');
    await this.createSubTask(issue, 'Extract Lessons Learned', 'ReviewAgent');
  }
}

完了基準

  • ポストモーテムテンプレート
  • Sev.1-2インシデントの自動ポストモーテム作成
  • ポストモーテムセクションでのAgent協力
  • 知識リポジトリへの保存
  • Vector DBへの埋め込み

検証メトリクス

validation_metrics:
  postmortem_completion_time: "<24時間"
  action_item_completion_rate: ">90%"
  lessons_learned_reuse_rate: ">50%"

3.3 Context Engineering Service ⭐

優先度: Medium 工数: 16時間 ステータス: 未着手

コンセプト

Gemini AIを使用して、非構造化URL/テキストから構造化JSONを抽出。実際のソース資料にAgentを根拠付け。

入力: "https://docs.github.com/en/actions/using-workflows/workflow-syntaxを読んでワークフローを作成"

Context Engineering Service:
1. URLコンテンツを取得
2. Geminiを使用して主要情報を抽出:
   - ワークフロー構文ルール
   - 必須フィールド
   - ベストプラクティス
3. 構造化JSONを返す:
{
  "workflowSyntax": {
    "requiredFields": ["name", "on", "jobs"],
    "jobStructure": {
      "runs-on": "required",
      "steps": "array of step objects"
    },
    "bestPractices": [
      "わかりやすいジョブ名を使用",
      "可能な限り依存関係をキャッシュ"
    ]
  }
}

4. Agentは構造化されたコンテキストを使用してワークフローを生成

実装例

// agents/context/ContextEngineer.ts
export class ContextEngineer {
  private gemini: GeminiClient;

  async extractContext(url: string, query: string): Promise<StructuredContext> {
    // 1. コンテンツを取得
    const content = await this.fetchURL(url);

    // 2. Geminiを使用して関連情報を抽出
    const prompt = `
次のクエリに答えるために、以下のコンテンツから関連情報を抽出してください: "${query}"

コンテンツ:
${content}

クエリに答えるために必要な関連情報のみを含む構造化JSONを返してください。
フォーマット: { "key_concepts": [...], "examples": [...], "best_practices": [...], "gotchas": [...] }
`;

    const response = await this.gemini.generate(prompt);

    // 3. JSONを解析して検証
    const context = JSON.parse(response);

    return context;
  }

  async groundAgentInContext(task: Task): Promise<Task> {
    // タスク説明からURLを検出
    const urls = this.extractURLs(task.description);

    if (urls.length === 0) return task;

    // すべてのURLからコンテキストを抽出
    const contexts = await Promise.all(
      urls.map(url => this.extractContext(url, task.description))
    );

    // 構造化されたコンテキストでタスクを強化
    task.enrichedContext = contexts;

    return task;
  }
}

完了基準

  • Gemini API統合
  • URLコンテンツ取得
  • コンテキスト抽出プロンプトエンジニアリング
  • 構造化JSON検証
  • Agent統合 (自動URL根拠付け)

検証メトリクス

validation_metrics:
  context_extraction_accuracy: ">90%"  # 人間評価
  extraction_latency: "<5秒/URL"
  agent_success_rate_improvement: ">20% with context"

Phase 4: Security & Monitoring (3週間、80時間)

4.1 HashiCorp Vault Dynamic Secrets ⭐⭐⭐

優先度: Critical 工数: 24時間 ステータス: 未着手

コンセプト

静的シークレットゼロ。すべてのシークレット (GitHubトークン、APIキー) を15分のTTLで動的生成。GitHub ActionsはOIDCを使用してVaultと認証。

アーキテクチャ

GitHub Actions (OIDC)
     ↓ (認証)
HashiCorp Vault
     ↓ (15分トークン発行)
GitHub Token (短命)
     ↓ (使用)
GitHub API

メリット

benefits:
  zero_standing_credentials: リポジトリに長期トークンなし
  automatic_rotation: 15分後にトークンが期限切れ
  full_audit_trail: Vaultがすべてのトークン発行をログ
  breach_mitigation: 盗まれたトークンが迅速に期限切れ

実装例

# .github/workflows/agent-execution.yml
name: Agent Execution

on:
  issues:
    types: [labeled]

permissions:
  id-token: write  # OIDCに必要
  contents: write

jobs:
  execute-task:
    runs-on: ubuntu-latest
    steps:
      - name: Authenticate with Vault
        id: vault
        uses: hashicorp/vault-action@v2
        with:
          url: ${{ secrets.VAULT_ADDR }}
          method: jwt
          role: github-actions
          jwtGithubAudience: https://github.com/${{ github.repository }}
          secrets: |
            secret/data/github token | GITHUB_TOKEN

      - name: Use short-lived token
        env:
          GITHUB_TOKEN: ${{ steps.vault.outputs.GITHUB_TOKEN }}
        run: |
          # トークンは15分で期限切れ
          gh issue comment ${{ github.event.issue.number }} --body "実行開始..."

Vault設定:

# vault/github-policy.hcl
path "secret/data/github" {
  capabilities = ["read"]
}

# vault/github-role.hcl
resource "vault_jwt_auth_backend_role" "github_actions" {
  backend        = "jwt"
  role_name      = "github-actions"
  token_ttl      = 900  # 15分
  token_policies = ["github-policy"]

  bound_claims = {
    sub = "repo:${var.github_repo}:*"
  }

  user_claim = "actor"
  role_type  = "jwt"
}

完了基準

  • Vaultサーバーのセットアップ (ローカルまたはクラウド)
  • OIDC認証設定
  • GitHub Token動的シークレットエンジン
  • 15分TTLの強制
  • 監査ログ有効化
  • GitHub Actions統合
  • セットアップ用ドキュメント

検証メトリクス

validation_metrics:
  token_issuance_success_rate: "100%"
  token_expiration_compliance: "100%"  # 15分以上のトークンなし
  audit_log_completeness: "100%"

4.2 KPI Monitoring System ⭐⭐

優先度: High 工数: 16時間 ステータス: 未着手

コンセプト

各Agentの組織設計KPIの自動収集。リアルタイムダッシュボード。SLA違反時のアラート。

追跡するKPI

AgentKPI目標測定方法
CoordinatorAgentタスク割り当て精度>95%正しいAgentへの割り当て率
CoordinatorAgent競合解決時間<5分検出から解決までの平均時間
CodeGenAgent実装完全性100%受け入れ基準達成率
CodeGenAgentテストカバレッジ>80%コードカバレッジ率
CodeGenAgentビルド成功率100%ビルド成功率
ReviewAgent品質スコア>85平均品質スコア
ReviewAgentレビュー所要時間<30分依頼から完了までの時間
IssueAgentトリアージ時間<5分ラベル付けと割り当ての時間
PRAgentPR作成時間<10分コード完了からPRまでの時間
DeploymentAgentデプロイメント成功率>99%デプロイメント成功率

実装例

// agents/monitoring/KPICollector.ts
export class KPICollector {
  async collectKPIs(
    period: 'daily' | 'weekly' | 'monthly'
  ): Promise<KPIReport> {
    const report: KPIReport = {
      period,
      startDate: this.getPeriodStart(period),
      endDate: new Date(),
      agents: {}
    };

    for (const agentType of Object.values(AgentType)) {
      report.agents[agentType] = await this.collectAgentKPIs(agentType, period);
    }

    // SLAコンプライアンスをチェック
    report.slaBreaches = await this.detectSLABreaches(report);

    // アラートを生成
    if (report.slaBreaches.length > 0) {
      await this.alertGuardian(report.slaBreaches);
    }

    // レポートを保存
    await this.storeReport(report);

    return report;
  }

  private async collectAgentKPIs(
    agentType: AgentType,
    period: string
  ): Promise<AgentKPIs> {
    const logs = await this.queryLogs(agentType, period);

    return {
      taskCompletionRate: this.calculateCompletionRate(logs),
      avgQualityScore: this.calculateAvgQuality(logs),
      avgDuration: this.calculateAvgDuration(logs),
      escalationRate: this.calculateEscalationRate(logs),
      // ... その他のKPI
    };
  }

  private async detectSLABreaches(report: KPIReport): Promise<SLABreach[]> {
    const breaches: SLABreach[] = [];

    for (const [agentType, kpis] of Object.entries(report.agents)) {
      const targets = AGENT_RESPONSIBILITIES[agentType].kpis;

      for (const target of targets) {
        const actual = kpis[target.name];
        if (!this.meetsTarget(actual, target.target)) {
          breaches.push({
            agentType,
            kpi: target.name,
            target: target.target,
            actual,
            severity: this.calculateSeverity(target.target, actual)
          });
        }
      }
    }

    return breaches;
  }
}

ダッシュボード

// scripts/kpi-dashboard.ts
import blessed from 'blessed';

function createDashboard() {
  const screen = blessed.screen({ smartCSR: true });

  // ヘッダー
  const header = blessed.box({
    top: 0,
    left: 0,
    width: '100%',
    height: 3,
    content: '{center}Agentic OS - KPIダッシュボード{/center}',
    style: { fg: 'cyan', bold: true }
  });

  // Agent KPIテーブル
  const table = blessed.table({
    top: 3,
    left: 0,
    width: '100%',
    height: '50%',
    data: [
      ['Agent', 'タスク完了', '品質スコア', '平均期間', 'ステータス'],
      ['CoordinatorAgent', '98%', '---', '3分', '✅'],
      ['CodeGenAgent', '95%', '87', '45分', '✅'],
      ['ReviewAgent', '100%', '92', '20分', '✅'],
      ['IssueAgent', '99%', '---', '2分', '✅'],
      ['PRAgent', '97%', '---', '8分', '✅'],
      ['DeploymentAgent', '100%', '---', '15分', '✅']
    ],
    style: { header: { fg: 'yellow', bold: true } }
  });

  // SLA違反
  const breaches = blessed.list({
    top: '50%',
    left: 0,
    width: '100%',
    height: '50%',
    label: ' SLA違反 ',
    items: [
      '⚠️ CodeGenAgent: テストカバレッジ 78% (目標: >80%)',
      '⚠️ PRAgent: PR作成時間 12分 (目標: <10分)'
    ],
    style: { fg: 'red' }
  });

  screen.append(header);
  screen.append(table);
  screen.append(breaches);

  screen.key(['escape', 'q', 'C-c'], () => process.exit(0));
  screen.render();

  // 10秒ごとに自動更新
  setInterval(() => {
    // KPIを更新
    screen.render();
  }, 10000);
}

createDashboard();

完了基準

  • 自動KPI収集 (日次、週次、月次)
  • KPI保存 (.ai/reports/kpi-{period}-{date}.json)
  • SLA違反検出
  • 違反時のGuardianアラート
  • リアルタイムダッシュボード (blessedまたはtmuxベース)

検証メトリクス

validation_metrics:
  kpi_collection_completeness: "100%"
  sla_breach_detection_accuracy: "100%"
  alert_delivery_latency: "<60秒"

4.3 MCP Server for External Integration ⭐

優先度: Medium 工数: 24時間 ステータス: 未着手

コンセプト

Model Context Protocol (MCP) サーバーがAgentic OSの機能を外部ツール (Lark、Slack、カスタムCLI) に公開。

MCPサーバー機能

// mcp-server/capabilities.ts
export const AGENTIC_OS_CAPABILITIES = {
  // タスク管理
  'agentic-os.createTask': async (params: { title: string, description: string }) => {
    // GitHub Issueを作成
    // 適切なAgentに割り当て
    // タスクIDを返す
  },

  'agentic-os.getTaskStatus': async (params: { taskId: string }) => {
    // GitHubからタスクステータスをクエリ
    // 現在のAgent、進捗、ETAを返す
  },

  // Agent制御
  'agentic-os.listAgents': async () => {
    // 現在のステータスですべてのAgentを返す
  },

  'agentic-os.triggerAgent': async (params: { agentType: string, task: Task }) => {
    // 特定のAgentを手動でトリガー
  },

  // 知識
  'agentic-os.searchKnowledge': async (params: { query: string }) => {
    // 関連する知識をVector DBでクエリ
  },

  // 監視
  'agentic-os.getKPIs': async (params: { period: string }) => {
    // KPIレポートを返す
  }
};

クライアント例 (Lark Bot)

// integrations/lark-bot/index.ts
import { MCPClient } from '@modelcontextprotocol/sdk';

const client = new MCPClient('agentic-os-server');

// ユーザーがLarkで入力: "/task ログイン機能を作成"
larkBot.onCommand('/task', async (message) => {
  const result = await client.call('agentic-os.createTask', {
    title: message.text,
    description: `Lark経由で${message.user}がリクエスト`
  });

  await larkBot.reply(`タスクを作成: #${result.taskId}\n割り当て: ${result.agent}\n追跡: ${result.url}`);
});

// ユーザーが入力: "/status #123"
larkBot.onCommand('/status', async (message) => {
  const taskId = message.text.match(/#(\d+)/)[1];
  const status = await client.call('agentic-os.getTaskStatus', { taskId });

  await larkBot.reply(`
タスク #${taskId}: ${status.title}
Agent: ${status.agent}
進捗: ${status.progress}%
ETA: ${status.eta}
  `);
});

完了基準

  • MCPサーバー実装
  • 10以上の機能を公開
  • 認証と認可
  • レート制限
  • クライアントSDK (TypeScript)
  • 統合例 (Lark、Slack)

検証メトリクス

validation_metrics:
  api_response_time: "<200ms (p95)"
  api_availability: ">99.9%"
  authentication_success_rate: "100%"

4.4 Continuous Monitoring with Prometheus & Grafana ⭐

優先度: Medium 工数: 16時間 ステータス: 未着手

コンセプト

Agentic OSメトリクスをPrometheusにエクスポートし、Grafanaダッシュボードで可視化。

エクスポートするメトリクス

// agents/monitoring/PrometheusExporter.ts
import { register, Counter, Histogram, Gauge } from 'prom-client';

// タスクメトリクス
const taskCompletionCounter = new Counter({
  name: 'agentic_os_task_completions_total',
  help: '完了したタスクの総数',
  labelNames: ['agent_type', 'status'] // status: success, failure, partial
});

const taskDurationHistogram = new Histogram({
  name: 'agentic_os_task_duration_seconds',
  help: 'タスク実行期間',
  labelNames: ['agent_type'],
  buckets: [30, 60, 120, 300, 600, 1800, 3600] // 秒
});

// Agentメトリクス
const activeAgentsGauge = new Gauge({
  name: 'agentic_os_active_agents',
  help: '現在アクティブなAgentの数',
  labelNames: ['agent_type']
});

// 品質メトリクス
const qualityScoreGauge = new Gauge({
  name: 'agentic_os_quality_score',
  help: '現在の品質スコア',
  labelNames: ['agent_type']
});

// 予算メトリクス
const budgetUsageGauge = new Gauge({
  name: 'agentic_os_budget_usage_usd',
  help: 'USD単位の現在の予算使用量',
  labelNames: ['period'] // period: daily, monthly
});

// メトリクスエンドポイントをエクスポート
export function setupMetricsEndpoint(app: Express) {
  app.get('/metrics', async (req, res) => {
    res.set('Content-Type', register.contentType);
    res.end(await register.metrics());
  });
}

Grafanaダッシュボード

{
  "dashboard": {
    "title": "Agentic OS Monitoring",
    "panels": [
      {
        "title": "タスク完了率",
        "targets": [
          {
            "expr": "rate(agentic_os_task_completions_total{status=\"success\"}[5m])"
          }
        ]
      },
      {
        "title": "タスク期間 (p95)",
        "targets": [
          {
            "expr": "histogram_quantile(0.95, rate(agentic_os_task_duration_seconds_bucket[5m]))"
          }
        ]
      },
      {
        "title": "アクティブAgent",
        "targets": [
          {
            "expr": "agentic_os_active_agents"
          }
        ]
      },
      {
        "title": "予算使用量",
        "targets": [
          {
            "expr": "agentic_os_budget_usage_usd{period=\"monthly\"}"
          }
        ]
      }
    ]
  }
}

完了基準

  • Prometheusメトリクスエクスポーター
  • 20以上のメトリクスをエクスポート
  • Grafanaダッシュボード JSON
  • アラートルール (予算>80%、SLA違反)
  • セットアップ用ドキュメント

検証メトリクス

validation_metrics:
  metrics_collection_reliability: "100%"
  scrape_latency: "<100ms"
  dashboard_load_time: "<2秒"

実装タイムライン

月1 (週1-4): Phase 1 - Foundation
├─ 週1: Six-Agent System (24h) + 組織設計Framework (24h)
├─ 週2: Economic Circuit Breaker (16h) + Agent Security Rules (16h)
├─ 週3: Enhanced Logging System (16h) + ドキュメント
└─ 週4: テスト + バグ修正

月2 (週5-7): Phase 2 - Parallel Execution
├─ 週5: DAG Dependency Resolution (12h) + Parallel Execution (16h)
├─ 週6: Resource-Based Concurrency (12h) + テスト
└─ 週7: 24/7 Autonomous System (20h) + 統合テスト

月3 (週8-11): Phase 3 - Knowledge Persistence
├─ 週8: Knowledge Persistence Layer (32h)
├─ 週9: Postmortem System (16h)
├─ 週10: Context Engineering Service (16h)
└─ 週11: テスト + ドキュメント

月4 (週12-14): Phase 4 - Security & Monitoring
├─ 週12: HashiCorp Vault (24h)
├─ 週13: KPI Monitoring (16h) + MCP Server (24h)
└─ 週14: Prometheus/Grafana (16h) + 最終テスト

総期間: 14週間 (1 FTE) 加速オプション: 7週間 (2 FTE)


成功メトリクス

Phase 1成功基準

phase_1_criteria:
  - "全6種類のAgent実装とテスト完了"
  - "組織設計KPIが定義され測定可能"
  - "Economic circuit breaker動作"
  - "セキュリティルールが強制されている"
  - "構造化ログシステム稼働"

Phase 2成功基準

phase_2_criteria:
  - "サイクル検出を含むDAGベース実行"
  - "70%以上の時間削減を達成する並列実行"
  - "介入なしで24/7自律システムが実行"
  - "OOMを防ぐリソースベースの並行処理"

Phase 3成功基準

phase_3_criteria:
  - "知識検索システムが稼働"
  - "Agentが実行前に知識をクエリ"
  - "Sev.1-2インシデントの自動生成ポストモーテム"
  - "Context engineeringがAgentの成功率を20%以上向上"

Phase 4成功基準

phase_4_criteria:
  - "静的シークレットゼロ (すべてVaultで動的)"
  - "リアルタイムダッシュボード付きKPI監視"
  - "10以上の機能を公開するMCPサーバー"
  - "Prometheus/Grafana監視稼働"

全体的な成功メトリクス

overall_success_metrics:
  efficiency_gain: "マルチタスク操作で10倍"
  time_reduction: "順次実行比70%以上"
  automation_rate: "90%以上 (人間介入<10%)"
  auto_recovery: "一時的な障害から95%以上"
  security: "静的シークレットゼロ、すべて<15分TTL"
  quality: "平均品質スコア85以上"
  uptime: "自律システム稼働率99.9%"

開始方法

前提条件

prerequisites:
  - Node.js 20+
  - Git
  - GitHub CLI (gh)
  - Claude Code CLI
  - tmux (24/7システム用)
  - Docker (Vault、Prometheus、Grafana用)

クイックスタート

# 1. 参照用にai-course-content-generatorをクローン
git clone https://github.com/user/ai-course-content-generator-v.0.0.1 ../reference

# 2. 分析レポートをレビュー
cat docs/analysis/agentic-os-integration-report.json | jq

# 3. Phase 1から開始
npm run implement:phase-1

# 4. docs/integration/ の統合ガイドに従う

関連ドキュメント

前提となるドキュメント

実装ガイド

詳細仕様


次のステップ

このドキュメント完了後

  1. workflow-integration.md を読んで既存の統合実績を学ぶ
  2. Phase 1実装 を開始
  3. Guides で実践的な使い方を学ぶ

質問がある場合


ドキュメントステータス: ✅ 完全 次のステップ: Guardian承認とレビュー、Phase 1実装開始 所有者: Guardian (@ShunsukeHayashi) 最終更新: 2025-10-10 バージョン: 1.0.0 ソース: INTEGRATION_ROADMAP.md