[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,90 +1,327 @@
---
id: wiki-2026-0508-finite-state-machines-fsm
title: Finite State Machines FSM
title: Finite State Machines (FSM)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [FSM-001]
aliases: [FSM, state machine, statechart, XState, hierarchical FSM, behavior tree]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, game-ai, fsm, State-pattern, software-Architecture]
confidence_score: 0.98
verification_status: applied
tags: [computer-science, fsm, state-machine, xstate, statechart, game-ai, control]
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: TypeScript / Python
framework: XState / Stateless / SCXML
---
# Finite State Machines (FSM, 유한 상태 머신)
# Finite State Machines (FSM)
## 📌 한 줄 통찰 (The Karpathy Summary)
> "복잡한 행동을 명확한 상태로 나누고, 조건에 따른 변천 과정을 설계하여 예측 가능한 지능을 구축하라" — 유한한 개수의 상태(State)와 상태 간의 전이(Transition), 그리고 전이를 발생시키는 이벤트로 시스템의 동작을 모델링하는 수학적/설계적 도구.
## 한 줄
> **"매 finite state + 매 transition (event-driven)"**. 매 oldest CS abstraction. 매 modern: 매 statechart (Harel), 매 XState, 매 behavior tree (game). 매 game AI, 매 UI workflow, 매 protocol, 매 LLM agent의 control 의 사용.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 시스템이 한 번에 오직 하나의 상태에만 머물도록 강제하고, 현재 상태와 입력값에 의해서만 다음 행동이 결정되도록 하여 복잡한 로직을 단순화하는 결정론적 제어 패턴.
- **핵심 구성 요소:**
- **States:** 시스템이 취할 수 있는 구체적인 행동이나 상황 (예: IDLE, CHASE, ATTACK).
- **Transitions:** 한 상태에서 다른 상태로 넘어가는 규칙.
- **[[Events|Events]] (Inputs):** 전이를 일으키는 자극 (예: 플레이어 발견, 체력 저하).
- **Actions:** 상태에 진입(Enter), 유지(Update), 혹은 퇴장(Exit)할 때 수행하는 작업.
- **의의:** 게임 AI, 컴파일러 설계, 네트워크 프로토콜, UI 네비게이션 등 로직의 명확한 관리가 필요한 모든 분야의 기반 기술.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순한 If-Else 문의 나열에서 벗어나, 상태 패턴(State Pattern)을 통해 코드의 확장성과 가독성을 획기적으로 높이는 방식으로 진화.
- **정책 변화:** Skybound 프로젝트의 모든 적 유닛과 보스 기체는 FSM 아키텍처를 기반으로 설계되어, 기획자의 의도에 맞는 정교하고 예측 가능한 행동 패턴을 보여줌.
### 매 component
- **State**: 매 finite set.
- **Initial state**.
- **Transition**: state × event → state.
- **Guard**: 매 transition condition.
- **Action**: 매 transition / entry / exit 의 effect.
## 🔗 지식 연결 (Graph)
- [[Behavior|Behavior]]-Trees-BT, Decision-Making, [[Physics|Physics]]-Engine,[[_system|system]]-Design-for-AI-Scale
- **Raw Source:** 10_Wiki/Topics/AI/[[Finite-State-Machines|Finite-State-Machines]]-FSM.md
### 매 variant
- **DFA**: 매 deterministic.
- **NFA**: 매 non-deterministic.
- **Statechart** (Harel): 매 nested + parallel.
- **HSM** (hierarchical).
- **Behavior tree**: 매 game alternative.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **Game AI**: 매 enemy behavior.
2. **UI**: 매 form workflow.
3. **Protocol**: 매 TCP, BLE.
4. **Compiler**: 매 lexer.
5. **LLM agent**: 매 conversation flow.
6. **Saga**: 매 distributed transaction.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Simple FSM (TypeScript)
```typescript
type State = 'idle' | 'fetching' | 'success' | 'error';
type Event = { type: 'FETCH' } | { type: 'RESOLVE'; data: any } | { type: 'REJECT' } | { type: 'RESET' };
## 🧪 검증 상태 (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
function transition(state: State, event: Event): State {
switch (state) {
case 'idle':
if (event.type === 'FETCH') return 'fetching';
break;
case 'fetching':
if (event.type === 'RESOLVE') return 'success';
if (event.type === 'REJECT') return 'error';
break;
case 'success':
case 'error':
if (event.type === 'RESET') return 'idle';
break;
}
return state;
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### XState (declarative)
```typescript
import { createMachine, assign, interpret } from 'xstate';
**선택 A를 써야 할 때:**
- *(TODO)*
const fetchMachine = createMachine({
id: 'fetch',
initial: 'idle',
context: { data: null, error: null },
states: {
idle: {
on: { FETCH: 'loading' },
},
loading: {
invoke: {
src: 'fetchData',
onDone: { target: 'success', actions: assign({ data: (_, e) => e.data }) },
onError: { target: 'failure', actions: assign({ error: (_, e) => e.data }) },
},
},
success: {
on: { REFRESH: 'loading' },
},
failure: {
on: { RETRY: 'loading' },
},
},
});
**선택 B를 써야 할 때:**
- *(TODO)*
const service = interpret(fetchMachine).start();
service.send({ type: 'FETCH' });
```
**기본값:**
> *(TODO)*
### Hierarchical (statechart)
```typescript
const trafficLight = createMachine({
initial: 'red',
states: {
red: {
after: { 5000: 'green' },
},
green: {
after: { 5000: 'yellow' },
},
yellow: {
initial: 'flashing',
states: {
flashing: {},
steady: {},
},
after: { 2000: 'red' },
},
},
});
```
## ❌ 안티패턴 (Anti-Patterns)
### Game AI FSM (Python)
```python
class EnemyAI:
def __init__(self):
self.state = 'patrol'
def update(self, world):
if self.state == 'patrol':
if world.player_visible(self): self.state = 'chase'
else: self.patrol_move()
elif self.state == 'chase':
if world.in_attack_range(self): self.state = 'attack'
elif not world.player_visible(self): self.state = 'search'
else: self.chase_player()
elif self.state == 'attack':
if not world.in_attack_range(self): self.state = 'chase'
else: self.attack()
elif self.state == 'search':
if world.search_timeout(): self.state = 'patrol'
elif world.player_visible(self): self.state = 'chase'
else: self.search_area()
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Behavior tree (alternative)
```python
class Node:
def tick(self): raise NotImplementedError
class Sequence(Node):
def __init__(self, *children): self.children = children
def tick(self):
for c in self.children:
if c.tick() != 'success': return 'fail'
return 'success'
class Selector(Node):
def __init__(self, *children): self.children = children
def tick(self):
for c in self.children:
if c.tick() == 'success': return 'success'
return 'fail'
ai = Selector(
Sequence(IsPlayerVisible(), AttackPlayer()),
PatrolArea(),
)
```
### Lexer (FSM)
```python
def lex(input):
state = 'start'
tokens = []
buf = ''
for ch in input + ' ':
if state == 'start':
if ch.isalpha(): state, buf = 'ident', ch
elif ch.isdigit(): state, buf = 'number', ch
elif state == 'ident':
if ch.isalnum(): buf += ch
else: tokens.append(('IDENT', buf)); state, buf = 'start', ''
elif state == 'number':
if ch.isdigit(): buf += ch
else: tokens.append(('NUMBER', int(buf))); state, buf = 'start', ''
return tokens
```
### LLM agent state machine
```typescript
const agent = createMachine({
initial: 'understanding',
states: {
understanding: {
on: { CLEAR: 'planning', NEEDS_INFO: 'asking' },
},
asking: {
on: { ANSWERED: 'understanding' },
},
planning: {
on: { READY: 'executing' },
},
executing: {
on: { COMPLETE: 'reflecting', NEED_REPLAN: 'planning', BLOCKED: 'asking' },
},
reflecting: {
on: { OK: 'done', RETRY: 'planning' },
},
done: { type: 'final' },
},
});
```
### Saga (distributed transaction)
```typescript
const orderSaga = createMachine({
initial: 'reserving',
context: { compensations: [] },
states: {
reserving: {
invoke: {
src: 'reserveInventory',
onDone: { target: 'charging', actions: 'pushCompensation' },
onError: 'failed',
},
},
charging: {
invoke: {
src: 'chargeCard',
onDone: 'completed',
onError: { target: 'compensating' },
},
},
compensating: {
invoke: {
src: 'runCompensations',
onDone: 'failed',
},
},
completed: { type: 'final' },
failed: { type: 'final' },
},
});
```
### State persistence
```typescript
const persistedState = JSON.stringify(service.getSnapshot());
localStorage.setItem('appState', persistedState);
// 매 restore
const restored = JSON.parse(localStorage.getItem('appState')!);
const restoredService = interpret(machine, { state: restored }).start();
```
### Visualizer (XState Inspector)
```typescript
import { inspect } from '@xstate/inspect';
inspect({ url: 'https://stately.ai/viz?inspect', iframe: false });
const service = interpret(machine, { devTools: true }).start();
```
### Test (path coverage)
```typescript
import { createModel } from '@xstate/test';
const testModel = createModel(machine).withEvents({
FETCH: { exec: async () => fireEvent.click(fetchBtn) },
RESOLVE: { ... },
});
testModel.getSimplePathPlans().forEach(plan => {
describe(plan.description, () => {
plan.paths.forEach(path => {
it(path.description, async () => {
await path.test(/* page */);
});
});
});
});
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| UI workflow | XState |
| Game AI | FSM or Behavior Tree |
| Lexer / parser | DFA |
| Distributed | Saga (XState compatible) |
| LLM agent | Statechart |
| Tiny linear | Plain switch |
**기본값**: 매 XState (TS) + 매 statechart (hierarchical) + 매 visualizer + 매 model-based test.
## 🔗 Graph
- 부모: [[Computer-Science]] · [[Control]]
- 변형: [[Statechart]] · [[Hierarchical-FSM]] · [[Behavior-Tree]]
- 응용: [[Game-AI]] · [[Saga-Pattern]] · [[LLM-Agent]]
- Adjacent: [[Exhaustiveness-Checking]] · [[Encapsulation-of-Domain-Invariants]] · [[Event-Driven-Architecture]]
## 🤖 LLM 활용
**언제**: 매 multi-step workflow. 매 game AI. 매 protocol.
**언제 X**: 매 1-2 state.
## ❌ 안티패턴
- **Boolean explosion**: 매 N flags 의 implicit FSM.
- **Hidden FSM**: 매 spaghetti.
- **No exhaustive transition**: 매 invalid state.
- **State + global side effect**: 매 untestable.
- **Reinvent XState**: 매 use library.
## 🧪 검증 / 중복
- Verified (Harel statecharts 1987, XState docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-04-26 | FSM auto |
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — FSM + 매 XState / hierarchical / game / saga / LLM agent code |