refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조

에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게
[공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류.
문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인).

- Topic_Programming → Domain_Programming (내부 구조 보존)
- Topic_Graphic → Domain_Design
- Topic_Business → Domain_Product
- Topic_General → Domain_General
- _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning),
  Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing)
- 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서)
- 빈 폴더 정리 (memory/procedures)
- 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Antigravity Agent
2026-07-11 11:05:56 +09:00
parent 6549ead309
commit c24165b8bc
6193 changed files with 1717 additions and 31 deletions
@@ -0,0 +1,185 @@
---
id: ai-agentic-patterns
title: Agentic Patterns — Plan / Reflect / Multi-agent
category: Coding
status: draft
source_trust_level: B
verification_status: conceptual
created_at: 2026-05-09
updated_at: 2026-05-09
tags: [ai, agent, agentic, vibe-coding]
tech_stack: { language: "TS / LLM", applicable_to: ["Backend"] }
applied_in: []
aliases: [agent, ReAct, Reflexion, multi-agent, planner, supervisor, swarm]
---
# Agentic Patterns
> Tool 호출 + 추론을 묶은 자율 시스템. **Plan → Execute → Reflect** loop. Multi-agent (각 역할별) 가 복잡 작업에 강력. 단 비용 / 신뢰성 / 안전성 = 새 도전.
## 📖 핵심 개념
- ReAct: Reasoning + Acting 인터리브 (위 function calling 의 기본).
- Plan-and-Execute: 먼저 계획 세움 → 실행.
- Reflection: 결과 자체 평가 → 재시도.
- Multi-agent: 역할별 (planner / coder / reviewer).
## 💻 코드 패턴
### Plan-and-Execute
```ts
async function planAndExecute(task: string) {
// 1. Plan
const plan = await llm.complete({
system: 'Decompose into 3-7 numbered steps. Output JSON: {"steps":[...]}.',
user: task,
response_format: { type: 'json_object' },
});
const steps = JSON.parse(plan).steps as string[];
// 2. Execute
const results: string[] = [];
for (const step of steps) {
const r = await agentLoop(step + `\n\nContext from previous: ${results.join('\n')}`);
results.push(r);
}
// 3. Synthesize
return llm.complete({
system: 'Synthesize the results.',
user: `Task: ${task}\n\nResults:\n${results.map((r, i) => `Step ${i + 1}: ${r}`).join('\n')}`,
});
}
```
### Reflection (자체 평가)
```ts
async function reflectiveAgent(task: string, maxAttempts = 3) {
let result: string | null = null;
for (let i = 0; i < maxAttempts; i++) {
result = await agentLoop(task + (i > 0 ? `\n\nPrevious attempt critique: ${critique}` : ''));
const critique = await llm.complete({
system: 'Evaluate the answer. If perfect, output "OK". Otherwise, point out specific issues.',
user: `Task: ${task}\nAnswer: ${result}`,
});
if (critique.startsWith('OK')) return result;
}
return result;
}
```
### Multi-agent (Planner + Worker)
```ts
async function multiAgent(task: string) {
const planner = createAgent({
system: 'You decompose tasks. Output JSON tasks for workers.',
tools: [],
});
const coder = createAgent({
system: 'You write code.',
tools: [readFile, writeFile, runTest],
});
const reviewer = createAgent({
system: 'You review code for bugs and style.',
tools: [readFile],
});
const tasks = JSON.parse(await planner.run(task));
for (const t of tasks) {
const code = await coder.run(t);
const review = await reviewer.run(code);
if (review.includes('LGTM')) continue;
await coder.run(`Fix issues: ${review}`); // refine
}
}
```
### Supervisor / Worker (LangGraph 스타일)
```ts
type State = { task: string; messages: Message[]; nextAgent: 'coder' | 'reviewer' | 'done' };
async function supervisor(state: State): Promise<State> {
const decision = await llm.complete({
system: 'Decide next: coder, reviewer, or done.',
user: JSON.stringify(state),
});
return { ...state, nextAgent: parseDecision(decision) };
}
async function graph(initial: State): Promise<State> {
let state = initial;
while (state.nextAgent !== 'done') {
state = await supervisor(state);
if (state.nextAgent === 'coder') state = await coderNode(state);
if (state.nextAgent === 'reviewer') state = await reviewerNode(state);
}
return state;
}
```
### Memory (단순)
```ts
class AgentMemory {
private notes: { ts: number; content: string }[] = [];
add(c: string) { this.notes.push({ ts: Date.now(), content: c }); }
recent(n = 10) { return this.notes.slice(-n).map(x => x.content).join('\n'); }
}
```
복잡 = vector DB + retrieval.
### 안전 가드 (guardrails)
```ts
async function safeExecute(plan: Step) {
// High-risk: 사용자 confirm
if (plan.action === 'delete_file' || plan.action === 'send_email') {
const ok = await askUser(`Confirm: ${plan.summary}`);
if (!ok) return { skipped: true };
}
return await execute(plan);
}
```
### Cost / iteration cap
```ts
class Budget {
constructor(private maxTokens: number, private maxIters: number) {}
used = { tokens: 0, iters: 0 };
check() {
if (this.used.tokens > this.maxTokens) throw new Error('budget exceeded');
if (this.used.iters > this.maxIters) throw new Error('iter limit');
}
}
```
## 🤔 의사결정 기준
| 작업 | 패턴 |
|---|---|
| 1-2 step | 단순 tool loop |
| 멀티 step + 반복 | Plan-and-Execute |
| 정확성 critical | Reflection |
| 복잡 도메인 (코딩, 조사) | Multi-agent |
| Long-running (시간 단위) | Temporal / Durable agents |
| 사용자 in-the-loop | 중간 confirm |
## ❌ 안티패턴
- **무한 loop 가능성**: max iters / max tokens / max time.
- **High-stakes action 자동**: 결제 / 삭제 / 메일은 confirm.
- **Memory 없이 long task**: context 잃음.
- **Agent 가 외부 prompt injection 따름**: system 권위 명시 + sanitize.
- **1 LLM 모든 역할**: 너무 큰 prompt + 혼란. 분리.
- **Reflection 무한**: 같은 결과 반복 — limit.
- **Cost 추적 없음**: 1 task 가 $10 — 알아채기 늦음.
## 🤖 LLM 활용 힌트
- Plan + tool loop + reflection + budget 4종.
- Multi-agent = 역할별 분리.
- Guardrail (HITL) 항상 있어야.
## 🔗 관련 문서
- [[AI_Function_Calling_Deep]]
- [[AI_Prompt_Engineering_Patterns]]
- [[AI_LLM_Eval_Patterns]]