mcpField
G
goal-seeking-agent-pattern

goal-seeking-agent-pattern

github.com/rysweetエージェントワークフロー76156 回インストール21 週間前に更新
リポジトリ

goal-seeking-agent-pattern について

goal-seeking-agent-patternは、経路が固定されない複数段階のタスクを扱う開発者向けの、目標駆動型エージェント設計ガイドです。目標分析、フェーズ計画、状態追跡、失敗からの復旧に加え、goal_agent_generatorとの連携を説明します。

主な機能

  1. 01自然言語の目標をフェーズに分解
  2. 02フェーズ依存関係と並列処理の管理
  3. 03成功基準に照らした進捗の追跡
  4. 04再試行や代替策による復旧
  5. 05goal_agent_generatorとの連携

活用シーン

  1. 01依存フェーズを含むデータ処理の計画
  2. 02CI失敗の診断と修正案の試行
  3. 03実行環境に応じたリリース手順の調整
  4. 04目標プロンプトからのエージェント生成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/rysweet/amplihack --skill goal-seeking-agent-pattern

インストール後、Claude Code で/goal-seeking-agent-patternを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

README.md
examples/
adaptive_testing.md
data_pipeline.md
workflow_automation.md
templates/
goal_prompt_template.md
integration_guide.md
tests/
test_skill_activation.md

詳細

目標追求型エージェントのパターンに関するスキル

1. 目標追求型エージェントとは?

目標追求型エージェントは、複数フェーズにわたる目標を次のように実行する自律型 AI エージェントです。

  1. 高レベルの目標を理解する:明示的な手順を指定せず、自然言語で目標を受け付けます
  2. 実行を計画する:目標を、依存関係と成功基準を含むフェーズに分割します
  3. 自律的に実行する:中間結果に基づいて判断し、動作を適応させます
  4. 自己評価する:成功基準に照らして進捗を評価し、アプローチを調整します
  5. 回復力をもって動作する:失敗に適切に対処し、代替ソリューションを探ります
主な特徴

自律性:エージェントは、規定された手順に従うだけでなく、目標を達成する方法を判断します

適応性:実行時の状況や中間結果に基づいて戦略を調整します

目標指向:手順(どのように達成するか)ではなく、成果(何を達成するか)に重点を置きます

複数フェーズ:複雑な目標を、依存関係を含む管理可能なフェーズに分解します

自己監視:進捗を追跡し、失敗を検出して、自律的に軌道修正します

従来型エージェントとの違い
従来型エージェント目標追求型エージェント
固定されたワークフローに従う状況に合わせてワークフローを適応させる
規定された手順成果指向の目標
失敗時に人間が介入自律的に復旧を試みる
単一フェーズで実行依存関係を含む複数フェーズ
固定的な判断ツリー動的に戦略を調整
目標追求型が適しているケース

目標追求型エージェントは、次のような場合に優れた効果を発揮します。

  • 問題空間が広い:成功への道筋が多数あります
  • 状況が変化する:実行時の状況が最適なアプローチに影響します
  • 失敗が想定される:人間の介入なしに自律的な復旧が必要です
  • 目標が明確である:成功基準は明確ですが、道筋には柔軟性があります
  • 複数ステップが複雑である:依存関係のあるフェーズ間での調整が必要です
目標追求型を避けるべきケース

次のような場合は、従来型エージェントまたはスクリプトを使用してください。

  • 決定論的な道筋が1つだけ:目標を達成する方法が1つしかありません
  • レイテンシが重要:可能な限り最速の実行が必要です(判断によるオーバーヘッドを避けます)
  • 安全性が重要:各ステップで人間による確認が必要です
  • ワークフローが単純:目標追求型の複雑さが利点を上回ります
  • 監査要件がある:決定論的で再現可能な実行が必要です

2. このパターンを使用する場面

問題を示す兆候

次のようなパターンが見られる場合は、目標追求型エージェントを使用してください。

パターン1:ワークフローの変動性

兆候:

  • 同じ目標でも、状況に応じて異なるアプローチが必要です
  • 複数の時点で手動による判断が必要です
  • ワークフローを整理すると、「状況によります」という回答になります

例:次の要因によって変化するリリースワークフロー:

  • 環境(ステージングと本番)
  • 変更の種類(ホットフィックスと機能追加)
  • 現在のシステム状態(正常と劣化)

解決策:目標追求型エージェントが状況を評価し、ワークフローを適応させます

パターン2:複数フェーズの複雑さ

兆候:

  • 目標の達成に、3~5つ以上の異なるフェーズが必要です
  • フェーズ間に依存関係があります(フェーズNの出力がフェーズN+1に渡されます)
  • 並列実行できる機会があります
  • フェーズごとに成功基準が異なります

例:次のフェーズで構成されるデータパイプライン:

  1. データ収集(複数のソース、並列実行)
  2. 変換(収集結果に依存)
  3. 検証(変換結果に依存)
  4. 公開(検証に合格した場合に実行)

解決策:目標追求型エージェントがフェーズを統括し、依存関係に対応します

パターン 3:自律的な復旧が必要

指標:

  • 失敗が予想され、復旧可能です
  • 複数の再試行/フォールバック戦略があります
  • 人間の介入には多くのコストや時間がかかります
  • 成功をプログラムで検証できます

例:CI 診断ワークフロー:

  • テストの失敗(別の方法で再試行)
  • 環境の問題(再設定して再試行)
  • 依存関係の競合(解決して再実行)

解決策:目標志向型エージェントが、成功するかエスカレーションするまで戦略を試します

パターン 4:適応的な意思決定

指標:

  • 実行時にトレードオフを評価する必要があります
  • 特性の異なる有効な解決策が複数あります
  • 最適化の目標があります(速度対品質対コスト)
  • コンテキストに応じたベストプラクティスがあります

例:修正エージェントのパターンマッチング:

  • 明らかな問題には QUICK モード
  • 不明瞭な問題には DIAGNOSTIC モード
  • 複雑な解決策には COMPREHENSIVE モード

解決策:目標志向型エージェントが問題の分析に基づいて戦略を選択します

パターン 5:ドメインの専門知識が必要

指標:

  • 実行には専門知識が必要です
  • ドメイン固有のツール/アプローチが複数あります
  • ベストプラクティスはドメインによって異なります
  • 専門のサブエージェントを連携させます

例:AKS SRE 自動化:

  • Azure 固有の操作(ARM、CLI)
  • Kubernetes の専門知識(kubectl、YAML)
  • ネットワークの知識(CNI、ingress)
  • セキュリティのプラクティス(RBAC、Key Vault)

解決策:ドメインの専門知識を備えた目標志向型エージェントが、専門的なアクションを連携させます

判断フレームワーク

この 5 つの質問からなるフレームワークを使って、目標志向型アプローチの適用可能性を評価します。

質問 1:目標は明確に定義されているものの、手順には柔軟性がありますか?

YES の場合:

  • 明確な成功基準があります
  • 有効なアプローチが複数あります
  • 実行時のコンテキストが最適な手順に影響します

NO の場合:

  • 正しいアプローチは 1 つだけです
  • 手順は決定論的です
  • 成功基準が曖昧です

YES の例:「AKS クラスターを本番環境に対応させる」(複数の手順があり、基準は明確) NO の例:「特定の kubectl コマンドを実行する」(手順は 1 つで、方法が指定されています)

質問 2:依存関係のある複数のフェーズがありますか?

YES の場合:

  • 目標を自然に 3~5 つ以上のフェーズに分割できます
  • フェーズの出力が後続のフェーズに渡されます
  • 一部のフェーズは並行して実行できます
  • あるフェーズの失敗が後続のフェーズに影響します

NO の場合:

  • 1 つのフェーズだけで実行できます
  • フェーズ間の依存関係はありません
  • 分岐のない、完全に逐次的な処理です

YES の例:データパイプライン(収集 → 変換 → 検証 → 公開) NO の例:ruff でコードをフォーマットする(1 つのアトミックな操作)

質問 3:自律的な復旧に価値がありますか?

YES の場合:

  • 失敗が頻繁に発生し、予想されます
  • 復旧戦略が複数あります
  • 人間の介入には多くのコストや時間がかかります
  • 成功を自動的に検証できます

NO の場合:

  • 失敗はまれなエッジケースです
  • 常に手動での調査が必要です
  • 安全性が極めて重要です(人間による検証が必要)
  • 成功をプログラムで検証できません

YES の例:CI 診断ワークフロー(複数の修正戦略を試す) NO の例:本番環境へのデプロイ(人間の承認が必要)

質問 4:コンテキストによってアプローチが大きく変わりますか?

YES の場合:

  • 環境の違いによって戦略が変わります
  • 現在のシステム状態が意思決定に影響します
  • トレードオフが状況によって異なります(速度対品質対コスト)
  • ドメイン固有のベストプラクティスが適用されます

NO の場合:

  • あらゆるコンテキストで同じアプローチが使えます
  • 環境への依存関係はありません
  • トレードオフを考慮する必要はありません

YES の例:修正エージェント(問題に応じて quick、diagnostic、comprehensive を選択) NO の例:UUID の生成(コンテキストに依存しない)

質問 5:複雑さに見合う価値はありますか?

YES の場合:

  • 問題が頻繁に繰り返し発生する(週に 2 回以上)
  • 手動での実行に 30 分以上かかる
  • 自動化による価値が高い
  • 保守コストが許容できる

NO の場合:

  • 一度限り、またはまれな問題である
  • 手動で素早く実行できる(5 分未満)
  • シンプルなスクリプトで十分である
  • 保守コストがメリットを上回る

YES の例:CI 失敗の診断(頻繁に発生し、時間がかかり、価値が高い) NO の例:一度限りのデータ移行(まれで、スクリプトで十分)

判断マトリックス

| 5 項目すべてが YES | 目標達成型エージェントを使用 | | 4 項目が YES、1 項目が NO | 目標達成型エージェントの使用を推奨 | | 3 項目が YES、2 項目が NO | よりシンプルなエージェントまたはハイブリッドを検討 | | 2 項目が YES、3 項目が NO | 従来型のエージェントのほうが適している可能性が高い | | 0~1 項目が YES | スクリプトまたはシンプルな自動化 |

3. アーキテクチャパターン

コンポーネントアーキテクチャ

目標達成型エージェントには、4 つの主要なコンポーネントがあります。

# Component 1: Goal Definition
class GoalDefinition:
    """Structured representation of objective"""
    raw_prompt: str              # Natural language goal
    goal: str                    # Extracted primary objective
    domain: str                  # Problem domain (security, data, automation, etc.)
    constraints: list[str]       # Technical/operational constraints
    success_criteria: list[str]  # How to verify success
    complexity: str              # simple, moderate, complex
    context: dict                # Additional metadata

# Component 2: Execution Plan
class ExecutionPlan:
    """Multi-phase plan with dependencies"""
    goal_id: uuid.UUID
    phases: list[PlanPhase]
    total_estimated_duration: str
    required_skills: list[str]
    parallel_opportunities: list[list[str]]  # Phases that can run parallel
    risk_factors: list[str]

# Component 3: Plan Phase
class PlanPhase:
    """Individual phase in execution plan"""
    name: str
    description: str
    required_capabilities: list[str]
    estimated_duration: str
    dependencies: list[str]          # Names of prerequisite phases
    parallel_safe: bool              # Can execute in parallel
    success_indicators: list[str]    # How to verify phase completion

# Component 4: Skill Definition
class SkillDefinition:
    """Capability needed for execution"""
    name: str
    description: str
    capabilities: list[str]
    implementation_type: str  # "native" or "delegated"
    delegation_target: str    # Agent to delegate to
実行フロー
┌─────────────────────────────────────────────────────────────┐
│ 1. GOAL ANALYSIS                                            │
│                                                             │
│  Input: Natural language objective                         │
│  Process: Extract goal, domain, constraints, criteria      │
│  Output: GoalDefinition                                    │
│                                                             │
│  [PromptAnalyzer.analyze_text(prompt)]                    │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 2. PLANNING                                                 │
│                                                             │
│  Input: GoalDefinition                                     │
│  Process: Decompose into phases, identify dependencies     │
│  Output: ExecutionPlan                                     │
│                                                             │
│  [ObjectivePlanner.generate_plan(goal_definition)]        │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 3. SKILL SYNTHESIS                                          │
│                                                             │
│  Input: ExecutionPlan                                      │
│  Process: Map capabilities to skills, identify agents      │
│  Output: list[SkillDefinition]                            │
│                                                             │
│  [SkillSynthesizer.synthesize(execution_plan)]            │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 4. AGENT ASSEMBLY                                           │
│                                                             │
│  Input: GoalDefinition, ExecutionPlan, Skills              │
│  Process: Combine into executable bundle                   │
│  Output: GoalAgentBundle                                   │
│                                                             │
│  [AgentAssembler.assemble(goal, plan, skills)]            │
└─────────────────────────────────────────────────────────────┘
                            ↓
┌─────────────────────────────────────────────────────────────┐
│ 5. EXECUTION (Auto-Mode)                                    │
│                                                             │
│  Input: GoalAgentBundle                                    │
│  Process: Execute phases, monitor progress, adapt          │
│  Output: Success or escalation                             │
│                                                             │
│  [Auto-mode with initial_prompt from bundle]              │
└─────────────────────────────────────────────────────────────┘
フェーズ依存関係の管理

フェーズ間の関係には 3 つの種類があります。

逐次依存:フェーズ B はフェーズ A の完了に依存します

Phase A → Phase B → Phase C

並列実行:フェーズを同時に実行できます

Phase A ──┬→ Phase B ──┐
          └→ Phase C ──┴→ Phase D

条件分岐:結果に基づいてフェーズを選択します

Phase A → [Decision] → Phase B (success path)
                    └→ Phase C (recovery path)
状態管理

目標達成型エージェントは、フェーズをまたいで状態を維持します。

class AgentState:
    """Runtime state for goal-seeking agent"""
    current_phase: str
    completed_phases: list[str]
    phase_results: dict[str, Any]  # Output from each phase
    failures: list[FailureRecord]  # Track what didn't work
    retry_count: int
    total_duration: timedelta
    context: dict                  # Shared context across phases
エラー処理

エラーからの復旧戦略は 3 つあります。

バックオフ付きリトライ:同じアプローチを使い、遅延を指数関数的に増やします

for attempt in range(MAX_RETRIES):
    try:
        result = execute_phase(phase)
        break
    except RetryableError as e:
        wait_time = INITIAL_DELAY * (2 ** attempt)
        sleep(wait_time)

代替戦略:同じ目標に対して異なるアプローチを使います

for strategy in STRATEGIES:
    try:
        result = execute_phase(phase, strategy)
        break
    except StrategyFailedError:
        continue  # Try next strategy
else:
    escalate_to_human("All strategies exhausted")

グレースフル・デグラデーション:部分的な成功を受け入れます

try:
    result = execute_phase_optimal(phase)
except OptimalFailedError:
    result = execute_phase_fallback(phase)  # Lower quality but works

4. goal_agent_generator との統合

goal_agent_generator モジュールは、目標達成型エージェントの実装を提供します。統合方法は次のとおりです。

コア API
from amplihack.goal_agent_generator import (
    PromptAnalyzer,
    ObjectivePlanner,
    SkillSynthesizer,
    AgentAssembler,
    GoalAgentPackager,
)

# Step 1: Analyze natural language goal
analyzer = PromptAnalyzer()
goal_definition = analyzer.analyze_text("""
Automate AKS cluster production readiness verification.
Check security, networking, monitoring, and compliance.
Generate report with actionable recommendations.
""")

# Step 2: Generate execution plan
planner = ObjectivePlanner()
execution_plan = planner.generate_plan(goal_definition)

# Step 3: Synthesize required skills
synthesizer = SkillSynthesizer()
skills = synthesizer.synthesize(execution_plan)

# Step 4: Assemble complete agent
assembler = AgentAssembler()
agent_bundle = assembler.assemble(
    goal_definition=goal_definition,
    execution_plan=execution_plan,
    skills=skills,
    bundle_name="aks-readiness-checker"
)

# Step 5: Package for deployment
packager = GoalAgentPackager()
packager.package(
    bundle=agent_bundle,
    output_dir=".claude/agents/goal-driven/aks-readiness-checker"
)
CLI 統合
# Generate agent from prompt file
amplihack goal-agent-generator create \
  --prompt ./prompts/aks-readiness.md \
  --output .claude/agents/goal-driven/aks-readiness-checker

# Generate agent from inline prompt
amplihack goal-agent-generator create \
  --inline "Automate CI failure diagnosis and fix iteration" \
  --output .claude/agents/goal-driven/ci-fixer

# List generated agents
amplihack goal-agent-generator list

# Test agent execution
amplihack goal-agent-generator test \
  --agent-path .claude/agents/goal-driven/ci-fixer \
  --dry-run
PromptAnalyzer の詳細

自然言語から構造化された情報を抽出します。

from amplihack.goal_agent_generator import PromptAnalyzer
from pathlib import Path

analyzer = PromptAnalyzer()

# From file
goal_def = analyzer.analyze(Path("./prompts/my-goal.md"))

# From text
goal_def = analyzer.analyze_text("Deploy and monitor microservices to AKS")

# GoalDefinition contains:
print(goal_def.goal)               # "Deploy and monitor microservices to AKS"
print(goal_def.domain)             # "deployment"
print(goal_def.constraints)        # ["Zero downtime", "Rollback capability"]
print(goal_def.success_criteria)   # ["All pods running", "Metrics visible"]
print(goal_def.complexity)         # "moderate"
print(goal_def.context)            # {"priority": "high", "scale": "medium"}

ドメインの分類:

  • data-processing:データ変換、分析、ETL
  • security-analysis:脆弱性スキャン、監査
  • automation:ワークフローの自動化、スケジューリング
  • testing:テスト生成、検証
  • deployment:リリース、公開、配布
  • monitoring:オブザーバビリティ、アラート
  • integration:API 接続、Webhook
  • reporting:ダッシュボード、メトリクス、要約

複雑さの判定:

  • simple:単一フェーズ、50 語未満、基本的な操作
  • moderate:2~4 フェーズ、50~150 語、ある程度の調整が必要
  • complex:5 フェーズ以上、150 語超、高度なオーケストレーション
ObjectivePlanner の詳細

複数フェーズの実行計画を生成します。

from amplihack.goal_agent_generator import ObjectivePlanner

planner = ObjectivePlanner()
plan = planner.generate_plan(goal_definition)

# ExecutionPlan contains:
for i, phase in enumerate(plan.phases, 1):
    print(f"Phase {i}: {phase.name}")
    print(f"  Description: {phase.description}")
    print(f"  Duration: {phase.estimated_duration}")
    print(f"  Capabilities: {', '.join(phase.required_capabilities)}")
    print(f"  Dependencies: {', '.join(phase.dependencies)}")
    print(f"  Parallel Safe: {phase.parallel_safe}")
    print(f"  Success Indicators: {phase.success_indicators}")

print(f"\nTotal Duration: {plan.total_estimated_duration}")
print(f"Required Skills: {', '.join(plan.required_skills)}")
print(f"Parallel Opportunities: {plan.parallel_opportunities}")
print(f"Risk Factors: {plan.risk_factors}")

ドメイン別のフェーズテンプレート:

  • data-processing:収集 → 変換 → 分析 → レポート作成
  • security-analysis:偵察 → 脆弱性の検出 → リスク評価 → レポート作成
  • automation:セットアップ → ワークフローの設計 → 実行 → 検証
  • testing:テスト計画 → 実装 → 実行 → 結果の分析
  • deployment:デプロイ前 → デプロイ → 検証 → デプロイ後
  • monitoring:モニターのセットアップ → データ収集 → 分析 → アラート
SkillSynthesizer の詳細

機能をスキルにマッピングします。

from amplihack.goal_agent_generator import SkillSynthesizer

synthesizer = SkillSynthesizer()
skills = synthesizer.synthesize(execution_plan)

# list[SkillDefinition]
for skill in skills:
    print(f"Skill: {skill.name}")
    print(f"  Description: {skill.description}")
    print(f"  Capabilities: {', '.join(skill.capabilities)}")
    print(f"  Type: {skill.implementation_type}")
    if skill.implementation_type == "delegated":
        print(f"  Delegates to: {skill.delegation_target}")

機能のマッピング:

  • data-* → data-processor スキル
  • security-*、vulnerability-* → security-analyzer スキル
  • test-* → tester スキル
  • deploy-* → deployer スキル
  • monitor-*、alert-* → monitor スキル
  • report-*、document-* → documenter スキル
AgentAssembler の詳細

コンポーネントを実行可能なバンドルに統合します。

from amplihack.goal_agent_generator import AgentAssembler

assembler = AgentAssembler()
bundle = assembler.assemble(
    goal_definition=goal_definition,
    execution_plan=execution_plan,
    skills=skills,
    bundle_name="custom-agent"  # Optional, auto-generated if omitted
)

# GoalAgentBundle contains:
print(bundle.id)                    # UUID
print(bundle.name)                  # "custom-agent" or auto-generated
print(bundle.version)               # "1.0.0"
print(bundle.status)                # "ready"
print(bundle.auto_mode_config)      # Configuration for auto-mode execution
print(bundle.metadata)              # Domain, complexity, skills, etc.

# Auto-mode configuration
config = bundle.auto_mode_config
print(config["max_turns"])          # Based on complexity
print(config["initial_prompt"])     # Generated execution prompt
print(config["success_criteria"])   # From goal definition
print(config["constraints"])        # From goal definition

自動モードの設定:

  • max_turns:5(シンプル)、10(中程度)、15(複雑)、フェーズが 1 つ増えるごとに 20% 増加
  • initial_prompt:目標、計画、成功基準を含む完全な Markdown プロンプト
  • working_dir:現在のディレクトリ
  • sdk:「claude」(デフォルト)
  • ui_mode:False(デフォルトはヘッドレス)
GoalAgentPackager の詳細

デプロイ用にバンドルをパッケージ化します。

from amplihack.goal_agent_generator import GoalAgentPackager
from pathlib import Path

packager = GoalAgentPackager()
packager.package(
    bundle=agent_bundle,
    output_dir=Path(".claude/agents/goal-driven/my-agent")
)

# Creates:
# .claude/agents/goal-driven/my-agent/
# ├── agent.md           # Agent definition
# ├── prompt.md          # Initial prompt
# ├── metadata.json      # Bundle metadata
# ├── plan.yaml          # Execution plan
# └── skills.yaml        # Required skills

5. 最近の Amplihack の例

amplihack プロジェクトの実際の目標達成型エージェント:

例 1:AKS SRE 自動化(Issue #1293)

問題:AKS クラスターの手動操作は時間がかかり、エラーが発生しやすいです。

目標達成型のソリューション:

# Goal: Automate AKS production readiness verification
goal = """
Verify AKS cluster production readiness:
- Security: RBAC, network policies, Key Vault integration
- Networking: Ingress, DNS, load balancers
- Monitoring: Container Insights, alerts, dashboards
- Compliance: Azure Policy, resource quotas
Generate actionable report with recommendations.
"""

# Agent decomposes into phases:
# 1. Security Audit (parallel): RBAC check, network policies, Key Vault
# 2. Networking Validation (parallel): Ingress test, DNS resolution, LB health
# 3. Monitoring Verification (parallel): Metrics, logs, alerts configured
# 4. Compliance Check (depends on 1-3): Azure Policy, quotas, best practices
# 5. Report Generation (depends on 4): Markdown report with findings

# Agent adapts based on findings:
# - If security issues found: Suggest fixes, offer to apply
# - If monitoring missing: Generate alert templates
# - If compliance violations: List remediation steps

主な特長:

  • 自律型:手順ごとの指示がなくても、複数のシステムを確認します
  • 適応型:調査の深さは確認結果に応じて変わります
  • 複数フェーズ:セキュリティ/ネットワーク/モニタリングを並行して実施し、レポートは順次作成します
  • ドメインエキスパート:Azure と Kubernetes の知識を組み込んでいます
  • 自己評価型:各チェックを検証し、結果を集約します

実装:

# Located in: .claude/agents/amplihack/specialized/azure-kubernetes-expert.md
# Uses knowledge base: .claude/data/azure_aks_expert/

# Integrates with goal_agent_generator:
from amplihack.goal_agent_generator import (
    PromptAnalyzer, ObjectivePlanner, AgentAssembler
)

analyzer = PromptAnalyzer()
goal_def = analyzer.analyze_text(goal)

planner = ObjectivePlanner()
plan = planner.generate_plan(goal_def)  # Generates 5-phase plan

# Domain-specific customization:
plan.phases[0].required_capabilities = [
    "rbac-audit", "network-policy-check", "key-vault-integration"
]

得られた教訓:

  • 複雑なインフラストラクチャでは、ドメインの専門知識が重要です
  • 並列実行により、合計所要時間を大幅に短縮できます
  • 実行可能な推奨事項によって、エージェントの価値が高まります
  • 包括的なナレッジベース(Q&A 形式)により、自律的な判断が可能になります
例 2:CI 診断ワークフロー

問題:CI の失敗には、手動での診断と修正の反復が必要です

目標達成型のソリューション:

# Goal: Diagnose CI failure and iterate fixes until success
goal = """
CI pipeline failing after push.
Diagnose failures, apply fixes, push updates, monitor CI.
Iterate until all checks pass.
Stop at mergeable state without auto-merging.
"""

# Agent decomposes into phases:
# 1. CI Status Monitoring: Check current CI state
# 2. Failure Diagnosis: Analyze logs, compare environments
# 3. Fix Application: Apply fixes based on failure patterns
# 4. Push and Wait: Commit fixes, push, wait for CI re-run
# 5. Success Verification: Confirm all checks pass

# Iterative loop:
# Phases 2-4 repeat until success or max iterations (5)

主な特長:

  • 反復型:成功するまで修正サイクルを繰り返します
  • 自律的な復旧:複数の修正方法を試します
  • 状態管理:試した修正を追跡し、失敗した修正の再試行を避けます
  • パターンマッチング:一般的な CI 失敗の種類を認識します
  • エスカレーション:最大反復回数に達した後、ユーザーに報告します

実装:

# Located in: .claude/agents/amplihack/specialized/ci-diagnostic-workflow.md

# Fix iteration loop:
MAX_ITERATIONS = 5
iteration = 0

while iteration < MAX_ITERATIONS:
    status = check_ci_status()

    if status["conclusion"] == "success":
        break

    # Diagnose failures
    failures = analyze_ci_logs(status)

    # Apply pattern-matched fixes
    for failure in failures:
        if "test" in failure["type"]:
            fix_test_failure(failure)
        elif "lint" in failure["type"]:
            fix_lint_failure(failure)
        elif "type" in failure["type"]:
            fix_type_failure(failure)

    # Commit and push
    git_commit_and_push(f"fix: CI iteration {iteration + 1}")

    # Wait for CI re-run
    wait_for_ci_completion()

    iteration += 1

if iteration >= MAX_ITERATIONS:
    escalate_to_user("CI still failing after 5 iterations")

得られた教訓:

  • 反復回数の上限により、無限ループを防げます
  • パターンマッチング(テスト/lint/型)により、対象を絞った修正が可能になります
  • スマートな待機(指数バックオフ)により、待ち時間を短縮できます
  • 自動マージは行いません。常に人間の承認が必要です
例 3:Pre-Commit 診断ワークフロー

問題:Pre-commit フックが、原因の分かりにくいエラーで失敗します

目標達成型のソリューション:

# Goal: Fix pre-commit hook failures before commit
goal = """
Pre-commit hooks failing.
Diagnose issues (formatting, linting, type checking).
Apply fixes locally, re-run hooks.
Ensure all hooks pass before allowing commit.
"""

# Agent decomposes into phases:
# 1. Hook Failure Analysis: Identify which hooks failed
# 2. Environment Check: Compare local vs pre-commit versions
# 3. Targeted Fixes: Apply fixes per hook type
# 4. Hook Re-run: Validate fixes, iterate if needed
# 5. Commit Readiness: Confirm all hooks pass

主な特長:

  • プッシュ前に重点を置く:CI にプッシュする前に問題を修正します
  • ツールのバージョン管理:ローカル環境のバージョンを pre-commit 設定に合わせます
  • フックに応じた修正:フックの種類ごとに適した方法で対応します
  • 高速な反復:CI の完了を待たず、すぐにフィードバックを得られます

実装:

# Located in: .claude/agents/amplihack/specialized/pre-commit-diagnostic.md

# Hook failure patterns:
HOOK_FIXES = {
    "ruff": lambda: subprocess.run(["ruff", "check", "--fix", "."]),
    "black": lambda: subprocess.run(["black", "."]),
    "mypy": lambda: add_type_ignores(),
    "trailing-whitespace": lambda: subprocess.run(["pre-commit", "run", "trailing-whitespace", "--all-files"]),
}

# Execution:
failed_hooks = detect_failed_hooks()

for hook in failed_hooks:
    if hook in HOOK_FIXES:
        HOOK_FIXES[hook]()
    else:
        generic_fix(hook)

# Re-run to verify
rerun_result = subprocess.run(["pre-commit", "run", "--all-files"])
if rerun_result.returncode == 0:
    print("All hooks passing, ready to commit!")

得られた教訓:

  • Pre-commit での修正は、CI での反復よりも高速です
  • ツールのバージョン不一致は、よくある原因です
  • 80%のケースで自動修正できます
  • 残りの20%は、明確な診断結果とともにエスカレーションします
例 4:Fix-Agent のパターンマッチング

問題:問題の種類によって、適切な修正方法が異なります

目標達成型のソリューション:

# Goal: Select optimal fix strategy based on problem context
goal = """
Analyze issue and select fix mode:
- QUICK: Obvious fixes (< 5 min)
- DIAGNOSTIC: Unclear root cause (investigation)
- COMPREHENSIVE: Complex issues (full workflow)
"""

# Agent decomposes into phases:
# 1. Issue Analysis: Classify problem type and complexity
# 2. Mode Selection: Choose QUICK/DIAGNOSTIC/COMPREHENSIVE
# 3. Fix Execution: Apply mode-appropriate strategy
# 4. Validation: Verify fix resolves issue

主な特長:

  • コンテキスト対応:問題の分析に基づいて方法を選択します
  • 複数モード:複雑さに応じた3つの修正モードがあります
  • パターン認識:過去の修正から学習します
  • 適応型:最初のモードで失敗した場合、複雑さを引き上げます

実装:

# Located in: .claude/agents/amplihack/specialized/fix-agent.md

# Mode selection logic:
def select_fix_mode(issue: Issue) -> FixMode:
    if issue.is_obvious() and issue.scope == "single-file":
        return FixMode.QUICK
    elif issue.root_cause_unclear():
        return FixMode.DIAGNOSTIC
    elif issue.is_complex() or issue.requires_architecture_change():
        return FixMode.COMPREHENSIVE
    else:
        return FixMode.DIAGNOSTIC  # Default to investigation

# Pattern frequency (from real usage):
FIX_PATTERNS = {
    "import": 0.15,      # Import errors (15%)
    "config": 0.12,      # Configuration issues (12%)
    "test": 0.18,        # Test failures (18%)
    "ci": 0.20,          # CI/CD problems (20%)
    "quality": 0.25,     # Code quality (linting, types) (25%)
    "logic": 0.10,       # Logic errors (10%)
}

# Template-based fixes for common patterns:
if issue.pattern == "import":
    apply_template("import-fix-template", issue)
elif issue.pattern == "config":
    apply_template("config-fix-template", issue)
# ... etc

得られた教訓:

  • パターンマッチングにより、テンプレートベースの修正が可能になります(80%をカバー)
  • モード選択によって過剰な設計を避け、適切な規模で対応できます
  • 原因が不明確な問題では、診断モードが重要です(根本原因の分析)
  • 使用状況データをテンプレートの優先順位付けに活用できます

6. 設計チェックリスト

目標達成型エージェントを設計する際は、このチェックリストを使用してください。

目標の定義
  • 目標が明確に定義されている
  • 成功基準が測定可能で、検証できる
  • 制約(時間、リソース、安全性)が明示されている
  • ドメインが特定されている(フェーズテンプレートに影響します)
  • 複雑さが見積もられている(単純/中程度/複雑)
フェーズの設計
  • 3~5 個のフェーズに分解されている(細かすぎず、粗すぎない)
  • フェーズ間の依存関係が明示されている
  • 並列実行できる箇所が特定されている
  • 各フェーズに明確な成功指標がある
  • フェーズの所要時間が見積もられている
スキルの割り当て
  • フェーズごとに必要な能力が特定されている
  • スキルが既存のエージェントまたはツールに割り当てられている
  • 委任先が指定されている
  • 不足している能力がない
エラー処理
  • 再試行方法が定義されている(最大試行回数、バックオフ)
  • 代替方法が特定されている
  • エスカレーションの基準が明確である(支援を求めるタイミング)
  • グレースフルデグラデーションの選択肢がある(フォールバック方法)
状態管理
  • フェーズをまたいで状態が追跡される
  • 後続処理で使用するフェーズの結果が保存される
  • 失敗履歴が保持される
  • コンテキストが適切に共有される
テスト
  • 成功シナリオがテストされている
  • 失敗からの復旧がテストされている
  • エッジケースが特定されている
  • パフォーマンスが検証されている(所要時間、リソース使用量)
ドキュメント
  • 目標が明確に記載されている
  • フェーズの説明がすべて記載されている
  • 使用例が示されている
  • 統合ポイントが明記されている
哲学への準拠
  • 徹底したシンプルさ(不要な複雑さがない)
  • 各フェーズの責務が単一である
  • 過剰なエンジニアリングがない(適切な規模のソリューション)
  • 再生成可能である(仕様が明確)

7. Agent SDK との統合(今後)

Agent SDK Skill が統合されると、目標追求型エージェントは次の機能を活用できます。

自律性の強化
# Agent SDK provides enhanced context management
from claude_agent_sdk import AgentContext, Tool

class GoalSeekingAgent:
    def __init__(self, context: AgentContext):
        self.context = context
        self.state = {}

    async def execute_phase(self, phase: PlanPhase):
        # SDK provides tools, memory, delegation
        tools = self.context.get_tools(phase.required_capabilities)
        memory = self.context.get_memory()

        # Execute with SDK support
        result = await phase.execute(tools, memory)

        # Store in context for downstream phases
        self.context.store_result(phase.name, result)
ツールの発見
# SDK enables dynamic tool discovery
available_tools = context.discover_tools(capability="data-processing")

# Select optimal tool for task
tool = context.select_tool(
    capability="data-transformation",
    criteria={"performance": "high", "accuracy": "required"}
)
メモリ管理
# SDK provides persistent memory across sessions
context.memory.store("deployment-history", deployment_record)
previous = context.memory.retrieve("deployment-history")

# Enables learning from past executions
if previous and previous.failed:
    # Avoid previous failure strategy
    strategy = select_alternative_strategy(previous.failure_reason)
エージェントへの委任
# SDK simplifies agent-to-agent delegation
result = await context.delegate(
    agent="security-analyzer",
    task="audit-rbac-policies",
    input={"cluster": cluster_name}
)

# Parallel delegation
results = await context.delegate_parallel([
    ("security-analyzer", "audit-rbac-policies"),
    ("network-analyzer", "validate-ingress"),
    ("monitoring-validator", "check-metrics")
])
可観測性
# SDK provides built-in tracing and metrics
with context.trace("data-transformation"):
    result = transform_data(input_data)

context.metrics.record("transformation-duration", duration)
context.metrics.record("transformation-accuracy", accuracy)
統合例
from claude_agent_sdk import AgentContext, create_agent
from amplihack.goal_agent_generator import GoalAgentBundle

# Create SDK-enabled goal-seeking agent
def create_goal_agent(bundle: GoalAgentBundle) -> Agent:
    context = AgentContext(
        name=bundle.name,
        version=bundle.version,
        capabilities=bundle.metadata["required_capabilities"]
    )

    # Register phases as agent tasks
    for phase in bundle.execution_plan.phases:
        context.register_task(
            name=phase.name,
            capabilities=phase.required_capabilities,
            executor=create_phase_executor(phase)
        )

    # Create agent with SDK
    agent = create_agent(context)

    # Execute goal
    return agent

# Usage:
agent = create_goal_agent(agent_bundle)
result = await agent.execute(bundle.auto_mode_config["initial_prompt"])

8. トレードオフ分析

目標追求型エージェントと従来型エージェント
項目目標追求型エージェント従来型エージェント
柔軟性高い — コンテキストに適応します低い — ワークフローが固定されています
開発時間中程度 — 目標とフェーズを定義します短い — 手順をスクリプト化します
実行時間長い — 意思決定のオーバーヘッドがあります短い — 直接実行します
保守性高い — 自ら適応します低い — 手動で更新します
デバッグのしやすさ難しい — 動的な振る舞いをします容易 — 予測可能なフローです
再利用性高い — 同じエージェントを異なるコンテキストで使用できます低い — 特定のコンテキストに限定されます
失敗への対応自律的に復旧します手動での介入が必要です
複雑さ高い — 複数フェーズの調整が必要です低い — 線形に実行します
それぞれを選ぶ場合

目標追求型を選ぶ場合:

  • 問題領域が広く、有効なアプローチが多数ある
  • 実行ごとにコンテキストが大きく異なる
  • 自律的な復旧に価値がある
  • コンテキストをまたいだ再利用が重要である
  • 開発時間への投資に見合う価値がある

従来型を選ぶ場合:

  • 決定的な経路が1つだけ存在する
  • パフォーマンスが重要である(低レイテンシが必要)
  • シンプルさを最優先する
  • 一度限り、または実行頻度が低い
  • デバッグと監査可能性が重要である
コストとメリットの分析

目標追求型のコスト:

  • 開発時間の増加(目標、フェーズ、機能の定義)
  • 実行時間の増加(意思決定のオーバーヘッド)
  • テストの複雑化(動的な振る舞い)
  • デバッグの難化(非決定的な経路)

目標追求型のメリット:

  • 自律的な動作(人間の介入が少ない)
  • コンテキストへの適応(さまざまな条件で動作)
  • 問題をまたいだ再利用(同じエージェントで異なる目標に対応)
  • 自己復旧(失敗に適切に対処)

損益分岐点:次のいずれかに該当する場合、目標追求型を導入する価値があります。

  • 週に2回以上繰り返し実行する、または
  • 手動での実行に30分以上かかる、または
  • 文書化が難しい専門知識が必要である、または
  • 自律的な復旧によって大きな価値が得られる

9. エスカレーションする場合

目標追求型エージェントは、次の場合に人間へエスカレーションする必要があります。

上限への到達

最大イテレーション数を超過した場合:

if iteration_count >= MAX_ITERATIONS:
    escalate(
        reason="Reached maximum iterations without success",
        context={
            "iterations": iteration_count,
            "attempted_strategies": attempted_strategies,
            "last_error": last_error
        }
    )

タイムアウトした場合:

if elapsed_time > MAX_DURATION:
    escalate(
        reason="Execution time exceeded limit",
        context={
            "elapsed": elapsed_time,
            "max_allowed": MAX_DURATION,
            "completed_phases": completed_phases
        }
    )
安全上の境界

破壊的な操作:

if operation.is_destructive() and not operation.has_approval():
    escalate(
        reason="Destructive operation requires human approval",
        operation=operation.description,
        impact=operation.estimate_impact()
    )

本番環境への変更:

if target_environment == "production":
    escalate(
        reason="Production deployments require human verification",
        changes=proposed_changes,
        rollback_plan=rollback_strategy
    )
不確実性の検出

信頼度が低い場合:

if decision_confidence < CONFIDENCE_THRESHOLD:
    escalate(
        reason="Confidence below threshold for autonomous decision",
        decision=decision_description,
        confidence=decision_confidence,
        alternatives=alternative_options
    )

戦略が競合している場合:

if len(viable_strategies) > 1 and not clear_winner:
    escalate(
        reason="Multiple viable strategies, need human judgment",
        strategies=viable_strategies,
        trade_offs=strategy_trade_offs
    )
予期しない状況

認識されないエラー:

if error_type not in KNOWN_ERROR_PATTERNS:
    escalate(
        reason="Encountered unknown error pattern",
        error=error_details,
        context=execution_context,
        recommendation="Manual investigation required"
    )

環境の不一致:

if detected_environment != expected_environment:
    escalate(
        reason="Environment mismatch detected",
        expected=expected_environment,
        detected=detected_environment,
        risk="Potential for incorrect behavior"
    )
エスカレーションのベストプラクティス

コンテキストを提示する:

  • 試みたこと
  • 失敗した内容とその理由
  • 検討した代替案
  • 現在のシステム状態

アクションを提案する:

  • 次のステップを推奨する
  • 診断コマンドを提示する
  • 手動で介入できるポイントを示す
  • 必要に応じてロールバックを提案する

復旧を可能にする:

  • 実行状態を保存する
  • 失敗を記録する
  • 再開機能を提供する
  • 手動での上書きを可能にする

エスカレーションの例:

escalate(
    reason="CI failure diagnosis unsuccessful after 5 iterations",
    context={
        "iterations": 5,
        "attempted_fixes": [
            "Import path corrections (iteration 1)",
            "Type annotation fixes (iteration 2)",
            "Test environment setup (iteration 3)",
            "Dependency version pins (iteration 4)",
            "Mock configuration (iteration 5)"
        ],
        "persistent_failures": [
            "test_integration.py::test_api_connection - Timeout",
            "test_models.py::test_validation - Assertion error"
        ],
        "system_state": "2 of 25 tests still failing",
        "ci_logs": "https://github.com/.../actions/runs/123456"
    },
    recommendations=[
        "Review test_api_connection timeout - may need increased timeout or mock",
        "Examine test_validation assertion - data structure may have changed",
        "Consider running tests locally with same environment as CI",
        "Check if recent changes affected integration test setup"
    ],
    next_steps={
        "manual_investigation": "Run failing tests locally with verbose output",
        "rollback_option": "git revert HEAD~5 if fixes made things worse",
        "resume_point": "Fix failures and run /amplihack:ci-diagnostic to resume"
    }
)

10. ワークフローの例

完全な例:データパイプライン自動化のための目標指向型エージェントの構築

ステップ 1:目標を定義する
# Goal: Automate Multi-Source Data Pipeline

## Objective

Collect data from multiple sources (S3, database, API), transform to common schema, validate quality, publish to data warehouse.

## Success Criteria

- All sources successfully ingested
- Data transformed to target schema
- Quality checks pass (completeness, accuracy)
- Data published to warehouse
- Pipeline completes within 30 minutes

## Constraints

- Must handle source unavailability gracefully
- No data loss (failed records logged)
- Idempotent (safe to re-run)
- Resource limits: 8GB RAM, 4 CPU cores

## Context

- Daily execution (automated schedule)
- Priority: High (blocking downstream analytics)
- Scale: Medium (100K-1M records per source)
ステップ 2:PromptAnalyzer で分析する
from amplihack.goal_agent_generator import PromptAnalyzer

analyzer = PromptAnalyzer()
goal_definition = analyzer.analyze_text(goal_text)

# Result:
# goal_definition.goal = "Automate Multi-Source Data Pipeline"
# goal_definition.domain = "data-processing"
# goal_definition.complexity = "moderate"
# goal_definition.constraints = [
#     "Must handle source unavailability gracefully",
#     "No data loss (failed records logged)",
#     "Idempotent (safe to re-run)",
#     "Resource limits: 8GB RAM, 4 CPU cores"
# ]
# goal_definition.success_criteria = [
#     "All sources successfully ingested",
#     "Data transformed to target schema",
#     "Quality checks pass (completeness, accuracy)",
#     "Data published to warehouse",
#     "Pipeline completes within 30 minutes"
# ]
ステップ 3:ObjectivePlanner で計画を生成する
from amplihack.goal_agent_generator import ObjectivePlanner

planner = ObjectivePlanner()
execution_plan = planner.generate_plan(goal_definition)

# Result: 4-phase plan
# Phase 1: Data Collection (parallel)
#   - Collect from S3 (parallel-safe)
#   - Collect from database (parallel-safe)
#   - Collect from API (parallel-safe)
#   Duration: 15 minutes
#   Success: All sources attempted, failures logged
#
# Phase 2: Data Transformation (depends on Phase 1)
#   - Parse raw data
#   - Transform to common schema
#   - Handle missing fields
#   Duration: 15 minutes
#   Success: All records transformed or logged as failed
#
# Phase 3: Quality Validation (depends on Phase 2)
#   - Completeness check
#   - Accuracy validation
#   - Consistency verification
#   Duration: 5 minutes
#   Success: Quality thresholds met
#
# Phase 4: Data Publishing (depends on Phase 3)
#   - Load to warehouse
#   - Update metadata
#   - Generate report
#   Duration: 10 minutes
#   Success: Data in warehouse, report generated
ステップ 4:スキルを統合する
from amplihack.goal_agent_generator import SkillSynthesizer

synthesizer = SkillSynthesizer()
skills = synthesizer.synthesize(execution_plan)

# Result: 3 skills
# Skill 1: data-collector
#   Capabilities: ["s3-read", "database-query", "api-fetch"]
#   Implementation: "native" (built-in)
#
# Skill 2: data-transformer
#   Capabilities: ["parsing", "schema-mapping", "validation"]
#   Implementation: "native" (built-in)
#
# Skill 3: data-publisher
#   Capabilities: ["warehouse-load", "metadata-update", "reporting"]
#   Implementation: "delegated" (delegates to warehouse tool)
ステップ 5:エージェントを組み立てる
from amplihack.goal_agent_generator import AgentAssembler

assembler = AgentAssembler()
agent_bundle = assembler.assemble(
    goal_definition=goal_definition,
    execution_plan=execution_plan,
    skills=skills,
    bundle_name="multi-source-data-pipeline"
)

# Result: GoalAgentBundle
# - Name: multi-source-data-pipeline
# - Max turns: 12 (moderate complexity, 4 phases)
# - Initial prompt: Full execution plan with phases
# - Status: "ready"
ステップ 6:エージェントをパッケージ化する
from amplihack.goal_agent_generator import GoalAgentPackager
from pathlib import Path

packager = GoalAgentPackager()
packager.package(
    bundle=agent_bundle,
    output_dir=Path(".claude/agents/goal-driven/multi-source-data-pipeline")
)

# Creates agent package:
# .claude/agents/goal-driven/multi-source-data-pipeline/
# ├── agent.md           # Agent definition
# ├── prompt.md          # Execution prompt
# ├── metadata.json      # Bundle metadata
# ├── plan.yaml          # Execution plan (4 phases)
# └── skills.yaml        # 3 required skills
ステップ 7:エージェントを実行する(自動モード)
# Execute via CLI
amplihack goal-agent-generator execute \
  --agent-path .claude/agents/goal-driven/multi-source-data-pipeline \
  --auto-mode \
  --max-turns 12

# Or programmatically:
from claude_code import execute_auto_mode

result = execute_auto_mode(
    initial_prompt=agent_bundle.auto_mode_config["initial_prompt"],
    max_turns=agent_bundle.auto_mode_config["max_turns"],
    working_dir=agent_bundle.auto_mode_config["working_dir"]
)
ステップ 8:実行を監視する

エージェントは自律的に実行します:

Phase 1: Data Collection [In Progress]
├── S3 Collection: ✓ COMPLETED (50K records, 5 minutes)
├── Database Collection: ✓ COMPLETED (75K records, 8 minutes)
└── API Collection: ✗ FAILED (timeout, retrying...)
    └── Retry 1: ✓ COMPLETED (25K records, 4 minutes)

Phase 1: ✓ COMPLETED (150K records total, 3 sources, 17 minutes)

Phase 2: Data Transformation [In Progress]
├── Parsing: ✓ COMPLETED (150K records parsed)
├── Schema Mapping: ✓ COMPLETED (148K records mapped, 2K failed)
└── Missing Fields: ✓ COMPLETED (defaults applied)

Phase 2: ✓ COMPLETED (148K records ready, 2K logged as failed, 12 minutes)

Phase 3: Quality Validation [In Progress]
├── Completeness: ✓ PASS (98.7% complete, threshold 95%)
├── Accuracy: ✓ PASS (99.2% accurate, threshold 98%)
└── Consistency: ✓ PASS (100% consistent)

Phase 3: ✓ COMPLETED (All checks passed, 4 minutes)

Phase 4: Data Publishing [In Progress]
├── Warehouse Load: ✓ COMPLETED (148K records loaded)
├── Metadata Update: ✓ COMPLETED (pipeline_run_id: 12345)
└── Report Generation: ✓ COMPLETED (report.html)

Phase 4: ✓ COMPLETED (Data published, 8 minutes)

Total Execution: ✓ SUCCESS (41 minutes, all success criteria met)
ステップ 9:結果を確認する
# Pipeline Execution Report

## Summary

- **Status**: SUCCESS
- **Duration**: 41 minutes (estimated: 30 minutes)
- **Records Processed**: 150K ingested, 148K published
- **Success Rate**: 98.7%

## Phase Results

### Phase 1: Data Collection

- S3: 50K records (5 min)
- Database: 75K records (8 min)
- API: 25K records (4 min, 1 retry)

### Phase 2: Data Transformation

- Successfully transformed: 148K records
- Failed transformations: 2K records (logged to failed_records.log)
- Failure reasons: Schema mismatch (1.5K), Invalid data (500)

### Phase 3: Quality Validation

- Completeness: 98.7% ✓
- Accuracy: 99.2% ✓
- Consistency: 100% ✓

### Phase 4: Data Publishing

- Warehouse load: Success
- Pipeline run ID: 12345
- Report: report.html

## Issues Encountered

1. API timeout (Phase 1): Resolved with retry
2. 2K transformation failures: Logged for manual review

## Recommendations

1. Investigate schema mismatches in API data
2. Add validation for API data format
3. Consider increasing timeout for API calls
ステップ 10:反復する(必要な場合)

パイプラインが失敗した場合、エージェントは適応します:

# Example: API source completely unavailable
if phase1_result["api"]["status"] == "unavailable":
    # Agent adapts: continues with partial data
    log_warning("API source unavailable, continuing with S3 + database")
    proceed_to_phase2_with_partial_data()

    # Report notes partial data
    add_to_report("Data incomplete: API source unavailable")

# Example: Quality validation fails
if phase3_result["completeness"] < THRESHOLD:
    # Agent tries recovery: fetch missing data
    missing_records = identify_missing_records()
    retry_collection_for_missing(missing_records)
    rerun_transformation()
    rerun_validation()

    # If still fails after retry, escalate
    if still_below_threshold:
        escalate("Quality threshold not met after retry")

11. 関連パターン

目標指向型エージェントは、他のパターンと関連し、統合できます:

ディベートパターン(マルチエージェントによる意思決定)

組み合わせる場合:

  • 目標指向型エージェントが、トレードオフを伴う複雑な意思決定に直面する
  • 複数の妥当なアプローチが存在する
  • 異なる視点からの合意形成が必要

例:

# Goal-seeking agent reaches decision point
if len(viable_strategies) > 1:
    # Invoke debate pattern
    result = invoke_debate(
        question="Which data transformation approach?",
        perspectives=["performance", "accuracy", "simplicity"],
        context=current_state
    )

    # Use debate result to select strategy
    selected_strategy = result.consensus
N バージョンパターン(冗長な実装)

組み合わせる場合:

  • 目標指向型エージェントが重要なフェーズを実行する
  • エラーのコストが高い
  • 複数の独立した実装が可能

例:

# Critical security validation phase
if phase.is_critical():
    # Generate N versions
    results = generate_n_versions(
        phase=phase,
        n=3,
        independent=True
    )

    # Use voting or comparison to select result
    validated_result = compare_and_validate(results)
カスケードパターン(フォールバック戦略)

組み合わせる場合:

  • 目標指向型エージェントに優先するアプローチがあるものの、フォールバックも必要
  • 品質とパフォーマンスのトレードオフがある
  • 段階的な機能低下が望ましい

例:

# Data transformation with fallback
try:
    # Optimal: ML-based transformation
    result = ml_transform(data)
except MLModelUnavailable:
    try:
        # Pragmatic: Rule-based transformation
        result = rule_based_transform(data)
    except RuleEngineError:
        # Minimal: Manual templates
        result = template_transform(data)
調査ワークフロー(ナレッジの発見)

組み合わせる場合:

  • 目標を達成するために既存システムを理解する必要がある
  • アーキテクチャやパターンの調査が必要
  • 実行前にナレッジを掘り起こす必要がある

例:

# Before automating deployment, understand current system
if goal.requires_system_knowledge():
    # Run investigation workflow
    investigation = run_investigation_workflow(
        scope="deployment pipeline",
        depth="comprehensive"
    )

    # Use findings to inform goal-seeking execution
    adapt_plan_based_on_investigation(investigation.findings)
ドキュメント駆動開発(仕様を先に定める)

組み合わせる場合:

  • 目標指向型エージェントがコードを生成または変更する
  • 明確な仕様によって逸脱を防げる
  • ドキュメントが唯一の信頼できる情報源である

例:

# Goal: Implement new feature
if goal.involves_code_changes():
    # DDD Phase 1: Generate specifications
    specs = generate_specifications(goal)

    # DDD Phase 2: Review and approve specs
    await human_review(specs)

    # Goal-seeking agent implements from specs
    implementation = execute_from_specifications(specs)
コミット前/CI 診断(品質ゲート)

組み合わせる場合:

  • 目標指向型エージェントがコードを変更する
  • コミットやプッシュの前に品質を確保する必要がある
  • 検証と修正を自動化する

例:

# After goal-seeking agent generates code
if changes_made:
    # Run pre-commit diagnostic
    pre_commit_result = run_pre_commit_diagnostic()

    if pre_commit_result.has_failures():
        # Agent fixes issues
        apply_pre_commit_fixes(pre_commit_result.failures)

    # After push, run CI diagnostic
    ci_result = run_ci_diagnostic_workflow()

    if ci_result.has_failures():
        # Agent iterates fixes
        iterate_ci_fixes_until_pass(ci_result)

12. 品質基準

目標指向型エージェントは、次の品質基準を満たす必要があります:

正確性

成功基準の検証:

  • エージェントは完了前にすべての成功基準を検証する
  • 中間フェーズの結果が検証される
  • サイレントフェイラーが発生しない(すべてのエラーが記録され、処理される)

テストカバレッジ:

  • 正常系をテストする(すべての成功基準を満たす)
  • 失敗シナリオをテストする(フェーズの失敗、再試行)
  • エッジケースを特定してテストする
  • 実システムとの統合を検証する
回復力

エラー処理:

  • 指数バックオフを伴う再試行ロジック
  • よくある失敗に対する代替戦略
  • 最適な経路が利用できない場合の段階的な機能低下
  • 明確なエスカレーション基準

状態管理:

  • フェーズの境界を越えて状態が永続化される
  • 失敗後に再開できる
  • 冪等な実行(安全に再実行できる)
  • 中断時にクリーンアップする
パフォーマンス

効率性:

  • 可能な場合はフェーズを並列実行する
  • 不要な作業をしない(再試行時に完了済みのフェーズをスキップする)
  • リソース使用量を上限内に保つ(メモリ、CPU、時間)
  • タイムアウト制限を適用する

レイテンシー:

  • ユースケースに適した意思決定のオーバーヘッド
  • ブロッキング待機を行わない(可能な場合は非同期にする)
  • 進捗を報告する(ブラックボックス状態の期間を作らない)
可観測性

ロギング:

  • フェーズの遷移が記録される
  • 判断が根拠とともに記録される
  • エラーがコンテキストとともに記録される
  • 結果がメトリクスとともに記録される

メトリクス:

  • フェーズごとの所要時間が追跡される
  • 成功率と失敗率が追跡される
  • リソース使用状況が監視される
  • 品質メトリクスが報告される

トレーシング:

  • 実行フローを追跡できる
  • フェーズ間の関連付けが維持される
  • デバッグ情報が十分にある
使いやすさ

ドキュメント:

  • 目標が明確に示されている
  • 成功基準が文書化されている
  • 使用例が用意されている
  • 統合ガイドが完成している

ユーザーエクスペリエンス:

  • 進捗状況が明確に報告される
  • 対応につながるエラーメッセージが表示される
  • 出力が人間に読みやすい
  • 簡単に呼び出して監視できる
原則への準拠

徹底したシンプルさ:

  • 不要なフェーズや複雑さがない
  • 機能する最もシンプルな方法を採用している
  • 時期尚早な最適化を行わない

単一責任:

  • 各フェーズの役割が明確である
  • 責任の重複がない
  • フェーズの境界が明確である

モジュール性:

  • スキルが複数のエージェントで再利用できる
  • フェーズが独立している
  • インターフェース(入力/出力)が明確である

再生成可能:

  • 仕様から再構築できる
  • ハードコードされたマジック値がない
  • 設定が外部化されている

13. はじめに

クイックスタート:初めての目標達成型エージェントを構築する

ステップ 1:amplihack をインストールする(まだの場合)

pip install amplihack

ステップ 2:目標プロンプトを作成する

cat > my-goal.md << 'EOF'
# Goal: Automated Security Audit

Check application for common security issues:
- SQL injection vulnerabilities
- XSS vulnerabilities
- Insecure dependencies
- Missing security headers

Generate report with severity levels and remediation steps.
EOF

ステップ 3:エージェントを生成する

amplihack goal-agent-generator create \
  --prompt my-goal.md \
  --output .claude/agents/goal-driven/security-auditor

ステップ 4:生成されたプランを確認する

cat .claude/agents/goal-driven/security-auditor/plan.yaml

ステップ 5:エージェントを実行する

amplihack goal-agent-generator execute \
  --agent-path .claude/agents/goal-driven/security-auditor \
  --auto-mode
一般的なユースケース

ユースケース 1:ワークフローの自動化

# Create release automation agent
echo "Automate release workflow: tag, build, test, deploy to staging" | \
  amplihack goal-agent-generator create --inline --output .claude/agents/goal-driven/release-automator

ユースケース 2:データパイプライン

# Create ETL pipeline agent
echo "Extract from sources, transform to schema, validate quality, load to warehouse" | \
  amplihack goal-agent-generator create --inline --output .claude/agents/goal-driven/etl-pipeline

ユースケース 3:診断ワークフロー

# Create performance diagnostic agent
echo "Diagnose application performance issues, identify bottlenecks, suggest optimizations" | \
  amplihack goal-agent-generator create --inline --output .claude/agents/goal-driven/perf-diagnostic
学習リソース

ドキュメント:

  • ~/.amplihack/.claude/skills/goal-seeking-agent-pattern/examples/ の例を確認する
  • ~/.amplihack/.claude/agents/amplihack/specialized/ にある実際のエージェント実装を読む
  • ~/.amplihack/.claude/skills/goal-seeking-agent-pattern/templates/integration_guide.md にある統合ガイドを確認する

練習:

  1. シンプルに始める:単一フェーズのエージェントを構築する(例:ファイルフォーマッター)
  2. 複雑さを加える:複数フェーズのエージェントを構築する(例:テスト生成と実行)
  3. 自律性を高める:エラー回復機能を備えたエージェントを構築する(例:CI 修正エージェント)
  4. 本番環境向けに構築する:完全な目標達成型エージェントを構築する(例:デプロイパイプライン)

サポートを受ける:

  • 判断フレームワーク(セクション 2)を確認する
  • 設計チェックリスト(セクション 6)を確認する
  • 実際の例(セクション 5)を調べる
  • アーキテクトエージェントに指針を求める
次のステップ

初めての目標達成型エージェントを構築したら:

  1. 十分にテストする:成功、失敗、エッジケースを網羅する
  2. 本番環境で監視する:メトリクス、ログ、失敗を追跡する
  3. 反復する:実際の使用状況に基づいて改善する
  4. 学びを文書化する:得られた知見を DISCOVERIES.md に反映する
  5. パターンを共有する:うまくいった手法を PATTERNS.md に追加する

成功の指標:

  • エージェントが 80%以上の割合で自律的に目標を達成する
  • 失敗時に明確なコンテキストを添えてエスカレーションする
  • 実行時間が許容範囲内である
  • ユーザーがエージェントの自律実行を信頼している

覚えておいてください:目標達成型エージェントは徹底してシンプルで、明確な目的に集中し、コンテキストに適応できる必要があります。シンプルに始め、正当な理由がある場合にのみ複雑さを加え、常に成功基準に照らして検証してください。

コメント