Agent階層システム
概要: Agent階層システムは、3層構造(Human/Coordinator/Specialist)による明確な責任・権限・エスカレーション経路を持つ自律型AI開発システムです。各Agentは専門性を持ち、組織設計原則に基づいて協調動作します。
対象読者: アーキテクト / 実装者 所要時間: 15分 前提知識: システム全体像
Agent階層構造
3層アーキテクチャ
┌─────────────────────────────────────────────────┐
│ Human Layer (戦略・承認) │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │TechLead │ │ PO │ │ CISO │ │
│ └────┬────┘ └────┬────┘ └────┬────┘ │
└───────┼───────────┼────────────┼──────────────┘
│ │ │
Escalation Escalation Escalation
│ │ │
┌───────┴───────────┴────────────┴──────────────┐
│ Coordinator Layer (統括) │
│ ┌──────────────────────────────────┐ │
│ │ CoordinatorAgent │ │
│ │ - タスク分解 (DAG構築) │ │
│ │ - Agent割り当て │ │
│ │ - 並行実行制御 │ │
│ │ - 進捗モニタリング │ │
│ └──────────┬────────────┬──────────┘ │
└─────────────┼────────────┼────────────────────┘
│ │
Dispatch Dispatch
│ │
┌─────────────┴────────────┴────────────────────┐
│ Specialist Layer (実行) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │CodeGen │ │Review │ │Issue │ │
│ │Agent │ │Agent │ │Agent │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ │
│ │PR │ │Deployment│ │
│ │Agent │ │Agent │ │
│ └──────────┘ └──────────┘ │
└────────────────────────────────────────────┘
層ごとの責任範囲
| 層 | 役割 | 責任範囲 | 権限 |
|---|---|---|---|
| Human Layer | 戦略決定・承認 | - アーキテクチャ決定<br>- 本番デプロイ承認<br>- セキュリティポリシー決定 | 最終決定権 |
| Coordinator Layer | 統括・調整 | - タスク分解<br>- Agent割り当て<br>- 並行実行制御 | リソース配分決定 |
| Specialist Layer | 専門実行 | - コード生成<br>- 品質判定<br>- デプロイ実行 | 実装レベル決定 |
Coordinator Layer
CoordinatorAgent
責務: タスク分解・Agent統括・並行実行制御
主要機能
1. タスク分解(Decomposition)
async decomposeTask(issue: Issue): Promise<Task[]> {
// 1. Issue本文から要件抽出
const requirements = await this.extractRequirements(issue);
// 2. タスク粒度判定(1-3時間単位)
const tasks = await this.breakdownIntoTasks(requirements);
// 3. 依存関係識別
const dependencies = await this.identifyDependencies(tasks);
// 4. 優先度・Severity評価
const prioritizedTasks = await this.prioritize(tasks, dependencies);
return prioritizedTasks;
}
例: Issue「Firebase Auth修正」の分解
Issue #270: Firebase Auth invalid-credential エラー修正
分解結果:
task-1:
description: "Firebase認証エラー原因特定"
priority: 1
dependencies: []
estimated_duration: 10分
task-2:
description: "E2Eテスト追加(Playwright)"
priority: 2
dependencies: [task-1]
estimated_duration: 5分
task-3:
description: "ドキュメント更新"
priority: 3
dependencies: [task-1, task-2]
estimated_duration: 3分
2. DAG構築(Dependency Graph)
async buildDAG(tasks: Task[]): Promise<DAG> {
// トポロジカルソート
const sorted = this.topologicalSort(tasks);
// 循環依存検出
if (this.hasCyclicDependency(sorted)) {
throw new Error('Circular dependency detected');
}
return {
nodes: tasks,
edges: this.buildEdges(tasks),
levels: this.computeLevels(sorted)
};
}
DAG例:
Level 1: [task-1]
Level 2: [task-2]
Level 3: [task-3]
task-1 → task-2 → task-3
3. 並行実行制御(Parallel Execution)
async executeParallel(dag: DAG, concurrency: number): Promise<Result[]> {
const results: Result[] = [];
// レベル順に実行
for (const level of dag.levels) {
const chunks = this.chunkArray(level, concurrency);
for (const chunk of chunks) {
// 同一レベル内は並行実行
const chunkResults = await Promise.all(
chunk.map(task => this.executeTask(task))
);
results.push(...chunkResults);
}
}
return results;
}
エスカレーション条件
| 条件 | エスカレーション先 | 理由 |
|---|---|---|
| タスク分解不能 | TechLead / PO | 要件不明確 |
| 技術的制約 | TechLead | 実現不可能判定 |
| リソース不足 | PO | 予算・時間超過 |
Specialist Layer
1. CodeGenAgent
責務: AI駆動コード生成・テスト自動生成
主要機能
export class CodeGenAgent extends BaseAgent {
async generateCode(spec: Specification): Promise<Code> {
// 1. 既存コードベース解析
const context = await this.analyzeCodebase();
// 2. アーキテクチャパターン適用
const pattern = this.selectPattern(spec.type);
// 3. TypeScript型安全性確保
const code = await this.generateTypeSafeCode(spec, pattern, context);
// 4. コメント・ドキュメント生成
await this.addDocumentation(code);
return code;
}
async generateTests(code: Code): Promise<Test[]> {
// 1. 単体テスト生成(Vitest/Jest)
const unitTests = await this.generateUnitTests(code);
// 2. E2Eテスト生成(Playwright)
const e2eTests = await this.generateE2ETests(code);
// 3. カバレッジ80%以上確保
await this.ensureCoverage(unitTests, e2eTests, 80);
return [...unitTests, ...e2eTests];
}
}
エスカレーション条件
| 条件 | エスカレーション先 | 理由 |
|---|---|---|
| TypeScriptコンパイルエラー(自動修正不能) | TechLead | 手動修正必要 |
| アーキテクチャ整合性違反 | TechLead | 設計判断必要 |
| セキュリティリスク検出 | CISO | セキュリティ審査 |
2. ReviewAgent
責務: 静的解析・セキュリティスキャン・品質判定
品質スコア算出
export class ReviewAgent extends BaseAgent {
async reviewCode(code: Code): Promise<ReviewResult> {
let score = 100;
// 静的解析
const eslintErrors = await this.runESLint(code);
score -= eslintErrors.length * 20;
// TypeScript型チェック
const tsErrors = await this.runTypeCheck(code);
score -= tsErrors.length * 30;
// セキュリティスキャン
const vulnerabilities = await this.runSecurityScan(code);
score -= vulnerabilities.critical * 40;
score -= vulnerabilities.high * 20;
score -= vulnerabilities.medium * 10;
return {
score,
passed: score >= 80,
issues: [...eslintErrors, ...tsErrors, ...vulnerabilities]
};
}
}
合格基準
quality_gate:
threshold: 80点
criteria:
- total_score: ≥80
- critical_vulnerabilities: 0
- typescript_errors: 0
- test_coverage: ≥80%
エスカレーション条件
| 条件 | エスカレーション先 | 理由 |
|---|---|---|
| Critical脆弱性検出 | CISO | 即座対応必須 |
| セキュリティポリシー違反 | CISO | ポリシー審査 |
| アーキテクチャ重大違反 | TechLead | 設計レビュー |
3. IssueAgent
責務: Issue自動分析・Label付与・担当者割り当て
Label体系(組織設計原則)
export class IssueAgent extends BaseAgent {
async analyzeIssue(issue: Issue): Promise<AnalysisResult> {
// 1. Issue種別判定(feature/bug/refactor/docs)
const type = await this.classifyType(issue);
// 2. Severity評価(Sev.1-5)
const severity = await this.evaluateSeverity(issue);
// 3. 影響度評価(Critical/High/Medium/Low)
const impact = await this.evaluateImpact(issue);
// 4. Label自動付与(組織設計原則体系)
const labels = this.selectLabels(type, severity, impact);
// 5. 担当者割り当て(CODEOWNERS参照)
const assignee = await this.assignResponsible(labels);
return {
type,
severity,
impact,
labels,
assignee
};
}
}
Label分類
| カテゴリ | Label例 | 意味 |
|---|---|---|
| 責任者 | 👤担当-開発者 | 実行権限 |
| 👥担当-テックリード | 確認権限 | |
| 👑担当-PO | 決裁権限 | |
| 🤖担当-AI Agent | 自動実行 | |
| Severity | 🔥Sev.1-Critical | 即座対応必須 |
| ⭐Sev.2-High | 24時間以内 | |
| ➡️Sev.3-Medium | 1週間以内 | |
| 📝Sev.4-Low | 優先度低 | |
| 💡Sev.5-Idea | アイデア | |
| 影響度 | 📊影響度-Critical | システム停止 |
| 📊影響度-High | 主要機能影響 | |
| 📊影響度-Medium | 一部機能影響 | |
| 📊影響度-Low | 軽微な影響 | |
| Agent | 🤖CodeGenAgent | コード生成担当 |
| 🤖ReviewAgent | レビュー担当 | |
| 🤖DeploymentAgent | デプロイ担当 | |
| 業務 | ✨feature | 新機能開発 |
| 🐛bug | バグ修正 | |
| 🔧refactor | リファクタリング | |
| 📚docs | ドキュメント |
4. PRAgent
責務: PR自動作成・説明文生成・Reviewer割り当て
PR自動生成
export class PRAgent extends BaseAgent {
async createPullRequest(branch: string, issue: Issue): Promise<PR> {
const description = await this.generateDescription(issue);
const pr = await octokit.pulls.create({
title: `${issue.type}: ${issue.title}`,
body: `
## 概要
${issue.description}
## 変更内容
${description.changes}
## テスト結果
${description.testResults}
## チェックリスト
- [x] ESLint通過
- [x] TypeScriptコンパイル成功
- [x] テストカバレッジ80%以上
- [x] セキュリティスキャン通過
Closes #${issue.number}
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
`,
draft: true,
base: "main",
head: branch
});
return pr;
}
}
責任範囲
- PR自動作成(Draft)
- 説明文自動生成
- Reviewer自動割り当て
- Closes #xxx 自動記載
5. DeploymentAgent
責務: CI/CD実行・デプロイ・Rollback
デプロイフロー
export class DeploymentAgent extends BaseAgent {
async deploy(environment: "staging" | "production"): Promise<DeployResult> {
// 1. ビルド検証
await this.runBuild();
// 2. E2Eテスト実行
await this.runE2ETests();
// 3. Firebase Deploy
const result = await this.firebaseDeploy(environment);
// 4. ヘルスチェック
await this.healthCheck(result.url);
// 5. Rollback準備
await this.prepareRollback();
return result;
}
}
デプロイ手順
deployment_process:
step_1:
action: "npm run build"
criteria: "ビルド成功"
step_2:
action: "npm run test:e2e"
criteria: "成功率90%以上"
step_3:
action: "Deploy to Staging"
approval: "自動"
step_4:
action: "Deploy to Production"
approval: "人間承認必須"
step_5:
action: "Health Check"
criteria: "30秒以内レスポンス"
エスカレーション条件
| 条件 | エスカレーション先 | 理由 |
|---|---|---|
| ビルド失敗 | TechLead | 手動修正必要 |
| E2Eテスト失敗率10%超 | TechLead | 品質基準未達 |
| 本番デプロイ障害 | PO + CTO | 緊急対応 |
Agent間連携プロトコル
メッセージ形式
interface AgentMessage {
from: AgentId;
to: AgentId;
type: 'request' | 'response' | 'notification';
payload: {
action: string;
data: any;
metadata: {
timestamp: Date;
priority: number;
sessionId: string;
};
};
}
連携例:Issue処理フロー
1. IssueAgent → CoordinatorAgent
{
type: 'request',
action: 'analyze_issue',
data: { issue_number: 270 }
}
2. CoordinatorAgent → CodeGenAgent
{
type: 'request',
action: 'generate_code',
data: {
task: 'Fix Firebase Auth',
files: ['src/auth/login.ts']
}
}
3. CodeGenAgent → ReviewAgent
{
type: 'notification',
action: 'code_ready_for_review',
data: { branch: 'fix/270-auth-bug' }
}
4. ReviewAgent → CoordinatorAgent
{
type: 'response',
action: 'review_completed',
data: {
score: 95,
passed: true
}
}
5. CoordinatorAgent → PRAgent
{
type: 'request',
action: 'create_pr',
data: {
branch: 'fix/270-auth-bug',
issue: 270
}
}
実装ガイドライン
BaseAgent実装
すべてのAgentはBaseAgentを継承:
// agents/base-agent.ts
export abstract class BaseAgent {
protected logger: Logger;
protected metrics: MetricsCollector;
abstract async execute(task: Task): Promise<AgentResult>;
protected async escalate(reason: string, target: string): Promise<void> {
// エスカレーションロジック
}
protected async recordMetrics(data: MetricData): Promise<void> {
// メトリクス記録
}
protected log(message: string, level: LogLevel = 'info'): void {
// ログ出力
}
}
エラーハンドリング
try {
const result = await agent.execute(task);
if (!result.success) {
// リトライ(最大3回)
await this.retry(agent, task, 3);
}
} catch (error) {
// エスカレーション
await agent.escalate(error.message, 'TechLead');
// ログ記録
await this.recordError(error, task);
}
KPI・メトリクス
Agent別KPI
| Agent | KPI | 目標値 | 計測方法 |
|---|---|---|---|
| CoordinatorAgent | タスク分解正確率 | 95% | 人間評価 |
| CodeGenAgent | コード生成成功率 | 90% | コンパイル成功率 |
| ReviewAgent | 品質スコア平均 | 85点 | 自動算出 |
| IssueAgent | Label付与正確率 | 100% | CODEOWNERS適合率 |
| PRAgent | PR自動作成成功率 | 95% | API成功率 |
| DeploymentAgent | デプロイ成功率 | 98% | ヘルスチェック |
自動収集
# Agent別メトリクス収集
npm run metrics:collect -- --agent=CodeGenAgent
# ダッシュボード更新
npm run dashboard:update
関連ドキュメント
- システム全体像 - 全体構成
- 並行実行アーキテクチャ - 並行実行の詳細
- 組織設計原則 - 5原則実装
- Agent運用マニュアル - 運用ガイド
次のステップ
- 並行実行アーキテクチャ - Agent並行実行の仕組みを学ぶ
- Agent運用マニュアル - 実際の運用方法を理解する
最終更新: 2025-10-10 バージョン: 2.0.0 管理者: AI Operations Lead