Back to catalog

Goal-Seeking Agent Pattern

Guides architects on when and how to use goal-seeking agents as a design pattern. This skill helps evaluate whether autonomous agents are appropriate for a given problem, how to structure their objectives, integrate with goal_agent_generator, and reference real amplihack examples like AKS SRE automation, CI diagnostics, pre-commit workflows, and fix-agent pattern matching.

  • Category: discovered
  • Tags: github, community
  • Version: 1.0.0
  • Author: walid
  • Downloads: 0
  • Updated: 2025-11-22

Download the latest version (v1.0.0) from this page.

SKILL.md

---
name: "Goal-Seeking Agent Pattern"
description: |
  Guides architects on when and how to use goal-seeking agents as a design pattern.
  This skill helps evaluate whether autonomous agents are appropriate for a given
  problem, how to structure their objectives, integrate with goal_agent_generator,
  and reference real amplihack examples like AKS SRE automation, CI diagnostics,
  pre-commit workflows, and fix-agent pattern matching.
auto-detection:
  triggers:
    - "complex workflow"
    - "autonomous agent"
    - "goal-seeking"
    - "adaptive behavior"
    - "multi-phase processing"
    - "task automation design"
    - "autonomous decision-making"
    - "multi-step process"
    - "workflow orchestration"
    - "self-directed agent"
allowed-tools: ["Read", "Grep", "Glob", "WebSearch"]
target-agents: ["architect"]
priority: "medium"
complexity: "medium"
---

# Goal-Seeking Agent Pattern Skill

## 1. What Are Goal-Seeking Agents?

Goal-seeking agents are autonomous AI agents that execute multi-phase objectives by:

1. **Understanding High-Level Goals**: Accept natural language objectives without explicit step-by-step instructions
2. **Planning Execution**: Break goals into phases with dependencies and success criteria
3. **Autonomous Execution**: Make decisions and adapt behavior based on intermediate results
4. **Self-Assessment**: Evaluate progress against success criteria and adjust approach
5. **Resilient Operation**: Handle failures gracefully and explore alternative solutions

### Core Characteristics

**Autonomy**: Agents decide HOW to achieve goals, not just follow prescriptive steps

**Adaptability**: Adjust strategy based on runtime conditions and intermediate results

**Goal-Oriented**: Focus on outcomes (what to achieve) rather than procedures (how to achieve)

**Multi-Phase**: Complex objectives decomposed into manageable phases with dependencies

**Self-Monitoring**: Track progress, detect failures, and course-correct autonomously

### Distinction from Traditional Agents

| Traditional Agent             | Goal-Seeking Agent            |
| ----------------------------- | ----------------------------- |
| Follows fixed workflow        | Adapts workflow to context    |
| Prescriptive steps            | Outcome-oriented objectives   |
| Human intervention on failure | Autonomous recovery attempts  |
| Single-phase execution        | Multi-phase with dependencies |
| Rigid decision tree           | Dynamic strategy adjustment   |

### When Goal-Seeking Makes Sense

Goal-seeking agents excel when:

- **Problem space is large**: Many possible paths to success
- **Context varies**: Runtime conditions affect optimal approach
- **Failures are expected**: Need autonomous recovery without human intervention
- **Objectives are clear**: Success criteria well-defined but path is flexible
- **Multi-step complexity**: Requires coordination across phases with dependencies

### When to Avoid Goal-Seeking

Use traditional agents or scripts when:

- **Single deterministic path**: Only one way to achieve goal
- **Latency-critical**: Need fastest possible execution (no decision overhead)
- **Safety-critical**: Human verification required at each step
- **Simple workflow**: Complexity of goal-seeking exceeds benefit
- **Audit requirements**: Need deterministic, reproducible execution

## 2. When to Use This Pattern

### Problem Indicators

Use goal-seeking agents when you observe these patterns:

#### Pattern 1: Workflow Variability

**Indicators**:

- Same objective requires different approaches based on context
- Manual decisions needed at multiple points
- "It depends" answers when mapping workflow

**Example**: Release workflow that varies by:

- Environment (staging vs production)
- Change type (hotfix vs feature)
- Current system state (healthy vs degraded)

**Solution**: Goal-seeking agent evaluates context and adapts workflow

#### Pattern 2: Multi-Phase Complexity

**Indicators**:

- Objective requires 3-5+ distinct phases
- Phases have dependencies (output of phase N feeds phase N+1)
- Parallel execution opportunities exist
- Success criteria differ per phase

**Example**: Data pipeline with phases:

1. Data collection (multiple sources, parallel)
2. Transformation (depends on collection results)
3. Validation (depends on transformation output)
4. Publishing (conditional on validation pass)

**Solution**: Goal-seeking agent orchestrates phases, handles dependencies

#### Pattern 3: Autonomous Recovery Needed

**Indicators**:

- Failures are expected and recoverable
- Multiple retry/fallback strategies exist
- Human intervention is expensive or slow
- Can verify success programmatically

**Example**: CI diagnostic workflow:

- Test failures (retry with different approach)
- Environment issues (reconfigure and retry)
- Dependency conflicts (resolve and rerun)

**Solution**: Goal-seeking agent tries strategies until success or escalation

#### Pattern 4: Adaptive Decision Making

**Indicators**:

- Need to evaluate trade-offs at runtime
- Multiple valid solutions with different characteristics
- Optimization objectives (speed vs quality vs cost)
- Context-dependent best practices

**Example**: Fix agent pattern matching:

- QUICK mode for obvious issues
- DIAGNOSTIC mode for unclear problems
- COMPREHENSIVE mode for complex solutions

**Solution**: Goal-seeking agent selects strategy based on problem analysis

#### Pattern 5: Domain Expertise Required

**Indicators**:

- Requires specialized knowledge to execute
- Multiple domain-specific tools/approaches
- Best practices vary by domain
- Coordination of specialized sub-agents

**Example**: AKS SRE automation:

- Azure-specific operations (ARM, CLI)
- Kubernetes expertise (kubectl, YAML)
- Networking knowledge (CNI, ingress)
- Security practices (RBAC, Key Vault)

**Solution**: Goal-seeking agent with domain expertise coordinates specialized actions

### Decision Framework

Use this 5-question framework to evaluate goal-seeking applicability:

#### Question 1: Is the objective well-defined but path flexible?

**YES if**:

- Clear success criteria exist
- Multiple valid approaches
- Runtime context affects optimal path

**NO if**:

- Only one correct approach
- Path is deterministic
- Success criteria ambiguous

**Example YES**: "Ensure AKS cluster is production-ready" (many paths, clear criteria)
**Example NO**: "Run specific kubectl command" (one path, prescriptive)

#### Question 2: Are there multiple phases with dependencies?

**YES if**:

- Objective naturally decomposes into 3-5+ phases
- Phase outputs feed subsequent phases
- Some phases can execute in parallel
- Failures in one phase affect downstream phases

**NO if**:

- Single-phase execution sufficient
- No inter-phase dependencies
- Purely sequential with no branching

**Example YES**: Data pipeline (collect → transform → validate → publish)
**Example NO**: Format code with ruff (single atomic operation)

#### Question 3: Is autonomous recovery valuable?

**YES if**:

- Failures are common and expected
- Multiple recovery strategies exist
- Human intervention is expensive/slow
- Can verify success automatically

**NO if**:

- Failures are rare edge cases
- Manual investigation always required
- Safety-critical (human verification needed)
- Cannot verify success programmatically

**Example YES**: CI diagnostic workflow (try multiple fix strategies)
**Example NO**: Deploy to production (human approval required)

#### Question 4: Does context significantly affect approach?

**YES if**:

- Environment differences change strategy
- Current system state affects decisions
- Trade-offs vary by situation (speed vs quality vs cost)
- Domain-specific best practices apply

**NO if**:

- Same approach works for all contexts
- No environmental dependencies
- No trade-off decisions needed

**Example YES**: Fix agent (quick vs diagnostic vs comprehensive based on issue)
**Example NO**: Generate UUID (context-independent)

#### Question 5: Is the complexity justified?

**YES if**:

- Problem is repeated frequently (2+ times/week)
- Manual execution takes 30+ minutes
- High value from automation
- Maintenance cost is acceptable

**NO if**:

- One-off or rare problem
- Quick manual execution (< 5 minutes)
- Simple script suffices
- Maintenance cost exceeds benefit

**Example YES**: CI failure diagnosis (frequent, time-consuming, high value)
**Example NO**: One-time data migration (rare, script sufficient)

### Decision Matrix

| All 5 YES | Use Goal-Seeking Agent |
| 4 YES, 1 NO | Probably use Goal-Seeking Agent |
| 3 YES, 2 NO | Consider simpler agent or hybrid |
| 2 YES, 3 NO | Traditional agent likely better |
| 0-1 YES | Script or simple automation |

## 3. Architecture Pattern

### Component Architecture

Goal-seeking agents have four core components:

```python
# 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
```

### Execution Flow

```
┌─────────────────────────────────────────────────────────────┐
│ 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]              │
└─────────────────────────────────────────────────────────────┘
```

### Phase Dependency Management

Phases can have three relationship types:

**Sequential Dependency**: Phase B depends on Phase A completion

```
Phase A → Phase B → Phase C
```

**Parallel Execution**: Phases can run concurrently

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

**Conditional Branching**: Phase selection based on results

```
Phase A → [Decision] → Phase B (success path)
                    └→ Phase C (recovery path)
```

### State Management

Goal-seeking agents maintain state across phases:

```python
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
```

### Error Handling

Three error recovery strategies:

**Retry with Backoff**: Same approach, exponential delay

```python
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)
```

**Alternative Strategy**: Different approach to same goal

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

**Graceful Degradation**: Accept partial success

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

## 4. Integration with goal_agent_generator

The `goal_agent_generator` module provides the implementation for goal-seeking agents. Here's how to integrate:

### Core API

```python
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 Integration

```bash
# 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 Details

Extracts structured information from natural language:

```python
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"}
```

Domain classification:

- `data-processing`: Data transformation, analysis, ETL
- `security-analysis`: Vulnerability scanning, audits
- `automation`: Workflow automation, scheduling
- `testing`: Test generation, validation
- `deployment`: Release, publishing, distribution
- `monitoring`: Observability, alerting
- `integration`: API connections, webhooks
- `reporting`: Dashboards, metrics, summaries

Complexity determination:

- `simple`: Single-phase, < 50 words, basic operations
- `moderate`: 2-4 phases, 50-150 words, some coordination
- `complex`: 5+ phases, > 150 words, sophisticated orchestration

### ObjectivePlanner Details

Generates multi-phase execution plans:

```python
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}")
```

Phase templates by domain:

- **data-processing**: Collection → Transformation → Analysis → Reporting
- **security-analysis**: Reconnaissance → Vulnerability Detection → Risk Assessment → Reporting
- **automation**: Setup → Workflow Design → Execution → Validation
- **testing**: Test Planning → Implementation → Execution → Results Analysis
- **deployment**: Pre-deployment → Deployment → Verification → Post-deployment
- **monitoring**: Setup Monitors → Data Collection → Analysis → Alerting

### SkillSynthesizer Details

Maps capabilities to skills:

```python
from amplihack.goal_agent_generator import SkillSynthesizer

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

# lis