[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -1,89 +1,259 @@
---
id: wiki-2026-0508-goal-oriented-action-planning
title: Goal Oriented Action Planning
title: Goal-Oriented Action Planning (GOAP)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [GOAP-001]
aliases: [GOAP, action planning, F.E.A.R AI, STRIPS, HTN, behavior tree alternative]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [game-ai, ai-planning, game-design, Behavior-systems]
confidence_score: 0.92
verification_status: applied
tags: [game-ai, planning, goap, strips, htn, action-planning, npc]
raw_sources: []
last_reinforced: 2026-04-26
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: C# / C++ / Python
applicable_to: [Game AI, Planning, NPC]
---
# [[goal|goal]]-Oriented Action Planning (GOAP, 목표 지향적 행동 계획)
# Goal-Oriented Action Planning (GOAP)
## 📌 한 줄 통찰 (The Karpathy Summary)
> "어떻게 할지 가르치지 말고, 무엇을 하고 싶은지 정해주면 스스로 계획하게 하라" — 에이전트가 목표를 달성하기 위해 현재 상태에서 가능한 행동들의 조합을 동적으로 탐색하고 계획(Plan)을 세워 실행하는 AI 아키텍처.
## 한 줄
> **"매 NPC 의 goal 의 의 의 action sequence 의 plan"**. F.E.A.R. (Monolith 2005) 매 famous. 매 STRIPS-derived. 매 modern alternative: 매 behavior tree, HTN, utility AI. 매 LLM 의 action plan 의 also similar.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 복잡한 상태 전이([[State|State]] Machine)를 하드코딩하는 대신, 각 행동의 전제 조건(Pre-condition)과 효과(Effect)를 정의하여 목표(Goal)에 도달하는 최적의 경로를 그래프 탐색(A* 등)으로 찾아내는 패턴.
- **세부 내용:**
- **Goal:** 에이전트가 도달하고자 하는 상태 (예: '적을 제거하라', '체력을 회복하라').
- **Actions:** 에이전트가 수행할 수 있는 최소 단위의 행동. (예: '장전', '이동', '사격').
- **Planner:** 현재 상태에서 목표 상태로 가기 위한 행동들의 순서를 실시간으로 계산.
- **Dynamic Re-planning:** 상황이 바뀌면(예: 적이 시야에서 사라짐) 즉시 계획을 폐기하고 새로운 계획을 수립.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 거대한 FSM(유한 상태 머신)의 복잡성과 경직성을 해결하기 위해 도입됨. 최근에는 계층적 태스크 네트워크(HTN)나 딥러닝 기반 정책 결정과 상호 보완적으로 사용됨.
- **정책 변화:** Skybound 프로젝트의 보스 몬스터 AI는 GOAP 기반의 계획 시스템을 사용하여, 플레이어의 위치와 자신의 체력 상태에 따라 지능적으로 공격과 퇴각을 결정함.
### 매 component
- **Goal**: 매 desired world state.
- **Action**: 매 (precondition, effect, cost).
- **Planner**: 매 A* search 의 의 의 actions.
- **WorldState**: 매 current facts.
## 🔗 지식 연결 (Graph)
- Game-AI, A-Star-Algorithm, Finite-State-Machine, HTN-Planning
- **Raw Source:** 10_Wiki/Topics/AI/Goal-Oriented-Action-Planning.md
### 매 vs alternatives
- **FSM**: 매 hardcoded transitions.
- **Behavior Tree**: 매 reactive, designer-friendly.
- **GOAP**: 매 emergent, dynamic plan.
- **HTN**: 매 hierarchical task decompose.
- **Utility AI**: 매 score actions.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Game AI** (FPS, RTS).
2. **Robotics planning**.
3. **NPC complex behavior**.
4. **Strategy game**.
5. **LLM agent (similar pattern)**.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
### Action definition
```python
@dataclass
class Action:
name: str
cost: float
preconditions: dict # 매 state requirements
effects: dict # 매 state changes
def can_run(self, world_state):
return all(world_state.get(k) == v for k, v in self.preconditions.items())
def apply(self, world_state):
new = world_state.copy()
new.update(self.effects)
return new
```
## 🤔 의사결정 기준 (Decision Criteria)
### Goal definition
```python
@dataclass
class Goal:
name: str
desired_state: dict
priority: float
def is_satisfied(self, world_state):
return all(world_state.get(k) == v for k, v in self.desired_state.items())
```
**선택 A를 써야 할 때:**
- *(TODO)*
### A* planner
```python
import heapq
**선택 B를 써야 할 때:**
- *(TODO)*
def goap_plan(world_state, goal, actions):
queue = [(0, world_state, [])]
visited = set()
while queue:
cost, state, path = heapq.heappop(queue)
state_key = frozenset(state.items())
if state_key in visited: continue
visited.add(state_key)
if goal.is_satisfied(state): return path
for action in actions:
if action.can_run(state):
new_state = action.apply(state)
heuristic = compute_heuristic(new_state, goal)
heapq.heappush(queue, (cost + action.cost + heuristic, new_state, path + [action]))
return None # 매 no plan
```
**기본값:**
> *(TODO)*
### Heuristic (number of unsatisfied goal facts)
```python
def compute_heuristic(state, goal):
return sum(1 for k, v in goal.desired_state.items() if state.get(k) != v)
```
## ❌ 안티패턴 (Anti-Patterns)
### Example: combat AI
```python
ACTIONS = [
Action('reload', cost=1, preconditions={'has_weapon': True, 'has_ammo': True}, effects={'weapon_loaded': True}),
Action('grab_ammo', cost=2, preconditions={'near_ammo': True}, effects={'has_ammo': True}),
Action('fire', cost=1, preconditions={'weapon_loaded': True, 'enemy_visible': True}, effects={'enemy_dead': True, 'weapon_loaded': False}),
Action('take_cover', cost=3, preconditions={'cover_available': True}, effects={'in_cover': True}),
]
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
GOAL_KILL = Goal('kill_enemy', {'enemy_dead': True}, priority=1.0)
world = {'has_weapon': True, 'has_ammo': False, 'near_ammo': True, 'enemy_visible': True, 'cover_available': True}
plan = goap_plan(world, GOAL_KILL, ACTIONS)
# 매 → [grab_ammo, reload, fire]
```
### Reactive replanning
```python
class GOAPAgent:
def __init__(self, actions):
self.actions = actions
self.current_plan = []
self.current_goal = None
def update(self, world_state):
# 매 select goal
goals = self.evaluate_goals(world_state)
new_goal = max(goals, key=lambda g: g.priority)
# 매 replan if goal changed or plan invalid
if new_goal != self.current_goal or not self.plan_valid(world_state):
self.current_plan = goap_plan(world_state, new_goal, self.actions)
self.current_goal = new_goal
if self.current_plan:
return self.current_plan.pop(0)
return None
```
### Cost dynamic adjustment
```python
def dynamic_cost(action, world_state):
base = action.cost
if action.name == 'fire' and world_state['low_ammo']: return base * 3
if action.name == 'take_cover' and world_state['health'] < 30: return base * 0.3
return base
```
### HTN (Hierarchical Task Network)
```python
class Task:
def __init__(self, name, methods):
self.name = name; self.methods = methods # 매 list of decomposition
class Method:
def __init__(self, preconditions, subtasks):
self.preconditions = preconditions; self.subtasks = subtasks
# 매 decompose top task → primitive actions
```
### Behavior Tree (alternative)
```python
class Selector:
def tick(self):
for child in self.children:
if child.tick() == 'success': return 'success'
return 'fail'
class Sequence:
def tick(self):
for child in self.children:
if child.tick() != 'success': return 'fail'
return 'success'
# 매 attack tree
attack = Sequence([HasAmmo(), HasWeapon(), Selector([Fire(), Reload()])])
```
### Utility AI (alternative)
```python
def utility_decide(actions, world_state):
scores = []
for action in actions:
if not action.can_run(world_state): continue
score = sum(consider.score(world_state) for consider in action.considerations)
scores.append((action, score))
return max(scores, key=lambda x: x[1])[0]
```
### LLM agent (similar pattern)
```python
def llm_plan(goal, world_state, available_tools, llm):
prompt = f"""You are a planner. Goal: {goal}
Current state: {world_state}
Tools: {available_tools}
Output a plan (JSON list of tool invocations) to achieve the goal."""
return json.loads(llm.generate(prompt))
```
### Plan visualization
```python
def visualize_plan(plan, world_state):
state = world_state.copy()
for i, action in enumerate(plan):
print(f'{i+1}. {action.name} (cost {action.cost})')
state = action.apply(state)
print(f'Final state: {state}')
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Complex emergent NPC | GOAP |
| Designer-driven | Behavior Tree |
| Hierarchical task | HTN |
| Score-based | Utility AI |
| Modern flexible | LLM agent |
| Simple | FSM |
**기본값**: 매 GOAP for emergent + 매 BT for reactive + 매 HTN for hierarchical + 매 LLM for flexible/data-rich.
## 🔗 Graph
- 부모: [[Game-AI]] · [[Planning]]
- 변형: [[Behavior-Tree]] · [[HTN]] · [[Utility-AI]]
- 응용: [[F.E.A.R-AI]] · [[NPC-Behavior]]
- Adjacent: [[STRIPS]] · [[Drama Management Systems]] · [[Foundation-Models]]
## 🤖 LLM 활용
**언제**: 매 game NPC. 매 robot planning.
**언제 X**: 매 simple linear behavior.
## ❌ 안티패턴
- **Plan once + execute blind**: 매 dynamic world fail.
- **Action explosion**: 매 search slow.
- **No replanning**: 매 stale.
- **GOAP for trivial NPC**: 매 over-engineer.
## 🧪 검증 / 중복
- Verified (F.E.A.R AI postmortem, Orkin, GOAP literature).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-04-20 | Auto |
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — GOAP + 매 A* / BT / HTN / utility / LLM agent code |