[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,109 +1,173 @@
|
||||
---
|
||||
id: wiki-2026-0508-s-component-state-store
|
||||
title: S component (State Store)
|
||||
title: S-component (State Store)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [State Store, Agent State, S-component]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.85
|
||||
verification_status: applied
|
||||
tags: [agent, state, architecture, llm]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
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
|
||||
framework: langgraph/anthropic-sdk
|
||||
---
|
||||
|
||||
# [[S-component (State Store)|S-component (State Store)]]
|
||||
# S-component (State Store)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
S-component(State Store)는 에이전트 하네스의 '기억'을 담당하는 물리적/논리적 저장소 계층이다. 에이전트의 현재 작업 상태, 과거 대화 이력, 추출된 지식, 그리고 영구적으로 보존해야 할 사용자 선호도를 저장하고 관리한다. 단순한 데이터베이스를 넘어, 에이전트가 시간이 지남에 따라 학습하고 진화할 수 있는 토대를 제공한다.
|
||||
## 매 한 줄
|
||||
> **"매 LLM agent 의 working memory + 영속 store"**. 매 LATS / LangGraph / Anthropic Memory Tool 2025 의 backbone 컴포넌트. 매 ephemeral conversation context 의 limit (200K-1M token) 을 넘어 agent 의 task-state, scratchpad, learned facts 를 영속화.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **다층 저장 구조**:
|
||||
* **단기 상태 (Short-term)**: 현재 세션의 휘발성 데이터 및 즉각적인 작업 맥락 보존.
|
||||
* **영구 상태 (Long-term)**: 세션을 넘어 지속되는 사용자 프로필, 프로젝트 규칙, 자가 학습된 지식 저장.
|
||||
* **체크포인트 (Checkpoints)**: 작업 중 특정 시점의 전체 상태를 스냅샷으로 저장하여 실패 시 복구 가능하게 함.
|
||||
* **지식 인덱싱 (RAG Integration)**: 대규모 텍스트나 데이터를 벡터 임베딩하여 에이전트가 필요할 때 의미 기반 검색(Semantic Search)을 통해 정보를 불러올 수 있도록 지원한다.
|
||||
* **데이터 직렬화 및 동기화**: 메모리 내의 복잡한 에이전트 상태 객체를 영구 저장소(JSON, SQL, Vector DB 등)에 효율적으로 저장하고, 여러 장치나 세션 간에 동기화한다.
|
||||
* **메모리 거버넌스**: 정보의 유효 기간(TTL)을 설정하여 오래된 정보를 자동으로 삭제하거나, 중요도가 낮은 데이터를 요약하여 저장 공간을 최적화(Compaction)한다.
|
||||
* **보안 및 암호화**: 저장된 메모리에 포함된 민감한 사용자 데이터나 시스템 비밀번호 등을 암호화하여 외부 유출을 방지한다.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **검색 정확도 vs 속도**: 저장된 데이터가 방대해질수록 관련 정보를 찾는 데 더 많은 시간과 컴퓨팅 자원이 소모된다.
|
||||
* **데이터 오염 (Memory Poisoning)**: 잘못된 정보가 S-component에 기록되면 이후 에이전트의 모든 판단에 악영향을 미치는 '영구적 지능 저하'가 발생할 수 있다.
|
||||
* **개인정보 보호**: 에이전트가 사용자의 모든 행동을 기억하게 될 때 발생하는 프라이버시 침해 리스크를 관리해야 한다.
|
||||
### 매 Layer
|
||||
- **Working memory**: current turn 의 scratchpad (tool result, observations).
|
||||
- **Episodic memory**: 매 session log + summarization.
|
||||
- **Semantic memory**: extracted facts + embeddings (vector DB).
|
||||
- **Procedural**: skill / playbook (file system).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
### Related Concepts
|
||||
* [[Agent Memory System|Agent Memory System]]
|
||||
* 연결 이유: S-component가 실질적으로 구현하는 논리적 시스템이다.
|
||||
* [[Inference-Coupled Persistence|Inference-Coupled Persistence]]
|
||||
* 연결 이유: 추론을 통해 S-component에 지식을 공급하는 기술적 방법이다.
|
||||
* [[C-component (Context Manager)|C-component (Context Manager)]]
|
||||
* 연결 이유: S-component에서 저장된 정보를 꺼내어 실제 모델 입력으로 변환하는 파트너이다.
|
||||
### 매 vs Context Window
|
||||
- Context = read-only attention. State = read-write.
|
||||
- Context = volatile. State = persistent across sessions.
|
||||
- Context = expensive (caching). State = cheap (KV / vector).
|
||||
|
||||
### Deeper Research Questions
|
||||
* 에이전트가 '잊어야 할 정보'를 스스로 판단하여 폐기하는 '능동적 망각 알고리즘'은 어떻게 설계해야 하는가?
|
||||
* 수백만 개의 에피소드 기억 중 현재 작업의 '인과 관계'를 가장 잘 설명하는 과거 사례를 순위화(Ranking)하는 최적의 모델은 무엇인가?
|
||||
* 분산 환경에서 여러 에이전트 하네스가 하나의 거대한 S-component를 공유할 때 발생하는 쓰기 충돌과 데이터 일관성 문제를 어떻게 해결하는가?
|
||||
### 매 응용
|
||||
1. Multi-session task agent (e.g., research assistant).
|
||||
2. CRM-style customer history.
|
||||
3. Coding agent 의 codebase index + recent edits.
|
||||
4. Game NPC memory.
|
||||
|
||||
### Practical Application Contexts
|
||||
* **Implementation:** SQLite나 PostgreSQL(pgvector)을 사용하여 로컬 및 서버 사이드 상태 저장소를 구축하고, 에이전트의 `MemoryState` 클래스와 연동한다.
|
||||
* **System Design:** 멀티 테넌트(Multi-tenant) 에이전트 서비스 구축 시, 사용자별로 S-component를 물리적으로 분리하여 데이터 유출 리스크를 원천 차단한다.
|
||||
## 💻 패턴
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-01*
|
||||
### LangGraph state schema
|
||||
```python
|
||||
from typing import TypedDict, Annotated
|
||||
from langgraph.graph import StateGraph
|
||||
import operator
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
class AgentState(TypedDict):
|
||||
messages: Annotated[list, operator.add]
|
||||
scratchpad: dict
|
||||
tool_calls: Annotated[list, operator.add]
|
||||
final_answer: str | None
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(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
|
||||
graph = StateGraph(AgentState)
|
||||
graph.add_node("plan", planner)
|
||||
graph.add_node("act", actor)
|
||||
graph.add_edge("plan", "act")
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Anthropic Memory Tool 2025
|
||||
```python
|
||||
import anthropic
|
||||
client = anthropic.Anthropic()
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4096,
|
||||
tools=[{"type": "memory_20250604", "name": "memory"}],
|
||||
messages=[{"role": "user", "content": "Remember: I prefer Python type hints."}],
|
||||
extra_headers={"anthropic-beta": "context-management-2025-06-04"},
|
||||
)
|
||||
# Memory persisted across calls; agent reads/writes via tool
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Redis-backed working state
|
||||
```ts
|
||||
import { createClient } from 'redis';
|
||||
const redis = createClient({ url: process.env.REDIS_URL });
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
class AgentStateStore {
|
||||
async get(sessionId: string): Promise<AgentState> {
|
||||
const data = await redis.get(`agent:${sessionId}`);
|
||||
return data ? JSON.parse(data) : { scratchpad: {}, messages: [] };
|
||||
}
|
||||
async set(sessionId: string, state: AgentState) {
|
||||
await redis.set(`agent:${sessionId}`, JSON.stringify(state), { EX: 3600 });
|
||||
}
|
||||
async append(sessionId: string, msg: Message) {
|
||||
await redis.rPush(`agent:${sessionId}:msgs`, JSON.stringify(msg));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Vector store for semantic
|
||||
```ts
|
||||
import { Pinecone } from '@pinecone-database/pinecone';
|
||||
const pc = new Pinecone();
|
||||
const idx = pc.index('agent-memory');
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
async function remember(fact: string, embed: (s: string) => Promise<number[]>) {
|
||||
const vec = await embed(fact);
|
||||
await idx.upsert([{ id: crypto.randomUUID(), values: vec, metadata: { fact, ts: Date.now() }}]);
|
||||
}
|
||||
async function recall(query: string, embed: (s: string) => Promise<number[]>) {
|
||||
const vec = await embed(query);
|
||||
const r = await idx.query({ vector: vec, topK: 5, includeMetadata: true });
|
||||
return r.matches.map(m => m.metadata?.fact);
|
||||
}
|
||||
```
|
||||
|
||||
### Summarization compaction
|
||||
```ts
|
||||
async function compactState(s: AgentState): Promise<AgentState> {
|
||||
if (s.messages.length < 50) return s;
|
||||
const summary = await llm.summarize(s.messages.slice(0, 30));
|
||||
return { ...s, messages: [{role: 'system', content: summary}, ...s.messages.slice(30)] };
|
||||
}
|
||||
```
|
||||
|
||||
### S-component in 6-component pattern (S/T/L/I/M/E)
|
||||
```ts
|
||||
// S = State, T = Tools, L = LLM, I = Input, M = Memory, E = Effect
|
||||
type Agent = {
|
||||
S: StateStore;
|
||||
T: ToolRegistry;
|
||||
L: LLMClient;
|
||||
I: InputParser;
|
||||
M: MemoryRetriever;
|
||||
E: SideEffectExecutor;
|
||||
};
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Single-turn, stateless | No S-component |
|
||||
| Multi-turn, single session | In-memory map |
|
||||
| Cross-session, single user | Redis / SQLite |
|
||||
| Production multi-user | DB + vector store + memory tool |
|
||||
| Coding agent | File system + git as state |
|
||||
|
||||
**기본값**: Redis + Postgres + Anthropic Memory Tool — 2026 의 production pattern.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Agent Architecture]] · [[Memory Systems]]
|
||||
- 변형: [[Working Memory]] · [[Episodic Memory]] · [[Semantic Memory]]
|
||||
- 응용: [[LangGraph]] · [[Anthropic Memory Tool]] · [[LATS]]
|
||||
- Adjacent: [[T-component (Tool Registry)]] · [[Context Engineering]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: state schema design, summarization prompt, recall query.
|
||||
**언제 X**: high-throughput stateless API (overhead ↑).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Unbounded growth**: state 의 GC 부재 → cost explosion.
|
||||
- **Stale state**: TTL 없는 cache 의 contradiction.
|
||||
- **Tight coupling**: S 와 L 의 직접 dep → testing 어려움.
|
||||
- **No versioning**: schema migration 깨짐.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (LangGraph docs, Anthropic Memory Tool 2025 release notes).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — S-component full coverage |
|
||||
|
||||
Reference in New Issue
Block a user