planning-goal
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGoal-Oriented Action Planning (GOAP)
面向目标的行动规划(GOAP)
Dynamic planning system using A* search to find optimal action sequences for complex objectives
基于A*搜索的动态规划系统,为复杂目标寻找最优行动序列
Quick Start
快速开始
bash
undefinedbash
undefinedDefine goal state and current state
定义目标状态与当前状态
Current: {code_written: true, tests_written: false, deployed: false}
Goal: {deployed: true, monitoring: true}
Current: {code_written: true, tests_written: false, deployed: false}
Goal: {deployed: true, monitoring: true}
GOAP generates optimal plan:
GOAP生成最优计划:
- write_tests -> tests_written: true
- run_tests -> tests_passed: true
- build_application -> built: true
- deploy_application -> deployed: true
- setup_monitoring -> monitoring: true
undefined- write_tests -> tests_written: true
- run_tests -> tests_passed: true
- build_application -> built: true
- deploy_application -> deployed: true
- setup_monitoring -> monitoring: true
undefinedWhen to Use
适用场景
- Complex multi-step tasks with dependencies requiring optimal ordering
- High-level goals needing systematic breakdown into concrete actions
- Deployment workflows with many prerequisites
- Refactoring projects requiring incremental, safe transformations
- Any task where conditions must be met before actions can execute
- 存在依赖关系、需要最优排序的复杂多步骤任务
- 需要系统拆解为具体行动的高级目标
- 包含众多前置条件的部署工作流
- 需要增量、安全转换的重构项目
- 任何需要先满足特定条件才能执行行动的任务
Prerequisites
前置条件
- Clear definition of current state (what is true now)
- Clear definition of goal state (what should be true)
- Available actions with known preconditions and effects
- 清晰定义当前状态(当前已达成的条件)
- 清晰定义目标状态(需要达成的条件)
- 明确可用行动及其前置条件与执行效果
Core Concepts
核心概念
GOAP Algorithm
GOAP算法
GOAP uses A* pathfinding through state space:
- State Space: All possible combinations of world facts
- Actions: Transforms with preconditions and effects
- Heuristic: Estimated cost to reach goal from current state
- Optimal Path: Lowest-cost action sequence achieving goal
GOAP通过A*路径搜索遍历状态空间:
- 状态空间:所有可能的世界事实组合
- 行动:带有前置条件与执行效果的状态转换操作
- 启发函数:从当前状态到目标状态的预估成本
- 最优路径:实现目标的最低成本行动序列
Action Definition
行动定义
Action: action_name
Preconditions: {condition1: true, condition2: value}
Effects: {new_condition: true, changed_value: new_value}
Cost: numeric_value
Execution: llm|code|hybrid
Fallback: alternative_actionAction: action_name
Preconditions: {condition1: true, condition2: value}
Effects: {new_condition: true, changed_value: new_value}
Cost: numeric_value
Execution: llm|code|hybrid
Fallback: alternative_actionExecution Modes
执行模式
| Mode | Description | Use Case |
|---|---|---|
| Focused | Direct action execution | Specific requested actions |
| Closed | Single-domain planning | Defined action set |
| Open | Creative problem solving | Novel solution discovery |
| 模式 | 描述 | 适用场景 |
|---|---|---|
| Focused | 直接执行指定行动 | 特定的请求行动 |
| Closed | 单领域规划 | 已定义的行动集合 |
| Open | 创造性问题解决 | 探索全新解决方案 |
Implementation Pattern
实现模式
typescript
interface WorldState {
[key: string]: boolean | string | number;
}
interface Action {
name: string;
preconditions: Partial<WorldState>;
effects: Partial<WorldState>;
cost: number;
execution: 'llm' | 'code' | 'hybrid';
tools?: string[];
fallback?: string;
}
interface Plan {
actions: Action[];
totalCost: number;
estimatedTime: string;
}
function generatePlan(
currentState: WorldState,
goalState: WorldState,
availableActions: Action[]
): Plan {
// A* search through state space
// Returns optimal action sequence
}typescript
interface WorldState {
[key: string]: boolean | string | number;
}
interface Action {
name: string;
preconditions: Partial<WorldState>;
effects: Partial<WorldState>;
cost: number;
execution: 'llm' | 'code' | 'hybrid';
tools?: string[];
fallback?: string;
}
interface Plan {
actions: Action[];
totalCost: number;
estimatedTime: string;
}
function generatePlan(
currentState: WorldState,
goalState: WorldState,
availableActions: Action[]
): Plan {
// A* search through state space
// Returns optimal action sequence
}Configuration
配置
yaml
goap_config:
planning:
algorithm: a_star
max_depth: 50
timeout_ms: 5000
execution:
mode: adaptive # focused | closed | open
parallel_actions: true
replan_on_failure: true
monitoring:
ooda_loop: true
observe_interval_ms: 1000
cost_weights:
time: 1.0
risk: 2.0
resource: 1.5yaml
goap_config:
planning:
algorithm: a_star
max_depth: 50
timeout_ms: 5000
execution:
mode: adaptive # focused | closed | open
parallel_actions: true
replan_on_failure: true
monitoring:
ooda_loop: true
observe_interval_ms: 1000
cost_weights:
time: 1.0
risk: 2.0
resource: 1.5Usage Examples
使用示例
Example 1: Software Deployment
示例1:软件部署
yaml
current_state:
code_written: true
tests_written: false
tests_passed: false
built: false
deployed: false
monitoring: false
goal_state:
deployed: true
monitoring: true
available_actions:
- name: write_tests
preconditions: {code_written: true}
effects: {tests_written: true}
cost: 3
- name: run_tests
preconditions: {tests_written: true}
effects: {tests_passed: true}
cost: 1
- name: build_application
preconditions: {tests_passed: true}
effects: {built: true}
cost: 2
- name: deploy_application
preconditions: {built: true}
effects: {deployed: true}
cost: 2
- name: setup_monitoring
preconditions: {deployed: true}
effects: {monitoring: true}
cost: 1yaml
current_state:
code_written: true
tests_written: false
tests_passed: false
built: false
deployed: false
monitoring: false
goal_state:
deployed: true
monitoring: true
available_actions:
- name: write_tests
preconditions: {code_written: true}
effects: {tests_written: true}
cost: 3
- name: run_tests
preconditions: {tests_written: true}
effects: {tests_passed: true}
cost: 1
- name: build_application
preconditions: {tests_passed: true}
effects: {built: true}
cost: 2
- name: deploy_application
preconditions: {built: true}
effects: {deployed: true}
cost: 2
- name: setup_monitoring
preconditions: {deployed: true}
effects: {monitoring: true}
cost: 1Generated Plan (cost: 9)
Generated Plan (cost: 9)
plan:
- write_tests
- run_tests
- build_application
- deploy_application
- setup_monitoring
undefinedplan:
- write_tests
- run_tests
- build_application
- deploy_application
- setup_monitoring
undefinedExample 2: Complex Refactoring
示例2:复杂重构
yaml
current_state:
legacy_code: true
documented: false
tested: false
refactored: false
goal_state:
refactored: true
tested: true
documented: true
generated_plan:
1. analyze_codebase:
effects: {understood: true}
2. write_tests_for_legacy:
requires: understood
effects: {tested: true}
3. document_current_behavior:
requires: understood
effects: {documented: true}
4. plan_refactoring:
requires: [documented, tested]
effects: {plan_ready: true}
5. execute_refactoring:
requires: plan_ready
effects: {refactored: true}
6. verify_tests_pass:
requires: refactored
validates: goal_achievedyaml
current_state:
legacy_code: true
documented: false
tested: false
refactored: false
goal_state:
refactored: true
tested: true
documented: true
generated_plan:
1. analyze_codebase:
effects: {understood: true}
2. write_tests_for_legacy:
requires: understood
effects: {tested: true}
3. document_current_behavior:
requires: understood
effects: {documented: true}
4. plan_refactoring:
requires: [documented, tested]
effects: {plan_ready: true}
5. execute_refactoring:
requires: plan_ready
effects: {refactored: true}
6. verify_tests_pass:
requires: refactored
validates: goal_achievedExample 3: OODA Loop Monitoring
示例3:OODA Loop监控
typescript
// Observe-Orient-Decide-Act loop during execution
async function executeWithOODA(plan: Plan): Promise<Result> {
for (const action of plan.actions) {
// OBSERVE: Check current state
const currentState = await observeState();
// ORIENT: Analyze deviations
const deviation = analyzeDeviation(currentState, expectedState);
// DECIDE: Replan if needed
if (deviation.significant) {
const newPlan = await replan(currentState, goalState);
return executeWithOODA(newPlan);
}
// ACT: Execute action
await executeAction(action);
}
}typescript
// Observe-Orient-Decide-Act loop during execution
async function executeWithOODA(plan: Plan): Promise<Result> {
for (const action of plan.actions) {
// OBSERVE: Check current state
const currentState = await observeState();
// ORIENT: Analyze deviations
const deviation = analyzeDeviation(currentState, expectedState);
// DECIDE: Replan if needed
if (deviation.significant) {
const newPlan = await replan(currentState, goalState);
return executeWithOODA(newPlan);
}
// ACT: Execute action
await executeAction(action);
}
}Execution Checklist
执行检查清单
- Define current state completely
- Define goal state with all required conditions
- Inventory available actions with preconditions/effects
- Calculate action costs realistically
- Generate plan using A* search
- Review plan for feasibility
- Execute with OODA loop monitoring
- Handle failures with adaptive replanning
- Verify goal state achieved
- 完整定义当前状态
- 定义包含所有必要条件的目标状态
- 梳理所有可用行动及其前置条件/执行效果
- 真实计算行动成本
- 使用A*搜索生成计划
- 审核计划的可行性
- 基于OODA Loop监控执行
- 通过自适应重规划处理失败
- 验证目标状态已达成
Best Practices
最佳实践
- Atomic Actions: Each action should have one clear purpose
- Explicit Preconditions: All requirements must be verifiable
- Predictable Effects: Action outcomes should be consistent
- Realistic Costs: Use costs to guide optimal path selection
- Replan Early: Detect failures quickly and adapt
- Parallel Where Possible: Execute independent actions concurrently
- 原子化行动:每个行动应仅有一个明确的目标
- 明确前置条件:所有要求必须可验证
- 可预测效果:行动的结果应保持一致
- 真实成本:通过成本引导最优路径选择
- 尽早重规划:快速检测失败并调整
- 尽量并行:并发执行独立行动
Error Handling
错误处理
Plan Generation Failures
计划生成失败
typescript
// No valid path exists
if (!plan) {
// Analyze which preconditions cannot be satisfied
const unsatisfiable = findUnsatisfiablePreconditions(goalState);
console.error(`Cannot reach goal: missing ${unsatisfiable}`);
// Suggest partial goals that ARE achievable
const partialGoals = suggestAchievableSubsets(goalState);
}typescript
// No valid path exists
if (!plan) {
// Analyze which preconditions cannot be satisfied
const unsatisfiable = findUnsatisfiablePreconditions(goalState);
console.error(`Cannot reach goal: missing ${unsatisfiable}`);
// Suggest partial goals that ARE achievable
const partialGoals = suggestAchievableSubsets(goalState);
}Execution Failures
执行失败
typescript
// Action failed during execution
if (actionResult.failed) {
// Check if alternative action available
if (action.fallback) {
await executeAction(action.fallback);
} else {
// Replan from current state
const newPlan = await replan(currentState, goalState);
}
}typescript
// Action failed during execution
if (actionResult.failed) {
// Check if alternative action available
if (action.fallback) {
await executeAction(action.fallback);
} else {
// Replan from current state
const newPlan = await replan(currentState, goalState);
}
}Metrics & Success Criteria
指标与成功标准
| Metric | Target | Description |
|---|---|---|
| Plan Generation Time | < 5s | Time to generate optimal plan |
| Goal Achievement Rate | > 95% | Percentage of goals fully achieved |
| Replanning Frequency | < 20% | Actions requiring replanning |
| Cost Accuracy | +/- 15% | Actual vs estimated cost |
| 指标 | 目标值 | 描述 |
|---|---|---|
| 计划生成时间 | < 5秒 | 生成最优计划的时间 |
| 目标达成率 | > 95% | 完全达成目标的比例 |
| 重规划频率 | < 20% | 需要重规划的行动占比 |
| 成本准确率 | +/- 15% | 实际成本与预估成本的误差范围 |
Integration Points
集成点
MCP Tools
MCP工具
javascript
// Orchestrate GOAP plan across swarm
task: "execute_goap_plan",
strategy: "adaptive",
priority: "high"
});
// Store successful patterns
action: "store",
namespace: "goap-patterns",
key: "deployment_plan_v1",
value: JSON.stringify(successfulPlan)
});javascript
// Orchestrate GOAP plan across swarm
task: "execute_goap_plan",
strategy: "adaptive",
priority: "high"
});
// Store successful patterns
action: "store",
namespace: "goap-patterns",
key: "deployment_plan_v1",
value: JSON.stringify(successfulPlan)
});Hooks
钩子
bash
undefinedbash
undefinedPre-task: Initialize GOAP session
Pre-task: Initialize GOAP session
Post-task: Store learned patterns
Post-task: Store learned patterns
undefinedundefinedRelated Skills
相关技能
- planning-code-goal - SPARC-enhanced code planning
- sparc-workflow - Structured development
- agent-orchestration - Swarm coordination
- planning-code-goal - 基于SPARC增强的代码规划
- sparc-workflow - 结构化开发
- agent-orchestration - 集群协调
References
参考资料
Version History
版本历史
- 1.0.0 (2026-01-02): Initial release - converted from goal-planner agent
- 1.0.0 (2026-01-02): 初始版本 - 由目标规划Agent转换而来