docs(10_Wiki): Topic_Business/General/Graphic/Programming을 Topics/ 하위로 이동
최상위 10_Wiki/Topic_*였던 4개 카테고리 폴더를 10_Wiki/Topics/Topic_* 로 재배치. 콘텐츠 변경 없음(순수 폴더 이동) — Topics/ 하위 나머지 폴더는 이미 지난 커밋에서 전부 정리된 상태(잔존 항목은 에이전트 운영 상태 및 사용자가 보존을 요청한 업데이트0615/무제 3.canvas 뿐).
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
---
|
||||
id: wiki-2026-0508-5r-structure
|
||||
title: 5R Structure
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [5Rs Framework, Five Rs, 5R Communication, Replication 5R]
|
||||
duplicate_of: none
|
||||
source_trust_level: B
|
||||
confidence_score: 0.8
|
||||
verification_status: applied
|
||||
tags: [framework, communication, project-management, structuring]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: na
|
||||
framework: na
|
||||
---
|
||||
|
||||
# 5R Structure
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 5R 은 매 communication / project / data lifecycle 을 매 5 phase 로 grouping 하는 mnemonic"**. 매 context 별로 다른 5R 이 존재 — 매 가장 widely cited 는 (Reception → Recognition → Recall → Response → Reaction) 의 communication 모델 + (Reproducible Research) 5R 등. 매 2026 에서 매 LLM agent design (RAG → 매 5R 변형) 에도 적용된다.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 가장 흔한 5R 변형
|
||||
- **Communication 5R** (Schramm 후속): Reception, Recognition, Recall, Response, Reaction.
|
||||
- **Reproducibility 5R** (Goble 2014): Re-run, Repeat, Reproduce, Reuse, Replicate.
|
||||
- **Waste hierarchy 5R**: Refuse, Reduce, Reuse, Repurpose, Recycle.
|
||||
- **Project 5R**: Right thing, Right time, Right way, Right resources, Right result.
|
||||
- **Customer-relationship 5R**: Reach, Relate, Retain, Reward, Refer.
|
||||
|
||||
### 매 공통 구조
|
||||
- 매 sequential 또는 매 layered.
|
||||
- 매 mnemonic 이 핵심 — 매 R 알파벳 시작 단어 force.
|
||||
- 매 framework, not theory — 매 prescriptive checklist.
|
||||
|
||||
### 매 응용
|
||||
1. **Research project**: 매 reproducibility 5R 로 매 paper review.
|
||||
2. **Customer onboarding**: 매 Reach→Refer 5R.
|
||||
3. **AI agent design**: 매 RAG (Retrieve, Rerank, Read, Reason, Respond) — 매 modern 5R.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: Reproducibility 5R 검증
|
||||
```python
|
||||
# Goble 2014 — 5R reproducibility checklist
|
||||
checklist = {
|
||||
"rerun": lambda paper: paper.has("docker_image"),
|
||||
"repeat": lambda paper: paper.has("seeds_fixed"),
|
||||
"reproduce": lambda paper: paper.has("data_open"),
|
||||
"reuse": lambda paper: paper.has("license_permissive"),
|
||||
"replicate": lambda paper: paper.has("methods_section_complete"),
|
||||
}
|
||||
score = sum(fn(paper) for fn in checklist.values()) / 5
|
||||
```
|
||||
|
||||
### Pattern 2: 매 RAG 5R agent
|
||||
```python
|
||||
def rag_5r(query: str, kb) -> str:
|
||||
docs = retrieve(query, kb, k=20) # Retrieve
|
||||
docs = rerank(query, docs, k=5) # Rerank
|
||||
chunks = read_full(docs) # Read
|
||||
plan = reason(query, chunks) # Reason
|
||||
return respond(plan) # Respond
|
||||
```
|
||||
|
||||
### Pattern 3: 매 Customer 5R funnel
|
||||
```sql
|
||||
SELECT stage,
|
||||
COUNT(*) AS users,
|
||||
LAG(COUNT(*)) OVER (ORDER BY stage_order) AS prev,
|
||||
COUNT(*)::float / NULLIF(LAG(COUNT(*)) OVER (ORDER BY stage_order), 0) AS conv
|
||||
FROM (
|
||||
SELECT user_id, 'reach' AS stage, 1 AS stage_order FROM impressions
|
||||
UNION ALL SELECT user_id, 'relate', 2 FROM signups
|
||||
UNION ALL SELECT user_id, 'retain', 3 FROM active_30d
|
||||
UNION ALL SELECT user_id, 'reward', 4 FROM rewards_claimed
|
||||
UNION ALL SELECT user_id, 'refer', 5 FROM referrals
|
||||
)
|
||||
GROUP BY stage, stage_order
|
||||
ORDER BY stage_order;
|
||||
```
|
||||
|
||||
### Pattern 4: Waste 5R audit
|
||||
```python
|
||||
items = [...] # household / office items
|
||||
for item in items:
|
||||
if can_refuse(item): act = "refuse"
|
||||
elif can_reduce(item): act = "reduce"
|
||||
elif can_reuse(item): act = "reuse"
|
||||
elif can_repurpose(item):act = "repurpose"
|
||||
else: act = "recycle"
|
||||
```
|
||||
|
||||
### Pattern 5: 매 Communication 5R review
|
||||
```markdown
|
||||
- Reception: was the message received? (delivery confirmation)
|
||||
- Recognition: was sender / topic identified?
|
||||
- Recall: can the receiver recall key points 24h later?
|
||||
- Response: did receiver respond?
|
||||
- Reaction: was behavior changed?
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Which 5R |
|
||||
|---|---|
|
||||
| 매 research paper review | Reproducibility 5R |
|
||||
| 매 sustainability audit | Waste 5R |
|
||||
| 매 customer growth | Reach→Refer |
|
||||
| 매 LLM agent | RAG 5R (Retrieve/Rerank/Read/Reason/Respond) |
|
||||
| 매 communication training | Reception→Reaction |
|
||||
|
||||
**기본값**: 매 context 명시 — 매 "5R" 단독 의 ambiguous. 매 always qualify (예: "RAG 5R", "Waste 5R").
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Pyramid Principle]] · [[MECE + Pyramid Principle--]]
|
||||
- 변형: [[Rule of Three]]
|
||||
- 응용: [[Knowledge synthesis]] · [[Process_Reflection_Template]]
|
||||
- Adjacent: [[Working-Backwards]] · [[Outside-Thinking]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 structured output template 생성 — 매 5-bullet checklist agent. 매 mnemonic 이 매 LLM recall 에 유리.
|
||||
**언제 X**: 매 단순 list — 매 5R force-fit 의 contrived.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Force-fit**: 매 4 또는 6 step 인데 매 5R 강제 → 매 awkward bucket.
|
||||
- **Buzzword usage**: 매 "5R framework" 만 언급, 매 actual 5 step 의 unclear.
|
||||
- **Cross-domain confusion**: 매 RAG 5R + Waste 5R 동일시 — 매 unrelated.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Goble *Better Software Practices* 2014, Schramm communication model derivatives).
|
||||
- 신뢰도 B+.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — 5 variants + RAG 5R modern application |
|
||||
@@ -0,0 +1,159 @@
|
||||
---
|
||||
id: wiki-2026-0508-automation-paradox
|
||||
title: Automation Paradox
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Paradox of Automation, Bainbridge's Ironies, Lights-Out Fallacy]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
verification_status: applied
|
||||
tags: [human-factors, automation, ai-safety, ergonomics, system-design]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: n/a
|
||||
framework: human-factors / HRO
|
||||
---
|
||||
|
||||
# Automation Paradox
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 자동화 의 better 일수록, human operator 의 role 의 critical 의 increase — skill atrophy 와 vigilance decrement 의 통한 catastrophic edge-case 의 amplification"**. Lisanne Bainbridge (1983) "Ironies of Automation" 의 origin, 2026 의 LLM agent + autonomous vehicle + algorithmic trading 의 era 의 acute relevance.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 4 ironies (Bainbridge)
|
||||
- **Designer 의 error**: automation 의 design 의 bug 의 operator 의 inherit
|
||||
- **Skill atrophy**: routine-task 의 takeover 의 인해 human skill 의 decay → emergency 의 unable
|
||||
- **Monitoring task**: vigilance 의 인해 의 unsuited 의 task 의 human 의 assign
|
||||
- **Trust calibration**: under-trust (rejection) 또는 over-trust (complacency) 의 binary failure
|
||||
|
||||
### 매 mechanisms
|
||||
- **Out-of-the-loop unfamiliarity (OOTLUF)** — automation handover 의 시 의 operator 의 context 의 lack
|
||||
- **Mode confusion** — automation 의 current state 의 mismatch (Air France 447, Tesla autopilot)
|
||||
- **Skill decay curve** — manual skill 의 disuse 의 인해 의 exponential degradation (~6 months)
|
||||
- **Calibration drift** — automation 의 reliability 의 over-extrapolation
|
||||
|
||||
### 매 응용
|
||||
1. Autonomous vehicle handover — Level 2/3 의 6-second take-over budget 의 unrealistic.
|
||||
2. LLM coding agent — generated code 의 review 의 automation bias 의 인해 의 bug 의 miss.
|
||||
3. Algorithmic trading kill-switch — flash-crash 의 인간 의 intervention 의 too late.
|
||||
4. Aviation glass cockpit — Air France 447 (2009) 의 stall 의 mode confusion.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Trust calibration metric (TLX-derived)
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
|
||||
@dataclass
|
||||
class TrustCalibration:
|
||||
perceived_reliability: float # 0-1, operator estimate
|
||||
actual_reliability: float # 0-1, measured
|
||||
|
||||
@property
|
||||
def miscalibration(self) -> float:
|
||||
"""Positive => over-trust, negative => under-trust."""
|
||||
return self.perceived_reliability - self.actual_reliability
|
||||
|
||||
def risk_class(self) -> str:
|
||||
gap = self.miscalibration
|
||||
if gap > 0.15: return "OVER_TRUST_DANGER"
|
||||
if gap < -0.15: return "REJECTION_DANGER"
|
||||
return "CALIBRATED"
|
||||
```
|
||||
|
||||
### Vigilance decrement model
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
def vigilance_curve(t_minutes: np.ndarray, base_hit_rate: float = 0.95) -> np.ndarray:
|
||||
"""Mackworth clock — 30-min decrement of ~0.2 in detection."""
|
||||
decay = 0.2 * (1 - np.exp(-t_minutes / 15))
|
||||
return np.clip(base_hit_rate - decay, 0, 1)
|
||||
|
||||
# Recommendation: rotate operators every 20 min on monitoring tasks
|
||||
```
|
||||
|
||||
### Handover protocol (autonomous vehicle)
|
||||
```python
|
||||
class L3HandoverManager:
|
||||
def __init__(self, min_takeover_seconds: float = 12.0):
|
||||
self.budget = min_takeover_seconds
|
||||
|
||||
def request_handover(self, driver_state: dict) -> dict:
|
||||
# 2026 SAE J3016 update: budget grew from 6s to 10-15s
|
||||
if not driver_state["eyes_on_road"]:
|
||||
return {"action": "MRM_pull_over", "reason": "OOTLUF"}
|
||||
if driver_state["secondary_task"] == "phone":
|
||||
return {"action": "MRM_pull_over", "reason": "high_OOTLUF_risk"}
|
||||
return {"action": "alert_takeover", "budget_s": self.budget}
|
||||
```
|
||||
|
||||
### LLM agent guardrail (skill-atrophy aware)
|
||||
```python
|
||||
class CodeReviewWithAutomationParadox:
|
||||
"""Force human active review on high-stakes diff to prevent atrophy."""
|
||||
|
||||
def __init__(self, llm_client):
|
||||
self.llm = llm_client
|
||||
|
||||
def review(self, diff: str, stakes: str) -> str:
|
||||
ai_review = self.llm.review(diff)
|
||||
if stakes == "high":
|
||||
# require human to manually annotate before showing AI review
|
||||
human = prompt_for_independent_review(diff)
|
||||
return reconcile(human, ai_review)
|
||||
return ai_review
|
||||
```
|
||||
|
||||
### Skill maintenance schedule
|
||||
```python
|
||||
def manual_practice_schedule(automation_uptime_pct: float) -> dict:
|
||||
"""Recommend periodic manual mode to combat skill decay."""
|
||||
if automation_uptime_pct > 0.9:
|
||||
return {"frequency": "weekly", "duration_min": 30}
|
||||
if automation_uptime_pct > 0.7:
|
||||
return {"frequency": "biweekly", "duration_min": 20}
|
||||
return {"frequency": "monthly", "duration_min": 15}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| High-stakes + rare edge case | Keep human in loop, force periodic manual mode |
|
||||
| Routine + low risk | Full automation OK |
|
||||
| L2/L3 autonomy | Long handover budget (12s+), DMS (driver monitoring) |
|
||||
| LLM agent | Active review on critical paths, not passive accept |
|
||||
| HRO (high-reliability) | Multiple redundant operators, rotation |
|
||||
|
||||
**기본값**: high-stakes automation 의 default — human-in-the-loop + periodic manual practice + miscalibration monitoring.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Neuroergonomics]] · [[Complex Systems]]
|
||||
- 변형: [[Neuromuscular-Control]]
|
||||
- 응용: [[AI_Safety_and_Alignment|AI Safety]] · [[Multi-agent-System]]
|
||||
- Adjacent: [[Burnout]] · [[Continuous Obsolescence]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: AI agent system design, code review automation, autonomous system handover protocol.
|
||||
**언제 X**: stateless automation 의 인간 의 involvement 의 unnecessary 인 case.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **"Lights-out" fallacy**: full automation 의 human 의 unnecessary 의 assume.
|
||||
- **6-second handover budget**: empirically insufficient — 12-15s baseline.
|
||||
- **Automation bias**: AI suggestion 의 default-accept — independent verification 의 missing.
|
||||
- **Skill decay 의 ignore**: emergency-only manual training 의 too late.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Bainbridge 1983 *Ironies of Automation*; Parasuraman & Manzey 2010 *Complacency and Bias*).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Bainbridge ironies, trust calibration, L3 handover, LLM agent guardrail |
|
||||
@@ -0,0 +1,180 @@
|
||||
---
|
||||
id: wiki-2026-0508-big-picture
|
||||
title: Big Picture
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Big Picture Thinking, System-Level View, Holistic View]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [meta, systems-thinking, architecture, decision-making]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: general
|
||||
---
|
||||
|
||||
# Big Picture
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 zoom out before you zoom in"**. Big Picture thinking 매 system-level perspective 의 prioritization — local optimization 매 global suboptimum 의 lead 가능. 2026 LLM 시대 매 context window 1M+ tokens 매 entire codebase 의 single prompt 의 fit 가능 — Big Picture 매 finally tractable computationally.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 Levels of abstraction
|
||||
- **L0 (atom)**: single function, single line.
|
||||
- **L1 (module)**: file, class, single concern.
|
||||
- **L2 (subsystem)**: service, package, bounded context.
|
||||
- **L3 (system)**: full application, deployment topology.
|
||||
- **L4 (ecosystem)**: organization, market, regulation.
|
||||
- 매 mistake: L0 의 stuck — never L3 까지 zoom out.
|
||||
|
||||
### 매 When to zoom out
|
||||
- 매 stuck 30+ min 의 single bug → L2 의 zoom out.
|
||||
- 매 architectural decision → L3 mandatory.
|
||||
- 매 hiring / team structure → L4.
|
||||
- 매 PR review → L1 + L2 mix.
|
||||
|
||||
### 매 응용
|
||||
1. Architecture review (data flow diagram).
|
||||
2. Incident postmortem (5 whys → systemic cause).
|
||||
3. Roadmap planning (quarter-level priorities).
|
||||
4. Code review (cross-cutting concerns).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: Context map (L3 view)
|
||||
```python
|
||||
# Visualize bounded contexts (DDD-style)
|
||||
contexts = {
|
||||
"auth": {"depends_on": [], "exposes": ["user_id", "session"]},
|
||||
"billing": {"depends_on": ["auth"], "exposes": ["invoice", "subscription"]},
|
||||
"notification": {"depends_on": ["auth", "billing"], "exposes": []},
|
||||
}
|
||||
|
||||
def find_critical_path(contexts):
|
||||
"""매 highest fan-in 의 service 의 SPOF candidate."""
|
||||
fan_in = {ctx: 0 for ctx in contexts}
|
||||
for ctx, info in contexts.items():
|
||||
for dep in info["depends_on"]:
|
||||
fan_in[dep] += 1
|
||||
return sorted(fan_in.items(), key=lambda x: -x[1])
|
||||
```
|
||||
|
||||
### Pattern 2: Zoom-out checklist
|
||||
```python
|
||||
ZOOM_OUT_QUESTIONS = [
|
||||
"Who else is affected by this change?",
|
||||
"What breaks if this fails at 3am?",
|
||||
"Is this the right problem to solve right now?",
|
||||
"What does success look like in 6 months?",
|
||||
"Who owns this when I leave?",
|
||||
]
|
||||
|
||||
def review_pr(pr_diff: str) -> list[str]:
|
||||
return [q for q in ZOOM_OUT_QUESTIONS if not answered_in(pr_diff, q)]
|
||||
```
|
||||
|
||||
### Pattern 3: Pre-mortem (L4 thinking)
|
||||
```python
|
||||
def premortem(project: str) -> dict:
|
||||
"""매 launch 전 의 'imagine it failed' exercise."""
|
||||
return {
|
||||
"tech_failure": "What technical assumption was wrong?",
|
||||
"market_failure": "Why did users not adopt?",
|
||||
"team_failure": "What organizational dynamic killed it?",
|
||||
"regulation": "What law/policy blocked it?",
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 4: Dependency graph (L2 → L3)
|
||||
```python
|
||||
import networkx as nx
|
||||
|
||||
def build_dep_graph(modules: dict[str, list[str]]) -> nx.DiGraph:
|
||||
g = nx.DiGraph()
|
||||
for mod, deps in modules.items():
|
||||
for d in deps:
|
||||
g.add_edge(mod, d)
|
||||
cycles = list(nx.simple_cycles(g))
|
||||
if cycles:
|
||||
print(f"매 architecture smell: {len(cycles)} cycles detected")
|
||||
return g
|
||||
```
|
||||
|
||||
### Pattern 5: LLM-assisted big picture (2026)
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
|
||||
client = Anthropic()
|
||||
|
||||
def architecture_summary(repo_dump: str) -> str:
|
||||
"""매 1M context 의 entire repo 의 fit — 2026 standard."""
|
||||
msg = client.messages.create(
|
||||
model="claude-opus-4-7-1m",
|
||||
max_tokens=4000,
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": f"""다음 repo 의 architecture 를 L3 perspective 의 summarize.
|
||||
Identify: (1) bounded contexts, (2) critical path, (3) tech debt hotspots.
|
||||
|
||||
{repo_dump}"""
|
||||
}],
|
||||
)
|
||||
return msg.content[0].text
|
||||
```
|
||||
|
||||
### Pattern 6: Tradeoff matrix
|
||||
```python
|
||||
def tradeoff_matrix(options: list[str], criteria: list[str], scores: dict) -> str:
|
||||
rows = []
|
||||
for opt in options:
|
||||
row = [opt] + [str(scores[(opt, c)]) for c in criteria]
|
||||
rows.append(" | ".join(row))
|
||||
return "\n".join(rows)
|
||||
|
||||
# Usage
|
||||
options = ["monolith", "microservices", "modular monolith"]
|
||||
criteria = ["dev_speed", "ops_cost", "scalability", "team_autonomy"]
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Bug fix < 1h | L0/L1 만 — zoom out 의 X. |
|
||||
| Recurring bug | L2 zoom out — systemic cause. |
|
||||
| New feature | L2 + L3 — fit 의 architecture. |
|
||||
| Postmortem | L3 + L4 mandatory. |
|
||||
| Quarterly planning | L4 only. |
|
||||
|
||||
**기본값**: 매 task 의 start 의 30 sec 의 L3 sketch — bounded contexts, data flow, failure modes.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Systems_Thinking|Systems-Thinking]] · [[Architecture]]
|
||||
- 응용: [[Architecture-Review]] · [[Postmortem]]
|
||||
- Adjacent: [[Bounded Context]] · [[Domain-Driven-Design]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: Architecture review, repo onboarding, postmortem synthesis, roadmap drafting. 매 1M context 의 entire codebase 의 fit 가능 — 매 truly novel 2026 capability.
|
||||
**언제 X**: Tactical bug fix (L0/L1), perf tuning of single function. 매 LLM 매 generic advice 의 emit — local context 의 lose.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Premature zoom-out**: 매 every bug 의 L4 의 escalate — 매 paralysis.
|
||||
- **Ivory tower architecture**: L3 만 — implementation reality 의 ignore.
|
||||
- **Big-picture-only PR review**: 매 nitpick 의 miss.
|
||||
- **Solo big-picture**: 매 architect 매 single person — bus factor 1.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified: Donella Meadows "Thinking in Systems" (2008), Eric Evans "DDD" (2003), Nicole Forsgren "Accelerate" (2018).
|
||||
- 신뢰도 A.
|
||||
- 중복: [[Systems_Thinking|Systems-Thinking]] 매 strict superset — Big Picture 매 daily-practice variant 의 framing.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content with L0-L4 levels, zoom-out patterns, LLM 1M context architecture summary |
|
||||
@@ -0,0 +1,203 @@
|
||||
---
|
||||
id: wiki-2026-0508-codebase-onboarding
|
||||
title: Codebase Onboarding
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Developer Onboarding, Code Onboarding, New Hire Ramp-up]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [engineering-management, devex, documentation, llm-tools, productivity]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: Python / TypeScript
|
||||
framework: Claude Code / Cursor / Sourcegraph
|
||||
---
|
||||
|
||||
# Codebase Onboarding
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 new engineer 의 first PR 의 ship 의 time 의 minimize — codebase mental model 의 building 의 single biggest leverage point"**. 2026 의 LLM-augmented onboarding 의 era 에서 의 Claude Code, Cursor, Sourcegraph Cody 의 통한 first-week productivity 의 historical 의 weeks 의 days 로 의 collapse — 매 documentation + tooling + buddy system 의 triplet 의 critical.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 4 phases
|
||||
- **Day 0–1: Environment** — repo clone, build, test 의 green
|
||||
- **Day 2–5: Map** — system architecture, ownership boundary, glossary
|
||||
- **Week 2: First PR** — small bug fix or doc 의 contribution
|
||||
- **Month 1: Ownership** — feature 의 lead, on-call participation
|
||||
|
||||
### 매 friction sources (Microsoft 2024 study)
|
||||
- Tribal knowledge (60% of blockers)
|
||||
- Stale documentation (45%)
|
||||
- Build / dev-env setup (30%)
|
||||
- Implicit code conventions (28%)
|
||||
- Domain language gaps (25%)
|
||||
|
||||
### 매 응용
|
||||
1. New hire ramp-up 의 5-day → 1.5-day 로 의 acceleration (LLM-assisted).
|
||||
2. Acquisition integration — acquired team 의 codebase 의 onboard.
|
||||
3. Open-source contributor 의 first-time contributor experience.
|
||||
4. Inner-source — cross-team contribution friction 의 reduce.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### CLAUDE.md / AGENTS.md (LLM context primer)
|
||||
```markdown
|
||||
# Project Context
|
||||
|
||||
## Stack
|
||||
- Backend: Python 3.13, FastAPI, Postgres 16, Redis 7
|
||||
- Frontend: Next.js 15 (App Router), React 19
|
||||
- Infra: AWS, Pulumi, GitHub Actions
|
||||
|
||||
## Conventions
|
||||
- Async-first; no sync DB calls in handlers.
|
||||
- Tests: pytest, ≥85% coverage required.
|
||||
- Commits: conventional commits (feat/fix/chore).
|
||||
|
||||
## Domain glossary
|
||||
- "Account" = billing entity (≠ User)
|
||||
- "Workspace" = collaboration scope
|
||||
- "Project" = single deployment unit
|
||||
|
||||
## Key files
|
||||
- `apps/api/main.py` — FastAPI entry
|
||||
- `packages/db/schema.sql` — canonical schema
|
||||
- `infra/pulumi/` — IaC
|
||||
|
||||
## Onboarding tasks
|
||||
1. Run `make bootstrap` then `make test`.
|
||||
2. Read `docs/architecture.md`.
|
||||
3. Pick a "good-first-issue" label.
|
||||
```
|
||||
|
||||
### `make bootstrap` (one-command setup)
|
||||
```makefile
|
||||
.PHONY: bootstrap test lint
|
||||
bootstrap:
|
||||
@command -v mise >/dev/null || curl https://mise.run | sh
|
||||
mise install
|
||||
uv sync
|
||||
pnpm install
|
||||
docker compose up -d postgres redis
|
||||
uv run alembic upgrade head
|
||||
@echo "Bootstrap complete. Run 'make test' to verify."
|
||||
|
||||
test:
|
||||
uv run pytest -x --cov=src
|
||||
pnpm test
|
||||
|
||||
lint:
|
||||
uv run ruff check .
|
||||
pnpm lint
|
||||
```
|
||||
|
||||
### Architecture Decision Records (ADR)
|
||||
```markdown
|
||||
# ADR-007: Why we chose Postgres over MongoDB
|
||||
Date: 2024-11-12
|
||||
Status: Accepted
|
||||
|
||||
## Context
|
||||
We need transactional consistency for billing.
|
||||
|
||||
## Decision
|
||||
Postgres 16 with row-level security.
|
||||
|
||||
## Consequences
|
||||
+ Strong ACID for money flows
|
||||
- Schema migrations require Alembic discipline
|
||||
```
|
||||
|
||||
### LLM-powered code map
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
|
||||
client = Anthropic()
|
||||
|
||||
def codebase_summary(repo_files: list[str]) -> str:
|
||||
"""Generate onboarding-friendly codebase map using prompt cache."""
|
||||
response = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4000,
|
||||
system=[
|
||||
{"type": "text", "text": "You are an onboarding assistant."},
|
||||
{"type": "text", "text": "\n".join(repo_files),
|
||||
"cache_control": {"type": "ephemeral"}},
|
||||
],
|
||||
messages=[{"role": "user", "content":
|
||||
"Produce a 1-page codebase map for a new hire: "
|
||||
"entry points, key modules, dependency layers, gotchas."}],
|
||||
)
|
||||
return response.content[0].text
|
||||
```
|
||||
|
||||
### Buddy system + PR mentoring
|
||||
```python
|
||||
@dataclass
|
||||
class OnboardingPlan:
|
||||
new_hire: str
|
||||
buddy: str
|
||||
week1_tasks: list[str]
|
||||
week2_tasks: list[str]
|
||||
|
||||
def daily_standup_questions(self) -> list[str]:
|
||||
return [
|
||||
"어제 의 가장 confusing 의 part?",
|
||||
"오늘 의 목표 의 1 of?",
|
||||
"block 의 의 의?",
|
||||
]
|
||||
```
|
||||
|
||||
### "First PR by EOD-1" success metric
|
||||
```python
|
||||
def first_pr_metrics(hires: list[dict]) -> dict:
|
||||
"""Lead indicator of onboarding health."""
|
||||
return {
|
||||
"median_days_to_first_pr": median(h["days_to_first_pr"] for h in hires),
|
||||
"median_days_to_first_merge": median(h["days_to_first_merge"] for h in hires),
|
||||
"30d_active_pct": sum(h["still_active_30d"] for h in hires) / len(hires),
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Greenfield team | Heavy CLAUDE.md, light ADR |
|
||||
| Legacy codebase | Strong ADR archive, code map LLM, buddy system |
|
||||
| Open source | Detailed CONTRIBUTING.md, good-first-issue queue |
|
||||
| Acquired team | Pair programming weeks 1-2, glossary front-loaded |
|
||||
| Remote-first | Async docs first, video walkthroughs |
|
||||
|
||||
**기본값**: modern team 의 default — CLAUDE.md + make bootstrap + buddy + first-PR-by-EOD-3.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Team Culture & Onboarding (팀 문화 및 온보딩)]]
|
||||
- 변형: [[Program Comprehension Strategies]]
|
||||
- 응용: [[Pull_Request_and_Issue_Tracking]]
|
||||
- Adjacent: [[GIT_PROTOCOL]] · [[Process_Reflection_Template]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: codebase summary generation, onboarding doc 의 audit (gap detection), new-hire Q&A bot.
|
||||
**언제 X**: tribal knowledge 의 LLM 의 fully replace 의 X — buddy system 의 still 의 essential.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **"Read the code"**: docs 의 absence 의 excuse 의 X. 매 entrypoint 의 explicit.
|
||||
- **Stale README**: bootstrap step 의 not-working 의 first-day blocker.
|
||||
- **Trial-by-fire**: 큰 critical 의 task 의 week-1 의 assign — burnout 의 amplify.
|
||||
- **Single buddy bottleneck**: buddy 의 vacation 의 의 onboarding 의 stall.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Microsoft 2024 *Developer Velocity Lab*; Stripe *Increment Magazine* onboarding issue).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — phases, CLAUDE.md, bootstrap, ADR, LLM code map |
|
||||
@@ -0,0 +1,174 @@
|
||||
---
|
||||
id: wiki-2026-0508-command-center
|
||||
title: Command Center
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [NOC, Operations Center, War Room]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [operations, incident-response, observability, sre]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: any
|
||||
framework: Grafana, Prometheus, PagerDuty
|
||||
---
|
||||
|
||||
# Command Center
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 Command Center 매 cross-system situational awareness 의 single pane"**. 매 NASA Mission Control 의 origin 매 modern SRE NOC, AWS-style war-room 의 조상. 2026 매 LLM-assisted incident commander (Claude Opus 4.7) 의 augment 의 standard.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 구성
|
||||
- **Big-board screens**: 매 service health, traffic, error budget, deploy state.
|
||||
- **Roles**: Incident Commander (IC), Comms lead, Scribe, SMEs.
|
||||
- **Comms channels**: 매 dedicated Slack/Teams + voice bridge.
|
||||
- **Runbooks**: 매 indexed, searchable, version-controlled.
|
||||
- **Decision log**: 매 incident timestamp + decision + reasoning.
|
||||
|
||||
### 매 incident phases
|
||||
1. **Detect** — 매 alert / customer report.
|
||||
2. **Triage** — 매 severity classification (sev1 ~ sev5).
|
||||
3. **Mitigate** — 매 immediate impact reduction.
|
||||
4. **Resolve** — 매 root-cause fix.
|
||||
5. **Postmortem** — 매 blameless review + action items.
|
||||
|
||||
### 매 응용
|
||||
1. Sev1 게임 day quarterly 매 muscle-memory 유지.
|
||||
2. **Single-pane dashboard** 의 SLO + error budget + on-call status.
|
||||
3. **Incident bot** 의 channel-create + role-assign + scribe-prompt 자동화.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Incident channel bot
|
||||
```typescript
|
||||
// incident-bot.ts
|
||||
async function createIncident(severity: 1 | 2 | 3) {
|
||||
const channel = await slack.conversations.create({
|
||||
name: `inc-${dayjs().format('YYYYMMDD-HHmm')}-sev${severity}`,
|
||||
});
|
||||
await pagerduty.createIncident({ severity });
|
||||
await postRunbookLink(channel.id);
|
||||
await assignRoles(channel.id, { ic: oncall(), scribe: backup() });
|
||||
return channel;
|
||||
}
|
||||
```
|
||||
|
||||
### Big-board layout (Grafana)
|
||||
```yaml
|
||||
# dashboard.yml
|
||||
panels:
|
||||
- row: top
|
||||
items: [global_qps, global_error_rate, p99_latency, saturation]
|
||||
- row: middle
|
||||
items: [api_health, db_health, cache_health, queue_depth]
|
||||
- row: bottom
|
||||
items: [deploy_state, on_call_roster, error_budget_burn]
|
||||
```
|
||||
|
||||
### Severity matrix
|
||||
```python
|
||||
# severity.py
|
||||
def classify(impact_users: int, impact_revenue_per_hr: float, data_loss: bool) -> int:
|
||||
if data_loss or impact_revenue_per_hr > 100_000: return 1
|
||||
if impact_users > 10_000: return 2
|
||||
if impact_users > 100: return 3
|
||||
return 4
|
||||
```
|
||||
|
||||
### Incident decision log (markdown)
|
||||
```markdown
|
||||
# inc-2026-0510-1432-sev1
|
||||
| Time | Actor | Decision | Reasoning |
|
||||
|---|---|---|---|
|
||||
| 14:32 | IC | Page DB on-call | DB cpu 100% 5m |
|
||||
| 14:38 | DB-SME | Failover replica | Primary unresponsive |
|
||||
| 14:41 | IC | Status page yellow | Degraded checkout |
|
||||
```
|
||||
|
||||
### LLM-assisted incident summary
|
||||
```python
|
||||
# llm_summary.py
|
||||
prompt = f"""
|
||||
You are an SRE assistant. Summarize this incident channel transcript:
|
||||
- Timeline (5 bullets max)
|
||||
- Root cause hypothesis
|
||||
- Customer impact
|
||||
- Followups
|
||||
|
||||
Transcript: {channel_transcript}
|
||||
"""
|
||||
summary = anthropic.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=2000,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
)
|
||||
```
|
||||
|
||||
### Runbook structure
|
||||
```markdown
|
||||
# runbook: api-5xx-spike
|
||||
## Detect: alert "api-5xx > 1% 5m"
|
||||
## Mitigate
|
||||
1. Check deploy in last 30m → rollback: `kubectl rollout undo deploy/api`
|
||||
2. Check DB connections → scale pool: `kubectl scale ...`
|
||||
## Verify
|
||||
- Error rate <0.1% for 10m
|
||||
## Escalate to
|
||||
- @api-team if 30m without recovery
|
||||
```
|
||||
|
||||
### Postmortem template
|
||||
```markdown
|
||||
## Summary
|
||||
## Timeline (UTC)
|
||||
## Root cause
|
||||
## Impact (users, $, duration)
|
||||
## What went well
|
||||
## What didn't
|
||||
## Action items (DRI, due date)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Sev1 (data loss / outage) | Full war room + exec comms + status page red |
|
||||
| Sev2 (degraded) | IC + 1 SME + status yellow |
|
||||
| Sev3 (minor) | On-call solo + ticket |
|
||||
| Recurring sev3 | Promote to project, root-cause |
|
||||
| Multi-org incident | Joint war room + shared scribe |
|
||||
|
||||
**기본값**: clear-roles + decision-log + blameless-postmortem.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Site Reliability Engineering]]
|
||||
- 변형: [[War Room]]
|
||||
- 응용: [[Observability]] · [[On-Call]]
|
||||
- Adjacent: [[Postmortem]] · [[Runbook]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 incident channel transcript 의 summarization, 매 timeline reconstruction, 매 postmortem 의 first-draft.
|
||||
**언제 X**: 매 critical mitigation decision — 매 human IC 의 final call. LLM 매 advisor only.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Hero culture**: 매 single SRE 의 24/7 매 burnout + bus-factor 1.
|
||||
- **Blame-game postmortem**: 매 culture 의 silence 야기.
|
||||
- **Runbook rot**: 매 6-month-old runbook 매 broken commands.
|
||||
- **Dashboard bloat**: 매 100+ panel 매 signal/noise 1:50.
|
||||
- **Status page lag**: 매 customer 가 first 알림 — 매 trust 손실.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Google _SRE Workbook_ Ch.9, PagerDuty _Incident Response Documentation_ 2025, Atlassian _Incident Management Handbook_).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — incident phases, severity matrix, runbook, anti-patterns |
|
||||
@@ -0,0 +1,161 @@
|
||||
---
|
||||
id: wiki-2026-0508-complex-systems
|
||||
title: Complex Systems
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Complexity Theory, Complex Adaptive Systems, CAS]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [systems-thinking, complexity, emergence, distributed-systems]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: n/a
|
||||
framework: n/a
|
||||
---
|
||||
|
||||
# Complex Systems
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 Complex System 매 part 의 sum 초과 의 emergent 결과 발생 system"**. 매 simple-rule 매 unpredictable global 의 야기. Santa Fe Institute (Holland, Kauffman, Mitchell) 의 lineage. 2026 매 LLM swarm, distributed micro-services, social platform 매 canonical 예.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 정의 specifics
|
||||
- **Many components** (10² ~ 10⁹).
|
||||
- **Local interaction** (no central control).
|
||||
- **Non-linearity**: 매 input → output 의 disproportionate.
|
||||
- **Emergence**: 매 macro behavior 매 micro rule 의 not directly inferrable.
|
||||
- **Adaptation**: 매 component 의 state-update 의 environment 응답.
|
||||
|
||||
### 매 simple ↔ complicated ↔ complex (Cynefin)
|
||||
- **Simple**: 매 cause↔effect obvious. Best practice 의 사용.
|
||||
- **Complicated**: 매 expert analysis required. Good practice.
|
||||
- **Complex**: 매 retrospect 만 cause 추론 가능. 매 probe-sense-respond.
|
||||
- **Chaotic**: 매 cause↔effect link absent. Act-sense-respond.
|
||||
|
||||
### 매 응용
|
||||
1. Distributed system design 매 emergent failure mode 의 anticipate.
|
||||
2. Org change 매 directly-controllable lever 부재 — 매 nudge.
|
||||
3. Market / social media 의 non-linear viral propagation.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Power-law detection (Pareto)
|
||||
```python
|
||||
import numpy as np, scipy.stats as st
|
||||
|
||||
def is_powerlaw(data: np.ndarray) -> bool:
|
||||
"""Heavy-tailed → likely complex, not Gaussian."""
|
||||
fit = st.powerlaw.fit(data)
|
||||
ks_p = st.kstest(data, "powerlaw", fit).pvalue
|
||||
return ks_p > 0.05
|
||||
```
|
||||
|
||||
### Agent-based model (Mesa)
|
||||
```python
|
||||
from mesa import Agent, Model
|
||||
from mesa.space import MultiGrid
|
||||
from mesa.time import RandomActivation
|
||||
|
||||
class Cell(Agent):
|
||||
def step(self):
|
||||
n = self.neighbors_alive()
|
||||
self.alive = (n == 3) or (self.alive and n == 2)
|
||||
|
||||
class Life(Model):
|
||||
def __init__(self, w=80, h=80):
|
||||
self.grid = MultiGrid(w, h, torus=True)
|
||||
self.schedule = RandomActivation(self)
|
||||
for x in range(w):
|
||||
for y in range(h):
|
||||
a = Cell(self)
|
||||
self.grid.place_agent(a, (x, y))
|
||||
self.schedule.add(a)
|
||||
```
|
||||
|
||||
### Feedback-loop diagram (Mermaid)
|
||||
```mermaid
|
||||
graph LR
|
||||
Demand --> Price
|
||||
Price -->|+| Supply
|
||||
Supply -->|-| Price
|
||||
Price -->|-| Demand
|
||||
```
|
||||
|
||||
### Tipping-point detection
|
||||
```python
|
||||
def early_warning_signal(timeseries):
|
||||
"""Increased variance + autocorrelation → near phase transition."""
|
||||
rolling_var = pd.Series(timeseries).rolling(50).var()
|
||||
rolling_ac = pd.Series(timeseries).rolling(50).apply(lambda x: x.autocorr(1))
|
||||
return rolling_var.iloc[-1] > rolling_var.mean() * 1.5 \
|
||||
and rolling_ac.iloc[-1] > 0.7
|
||||
```
|
||||
|
||||
### Causal-loop policy lever map
|
||||
```yaml
|
||||
# policy_levers.yml
|
||||
goal: reduce-incident-rate
|
||||
levers:
|
||||
- lever: deploy-frequency
|
||||
feedback: positive # more deploys → more incidents short-term
|
||||
horizon: weeks
|
||||
- lever: test-coverage
|
||||
feedback: negative # higher coverage → fewer incidents
|
||||
horizon: months
|
||||
- lever: oncall-rotation-size
|
||||
feedback: negative # larger rotation → less burnout → fewer incidents
|
||||
horizon: quarters
|
||||
```
|
||||
|
||||
### Network resilience metric
|
||||
```python
|
||||
import networkx as nx
|
||||
def fragility(G: nx.Graph) -> float:
|
||||
"""Higher = more fragile to targeted node removal."""
|
||||
bc = nx.betweenness_centrality(G)
|
||||
return max(bc.values()) - np.median(list(bc.values()))
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Linear, well-understood | Optimization, KPI |
|
||||
| Complicated (expert solvable) | Plan + execute |
|
||||
| Complex (emergent) | Probe + small experiments + observe |
|
||||
| Chaotic (crisis) | Act first, stabilize, then sense |
|
||||
| Pre-tipping point | Early-warning + circuit-breaker |
|
||||
|
||||
**기본값**: probe-sense-respond + diversity + redundancy.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Systems_Thinking|Systems Thinking]]
|
||||
- 변형: [[Complex Adaptive Systems]]
|
||||
- 응용: [[Distributed Systems]]
|
||||
- Adjacent: [[Emergence]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 system map 의 first-draft, 매 feedback-loop 의 surface, 매 policy lever brainstorm.
|
||||
**언제 X**: 매 prediction 의 complex system — 매 LLM 매 false confidence 매 위험. 매 historical analogy 의 limit.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Linear thinking**: 매 cause→effect 의 direct mapping 매 complex 에서 wrong.
|
||||
- **Optimization fallacy**: 매 single metric 의 optimization 매 emergent failure 야기 (Goodhart).
|
||||
- **Central control assumption**: 매 top-down command 매 local-rule system 매 ineffective.
|
||||
- **Reductionism over-reach**: 매 component 의 분석 매 emergent property 의 missing.
|
||||
- **Plan-the-future fallacy**: 매 5-year-plan 매 complex domain 매 fiction.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Mitchell _Complexity: A Guided Tour_, Holland _Hidden Order_, Snowden Cynefin Framework, Santa Fe Institute lectures, Donella Meadows _Thinking in Systems_).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Cynefin, agent-based model, power law, anti-patterns |
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
id: wiki-2026-0508-concurrent-programming
|
||||
title: Concurrent Programming
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Concurrency, Multithreading, Async Programming]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [programming, concurrency, parallelism, systems]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: Go, Rust, Python, JavaScript
|
||||
framework: tokio, asyncio, goroutines
|
||||
---
|
||||
|
||||
# Concurrent Programming
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 concurrency 매 task 의 interleaving — parallelism 의 simultaneous 와 별개"**. Hoare CSP, Hewitt Actor 의 lineage. 2026 매 Rust async, Go goroutines, Java virtual threads (Project Loom GA), Python free-threaded mode 매 mainstream.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 Concurrency vs Parallelism
|
||||
- **Concurrency**: 매 dealing-with-many things at once (composition).
|
||||
- **Parallelism**: 매 doing-many things at once (execution).
|
||||
- 매 concurrent 코드 매 single-core 매 still concurrent. 매 parallel 매 multi-core required.
|
||||
|
||||
### 매 Primitives
|
||||
- **Threads / processes**: 매 OS-level. Heavyweight.
|
||||
- **Coroutines / fibers / virtual threads**: 매 user-mode lightweight.
|
||||
- **Async / await**: 매 cooperative scheduling.
|
||||
- **Channels**: 매 message passing (Go, Rust mpsc).
|
||||
- **Mutex / RWLock / Semaphore**: 매 shared-memory sync.
|
||||
- **Atomic**: 매 lock-free primitive.
|
||||
|
||||
### 매 응용
|
||||
1. Web server: 매 1 connection-per-virtual-thread (Loom) / async (tokio).
|
||||
2. Pipeline: 매 channel-based fan-out / fan-in.
|
||||
3. Actor system: 매 isolation per actor + supervision (Erlang/Elixir, Akka).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Go: goroutine + channel
|
||||
```go
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func worker(id int, jobs <-chan int, results chan<- int) {
|
||||
for j := range jobs {
|
||||
results <- j * 2
|
||||
}
|
||||
fmt.Println("worker", id, "done")
|
||||
}
|
||||
|
||||
func main() {
|
||||
jobs := make(chan int, 100)
|
||||
results := make(chan int, 100)
|
||||
for w := 1; w <= 3; w++ {
|
||||
go worker(w, jobs, results)
|
||||
}
|
||||
for j := 1; j <= 9; j++ { jobs <- j }
|
||||
close(jobs)
|
||||
for r := 1; r <= 9; r++ { <-results }
|
||||
}
|
||||
```
|
||||
|
||||
### Rust: tokio + select!
|
||||
```rust
|
||||
use tokio::{select, time::{sleep, Duration}};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let task1 = async { sleep(Duration::from_millis(100)).await; "fast" };
|
||||
let task2 = async { sleep(Duration::from_millis(200)).await; "slow" };
|
||||
select! {
|
||||
v = task1 => println!("got {v}"),
|
||||
v = task2 => println!("got {v}"),
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Java 21+: virtual threads
|
||||
```java
|
||||
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
IntStream.range(0, 10_000).forEach(i ->
|
||||
executor.submit(() -> {
|
||||
Thread.sleep(Duration.ofSeconds(1));
|
||||
return i;
|
||||
}));
|
||||
} // 10k virtual threads, ~negligible memory
|
||||
```
|
||||
|
||||
### Python: asyncio TaskGroup (3.11+)
|
||||
```python
|
||||
import asyncio
|
||||
import httpx
|
||||
|
||||
async def fetch(client, url):
|
||||
r = await client.get(url)
|
||||
return r.status_code
|
||||
|
||||
async def main():
|
||||
async with httpx.AsyncClient() as client:
|
||||
async with asyncio.TaskGroup() as tg:
|
||||
tasks = [tg.create_task(fetch(client, u)) for u in URLS]
|
||||
results = [t.result() for t in tasks]
|
||||
```
|
||||
|
||||
### Rust: structured concurrency (tokio JoinSet)
|
||||
```rust
|
||||
use tokio::task::JoinSet;
|
||||
let mut set = JoinSet::new();
|
||||
for url in urls { set.spawn(fetch(url)); }
|
||||
while let Some(res) = set.join_next().await {
|
||||
println!("{:?}", res?);
|
||||
}
|
||||
```
|
||||
|
||||
### Lock-free atomic counter
|
||||
```rust
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn bump() -> u64 {
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
```
|
||||
|
||||
### Actor pattern (Elixir)
|
||||
```elixir
|
||||
defmodule Counter do
|
||||
use GenServer
|
||||
def start_link(_), do: GenServer.start_link(__MODULE__, 0, name: __MODULE__)
|
||||
def init(s), do: {:ok, s}
|
||||
def handle_call(:inc, _, s), do: {:reply, s+1, s+1}
|
||||
end
|
||||
```
|
||||
|
||||
### Backpressure with bounded channel
|
||||
```go
|
||||
sem := make(chan struct{}, 10) // max 10 concurrent
|
||||
for _, url := range urls {
|
||||
sem <- struct{}{}
|
||||
go func(u string) { defer func(){ <-sem }(); fetch(u) }(url)
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| I/O-bound, 10k+ connections | Async (tokio, asyncio, Loom) |
|
||||
| CPU-bound, multi-core | Threads / rayon (Rust) |
|
||||
| Pipeline, multi-stage | Channels (Go, Rust mpsc) |
|
||||
| Isolation + fault tolerance | Actors (Elixir, Akka) |
|
||||
| Shared mutable state | Mutex + minimize critical section |
|
||||
| Hot counter | Atomic, no lock |
|
||||
|
||||
**기본값**: structured concurrency + bounded channel + cancellation propagation.
|
||||
|
||||
## 🔗 Graph
|
||||
- 변형: [[Async Programming]]
|
||||
- 응용: [[Distributed Systems]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 concurrent code review 의 race-condition spotting, 매 deadlock-pattern detection, 매 channel-pattern translation.
|
||||
**언제 X**: 매 subtle memory-ordering bug — 매 formal verification (TLA+, loom) 의 사용.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Shared mutable state without sync**: 매 race condition. UB in C++/Rust.
|
||||
- **Mutex in hot path**: 매 contention 의 serialization. 매 atomic / per-thread state.
|
||||
- **Unbounded goroutine spawn**: 매 OOM. 매 bounded pool / semaphore.
|
||||
- **Sync I/O in async function**: 매 single blocked task → 매 entire executor stall.
|
||||
- **Lock ordering inconsistent**: 매 deadlock. 매 always same order.
|
||||
- **Cancellation 의 ignore**: 매 dangling task / resource leak.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Hoare _Communicating Sequential Processes_, Go Memory Model 2022, Rust Async Book, JEP 444 (Java Virtual Threads), Python PEP 703).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — primitives, Go/Rust/Java/Python pattern, anti-patterns |
|
||||
@@ -0,0 +1,218 @@
|
||||
---
|
||||
id: wiki-2026-0508-continuous-obsolescence
|
||||
title: Continuous Obsolescence
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Tech Obsolescence, Software Decay, DIMINISHING-Manufacturing-Sources]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.88
|
||||
verification_status: applied
|
||||
tags: [software-engineering, lifecycle, dependency-management, technical-debt]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: process
|
||||
framework: lifecycle-management
|
||||
---
|
||||
|
||||
# Continuous Obsolescence
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 modern software 의 dependency tree 의 매일 obsolete 의 part — passive 의 X, continuous mitigation 의 require"**. 매 originally defense/aerospace term (DMSMS — Diminishing Manufacturing Sources & Material Shortages) 의 software lifecycle 의 adapted. 매 2026 의 LLM-driven dependency upgrade automation (Renovate AI, Dependabot Auto-merge) 의 매 mitigation 의 first-line defense.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 obsolescence 의 종류
|
||||
- **Hard obsolescence**: 매 dependency 의 end-of-life (Python 3.7, Node 14, Ubuntu 18.04).
|
||||
- **Soft obsolescence**: 매 community migration (jQuery → React, Webpack → Vite).
|
||||
- **Security obsolescence**: 매 unpatched CVE 의 forcing function.
|
||||
- **API obsolescence**: 매 deprecated endpoints (AWS SDK v2 → v3).
|
||||
- **Hardware obsolescence**: 매 ARM migration / Apple Silicon / x86_64 deprecation.
|
||||
|
||||
### 매 cost dynamics
|
||||
- **Linear today**: 매 weekly dep update 의 trivial.
|
||||
- **Exponential 후**: 매 1-year skip 의 cascade — major version jumps 의 breaking change 의 multiply.
|
||||
- **Cliff event**: 매 EOL 의 forced sudden migration ("Python 2 to 3" 의 trauma).
|
||||
|
||||
### 매 mitigation strategies
|
||||
1. **Continuous (default)**: 매 weekly automated PR via Renovate/Dependabot.
|
||||
2. **Tiered**: 매 dev-deps 의 aggressive / runtime-deps 의 conservative.
|
||||
3. **Frozen + audit**: 매 occasional 의 enterprise — 매 annual mass-upgrade.
|
||||
4. **Replace-not-upgrade**: 매 abandoned deps 의 fork or rewrite.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### 매 Renovate config (modern 2026 baseline)
|
||||
```json
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": ["config:recommended", "schedule:weekly", ":automergeMinor"],
|
||||
"packageRules": [
|
||||
{
|
||||
"matchUpdateTypes": ["minor", "patch"],
|
||||
"matchCurrentVersion": "!/^0/",
|
||||
"automerge": true
|
||||
},
|
||||
{
|
||||
"matchUpdateTypes": ["major"],
|
||||
"addLabels": ["needs-review"],
|
||||
"automerge": false
|
||||
},
|
||||
{
|
||||
"matchPackagePatterns": ["^@types/"],
|
||||
"automerge": true,
|
||||
"schedule": ["at any time"]
|
||||
}
|
||||
],
|
||||
"vulnerabilityAlerts": { "labels": ["security"], "automerge": false },
|
||||
"dependencyDashboard": true
|
||||
}
|
||||
```
|
||||
|
||||
### 매 dep-EOL scanner
|
||||
```python
|
||||
# Scan for end-of-life dependencies
|
||||
import requests
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
EOL_API = "https://endoflife.date/api"
|
||||
|
||||
def check_eol(packages: dict[str, str]) -> list[dict]:
|
||||
"""packages: {'python': '3.10.5', 'node': '18.17.0', ...}"""
|
||||
issues = []
|
||||
for name, version in packages.items():
|
||||
major_minor = ".".join(version.split(".")[:2])
|
||||
try:
|
||||
data = requests.get(f"{EOL_API}/{name}/{major_minor}.json", timeout=5).json()
|
||||
if data.get("eol") and data["eol"] != False:
|
||||
issues.append({
|
||||
"package": name, "version": version,
|
||||
"eol_date": data["eol"], "latest": data.get("latest"),
|
||||
})
|
||||
except (requests.RequestException, json.JSONDecodeError):
|
||||
continue
|
||||
return issues
|
||||
|
||||
# usage
|
||||
deps = {"python": "3.10.5", "node": "18.17.0", "ubuntu": "20.04"}
|
||||
for issue in check_eol(deps):
|
||||
print(f"⚠️ {issue['package']} {issue['version']} EOL {issue['eol_date']}")
|
||||
```
|
||||
|
||||
### 매 dep-graph 의 staleness audit
|
||||
```python
|
||||
# JS/TS — npm outdated programmatic
|
||||
import subprocess, json
|
||||
|
||||
def staleness_audit() -> dict:
|
||||
out = subprocess.run(["npm", "outdated", "--json"], capture_output=True, text=True)
|
||||
data = json.loads(out.stdout) if out.stdout else {}
|
||||
|
||||
severity = {"critical": [], "high": [], "medium": [], "low": []}
|
||||
for pkg, info in data.items():
|
||||
cur = info["current"].split(".")
|
||||
wanted = info["wanted"].split(".")
|
||||
latest = info["latest"].split(".")
|
||||
if cur[0] != latest[0]:
|
||||
severity["high"].append(f"{pkg}: {info['current']} → {info['latest']} (major)")
|
||||
elif cur[1] != latest[1]:
|
||||
severity["medium"].append(f"{pkg}: {info['current']} → {info['latest']} (minor)")
|
||||
else:
|
||||
severity["low"].append(f"{pkg}: {info['current']} → {info['latest']} (patch)")
|
||||
return severity
|
||||
```
|
||||
|
||||
### 매 LLM-assisted migration (Claude Opus 4.7)
|
||||
```python
|
||||
import anthropic
|
||||
|
||||
client = anthropic.Anthropic()
|
||||
|
||||
def llm_migration_plan(from_version: str, to_version: str, package: str, codebase_glob: str):
|
||||
"""Generate a migration checklist + automated edits."""
|
||||
msg = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4096,
|
||||
system=[
|
||||
{"type": "text",
|
||||
"text": "You are a senior engineer planning library migrations. Be specific.",
|
||||
"cache_control": {"type": "ephemeral"}},
|
||||
],
|
||||
messages=[{
|
||||
"role": "user",
|
||||
"content": f"""Migrate {package} from {from_version} to {to_version}.
|
||||
|
||||
Codebase pattern: {codebase_glob}
|
||||
|
||||
Output:
|
||||
1. Breaking changes list with file/line patterns to grep
|
||||
2. Automated codemod snippets (jscodeshift / ast-grep)
|
||||
3. Manual review checklist
|
||||
4. Rollback plan""",
|
||||
}],
|
||||
)
|
||||
return msg.content[0].text
|
||||
```
|
||||
|
||||
### 매 frozen + audit 의 quarterly upgrade
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
# scripts/quarterly-upgrade.sh — mass dependency refresh
|
||||
set -e
|
||||
|
||||
# 1. Snapshot current state
|
||||
git checkout -b "deps/$(date +%Y-Q%q)"
|
||||
cp package-lock.json package-lock.snapshot.json
|
||||
|
||||
# 2. Update everything to latest minor/patch
|
||||
bunx npm-check-updates -u --target minor
|
||||
bun install
|
||||
|
||||
# 3. Run full test matrix
|
||||
bun run test:unit
|
||||
bun run test:integration
|
||||
bun run test:e2e
|
||||
|
||||
# 4. If green, push for review
|
||||
git add package*.json && git commit -m "chore: quarterly dep refresh"
|
||||
git push -u origin HEAD
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 active product / SaaS | Renovate weekly + automerge minor |
|
||||
| 매 enterprise / regulated | Quarterly mass upgrade + security patches weekly |
|
||||
| 매 legacy / frozen | Replace-not-upgrade for critical deps; sandbox the rest |
|
||||
| 매 OSS library | Conservative — minimum supported versions wide |
|
||||
| 매 DMSMS / hardware-bound | Multi-source + lifecycle stockpile |
|
||||
|
||||
**기본값**: 매 Renovate weekly + automerge minor + manual review major.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Technical Debt]]
|
||||
- Adjacent: [[Renovate]] · [[Dependabot]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 migration plan 의 generation / 매 changelog 의 breaking-change extraction / 매 codemod 의 draft.
|
||||
**언제 X**: 매 production execution 의 automerge — 매 major version 의 always human review.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **매 "if it ain't broke"**: 매 cliff event 의 inevitable.
|
||||
- **매 manual cherry-pick patches**: 매 missing 의 known CVEs.
|
||||
- **매 yearly big-bang upgrade**: 매 cascade 의 breaking change 의 untestable.
|
||||
- **매 abandoned deps 의 indefinite use**: 매 forking decision 의 delay 의 cost compound.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (DoD DMSMS Guidebook; Renovate documentation; Anthropic *Claude Code agent migration patterns* 2026).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — obsolescence types + Renovate/Dependabot patterns + LLM migration |
|
||||
@@ -0,0 +1,149 @@
|
||||
---
|
||||
id: wiki-2026-0508-enterprise-service-bus
|
||||
title: Enterprise Service Bus
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [ESB, Service Bus, Integration Bus]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [architecture, integration, soa, messaging, esb]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: java
|
||||
framework: apache-camel
|
||||
---
|
||||
|
||||
# Enterprise Service Bus
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 ESB = SOA 시대 의 integration backbone — 매 2026 의 legacy + event mesh 의 hybrid"**. 매 hub-and-spoke 의 anti-pattern 회피 위한 message-bus pattern. 매 modern 의 Kafka + service mesh + iPaaS (MuleSoft, Boomi) 가 ESB 의 기능 의 분산.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 ESB 의 6 capabilities
|
||||
- **Routing**: 매 content-based, header-based.
|
||||
- **Transformation**: 매 XML↔JSON↔Avro, schema mapping.
|
||||
- **Protocol bridging**: 매 SOAP↔REST↔AMQP↔JMS↔FTP.
|
||||
- **Orchestration**: 매 multi-step workflow (BPEL, Camel routes).
|
||||
- **Mediation**: 매 versioning, throttling, security policy.
|
||||
- **Monitoring**: 매 audit, SLA tracking, error queues.
|
||||
|
||||
### 매 versus alternatives
|
||||
- **Point-to-point**: 매 N×N integration — ESB 의 N+1.
|
||||
- **Hub-and-spoke**: 매 single hub bottleneck — ESB 의 distributed.
|
||||
- **Event mesh (modern)**: 매 Kafka + Schema Registry — 매 ESB 보다 throughput ↑, transformation logic 의 service-side.
|
||||
- **iPaaS**: 매 cloud-native ESB — 매 SaaS connector 의 thousand+.
|
||||
|
||||
### 매 응용
|
||||
1. Bank legacy mainframe ↔ digital channel integration.
|
||||
2. ERP (SAP) ↔ CRM (Salesforce) sync.
|
||||
3. B2B EDI translation (X12, EDIFACT).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Apache Camel content-based router
|
||||
```java
|
||||
from("jms:queue:incomingOrders")
|
||||
.choice()
|
||||
.when(jsonpath("$.priority == 'HIGH'"))
|
||||
.to("kafka:high-priority-orders")
|
||||
.when(jsonpath("$.region == 'EU'"))
|
||||
.to("amqp:eu-orders")
|
||||
.otherwise()
|
||||
.to("jms:queue:standardOrders")
|
||||
.end();
|
||||
```
|
||||
|
||||
### XML → JSON transformation
|
||||
```java
|
||||
from("file:input/orders?include=.*\\.xml")
|
||||
.unmarshal().jacksonXml(Order.class)
|
||||
.marshal().json(JsonLibrary.Jackson)
|
||||
.to("http://api.example.com/orders");
|
||||
```
|
||||
|
||||
### Saga orchestration (Camel)
|
||||
```java
|
||||
from("direct:placeOrder")
|
||||
.saga()
|
||||
.compensation("direct:cancelOrder")
|
||||
.timeout(java.time.Duration.ofMinutes(5))
|
||||
.to("direct:reserveInventory")
|
||||
.to("direct:chargePayment")
|
||||
.to("direct:scheduleShipment");
|
||||
```
|
||||
|
||||
### Dead letter channel
|
||||
```java
|
||||
errorHandler(deadLetterChannel("jms:queue:dlq")
|
||||
.maximumRedeliveries(3)
|
||||
.redeliveryDelay(2000)
|
||||
.useExponentialBackOff());
|
||||
```
|
||||
|
||||
### Modern replacement: Kafka + KStreams
|
||||
```java
|
||||
StreamsBuilder builder = new StreamsBuilder();
|
||||
builder.stream("orders", Consumed.with(Serdes.String(), orderSerde))
|
||||
.filter((k, v) -> v.getAmount() > 1000)
|
||||
.mapValues(o -> enrichWithCustomer(o))
|
||||
.to("high-value-orders");
|
||||
```
|
||||
|
||||
### Service mesh sidecar (Istio) replacement
|
||||
```yaml
|
||||
apiVersion: networking.istio.io/v1beta1
|
||||
kind: VirtualService
|
||||
metadata:
|
||||
name: order-routing
|
||||
spec:
|
||||
http:
|
||||
- match:
|
||||
- headers:
|
||||
x-region:
|
||||
exact: EU
|
||||
route:
|
||||
- destination:
|
||||
host: order-service-eu
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Greenfield microservices | Kafka + service mesh, ESB X |
|
||||
| Legacy mainframe + SaaS integration | iPaaS (MuleSoft, Boomi) |
|
||||
| Heavy XML/SOAP B2B | Apache Camel or MuleSoft |
|
||||
| Event-driven architecture | Kafka + Schema Registry |
|
||||
| Complex orchestration | Camel + Saga or Temporal.io |
|
||||
|
||||
**기본값**: 매 2026 의 new project — Kafka + service mesh. 매 legacy integration — Camel or iPaaS. 매 traditional ESB (WSO2, Mule 3) 의 신규 도입 X.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Service-oriented-Architecture|Service-Oriented Architecture (SOA)]]
|
||||
- 변형: [[Service Mesh]]
|
||||
- 응용: [[Legacy Modernization]] · [[API Gateway]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 EIP pattern matching, 매 Camel DSL generation, 매 XSLT/XPath debugging, 매 legacy SOAP WSDL → REST OpenAPI 변환.
|
||||
**언제 X**: 매 production routing rules 의 직접 deploy — 매 정확한 schema validation, dead-letter handling 의 review 필요. 매 transformation logic 의 round-trip test 필수.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **God-ESB**: 매 모든 business logic 의 ESB 의 집중 — 매 bus 의 monolith. 매 logic 의 service-side.
|
||||
- **Synchronous chains**: 매 ESB 의 long sync calls — 매 cascading failure. 매 async + saga.
|
||||
- **No schema governance**: 매 transformation 의 implicit contract — 매 producer change 시 silent break.
|
||||
- **2026 의 new ESB 도입**: 매 platform team 의 maintenance cost ↑ — 매 Kafka + iPaaS 의 분산.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Hohpe & Woolf "Enterprise Integration Patterns" 2003, Apache Camel docs 4.x, Gartner ESB→iPaaS 의 2024 report).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Camel patterns, modern Kafka/mesh replacement, iPaaS context 추가 |
|
||||
@@ -0,0 +1,158 @@
|
||||
---
|
||||
id: wiki-2026-0508-feedback-loops
|
||||
title: Feedback Loops
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Feedback Control, Closed Loop, Cybernetic Feedback]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [systems, control-theory, cybernetics, dynamics]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: control-systems
|
||||
---
|
||||
|
||||
# Feedback Loops
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 system output 의 input 의 re-entry — 매 stability 또는 amplification 의 결정"**. 매 1948 Wiener 의 Cybernetics 가 unifying frame. 매 2026 의 RLHF, autoscaling, climate tipping points, social media engagement loop 의 modern instances.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 2 polarities
|
||||
- **Negative (balancing)**: 매 deviation 의 dampen — 매 thermostat, homeostasis, PID controller.
|
||||
- **Positive (reinforcing)**: 매 deviation 의 amplify — 매 viral growth, asset bubble, ice-albedo feedback, runaway selection.
|
||||
|
||||
### 매 5 archetypes (Senge)
|
||||
- **Limits to growth**: 매 reinforcing + balancing — 매 S-curve.
|
||||
- **Shifting the burden**: 매 quick fix 의 underlying issue 의 weaken.
|
||||
- **Tragedy of the commons**: 매 individual reinforcing → collective collapse.
|
||||
- **Fixes that fail**: 매 short-term fix 의 long-term backfire.
|
||||
- **Success to the successful**: 매 winner-take-all reinforcing.
|
||||
|
||||
### 매 stability concepts
|
||||
- **Gain**: 매 output/input ratio.
|
||||
- **Phase margin**: 매 stability buffer (>45° robust).
|
||||
- **Time delay**: 매 instability driver (Bode-Nyquist).
|
||||
- **Setpoint vs. error**: 매 target — actual.
|
||||
|
||||
### 매 응용
|
||||
1. PID controller (industrial process).
|
||||
2. RLHF (LLM 의 preference loop).
|
||||
3. Autoscaling (Kubernetes HPA, target CPU).
|
||||
4. Insulin-glucose homeostasis.
|
||||
5. Market price discovery.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### PID controller
|
||||
```python
|
||||
class PID:
|
||||
def __init__(self, kp: float, ki: float, kd: float, setpoint: float):
|
||||
self.kp, self.ki, self.kd = kp, ki, kd
|
||||
self.setpoint = setpoint
|
||||
self.integral = 0.0
|
||||
self.prev_error = 0.0
|
||||
|
||||
def step(self, measurement: float, dt: float) -> float:
|
||||
error = self.setpoint - measurement
|
||||
self.integral += error * dt
|
||||
derivative = (error - self.prev_error) / dt if dt > 0 else 0
|
||||
self.prev_error = error
|
||||
return self.kp * error + self.ki * self.integral + self.kd * derivative
|
||||
```
|
||||
|
||||
### Logistic growth (limits-to-growth archetype)
|
||||
```python
|
||||
import numpy as np
|
||||
from scipy.integrate import odeint
|
||||
|
||||
def logistic(N, t, r, K):
|
||||
return r * N * (1 - N / K)
|
||||
|
||||
t = np.linspace(0, 50, 500)
|
||||
N = odeint(logistic, y0=1, t=t, args=(0.3, 1000))
|
||||
# Reinforcing (rN) + balancing ((1 - N/K))
|
||||
```
|
||||
|
||||
### Autoscaling reactive loop
|
||||
```python
|
||||
def autoscale_step(current_replicas: int, cpu_utilization: float,
|
||||
target: float = 0.7, max_replicas: int = 100) -> int:
|
||||
desired = int(current_replicas * cpu_utilization / target)
|
||||
return max(1, min(desired, max_replicas))
|
||||
```
|
||||
|
||||
### Reinforcement learning (RLHF reward model loop)
|
||||
```python
|
||||
def rlhf_iteration(policy, reward_model, prompts, ppo_optimizer):
|
||||
rollouts = [policy.generate(p) for p in prompts]
|
||||
rewards = [reward_model.score(p, r) for p, r in zip(prompts, rollouts)]
|
||||
advantages = compute_advantages(rewards)
|
||||
ppo_optimizer.step(policy, rollouts, advantages)
|
||||
# Loop closes: policy → output → reward → policy update
|
||||
```
|
||||
|
||||
### Stability check (root locus)
|
||||
```python
|
||||
import numpy as np
|
||||
from scipy.signal import TransferFunction, bode
|
||||
|
||||
# Open-loop transfer function
|
||||
sys = TransferFunction([1], [1, 2, 3, 1]) # 3rd order
|
||||
w, mag, phase = bode(sys)
|
||||
# Phase margin: phase at gain crossover + 180°
|
||||
```
|
||||
|
||||
### Detect runaway positive feedback
|
||||
```python
|
||||
def detect_runaway(time_series: list[float], window: int = 10, threshold: float = 1.5) -> bool:
|
||||
"""Exponential growth detector — log-linear fit slope."""
|
||||
import numpy as np
|
||||
if len(time_series) < window:
|
||||
return False
|
||||
y = np.log(np.maximum(time_series[-window:], 1e-9))
|
||||
slope = np.polyfit(range(window), y, 1)[0]
|
||||
return slope > np.log(threshold) / window
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Process regulation, setpoint tracking | PID (negative feedback) |
|
||||
| Growth modeling | logistic / Gompertz (mixed) |
|
||||
| Cascading failure prevention | rate limiters + circuit breakers |
|
||||
| Slow process w/ delay | feed-forward + smith predictor |
|
||||
| ML training | RLHF / GRPO with KL regularization |
|
||||
|
||||
**기본값**: 매 negative feedback 의 default for stability. 매 positive feedback 의 explicit guard (rate limit, kill switch).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Cybernetics Foundations|Cybernetics]] · [[Control Theory]] · [[Systems_Thinking|Systems Thinking]]
|
||||
- 응용: [[RLHF]] · [[Homeostasis (항상성)|Homeostasis]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 archetype identification, 매 PID gain initial estimation, 매 system dynamics diagram 의 stock-flow conversion.
|
||||
**언제 X**: 매 safety-critical control gain tuning — 매 hardware-in-the-loop testing, 매 actual phase margin verification 필수.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Ignoring delay**: 매 time-delay 의 PID 의 instability — 매 dead-time compensation 필요.
|
||||
- **High gain assumption = better tracking**: 매 oscillation, 매 noise amplification.
|
||||
- **Open-loop control for safety-critical**: 매 disturbance rejection X — 매 closed-loop 필수.
|
||||
- **Reinforcing loop 의 무방어 deploy**: 매 viral metric 의 optimization — 매 social harm runaway (engagement maximization → polarization).
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Wiener "Cybernetics" 1948, Åström & Murray "Feedback Systems" 2nd ed, Sterman "Business Dynamics" 2000, Senge "Fifth Discipline" rev. ed).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — PID, Senge archetypes, RLHF/autoscaling 추가 |
|
||||
@@ -0,0 +1,16 @@
|
||||
# 🚩 Agent Git Operation Mapping Protocol
|
||||
|
||||
| 유저 명령어 | 실행 액션 | 대상 리모트/브랜치 |
|
||||
| :--- | :--- | :--- |
|
||||
| **"Agent 최신화해"** | `git pull origin <current_branch>` | https://github.com/g1nations/TeamG1.git |
|
||||
| **"Agent 커밋해"** | `git add .` <br> `git commit -m "Update Agent Systems"` <br> `git push origin <current_branch>` | https://github.com/g1nations/TeamG1.git |
|
||||
|
||||
## 🛠️ 세부 수칙
|
||||
1. **Target Directory**: `E:\Wiki\2nd\Agent`
|
||||
2. **Git Address**: `https://github.com/g1nations/TeamG1.git`
|
||||
3. **Auto-Pilot**: 해당 명령어가 입력되면 추가 질문 없이 즉시 실행 후 보고한다.
|
||||
4. **Note**: `2nd` 프로젝트 하위에 있으나, 별도의 리모트 주소를 가진 독립 구역으로 취급한다.
|
||||
|
||||
---
|
||||
**승인인**: AI 개발부장 코다리 🫡
|
||||
**일시**: 2026-04-22
|
||||
@@ -0,0 +1,195 @@
|
||||
---
|
||||
id: wiki-2026-0508-inference-coupled-persistence
|
||||
title: Inference-Coupled Persistence
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [ICP, Inference-Time Memory, Coupled Persistence]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.85
|
||||
verification_status: applied
|
||||
tags: [llm, memory, inference, kv-cache, persistence]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: vllm
|
||||
---
|
||||
|
||||
# Inference-Coupled Persistence
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 KV-cache 의 disk 의 spill 매 conversation 의 resume"**. Inference-Coupled Persistence (ICP) 매 LLM serving system 의 inference state (KV-cache, attention states) 의 durable storage 의 couple 매 pattern. 2026 vLLM 0.7+ / SGLang 매 native support — long conversations cost-effective.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 Why ICP
|
||||
- 매 1M token context 의 KV-cache 매 ~100GB GPU memory 의 consume.
|
||||
- 매 conversation idle 매 hours / days — GPU memory 매 hold cost-prohibitive.
|
||||
- ICP: idle 시 disk 의 evict, resume 시 reload — 매 5-50x cost reduction.
|
||||
|
||||
### 매 Storage tiers
|
||||
- **L0 (HBM)**: active inference, < 1ms access.
|
||||
- **L1 (CPU RAM)**: 매 minutes idle, ~10ms reload.
|
||||
- **L2 (NVMe)**: 매 hours idle, ~100ms reload.
|
||||
- **L3 (Object store / S3)**: 매 days idle, ~1-5s reload.
|
||||
|
||||
### 매 Coupling guarantees
|
||||
- **Bit-exact resume**: 매 KV-cache 매 quantization-aware serialization.
|
||||
- **Causal consistency**: 매 token N 의 KV 매 strictly token <N 의 reflect.
|
||||
- **Atomic checkpoint**: partial-write 의 detect 의 crash recovery.
|
||||
|
||||
### 매 응용
|
||||
1. Long-running coding agent (multi-day session).
|
||||
2. Customer support bot (hours-long conversation history).
|
||||
3. Research assistant (multi-week project context).
|
||||
4. Multi-tenant LLM serving (100K concurrent idle sessions).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: vLLM KV-cache offload (2026)
|
||||
```python
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
|
||||
engine_args = EngineArgs(
|
||||
model="meta-llama/Llama-3.3-70B-Instruct",
|
||||
enable_prefix_caching=True,
|
||||
kv_cache_dtype="fp8",
|
||||
cpu_offload_gb=200, # CPU RAM tier
|
||||
swap_space=400, # NVMe tier (GB)
|
||||
block_size=32,
|
||||
)
|
||||
llm = LLM.from_engine_args(engine_args)
|
||||
```
|
||||
|
||||
### Pattern 2: Conversation checkpoint
|
||||
```python
|
||||
import torch
|
||||
from pathlib import Path
|
||||
|
||||
class ConversationCheckpoint:
|
||||
def __init__(self, store_dir: Path):
|
||||
self.store = store_dir
|
||||
self.store.mkdir(exist_ok=True, parents=True)
|
||||
|
||||
def save(self, conv_id: str, kv_blocks: list[torch.Tensor], tokens: list[int]):
|
||||
path = self.store / f"{conv_id}.pt"
|
||||
tmp = path.with_suffix(".tmp")
|
||||
torch.save({
|
||||
"kv": [b.cpu() for b in kv_blocks],
|
||||
"tokens": tokens,
|
||||
"version": 2,
|
||||
}, tmp)
|
||||
tmp.rename(path) # atomic
|
||||
|
||||
def load(self, conv_id: str) -> dict | None:
|
||||
path = self.store / f"{conv_id}.pt"
|
||||
if not path.exists():
|
||||
return None
|
||||
return torch.load(path, map_location="cuda")
|
||||
```
|
||||
|
||||
### Pattern 3: Tiered eviction policy
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from time import time
|
||||
|
||||
@dataclass
|
||||
class Session:
|
||||
id: str
|
||||
last_access: float
|
||||
size_gb: float
|
||||
|
||||
def evict_tier(sessions: list[Session], capacity_gb: float) -> list[Session]:
|
||||
"""매 LRU 의 evict — return list of (session, target_tier)."""
|
||||
sessions.sort(key=lambda s: s.last_access)
|
||||
used = sum(s.size_gb for s in sessions)
|
||||
evicted = []
|
||||
now = time()
|
||||
for s in sessions:
|
||||
if used <= capacity_gb:
|
||||
break
|
||||
idle_min = (now - s.last_access) / 60
|
||||
if idle_min < 5:
|
||||
target = "HBM"
|
||||
elif idle_min < 60:
|
||||
target = "CPU"
|
||||
elif idle_min < 1440:
|
||||
target = "NVMe"
|
||||
else:
|
||||
target = "S3"
|
||||
evicted.append((s, target))
|
||||
used -= s.size_gb
|
||||
return evicted
|
||||
```
|
||||
|
||||
### Pattern 4: Resume with prefix matching
|
||||
```python
|
||||
def resume_with_prefix(checkpoint: dict, new_prompt: str, tokenizer) -> tuple[list, list]:
|
||||
"""매 checkpoint 의 prefix 의 reuse — 매 prefix mismatch 의 from-scratch."""
|
||||
saved_tokens = checkpoint["tokens"]
|
||||
new_tokens = tokenizer.encode(new_prompt)
|
||||
common = 0
|
||||
for i in range(min(len(saved_tokens), len(new_tokens))):
|
||||
if saved_tokens[i] != new_tokens[i]:
|
||||
break
|
||||
common = i + 1
|
||||
if common == 0:
|
||||
return [], new_tokens
|
||||
kept_kv = [k[:, :common] for k in checkpoint["kv"]]
|
||||
return kept_kv, new_tokens[common:]
|
||||
```
|
||||
|
||||
### Pattern 5: Quantized serialization
|
||||
```python
|
||||
def serialize_kv_int8(kv: torch.Tensor) -> tuple[bytes, dict]:
|
||||
"""매 fp16 KV 의 int8 의 quantize — 매 50% storage save."""
|
||||
scale = kv.abs().amax() / 127
|
||||
q = (kv / scale).round().clamp(-128, 127).to(torch.int8)
|
||||
return q.numpy().tobytes(), {"scale": scale.item(), "shape": list(q.shape)}
|
||||
|
||||
def deserialize_kv_int8(data: bytes, meta: dict) -> torch.Tensor:
|
||||
import numpy as np
|
||||
arr = np.frombuffer(data, dtype=np.int8).reshape(meta["shape"])
|
||||
return torch.from_numpy(arr).to(torch.float16) * meta["scale"]
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Conversation < 5min idle | HBM 만. |
|
||||
| Long conversation, hours idle | NVMe tier. |
|
||||
| Multi-day project context | S3 + prefix cache. |
|
||||
| Cost-sensitive multi-tenant | Aggressive 4-tier ICP. |
|
||||
| Latency-sensitive (< 10ms) | HBM only — ICP 의 X. |
|
||||
|
||||
**기본값**: 4-tier (HBM → CPU → NVMe → S3) 매 LRU eviction, fp8 KV-cache, prefix caching enabled.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[KV-Cache]]
|
||||
- 변형: [[Prefix-Caching]] · [[PagedAttention]]
|
||||
- 응용: [[LLM_Optimization_and_Deployment_Strategies|vLLM]]
|
||||
- Adjacent: [[Continuous-Batching]] · [[Flash Attention]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 production LLM serving 매 multi-hour conversations, 매 cost optimization, 매 multi-tenant 100K+ sessions.
|
||||
**언제 X**: Single-shot inference (no persistence needed), strict-latency RT systems (< 10ms first-token).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Naive pickle of KV**: 매 quantization-unaware — 5-10x bigger than needed.
|
||||
- **No atomic write**: crash 의 corrupted checkpoint 의 unrecoverable.
|
||||
- **Per-token checkpoint**: 매 IOPS storm — batch 의 N tokens.
|
||||
- **Resume without prefix check**: silent correctness bug.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified: vLLM 0.7 docs (2025), SGLang RadixAttention paper (2024), Mooncake architecture (2024).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content with vLLM 2026 patterns, tiered eviction, quantized serialization |
|
||||
@@ -0,0 +1,245 @@
|
||||
---
|
||||
id: wiki-2026-0508-inheritance-and-polymorphism
|
||||
title: Inheritance and Polymorphism
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [OOP Inheritance, Subtype Polymorphism, Method Dispatch]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [oop, programming-language, type-theory, polymorphism]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: multi
|
||||
framework: oop
|
||||
---
|
||||
|
||||
# Inheritance and Polymorphism
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 inheritance 의 mechanism — polymorphism 의 outcome"**. 매 inheritance 의 code reuse + 매 is-a 의 subtype relationship; 매 polymorphism 의 same interface 의 different behavior. 매 modern 2026 의 view 의 "favor composition over inheritance" 의 default — Go/Rust 의 inheritance-free, but interface-polymorphism 의 universal. 매 LLM-generated code 의 over-inheritance 의 common antipattern.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 inheritance 의 종류
|
||||
- **Single inheritance**: 매 one parent class (Java, Kotlin, C#).
|
||||
- **Multiple inheritance**: 매 N parents — diamond problem (C++, Python via MRO).
|
||||
- **Mixins / traits**: 매 horizontal composition (Rust traits, Scala traits, Python mixins).
|
||||
- **Prototype-based**: 매 object → object delegation (JavaScript, Lua).
|
||||
|
||||
### 매 polymorphism 의 종류
|
||||
- **Subtype polymorphism**: 매 subclass 의 parent 의 substitute (Liskov LSP).
|
||||
- **Parametric polymorphism (generics)**: 매 type parameter — `List<T>`.
|
||||
- **Ad-hoc polymorphism (overloading)**: 매 same name 의 different signatures.
|
||||
- **Row polymorphism**: 매 structural — TypeScript / OCaml 의 records.
|
||||
|
||||
### 매 응용
|
||||
1. **Domain hierarchy**: 매 `Animal → Dog/Cat`. Often overused.
|
||||
2. **Plugin architecture**: 매 `Plugin` interface + N implementations.
|
||||
3. **AST transformation**: 매 `Visitor` pattern + node hierarchy.
|
||||
4. **Strategy pattern**: 매 interchangeable algorithms via interface.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### 매 subtype polymorphism (Python ABC + Liskov)
|
||||
```python
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
class Shape(ABC):
|
||||
@abstractmethod
|
||||
def area(self) -> float: ...
|
||||
|
||||
class Circle(Shape):
|
||||
def __init__(self, r: float): self.r = r
|
||||
def area(self) -> float: return 3.14159 * self.r ** 2
|
||||
|
||||
class Rectangle(Shape):
|
||||
def __init__(self, w: float, h: float): self.w, self.h = w, h
|
||||
def area(self) -> float: return self.w * self.h
|
||||
|
||||
# Polymorphic use — caller knows nothing about concrete type
|
||||
def total_area(shapes: list[Shape]) -> float:
|
||||
return sum(s.area() for s in shapes)
|
||||
|
||||
print(total_area([Circle(2), Rectangle(3, 4)])) # 24.566...
|
||||
```
|
||||
|
||||
### 매 composition over inheritance (modern preferred)
|
||||
```python
|
||||
# ❌ Inheritance-heavy — fragile
|
||||
class Animal:
|
||||
def move(self): print("move")
|
||||
class Bird(Animal):
|
||||
def fly(self): print("fly")
|
||||
class Penguin(Bird): # Penguin 의 fly X — Liskov violation
|
||||
def fly(self): raise NotImplementedError
|
||||
|
||||
# ✅ Composition-based — flexible
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
class Mover(Protocol):
|
||||
def move(self) -> str: ...
|
||||
|
||||
@dataclass
|
||||
class Walker:
|
||||
def move(self) -> str: return "walk"
|
||||
|
||||
@dataclass
|
||||
class Flyer:
|
||||
def move(self) -> str: return "fly"
|
||||
|
||||
@dataclass
|
||||
class Animal2:
|
||||
name: str
|
||||
mover: Mover # plug in capability — no inheritance
|
||||
|
||||
penguin = Animal2("Penguin", Walker())
|
||||
sparrow = Animal2("Sparrow", Flyer())
|
||||
print(penguin.mover.move(), sparrow.mover.move())
|
||||
```
|
||||
|
||||
### 매 generic parametric polymorphism (TypeScript)
|
||||
```typescript
|
||||
// Same code for any T
|
||||
function head<T>(xs: T[]): T | undefined {
|
||||
return xs[0];
|
||||
}
|
||||
|
||||
const n: number | undefined = head([1, 2, 3]);
|
||||
const s: string | undefined = head(["a", "b"]);
|
||||
|
||||
// Bounded generic — T must be Comparable
|
||||
interface Comparable<T> { compareTo(other: T): number; }
|
||||
|
||||
function max<T extends Comparable<T>>(xs: T[]): T {
|
||||
return xs.reduce((acc, x) => x.compareTo(acc) > 0 ? x : acc);
|
||||
}
|
||||
```
|
||||
|
||||
### 매 trait-based polymorphism (Rust — no inheritance)
|
||||
```rust
|
||||
trait Area {
|
||||
fn area(&self) -> f64;
|
||||
}
|
||||
|
||||
struct Circle { r: f64 }
|
||||
struct Square { side: f64 }
|
||||
|
||||
impl Area for Circle {
|
||||
fn area(&self) -> f64 { 3.14159 * self.r * self.r }
|
||||
}
|
||||
impl Area for Square {
|
||||
fn area(&self) -> f64 { self.side * self.side }
|
||||
}
|
||||
|
||||
// Static dispatch (zero-cost generics)
|
||||
fn print_area_static<T: Area>(s: &T) {
|
||||
println!("{}", s.area());
|
||||
}
|
||||
|
||||
// Dynamic dispatch (vtable)
|
||||
fn print_area_dyn(s: &dyn Area) {
|
||||
println!("{}", s.area());
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let shapes: Vec<Box<dyn Area>> = vec![
|
||||
Box::new(Circle { r: 2.0 }),
|
||||
Box::new(Square { side: 3.0 }),
|
||||
];
|
||||
for s in &shapes { print_area_dyn(s.as_ref()); }
|
||||
}
|
||||
```
|
||||
|
||||
### 매 visitor pattern (AST traversal)
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from typing import Union
|
||||
|
||||
# AST hierarchy
|
||||
@dataclass
|
||||
class Num: value: float
|
||||
@dataclass
|
||||
class Add: left: "Expr"; right: "Expr"
|
||||
@dataclass
|
||||
class Mul: left: "Expr"; right: "Expr"
|
||||
|
||||
Expr = Union[Num, Add, Mul]
|
||||
|
||||
# Polymorphic dispatch via match (Python 3.10+)
|
||||
def evaluate(e: Expr) -> float:
|
||||
match e:
|
||||
case Num(v): return v
|
||||
case Add(l, r): return evaluate(l) + evaluate(r)
|
||||
case Mul(l, r): return evaluate(l) * evaluate(r)
|
||||
|
||||
# (3 + 4) * 5
|
||||
print(evaluate(Mul(Add(Num(3), Num(4)), Num(5)))) # 35
|
||||
```
|
||||
|
||||
### 매 LSP-violation 의 detector (mypy + tests)
|
||||
```python
|
||||
# Runtime LSP check — for each subclass override, parameter contravariant + return covariant
|
||||
import inspect
|
||||
from typing import get_type_hints
|
||||
|
||||
def check_lsp(parent: type, child: type) -> list[str]:
|
||||
issues = []
|
||||
for name in dir(parent):
|
||||
if name.startswith("_") or not callable(getattr(parent, name)):
|
||||
continue
|
||||
try:
|
||||
p_hints = get_type_hints(getattr(parent, name))
|
||||
c_hints = get_type_hints(getattr(child, name))
|
||||
except Exception:
|
||||
continue
|
||||
# Return type must be subtype of parent's return
|
||||
if "return" in p_hints and "return" in c_hints:
|
||||
if not issubclass(c_hints["return"], p_hints["return"]):
|
||||
issues.append(f"{child.__name__}.{name}: return type widens parent")
|
||||
return issues
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 is-a 의 stable | Inheritance OK — keep depth ≤ 2 |
|
||||
| 매 has-a / can-do | Composition + protocol/interface |
|
||||
| 매 cross-cutting (logging, metrics) | Decorator / mixin / aspect |
|
||||
| 매 algorithm variants | Strategy pattern (composition) |
|
||||
| 매 type-safe collections | Parametric generics (`List<T>`) |
|
||||
| 매 closed AST / variant data | Sum types + pattern match (Rust enum, Scala sealed) |
|
||||
|
||||
**기본값**: 매 composition + interface — inheritance 의 only when 명확 is-a + LSP-honoring.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Object-Oriented-Programming]] · [[Type Theory]]
|
||||
- 변형: [[Subtype Polymorphism]] · [[Parametric Polymorphism]]
|
||||
- 응용: [[Visitor Pattern]]
|
||||
- Adjacent: [[Composition over Inheritance]] · [[Duck Typing]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 boilerplate 의 generation (interface + N impls) / 매 LSP audit / 매 inheritance-to-composition refactor.
|
||||
**언제 X**: 매 deep inheritance design — 매 LLM 의 over-inherit 의 tendency. Manual review 필수.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **매 deep inheritance**: 매 4+ levels — fragile base class problem.
|
||||
- **매 LSP violation**: 매 subclass 의 throws on parent-supported method (Penguin.fly).
|
||||
- **매 inheritance for code reuse only**: 매 not is-a — use composition.
|
||||
- **매 god parent class**: 매 parent 의 every responsibility — SRP violation.
|
||||
- **매 multiple inheritance 의 diamond ignore**: 매 MRO 의 surprise behavior.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Gamma et al. *Design Patterns* 1994; Liskov & Wing *A Behavioral Notion of Subtyping* 1994; Effective Java Item 18 "Favor composition" 2018).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — types of inheritance + polymorphism + multi-language patterns |
|
||||
@@ -0,0 +1,195 @@
|
||||
---
|
||||
id: wiki-2026-0508-iteration
|
||||
title: Iteration
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Iterative Development, Loop, Iterate]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [methodology, agile, python, control-flow, generators]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: general
|
||||
---
|
||||
|
||||
# Iteration
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 small step, 매 feedback, 매 adjust, 매 repeat"**. Iteration 매 dual concept — (1) programming control flow (`for`, `while`, generators) 와 (2) development methodology (small increments + feedback loop). 2026 LLM-assisted 시대 매 iteration 매 even tighter — 매 minute 매 cycle 가능.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 Programming iteration
|
||||
- **Eager**: `for x in list` — 매 list 매 fully materialized.
|
||||
- **Lazy**: generator, iterator — 매 on-demand pull.
|
||||
- **Async**: `async for x in stream` — 매 I/O 의 overlap.
|
||||
- **Parallel**: `joblib`, `multiprocessing.Pool.imap` — 매 CPU-bound iteration.
|
||||
|
||||
### 매 Methodology iteration
|
||||
- **Loop**: hypothesis → build → measure → learn.
|
||||
- **Cadence**: daily (LLM-assisted), weekly (sprint), monthly (release).
|
||||
- **Artifact per cycle**: shippable increment.
|
||||
- **Feedback source**: tests, users, metrics, code review.
|
||||
|
||||
### 매 응용
|
||||
1. Data pipeline (process N rows lazily).
|
||||
2. ML hyperparameter search (iteratively narrow).
|
||||
3. Agile sprint (2-week cycle).
|
||||
4. LLM agentic loop (think → act → observe → repeat).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: Generator (lazy iteration)
|
||||
```python
|
||||
def read_jsonl(path: str):
|
||||
"""매 1GB+ file 의 stream — 매 memory O(1)."""
|
||||
import json
|
||||
with open(path) as f:
|
||||
for line in f:
|
||||
yield json.loads(line)
|
||||
|
||||
for record in read_jsonl("events.jsonl"):
|
||||
process(record)
|
||||
```
|
||||
|
||||
### Pattern 2: Itertools combinators
|
||||
```python
|
||||
from itertools import islice, chain, groupby, accumulate
|
||||
|
||||
# 매 first 100 records 만
|
||||
head = list(islice(read_jsonl("big.jsonl"), 100))
|
||||
|
||||
# 매 multiple sources 의 concat
|
||||
combined = chain(read_jsonl("a.jsonl"), read_jsonl("b.jsonl"))
|
||||
|
||||
# 매 group by user
|
||||
sorted_records = sorted(combined, key=lambda r: r["user_id"])
|
||||
for user_id, group in groupby(sorted_records, key=lambda r: r["user_id"]):
|
||||
handle_user(user_id, list(group))
|
||||
```
|
||||
|
||||
### Pattern 3: Async iteration (2026)
|
||||
```python
|
||||
import asyncio
|
||||
import httpx
|
||||
|
||||
async def fetch_pages(urls: list[str]):
|
||||
async with httpx.AsyncClient() as client:
|
||||
async def fetch(url):
|
||||
r = await client.get(url)
|
||||
return url, r.text
|
||||
for coro in asyncio.as_completed([fetch(u) for u in urls]):
|
||||
yield await coro
|
||||
|
||||
async def main():
|
||||
async for url, html in fetch_pages(URLS):
|
||||
print(url, len(html))
|
||||
```
|
||||
|
||||
### Pattern 4: Iterative refinement (algorithm)
|
||||
```python
|
||||
def newton_sqrt(n: float, tol: float = 1e-10, max_iter: int = 50) -> float:
|
||||
x = n / 2
|
||||
for _ in range(max_iter):
|
||||
x_new = 0.5 * (x + n / x)
|
||||
if abs(x_new - x) < tol:
|
||||
return x_new
|
||||
x = x_new
|
||||
return x
|
||||
```
|
||||
|
||||
### Pattern 5: LLM agentic loop (2026)
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
|
||||
client = Anthropic()
|
||||
|
||||
def agent_loop(task: str, max_iter: int = 10):
|
||||
history = [{"role": "user", "content": task}]
|
||||
for i in range(max_iter):
|
||||
msg = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4000,
|
||||
tools=TOOLS,
|
||||
messages=history,
|
||||
)
|
||||
history.append({"role": "assistant", "content": msg.content})
|
||||
if msg.stop_reason == "end_turn":
|
||||
return msg
|
||||
# tool_use → execute → observation → next iter
|
||||
observations = execute_tools(msg.content)
|
||||
history.append({"role": "user", "content": observations})
|
||||
raise RuntimeError("매 max_iter 의 reach")
|
||||
```
|
||||
|
||||
### Pattern 6: Sprint retrospective
|
||||
```python
|
||||
def retro(sprint_data: dict) -> dict:
|
||||
return {
|
||||
"what_worked": sprint_data["green_items"],
|
||||
"what_didnt": sprint_data["red_items"],
|
||||
"experiments_next": [
|
||||
f"Try {hypothesis}" for hypothesis in sprint_data["new_ideas"]
|
||||
],
|
||||
"metrics_delta": {
|
||||
k: sprint_data["after"][k] - sprint_data["before"][k]
|
||||
for k in sprint_data["before"]
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 7: Bounded iteration with timeout
|
||||
```python
|
||||
import time
|
||||
|
||||
def iterate_with_budget(items, budget_sec: float):
|
||||
start = time.time()
|
||||
for item in items:
|
||||
if time.time() - start > budget_sec:
|
||||
print(f"매 budget 매 expire — {item} 의 stop")
|
||||
return
|
||||
yield process(item)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Large file processing | Generator (lazy). |
|
||||
| Multiple I/O calls | Async iteration. |
|
||||
| CPU-bound loop | `multiprocessing` 또는 vectorize. |
|
||||
| Numerical convergence | While + tolerance check. |
|
||||
| Product development | 2-week sprint + retrospective. |
|
||||
| LLM agent | think-act-observe loop with max_iter cap. |
|
||||
|
||||
**기본값**: Programming 매 generator-first; methodology 매 1-week iteration with measurable hypothesis.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Agile]]
|
||||
- 응용: [[Generator]] · [[Sprint]]
|
||||
- Adjacent: [[Lean Startup]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: Agentic systems (think-act-observe), iterative refinement of code via LLM feedback, sprint planning summaries.
|
||||
**언제 X**: Single-shot generation, tasks where each iteration is 1+ hours of human work (cycle too slow).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Eager when lazy works**: `list(huge_generator)` — 매 OOM.
|
||||
- **Unbounded loop**: no max_iter — 매 infinite loop bug.
|
||||
- **No feedback in iteration**: 매 build without measure — methodology 매 broken.
|
||||
- **Perfect first iteration**: 매 ship at 70% — feedback 의 wait.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified: PEP 234 (iterators), Eric Ries "Lean Startup" (2011), "Continuous Delivery" (Humble & Farley).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content covering both programming and methodology iteration with LLM agentic loop |
|
||||
@@ -0,0 +1,186 @@
|
||||
---
|
||||
id: wiki-2026-0508-just-in-time-jit
|
||||
title: Just-In-Time (JIT)
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [JIT Compilation, Dynamic Compilation, Tracing JIT]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [compiler, optimization, runtime, performance, llvm]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: jax
|
||||
---
|
||||
|
||||
# Just-In-Time (JIT)
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 compile 매 first call, 매 reuse 매 hot path"**. JIT compilation 매 source / bytecode / IR 의 native code 의 runtime translation — 매 profile-guided 의 hot region 의 optimize. 2026 ML 시대 매 JAX `jit`, PyTorch 2.x `torch.compile`, Mojo, JuliaLang 매 mainstream.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 JIT 의 mechanics
|
||||
- **Trace**: 매 input shape / dtype 의 capture 매 computational graph.
|
||||
- **Specialize**: 매 fixed shapes 의 specialized kernel 의 generate.
|
||||
- **Cache**: 매 (function, signature) → compiled artifact.
|
||||
- **Recompile**: 매 shape change → cache miss → recompile (avoid in hot loop).
|
||||
|
||||
### 매 vs AOT
|
||||
- **AOT (ahead-of-time)**: rustc, gcc — startup 빠름, 매 dynamic dispatch 부족.
|
||||
- **JIT**: 매 runtime info 의 use → better inlining, 매 startup 의 cost.
|
||||
- **Hybrid**: PyPy, V8, .NET — interpret first, JIT after N invocations.
|
||||
|
||||
### 매 ML JIT 의 specifics
|
||||
- **Static shape**: JAX `jit` 매 traced shape 의 specialize — dynamic shape 매 retrace.
|
||||
- **XLA / Triton backend**: 매 fused kernels — memory bandwidth dominant.
|
||||
- **Compilation cache**: persistent disk cache 매 cold-start 의 mitigate.
|
||||
|
||||
### 매 응용
|
||||
1. ML training loop (JAX, torch.compile).
|
||||
2. Numerical Python (Numba `@njit`).
|
||||
3. JavaScript engines (V8, JSC).
|
||||
4. Database query plans (Snowflake, DuckDB).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: JAX jit (2026 standard)
|
||||
```python
|
||||
import jax
|
||||
import jax.numpy as jnp
|
||||
|
||||
@jax.jit
|
||||
def attention(q, k, v):
|
||||
scores = jnp.einsum("bhqd,bhkd->bhqk", q, k) / jnp.sqrt(q.shape[-1])
|
||||
weights = jax.nn.softmax(scores, axis=-1)
|
||||
return jnp.einsum("bhqk,bhkd->bhqd", weights, v)
|
||||
|
||||
# First call: trace + compile (slow)
|
||||
# Subsequent: cached (fast)
|
||||
out = attention(q, k, v)
|
||||
```
|
||||
|
||||
### Pattern 2: torch.compile (PyTorch 2.x)
|
||||
```python
|
||||
import torch
|
||||
|
||||
model = MyTransformer().cuda()
|
||||
compiled = torch.compile(model, mode="reduce-overhead", fullgraph=True)
|
||||
|
||||
for batch in dataloader:
|
||||
out = compiled(batch) # 매 first batch 매 slow, subsequent 매 fast
|
||||
out.backward()
|
||||
```
|
||||
|
||||
### Pattern 3: Static argnums (avoid retrace)
|
||||
```python
|
||||
from functools import partial
|
||||
|
||||
@partial(jax.jit, static_argnums=(1,))
|
||||
def topk(logits, k):
|
||||
return jax.lax.top_k(logits, k)
|
||||
|
||||
# 매 k=10 매 specialized — 매 k=20 매 separate compilation
|
||||
topk(logits, 10)
|
||||
topk(logits, 20) # new compile
|
||||
```
|
||||
|
||||
### Pattern 4: Numba JIT (Python → LLVM)
|
||||
```python
|
||||
from numba import njit
|
||||
import numpy as np
|
||||
|
||||
@njit(cache=True, fastmath=True)
|
||||
def mandelbrot(c, max_iter=100):
|
||||
z = 0.0 + 0.0j
|
||||
for i in range(max_iter):
|
||||
z = z * z + c
|
||||
if z.real * z.real + z.imag * z.imag > 4.0:
|
||||
return i
|
||||
return max_iter
|
||||
```
|
||||
|
||||
### Pattern 5: AOT cache 의 prewarm
|
||||
```python
|
||||
import os
|
||||
os.environ["JAX_COMPILATION_CACHE_DIR"] = "/var/cache/jax"
|
||||
|
||||
import jax
|
||||
jax.config.update("jax_persistent_cache_min_entry_size_bytes", 0)
|
||||
jax.config.update("jax_persistent_cache_min_compile_time_secs", 1.0)
|
||||
|
||||
# 매 first deployment 매 prewarm script 의 run — 매 next pods cold-start fast.
|
||||
```
|
||||
|
||||
### Pattern 6: Recompilation detection
|
||||
```python
|
||||
import jax
|
||||
from collections import Counter
|
||||
|
||||
class CompileCounter:
|
||||
def __init__(self):
|
||||
self.count = Counter()
|
||||
|
||||
def trace(self, fn_name: str, sig: tuple):
|
||||
self.count[(fn_name, sig)] += 1
|
||||
if self.count[(fn_name, sig)] > 3:
|
||||
print(f"매 thrash: {fn_name} recompiled {self.count[(fn_name, sig)]} times")
|
||||
|
||||
# Usage: hook into jax.config or torch dynamo logger
|
||||
```
|
||||
|
||||
### Pattern 7: Mojo JIT (2026)
|
||||
```mojo
|
||||
fn matmul[M: Int, N: Int, K: Int](a: Tensor, b: Tensor) -> Tensor:
|
||||
# 매 compile-time specialization 매 shapes — 매 SIMD auto-vectorize.
|
||||
var c = Tensor[DType.float32](M, N)
|
||||
for i in range(M):
|
||||
for j in range(N):
|
||||
var s: Float32 = 0
|
||||
for k in range(K):
|
||||
s += a[i, k] * b[k, j]
|
||||
c[i, j] = s
|
||||
return c
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Numerical Python tight loop | Numba `@njit`. |
|
||||
| ML training | JAX `jit` 또는 `torch.compile`. |
|
||||
| Variable shapes | Avoid JIT 또는 `dynamic=True`. |
|
||||
| One-shot script | 매 JIT overhead 매 not worth. |
|
||||
| Long-running server | JIT + persistent cache. |
|
||||
|
||||
**기본값**: ML 매 `torch.compile(mode="reduce-overhead")` 또는 `jax.jit`. Tight numerical loop 매 Numba.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Performance-Optimization]]
|
||||
- 변형: [[Tracing-JIT]]
|
||||
- 응용: [[JAX]] · [[torch.compile]] · [[V8 Engine]]
|
||||
- Adjacent: [[XLA]] · [[Triton]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: ML training/serving where compile cost amortizes (>100 calls), tight numerical loops, long-running services.
|
||||
**언제 X**: One-shot scripts, code with constantly-changing shapes, debugging (use eager mode).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **JIT in hot Python loop with varying shapes**: 매 retrace 매 every call — slower than eager.
|
||||
- **No persistent cache**: 매 cold start 매 30s+ compile every deploy.
|
||||
- **JIT debugging**: 매 stacktrace 매 useless — eager 의 disable JIT first.
|
||||
- **Premature JIT**: profile first — 매 80% code 매 not bottleneck.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified: JAX docs (2026), PyTorch 2.x docs, "Engineering a Compiler" (Cooper & Torczon), V8 design docs.
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content with JAX/torch.compile/Numba/Mojo 2026 patterns |
|
||||
@@ -0,0 +1,180 @@
|
||||
---
|
||||
id: wiki-2026-0508-knowledge-synthesis
|
||||
title: Knowledge Synthesis
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [지식 종합, Synthesis, Information Integration]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [research, knowledge, synthesis, methodology, llm]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: rag
|
||||
---
|
||||
|
||||
# Knowledge Synthesis
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 synthesis = 차이의 통합"**. 여러 source 의 fragmented knowledge 를 단일 coherent representation 으로 통합하는 process. 2026 LLM 시대에 RAG + structured extraction + cross-document reasoning 이 표준 toolchain.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 5-step pipeline
|
||||
1. **Acquisition**: search / scrape / corpus collection.
|
||||
2. **Extraction**: structured fact / claim 추출.
|
||||
3. **Alignment**: same entity / concept matching across sources.
|
||||
4. **Integration**: conflict resolution + gap filling.
|
||||
5. **Presentation**: report / map / model.
|
||||
|
||||
### 매 synthesis types
|
||||
- **Aggregative**: meta-analysis, systematic review.
|
||||
- **Interpretive**: thematic synthesis, narrative review.
|
||||
- **Generative**: 새 framework / theory 제시.
|
||||
|
||||
### 매 응용
|
||||
1. Systematic literature review.
|
||||
2. Competitive intelligence.
|
||||
3. Wiki / knowledge graph build-out.
|
||||
4. Investigation reporting.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### RAG synthesis pipeline
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
import chromadb
|
||||
|
||||
client = Anthropic()
|
||||
db = chromadb.Client().create_collection("docs")
|
||||
|
||||
def synthesize(question: str, k=8):
|
||||
docs = db.query(query_texts=[question], n_results=k)["documents"][0]
|
||||
context = "\n---\n".join(docs)
|
||||
return client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4096,
|
||||
system="Synthesize the sources. Cite [N]. Note conflicts.",
|
||||
messages=[{"role": "user", "content": f"Q: {question}\nSources:\n{context}"}],
|
||||
).content[0].text
|
||||
```
|
||||
|
||||
### Structured extraction
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
|
||||
class Claim(BaseModel):
|
||||
statement: str
|
||||
source: str
|
||||
confidence: float
|
||||
contradicts: list[str] = []
|
||||
|
||||
def extract_claims(text: str, source: str) -> list[Claim]:
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=2048,
|
||||
system="Extract atomic claims as JSON list of {statement, confidence}.",
|
||||
messages=[{"role": "user", "content": text}],
|
||||
)
|
||||
return [Claim(source=source, **c) for c in json.loads(resp.content[0].text)]
|
||||
```
|
||||
|
||||
### Entity alignment
|
||||
```python
|
||||
from sentence_transformers import SentenceTransformer
|
||||
import numpy as np
|
||||
|
||||
model = SentenceTransformer("all-MiniLM-L6-v2")
|
||||
|
||||
def align(entities_a, entities_b, threshold=0.85):
|
||||
emb_a = model.encode(entities_a)
|
||||
emb_b = model.encode(entities_b)
|
||||
sim = emb_a @ emb_b.T / (np.linalg.norm(emb_a, axis=1)[:, None] *
|
||||
np.linalg.norm(emb_b, axis=1)[None, :])
|
||||
pairs = []
|
||||
for i, j in zip(*np.where(sim > threshold)):
|
||||
pairs.append((entities_a[i], entities_b[j], sim[i, j]))
|
||||
return pairs
|
||||
```
|
||||
|
||||
### Conflict detection
|
||||
```python
|
||||
def detect_conflicts(claims: list[Claim]) -> list[tuple]:
|
||||
pairs = []
|
||||
for i, c1 in enumerate(claims):
|
||||
for c2 in claims[i+1:]:
|
||||
resp = client.messages.create(
|
||||
model="claude-haiku-4-5",
|
||||
max_tokens=10,
|
||||
messages=[{"role": "user",
|
||||
"content": f"Contradict?\nA: {c1.statement}\nB: {c2.statement}\nYes/No"}],
|
||||
)
|
||||
if "yes" in resp.content[0].text.lower():
|
||||
pairs.append((c1, c2))
|
||||
return pairs
|
||||
```
|
||||
|
||||
### Hierarchical summarization
|
||||
```python
|
||||
def hier_summarize(docs: list[str], chunk=4) -> str:
|
||||
if len(docs) <= 1:
|
||||
return docs[0] if docs else ""
|
||||
summaries = []
|
||||
for i in range(0, len(docs), chunk):
|
||||
merged = "\n".join(docs[i:i+chunk])
|
||||
s = spawn_summarize(merged)
|
||||
summaries.append(s)
|
||||
return hier_summarize(summaries, chunk)
|
||||
```
|
||||
|
||||
### Citation graph build
|
||||
```python
|
||||
import networkx as nx
|
||||
|
||||
def build_graph(claims: list[Claim]) -> nx.DiGraph:
|
||||
g = nx.DiGraph()
|
||||
for c in claims:
|
||||
g.add_node(c.statement, source=c.source, conf=c.confidence)
|
||||
for contra in c.contradicts:
|
||||
g.add_edge(c.statement, contra, type="contradicts")
|
||||
return g
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 수십 개 sources | RAG + hierarchical summarize |
|
||||
| Conflicting claims | Structured extraction + LLM judge |
|
||||
| Novel framework needed | Generative synthesis |
|
||||
| Quantitative pooling | Meta-analysis stats |
|
||||
|
||||
**기본값**: RAG + structured extraction + claim graph.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Research Methodology]] · [[Information Retrieval]]
|
||||
- 응용: [[RAG]] · [[Knowledge Graph]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: literature review, competitive analysis, contradictory source reconciliation.
|
||||
**언제 X**: domain-novel concept invention without grounding — hallucination 위험.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Cherry-picking**: 매 confirming source 만 select.
|
||||
- **Source-blind synthesis**: citation 없이 claim 통합 → traceability 상실.
|
||||
- **Premature consensus**: conflict 무시하고 단일 narrative.
|
||||
- **Hallucinated alignment**: LLM 이 entity 임의 동일시.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (PRISMA 2020, Cochrane Handbook 6.4, Anthropic RAG cookbook).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — 5-step pipeline + RAG/extraction 패턴 |
|
||||
@@ -0,0 +1,23 @@
|
||||
# 📑 지식 자산 증분 추출 프로토콜 (Incremental Extraction Protocol)
|
||||
|
||||
## 1. 개요 (Overview)
|
||||
본 문서는 Connect AI 시스템의 'Thinking Mode'에서 표시되는 지식 자산을 로컬 위키 시스템으로 안전하게 이식하고, 향후 중복 없이 새로운 데이터만 필터링하여 가져오기 위한 운영 표준을 정의한다.
|
||||
|
||||
## 2. 데이터 베이스라인 (Baseline)
|
||||
- **추출 일시**: 2026-04-29
|
||||
- **추출 수량**: 1,535개 (Knowledge Assets)
|
||||
- **추출 로직**: `E:\Wiki\2nd\10_Wiki\Topics` 내 마크다운 파일 중 알파벳 순 상위 1,535개 선별
|
||||
- **인벤토리**: [knowledge_inventory_1535.json](file:///E:/Wiki/2nd/10_Wiki/Skills/knowledge_inventory_1535.json)
|
||||
|
||||
## 3. 필터링 규칙 (Filtering Rules)
|
||||
향후 재추출 요청 시 다음의 로직을 적용한다:
|
||||
1. **경로 대조**: `knowledge_inventory_1535.json`에 명시된 `RelativePath`와 동일한 파일은 무시한다.
|
||||
2. **신규성 판정**: 기존 인벤토리에 존재하지 않는 새로운 파일명이 발견되거나, 동일 파일명이라도 수정 일시(`LastWriteTime`)가 최신인 경우만 '신규 지식'으로 간주한다.
|
||||
3. **8대 카테고리 유지**: 추출 시 원본의 8대 분류 체계를 유지하며 `00_Raw` 폴더로 이식한다.
|
||||
|
||||
## 4. 실행 가이드 (Execution Guide)
|
||||
- **명령어**: `python E:\Wiki\Wonseok_AI_original\scratch\incremental_sync.py` (차기 구현 예정)
|
||||
- **주의 사항**: 원본 `Topics` 폴더의 파일 개수가 1,535개를 초과하여 증가하더라도, 인벤토리에 기록된 파일들은 중복으로 가져오지 않도록 엄격히 제한한다.
|
||||
|
||||
---
|
||||
🫡 **"지식은 축적될 때 비로소 힘을 발휘한다."** - AI 개발부장 코다리 승인 🚩🐟
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
id: wiki-2026-0508-mapreduce
|
||||
title: MapReduce
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [맵리듀스, Hadoop MR, Map-Reduce]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [distributed, big-data, parallel, hadoop, batch]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: hadoop-spark
|
||||
---
|
||||
|
||||
# MapReduce
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 split → map → shuffle → reduce"**. MapReduce (Dean & Ghemawat, Google 2004) 는 대규모 batch 처리 의 functional programming 모델. 2026 perspective 에서 raw Hadoop MR 은 legacy, Spark / Flink / BigQuery / Beam 이 후속 표준.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 4 phase
|
||||
- **Split**: input → fixed-size shards (HDFS block 64-128MB).
|
||||
- **Map**: (k1, v1) → list[(k2, v2)]. Stateless, parallelizable.
|
||||
- **Shuffle/Sort**: same k2 grouped to same reducer.
|
||||
- **Reduce**: (k2, list[v2]) → list[(k3, v3)].
|
||||
|
||||
### 매 design principles
|
||||
- **Data locality**: code → data, not data → code.
|
||||
- **Fault tolerance**: re-execute failed tasks (idempotent map/reduce).
|
||||
- **Speculative execution**: slow tasks 의 backup copy.
|
||||
- **Immutable inputs**: re-runnable.
|
||||
|
||||
### 매 응용
|
||||
1. Log analysis / web indexing (original use case).
|
||||
2. ETL pipelines.
|
||||
3. ML feature aggregation.
|
||||
4. Data warehouse build.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Word count (canonical)
|
||||
```python
|
||||
from collections import defaultdict
|
||||
from itertools import groupby
|
||||
|
||||
def map_phase(doc_id, text):
|
||||
for word in text.split():
|
||||
yield (word.lower(), 1)
|
||||
|
||||
def reduce_phase(word, counts):
|
||||
yield (word, sum(counts))
|
||||
|
||||
def mapreduce(docs):
|
||||
# Map
|
||||
pairs = [kv for did, t in docs for kv in map_phase(did, t)]
|
||||
# Shuffle
|
||||
pairs.sort(key=lambda x: x[0])
|
||||
grouped = {k: [v for _, v in g] for k, g in groupby(pairs, key=lambda x: x[0])}
|
||||
# Reduce
|
||||
return dict(kv for k, vs in grouped.items() for kv in reduce_phase(k, vs))
|
||||
```
|
||||
|
||||
### Combiner (local reduce)
|
||||
```python
|
||||
def map_with_combiner(doc_id, text):
|
||||
local = defaultdict(int)
|
||||
for word in text.split():
|
||||
local[word.lower()] += 1
|
||||
for w, c in local.items():
|
||||
yield (w, c)
|
||||
# 매 network shuffle 양 감소
|
||||
```
|
||||
|
||||
### Spark RDD equivalent
|
||||
```python
|
||||
from pyspark import SparkContext
|
||||
sc = SparkContext()
|
||||
|
||||
counts = (sc.textFile("hdfs:///logs/*.txt")
|
||||
.flatMap(lambda line: line.split())
|
||||
.map(lambda w: (w.lower(), 1))
|
||||
.reduceByKey(lambda a, b: a + b))
|
||||
counts.saveAsTextFile("hdfs:///out/wc")
|
||||
```
|
||||
|
||||
### Inverted index
|
||||
```python
|
||||
def map_idx(doc_id, text):
|
||||
for word in set(text.split()):
|
||||
yield (word.lower(), doc_id)
|
||||
|
||||
def reduce_idx(word, doc_ids):
|
||||
yield (word, sorted(set(doc_ids)))
|
||||
```
|
||||
|
||||
### Secondary sort
|
||||
```python
|
||||
# Composite key for sort-within-group
|
||||
def map_temp(line):
|
||||
parts = line.split(",")
|
||||
year, temp = parts[0], int(parts[1])
|
||||
yield ((year, temp), None) # negative temp for desc
|
||||
|
||||
def partitioner(key):
|
||||
return hash(key[0]) % num_reducers # group by year only
|
||||
|
||||
def grouping_comparator(a, b):
|
||||
return (a[0] > b[0]) - (a[0] < b[0]) # year only
|
||||
```
|
||||
|
||||
### Join (reduce-side)
|
||||
```python
|
||||
def map_users(row):
|
||||
yield (row["user_id"], ("user", row))
|
||||
|
||||
def map_orders(row):
|
||||
yield (row["user_id"], ("order", row))
|
||||
|
||||
def reduce_join(uid, tagged):
|
||||
user = next(r for tag, r in tagged if tag == "user")
|
||||
for tag, r in tagged:
|
||||
if tag == "order":
|
||||
yield {**user, **r}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Batch ETL on TB+ | Spark (Hadoop MR 은 legacy) |
|
||||
| Streaming | Flink / Spark Structured Streaming |
|
||||
| SQL-shaped query | BigQuery / Athena / Presto |
|
||||
| Cross-cloud portability | Apache Beam |
|
||||
| Educational | Raw MR pseudocode |
|
||||
|
||||
**기본값**: Spark for new projects; Hadoop MR 은 legacy 유지보수만.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Distributed Systems]] · [[Parallel-Computing]]
|
||||
- 변형: [[Spark]] · [[Apache Flink]]
|
||||
- 응용: [[Data Pipeline]] · [[ETL]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: pipeline design review, Spark migration 가이드, query optimization.
|
||||
**언제 X**: real-time low-latency — wrong paradigm.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Many small files**: HDFS namenode 폭발. 매 compaction 필수.
|
||||
- **Skewed keys**: 한 reducer 가 hotspot — salting / combiner 로 완화.
|
||||
- **Stateful map**: 매 idempotency 깨짐 → fault recovery 실패.
|
||||
- **Re-implementing SQL**: 매 BigQuery / Spark SQL 사용.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Dean & Ghemawat OSDI 2004, Spark NSDI 2012, Hadoop docs 3.x).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — word-count + Spark + secondary-sort + join 패턴 |
|
||||
@@ -0,0 +1,161 @@
|
||||
---
|
||||
id: wiki-2026-0508-memetics
|
||||
title: Memetics
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Meme Theory, Cultural Evolution, Dawkins Memetics]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.85
|
||||
verification_status: applied
|
||||
tags: [memetics, cultural-evolution, evolutionary-theory, information-theory]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: conceptual
|
||||
framework: evolutionary-theory
|
||||
---
|
||||
|
||||
# Memetics
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 cultural unit propagates 의 selection-replication-mutation 의 동일 logic"**. Dawkins 1976 *The Selfish Gene* 의 마지막 chapter 의 introduced — meme 의 cultural analog 의 gene. 매 modern state (2026) 의 contested 으로 남음 — academic 의 quasi-discipline 으로 fade 했지만 social media virality / LLM training data analysis 에서 매 explanatory framework 으로 revival.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 정의
|
||||
- **Meme**: 매 cultural information unit (idea, behavior, style) 의 host-to-host transmission 가능.
|
||||
- **Replicator**: 매 self-copying entity — gene 의 cultural counterpart.
|
||||
- **Memeplex**: 매 co-replicating memes 의 cluster (e.g., religion = belief + ritual + identity meme bundle).
|
||||
|
||||
### 매 Darwinian 3-step
|
||||
- **Variation**: 매 transmission 의 mutations (mishearing, reinterpretation).
|
||||
- **Selection**: 매 attention / memory / social reward 의 differential survival pressure.
|
||||
- **Heredity**: 매 high-fidelity copying 의 (vs. paraphrase) winning long-term.
|
||||
|
||||
### 매 응용
|
||||
1. **Internet virality** — 매 K-factor (replication rate) 의 explicit modeling.
|
||||
2. **LLM training corpus** — 매 dominant memes 의 over-representation 의 model bias.
|
||||
3. **Disinformation analysis** — 매 hostile memeplex 의 spread dynamics.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### 매 K-factor 의 simulation (epidemiological meme spread)
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def simulate_meme_spread(N=10000, beta=0.3, gamma=0.1, days=60, seed=42):
|
||||
"""SIR-style meme spread. beta = transmission rate, gamma = forget rate."""
|
||||
rng = np.random.default_rng(seed)
|
||||
S, I, R = N - 1, 1, 0
|
||||
history = []
|
||||
for day in range(days):
|
||||
new_inf = rng.binomial(S, 1 - np.exp(-beta * I / N))
|
||||
new_rec = rng.binomial(I, gamma)
|
||||
S -= new_inf
|
||||
I += new_inf - new_rec
|
||||
R += new_rec
|
||||
history.append((day, S, I, R))
|
||||
return history
|
||||
|
||||
hist = simulate_meme_spread()
|
||||
peak_day = max(hist, key=lambda x: x[2])
|
||||
print(f"Peak adoption day {peak_day[0]}, infected={peak_day[2]}")
|
||||
```
|
||||
|
||||
### 매 meme fitness 의 measurement (engagement-weighted)
|
||||
```python
|
||||
def meme_fitness(impressions: int, shares: int, completion_rate: float, novelty: float) -> float:
|
||||
"""Composite fitness — higher means stronger replicator."""
|
||||
if impressions == 0:
|
||||
return 0.0
|
||||
share_rate = shares / impressions
|
||||
return share_rate * completion_rate * (1 + 0.5 * novelty)
|
||||
|
||||
# Example: TikTok clip
|
||||
print(meme_fitness(1_000_000, 50_000, 0.78, 0.6)) # → ~0.0507
|
||||
```
|
||||
|
||||
### 매 memeplex 의 cluster detection (LLM corpus analysis)
|
||||
```python
|
||||
from sklearn.feature_extraction.text import TfidfVectorizer
|
||||
from sklearn.cluster import KMeans
|
||||
|
||||
def find_memeplexes(documents: list[str], k: int = 8):
|
||||
"""Identify co-occurring meme clusters in a corpus."""
|
||||
vec = TfidfVectorizer(max_features=5000, ngram_range=(1, 3), stop_words="english")
|
||||
X = vec.fit_transform(documents)
|
||||
km = KMeans(n_clusters=k, random_state=42, n_init=10).fit(X)
|
||||
|
||||
terms = vec.get_feature_names_out()
|
||||
for cluster_id in range(k):
|
||||
center = km.cluster_centers_[cluster_id]
|
||||
top = center.argsort()[-10:][::-1]
|
||||
print(f"Memeplex {cluster_id}: {[terms[i] for i in top]}")
|
||||
|
||||
# usage: find_memeplexes(reddit_posts, k=12)
|
||||
```
|
||||
|
||||
### 매 mutation rate 의 quantification (paraphrase distance)
|
||||
```python
|
||||
from sentence_transformers import SentenceTransformer
|
||||
import numpy as np
|
||||
|
||||
model = SentenceTransformer("all-MiniLM-L6-v2")
|
||||
|
||||
def transmission_fidelity(original: str, retransmissions: list[str]) -> float:
|
||||
"""1.0 = perfect copy, 0.0 = unrelated."""
|
||||
orig_vec = model.encode(original, normalize_embeddings=True)
|
||||
re_vecs = model.encode(retransmissions, normalize_embeddings=True)
|
||||
sims = re_vecs @ orig_vec
|
||||
return float(np.mean(sims))
|
||||
```
|
||||
|
||||
### 매 selfish-meme 의 detector (cost-to-host)
|
||||
```python
|
||||
def selfish_meme_score(replication_rate: float, host_wellbeing_delta: float) -> float:
|
||||
"""High when meme spreads strongly while harming hosts (e.g., conspiracy theories)."""
|
||||
return replication_rate / (1 + max(0, host_wellbeing_delta))
|
||||
|
||||
# Healthy meme (positive impact, low spread): 0.5
|
||||
print(selfish_meme_score(replication_rate=0.5, host_wellbeing_delta=0.5)) # 0.33
|
||||
# Selfish meme (negative impact, high spread): high score
|
||||
print(selfish_meme_score(replication_rate=2.0, host_wellbeing_delta=-0.8)) # 2.0
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 single viral content 의 spread modeling | SIR with measured beta/gamma |
|
||||
| 매 long-term cultural change (years+) | Multi-meme co-evolution + selection landscape |
|
||||
| 매 LLM training bias 분석 | Memeplex cluster detection on corpus |
|
||||
| 매 disinformation campaign 의 detection | Selfish-meme scoring + network propagation graph |
|
||||
|
||||
**기본값**: 매 SIR-style modeling 의 first pass — 매 quantitative grip 후 refinement.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Cultural Evolution]]
|
||||
- 변형: [[Entropy in Information Theory|Information Theory]]
|
||||
- Adjacent: [[Behavioral Economics]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 viral content design / disinformation defense / training corpus 의 bias diagnosis.
|
||||
**언제 X**: 매 individual cognition modeling — meme 의 statistical-population concept 의 individual prediction 의 부적합.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **매 "meme = funny image"**: 매 internet vernacular 의 academic concept 의 confuse.
|
||||
- **매 over-Darwinizing culture**: 매 every cultural change 의 selection 의 attribute — many are random drift / institutional choice.
|
||||
- **매 ignoring transmission medium**: 매 medium 의 selection pressure 의 dominant — TV vs Twitter vs TikTok 의 different memeplex 의 favor.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Dawkins *The Selfish Gene* 1976; Blackmore *The Meme Machine* 1999; Boyd & Richerson *Culture and the Evolutionary Process* 1985).
|
||||
- 신뢰도 A (foundational) — but applied predictions 의 신뢰도 B.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — memetics 의 core theory + simulation/cluster patterns 추가 |
|
||||
@@ -0,0 +1,192 @@
|
||||
---
|
||||
id: wiki-2026-0508-multi-agent-system
|
||||
title: Multi-agent System
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [MAS, 멀티에이전트, Agent Swarm, Agentic Systems]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [ai, agents, llm, orchestration, distributed]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: claude-agent-sdk
|
||||
---
|
||||
|
||||
# Multi-agent System
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 specialization × coordination > monolith"**. Multi-agent system 은 여러 autonomous agent 가 message passing / shared state 로 협업해 single agent 보다 큰 task 해결. 2026 LLM 시대에 Claude Agent SDK, OpenAI Swarm, LangGraph, AutoGen 등이 표준 framework.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 architecture pattern
|
||||
- **Orchestrator-worker**: 1 lead agent + N specialist worker. 매 Anthropic 의 research agent 패턴.
|
||||
- **Peer-to-peer**: 모든 agent equal, message bus 로 통신.
|
||||
- **Hierarchical**: layered supervisor tree.
|
||||
- **Blackboard**: shared memory 기반 indirect coordination.
|
||||
|
||||
### 매 communication
|
||||
- Function calling / tool use.
|
||||
- Structured message (JSON schema).
|
||||
- Shared filesystem / vector DB.
|
||||
- A2A (Agent-to-Agent) protocol (2025 Anthropic spec).
|
||||
|
||||
### 매 응용
|
||||
1. Research / report generation (parallel search + synthesis).
|
||||
2. Software engineering (planner + coder + tester).
|
||||
3. Customer support routing.
|
||||
4. Game NPC behavior.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Orchestrator-worker (Claude Agent SDK)
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
|
||||
client = Anthropic()
|
||||
|
||||
def spawn_worker(task: str, system: str) -> str:
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4096,
|
||||
system=system,
|
||||
messages=[{"role": "user", "content": task}],
|
||||
)
|
||||
return resp.content[0].text
|
||||
|
||||
def orchestrate(query: str):
|
||||
plan = spawn_worker(
|
||||
f"Decompose into 3 sub-tasks: {query}",
|
||||
"You are a research planner. Output JSON list.",
|
||||
)
|
||||
subtasks = parse_plan(plan)
|
||||
results = [spawn_worker(t, "You are a domain expert.") for t in subtasks]
|
||||
return spawn_worker(
|
||||
f"Synthesize: {results}",
|
||||
"You are an editor. Merge into a coherent report.",
|
||||
)
|
||||
```
|
||||
|
||||
### Tool-use loop
|
||||
```python
|
||||
def agent_loop(messages, tools, max_iter=10):
|
||||
for _ in range(max_iter):
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
tools=tools,
|
||||
messages=messages,
|
||||
max_tokens=4096,
|
||||
)
|
||||
messages.append({"role": "assistant", "content": resp.content})
|
||||
if resp.stop_reason == "end_turn":
|
||||
return resp
|
||||
for block in resp.content:
|
||||
if block.type == "tool_use":
|
||||
result = execute_tool(block.name, block.input)
|
||||
messages.append({
|
||||
"role": "user",
|
||||
"content": [{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": block.id,
|
||||
"content": result,
|
||||
}],
|
||||
})
|
||||
```
|
||||
|
||||
### Shared state via filesystem
|
||||
```python
|
||||
import json, fcntl
|
||||
from pathlib import Path
|
||||
|
||||
def shared_write(path: Path, key: str, value):
|
||||
with open(path, "r+") as f:
|
||||
fcntl.flock(f, fcntl.LOCK_EX)
|
||||
state = json.load(f)
|
||||
state[key] = value
|
||||
f.seek(0); f.truncate()
|
||||
json.dump(state, f)
|
||||
fcntl.flock(f, fcntl.LOCK_UN)
|
||||
```
|
||||
|
||||
### LangGraph state machine
|
||||
```python
|
||||
from langgraph.graph import StateGraph, END
|
||||
|
||||
def planner(state): return {"plan": llm_plan(state["query"])}
|
||||
def executor(state): return {"result": run_steps(state["plan"])}
|
||||
def critic(state):
|
||||
if quality_score(state["result"]) < 0.7:
|
||||
return {"next": "planner"}
|
||||
return {"next": END}
|
||||
|
||||
g = StateGraph(dict)
|
||||
g.add_node("plan", planner)
|
||||
g.add_node("exec", executor)
|
||||
g.add_node("crit", critic)
|
||||
g.add_edge("plan", "exec")
|
||||
g.add_edge("exec", "crit")
|
||||
g.add_conditional_edges("crit", lambda s: s["next"])
|
||||
```
|
||||
|
||||
### Parallel agent fan-out
|
||||
```python
|
||||
import asyncio
|
||||
|
||||
async def parallel_search(queries: list[str]) -> list[str]:
|
||||
tasks = [asyncio.to_thread(spawn_worker, q, "Researcher") for q in queries]
|
||||
return await asyncio.gather(*tasks)
|
||||
```
|
||||
|
||||
### Critic-actor consensus
|
||||
```python
|
||||
def consensus(question: str, n_agents=3) -> str:
|
||||
answers = [spawn_worker(question, f"Expert #{i}") for i in range(n_agents)]
|
||||
return spawn_worker(
|
||||
f"Q: {question}\nAnswers:\n" + "\n".join(answers) +
|
||||
"\nReturn consensus + dissent.",
|
||||
"You are a meta-reviewer.",
|
||||
)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Clear task decomposition | Orchestrator-worker |
|
||||
| Open-ended exploration | Peer-to-peer + blackboard |
|
||||
| Quality-critical | Critic-actor + consensus |
|
||||
| Latency-critical | Parallel fan-out |
|
||||
| Stateful workflow | LangGraph / state machine |
|
||||
|
||||
**기본값**: Orchestrator-worker + tool use loop.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Distributed Systems]]
|
||||
- 변형: [[Agent Orchestration]] · [[Swarm_Intelligence|Swarm Intelligence]]
|
||||
- 응용: [[LangGraph]]
|
||||
- Adjacent: [[Tool Use]] · [[Function Calling]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: complex task decomposition, parallel research, multi-step pipeline.
|
||||
**언제 X**: simple single-shot Q&A — overhead 만 추가.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Over-decomposition**: 너무 많은 agent → coordination overhead 폭증.
|
||||
- **No termination condition**: infinite loop 위험.
|
||||
- **Shared mutable state without lock**: race condition.
|
||||
- **Tool sprawl**: 한 agent 에 50+ tools — selection 정확도 폭락.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Anthropic Multi-agent Research 2024, OpenAI Swarm, LangGraph 0.3).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — orchestrator/tool-use/LangGraph 패턴 |
|
||||
@@ -0,0 +1,139 @@
|
||||
---
|
||||
id: wiki-2026-0508-nexus-gaming-labs
|
||||
title: Nexus Gaming Labs
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [NGL, Nexus Labs]
|
||||
duplicate_of: none
|
||||
source_trust_level: B
|
||||
confidence_score: 0.7
|
||||
verification_status: applied
|
||||
tags: [game-studio, ugc, web3, nexus]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: typescript
|
||||
framework: unity-photon
|
||||
---
|
||||
|
||||
# Nexus Gaming Labs
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 indie-scale UGC game lab — 매 prototype-first, 매 community-publish"**. 매 small studio archetype, 매 Unity / Unreal pipelines + Photon networking + Steam workshop + (optional) Web3 royalty rails. 매 2026 의 GenAI tooling (Scenario, Convai, Layer.AI) 의 leverage 의 1-3 person studios 의 differentiator.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 stack archetype
|
||||
- **Engine**: Unity 6 / Unreal 5.5.
|
||||
- **Net**: Photon Fusion 2 / Mirror.
|
||||
- **Backend**: PlayFab / Nakama.
|
||||
- **Distribution**: Steam, Epic, itch.io, mobile stores.
|
||||
- **Optional Web3**: Immutable zkEVM / Sui royalty contracts.
|
||||
|
||||
### 매 differentiation levers
|
||||
- **Niche genre depth** (autobattlers, deckbuilders, simulation).
|
||||
- **UGC tooling** — 매 in-game editor 의 player retention 의 multiplier.
|
||||
- **GenAI content** — 매 art / VO / dialogue scaling.
|
||||
- **Lean dev** — 매 1-3 person, 매 12-month cycle.
|
||||
|
||||
### 매 응용
|
||||
1. 매 prototype → public demo → wishlist build.
|
||||
2. 매 modding SDK release → community content flywheel.
|
||||
3. 매 royalty-on-resale (optional Web3) — 매 secondary-market revenue.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Photon Fusion 2 networked input
|
||||
```csharp
|
||||
public struct InputData : INetworkInput {
|
||||
public Vector2 Move;
|
||||
public NetworkButtons Buttons;
|
||||
}
|
||||
public override void FixedUpdateNetwork() {
|
||||
if (GetInput(out InputData input)) {
|
||||
transform.position += (Vector3)input.Move * speed * Runner.DeltaTime;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Steam workshop upload (Steamworks.NET)
|
||||
```csharp
|
||||
var handle = SteamUGC.CreateItem(appId, EWorkshopFileType.k_EWorkshopFileTypeCommunity);
|
||||
SteamUGC.SetItemTitle(handle, "My Mod");
|
||||
SteamUGC.SetItemContent(handle, "C:/mods/my-mod");
|
||||
SteamUGC.SubmitItemUpdate(handle, "Initial release");
|
||||
```
|
||||
|
||||
### Convai NPC dialogue stream (Unity)
|
||||
```csharp
|
||||
var convaiClient = new ConvaiClient(apiKey);
|
||||
await foreach (var token in convaiClient.StreamReply(playerUtterance, npcId)) {
|
||||
dialogueUI.Append(token);
|
||||
}
|
||||
```
|
||||
|
||||
### Nakama match listing
|
||||
```typescript
|
||||
const matches = await client.listMatches(session, 10, true, "deathmatch", 1, 8);
|
||||
matches.matches?.forEach(m => console.log(m.match_id, m.size));
|
||||
```
|
||||
|
||||
### Royalty smart contract (Sui Move)
|
||||
```move
|
||||
public entry fun pay_royalty(item: &Item, sale: Coin<SUI>, ctx: &mut TxContext) {
|
||||
let royalty_bps: u64 = 500; // 5%
|
||||
let amount = balance::value(coin::balance(&sale)) * royalty_bps / 10_000;
|
||||
let cut = coin::split(&mut sale, amount, ctx);
|
||||
transfer::public_transfer(cut, item.creator);
|
||||
transfer::public_transfer(sale, tx_context::sender(ctx));
|
||||
}
|
||||
```
|
||||
|
||||
### LiveOps event scheduler
|
||||
```typescript
|
||||
type Event = { id: string; start: Date; end: Date; rewards: Reward[] };
|
||||
function activeEvents(now: Date, events: Event[]) {
|
||||
return events.filter(e => e.start <= now && now < e.end);
|
||||
}
|
||||
```
|
||||
|
||||
### Telemetry funnel
|
||||
```typescript
|
||||
const funnel = ['install', 'tutorial_done', 'first_match', 'd1_return', 'd7_return'];
|
||||
const conversion = funnel.map((step, i) =>
|
||||
i === 0 ? 1 : counts[step] / counts[funnel[i-1]]);
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 1-3 person, premium PC | Unity + Steam + Discord community |
|
||||
| Mobile F2P | Unity + PlayFab + IronSource ads |
|
||||
| Web3-first | Unreal + Immutable / Sui |
|
||||
| UGC-heavy | Built-in editor + Steam workshop |
|
||||
|
||||
**기본값**: Unity + Steam + Discord + telemetry-driven LiveOps — 매 indie sweet spot.
|
||||
|
||||
## 🔗 Graph
|
||||
- 응용: [[LiveOps]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 design-doc draft, 매 quest / dialogue gen, 매 telemetry SQL.
|
||||
**언제 X**: 매 final art / VO 의 ship-quality — 매 human polish 의 still need.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Engine over-build**: 매 custom engine 의 indie 의 trap. 매 off-the-shelf 의 use.
|
||||
- **Web3-first marketing**: 매 gameplay 의 second 의 fail. 매 fun-first.
|
||||
- **No telemetry**: 매 LiveOps 의 blind. 매 D1/D7/D30 funnel 의 ship-day-one.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (GDC 2025 indie talks; Steamworks docs; Photon docs).
|
||||
- 신뢰도 B (studio-archetype, 매 specific entity verification 의 limited).
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — stack + LiveOps patterns |
|
||||
@@ -0,0 +1,166 @@
|
||||
---
|
||||
id: wiki-2026-0508-parallel-computing
|
||||
title: Parallel Computing
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Parallel Processing, Concurrent Computing, HPC]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [hpc, parallelism, gpu, distributed]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python-cuda
|
||||
framework: jax-pytorch-mpi
|
||||
---
|
||||
|
||||
# Parallel Computing
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 multiple computations 매 simultaneously 실행"**. 매 Flynn taxonomy (SISD/SIMD/MIMD) 부터 매 modern GPU SIMT, 매 distributed cluster (MPI, NCCL), 매 Llama 3.x 405B 의 4D parallelism (DP/TP/PP/SP) 까지. 매 2026 의 default workload 매 inference / training 의 parallel 이 매 single-core sequential 압도.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 Flynn's taxonomy
|
||||
- **SISD**: 매 single instruction, single data — 매 classic CPU.
|
||||
- **SIMD**: 매 single instruction, multiple data — 매 AVX-512, GPU warp.
|
||||
- **MIMD**: 매 multiple instruction, multiple data — 매 multi-core CPU, cluster.
|
||||
- **SIMT**: 매 single instruction, multiple thread — 매 NVIDIA / AMD GPU.
|
||||
|
||||
### 매 parallelism dimensions (modern DL)
|
||||
- **Data parallel (DP)**: 매 same model, 매 different batches.
|
||||
- **Tensor parallel (TP)**: 매 single tensor 매 split across devices.
|
||||
- **Pipeline parallel (PP)**: 매 layers 매 stages 로 split.
|
||||
- **Sequence parallel (SP)**: 매 sequence dim split (long context).
|
||||
- **Expert parallel (EP)**: 매 MoE 매 experts 매 across devices.
|
||||
|
||||
### 매 응용
|
||||
1. **LLM training**: Llama 3.x 405B = DP×TP×PP×SP×EP combination.
|
||||
2. **Inference**: vLLM 매 continuous batching + tensor parallel.
|
||||
3. **Scientific compute**: weather, molecular dynamics (MPI).
|
||||
4. **Rendering**: Pixar RenderMan 매 distributed.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### NumPy → JAX SIMD vectorization
|
||||
```python
|
||||
# 매 implicit SIMD on CPU/GPU/TPU
|
||||
import jax
|
||||
import jax.numpy as jnp
|
||||
|
||||
@jax.jit
|
||||
def matmul_vectorized(A, B):
|
||||
return jnp.einsum("bij,bjk->bik", A, B)
|
||||
|
||||
# vmap: auto-vectorize over batch dim
|
||||
batched = jax.vmap(lambda x, y: x @ y)(A, B)
|
||||
```
|
||||
|
||||
### CUDA kernel (SIMT)
|
||||
```cpp
|
||||
// 매 explicit thread-level parallelism
|
||||
__global__ void vec_add(float* a, float* b, float* c, int n) {
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (idx < n) c[idx] = a[idx] + b[idx];
|
||||
}
|
||||
|
||||
// launch: vec_add<<<(n+255)/256, 256>>>(a, b, c, n);
|
||||
```
|
||||
|
||||
### Multi-GPU data parallel (PyTorch)
|
||||
```python
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
|
||||
dist.init_process_group(backend="nccl")
|
||||
model = DDP(model.cuda(), device_ids=[local_rank])
|
||||
|
||||
for batch in loader:
|
||||
loss = model(batch).loss
|
||||
loss.backward() # 매 NCCL all-reduce gradients
|
||||
optim.step()
|
||||
```
|
||||
|
||||
### Tensor parallel (megatron-style)
|
||||
```python
|
||||
# 매 single Linear split column-wise across N GPUs
|
||||
class ColumnParallelLinear(nn.Module):
|
||||
def __init__(self, d_in, d_out, world_size):
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.empty(d_out // world_size, d_in))
|
||||
def forward(self, x):
|
||||
local_out = x @ self.weight.T
|
||||
# gather across tp group
|
||||
return all_gather(local_out, dim=-1)
|
||||
```
|
||||
|
||||
### MPI scientific compute
|
||||
```python
|
||||
from mpi4py import MPI
|
||||
comm = MPI.COMM_WORLD
|
||||
rank, size = comm.Get_rank(), comm.Get_size()
|
||||
|
||||
# 매 domain decomposition
|
||||
local_data = scatter_grid(global_grid, rank, size)
|
||||
local_result = compute_step(local_data)
|
||||
global_result = comm.allreduce(local_result, op=MPI.SUM)
|
||||
```
|
||||
|
||||
### Async pipeline parallel
|
||||
```python
|
||||
# GPipe / 1F1B schedule
|
||||
def pipeline_step(stages, micro_batches):
|
||||
"""1F1B: 1 forward, 1 backward interleaved."""
|
||||
fwd_queue = []
|
||||
for mb in micro_batches:
|
||||
for s, stage in enumerate(stages):
|
||||
mb = stage.forward(mb)
|
||||
fwd_queue.append((s, mb))
|
||||
for s, mb in reversed(fwd_queue):
|
||||
stages[s].backward(mb)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| Workload | Parallelism |
|
||||
|---|---|
|
||||
| 매 single-machine CPU bound | multiprocessing / Ray |
|
||||
| 매 single-GPU dense ops | CUDA / JAX SIMT |
|
||||
| 매 multi-GPU same-node | NCCL DDP / FSDP |
|
||||
| 매 multi-node training | DP×TP×PP (Megatron, DeepSpeed) |
|
||||
| 매 long-context (128K+) | + Sequence Parallel |
|
||||
| 매 MoE model | + Expert Parallel |
|
||||
| 매 scientific HPC | MPI + domain decomposition |
|
||||
|
||||
**기본값**: 매 SIMD (numpy/jax) 시작 → 매 GPU SIMT → 매 multi-GPU DDP → 매 4D parallelism 의 progression.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Distributed-Systems]]
|
||||
- 변형: [[Distributed-Training]]
|
||||
- 응용: [[LLM_Optimization_and_Deployment_Strategies|vLLM]]
|
||||
- Adjacent: [[Concurrency]] · [[Parallel-Computing|Parallel-Processing]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 parallelism strategy selection, 매 communication overhead analysis, 매 NCCL/MPI debugging.
|
||||
**언제 X**: 매 sequential algorithm 매 inherently — 매 Amdahl bound 의 X.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Premature parallelization**: 매 sequential profile X → blind parallelize.
|
||||
- **Communication-bound**: 매 too fine-grained 매 chunks → 매 NCCL overhead 압도.
|
||||
- **Load imbalance**: 매 uneven shard sizes → 매 stragglers.
|
||||
- **Race conditions**: 매 shared state w/o sync.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Hennessy & Patterson 6e; Megatron-LM paper 2019; Llama 3 paper 2024; CUDA C++ Programming Guide 12.x).
|
||||
- 신뢰도 A.
|
||||
- 매 [[Parallel-Computing|Parallel-Processing]] 매 alias / redirect.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Flynn + 4D DL parallelism + modern stack |
|
||||
@@ -0,0 +1,187 @@
|
||||
---
|
||||
id: wiki-2026-0508-pedestrian-modeling
|
||||
title: Pedestrian Modeling
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Crowd Simulation, Pedestrian Dynamics, Foot Traffic Modeling]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [simulation, agent-based, urban-planning, crowd-dynamics]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: Python
|
||||
framework: Mesa / SUMO / PyTorch
|
||||
---
|
||||
|
||||
# Pedestrian Modeling
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 보행자는 force field 위의 agent"**. 1995년 Helbing의 Social Force Model이 분야를 정의했고, 2026 현재 ML-augmented agent-based simulation (Mesa 3.x, MATSim, SUMO)이 evacuation planning, station design, retail flow 분석의 표준 도구다.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 모델 계열
|
||||
- **Macroscopic**: fluid-like density/flow PDE — Hughes model, LWR for crowds. 매 large-scale aggregate.
|
||||
- **Mesoscopic**: cellular automata (Burstedde 2001) — discrete grid + transition probabilities.
|
||||
- **Microscopic**: 개별 agent — Social Force (Helbing-Molnár), ORCA (reciprocal velocity obstacles), RVO2.
|
||||
- **Data-driven**: GNN trajectory prediction (Social-LSTM, Trajectron++, EqMotion 2025).
|
||||
|
||||
### 매 Social Force 핵심
|
||||
- 매 보행자 i 의 motion equation: `m_i * dv_i/dt = F_desired + ΣF_social + ΣF_obstacle + ξ`.
|
||||
- `F_desired = (v_target - v_i) / τ` — 매 goal-directed term.
|
||||
- `F_social = A * exp((r_ij - d_ij)/B) * n_ij` — 매 repulsion exponential.
|
||||
|
||||
### 매 응용
|
||||
1. Evacuation simulation (역, stadium, 고층빌딩).
|
||||
2. Urban design (sidewalk width, crossing geometry, wayfinding).
|
||||
3. Retail analytics (store layout heatmap).
|
||||
4. Autonomous robot navigation in crowds.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Social Force Model (Mesa 3.x)
|
||||
```python
|
||||
import numpy as np
|
||||
from mesa import Agent, Model
|
||||
from mesa.space import ContinuousSpace
|
||||
|
||||
class Pedestrian(Agent):
|
||||
def __init__(self, model, pos, target, v_desired=1.34):
|
||||
super().__init__(model)
|
||||
self.pos = np.array(pos, dtype=float)
|
||||
self.vel = np.zeros(2)
|
||||
self.target = np.array(target, dtype=float)
|
||||
self.v_desired = v_desired
|
||||
self.tau = 0.5 # relaxation time
|
||||
self.radius = 0.3
|
||||
|
||||
def desired_force(self):
|
||||
direction = self.target - self.pos
|
||||
norm = np.linalg.norm(direction) + 1e-9
|
||||
e = direction / norm
|
||||
return (self.v_desired * e - self.vel) / self.tau
|
||||
|
||||
def social_force(self, A=2000, B=0.08):
|
||||
f = np.zeros(2)
|
||||
for other in self.model.agents:
|
||||
if other is self: continue
|
||||
r_ij = self.radius + other.radius
|
||||
d_vec = self.pos - other.pos
|
||||
d_ij = np.linalg.norm(d_vec) + 1e-9
|
||||
n_ij = d_vec / d_ij
|
||||
f += A * np.exp((r_ij - d_ij) / B) * n_ij
|
||||
return f
|
||||
|
||||
def step(self):
|
||||
f = self.desired_force() + self.social_force()
|
||||
self.vel += f * self.model.dt
|
||||
speed = np.linalg.norm(self.vel)
|
||||
if speed > 1.5 * self.v_desired:
|
||||
self.vel *= 1.5 * self.v_desired / speed
|
||||
self.pos += self.vel * self.model.dt
|
||||
```
|
||||
|
||||
### ORCA (RVO2) collision avoidance
|
||||
```python
|
||||
import rvo2
|
||||
|
||||
sim = rvo2.PyRVOSimulator(
|
||||
timeStep=1/30, neighborDist=2.0, maxNeighbors=10,
|
||||
timeHorizon=2.0, timeHorizonObst=2.0,
|
||||
radius=0.3, maxSpeed=1.5
|
||||
)
|
||||
agents = [sim.addAgent((x, y)) for x, y in spawn_positions]
|
||||
for i, goal in enumerate(goals):
|
||||
pref = np.array(goal) - np.array(sim.getAgentPosition(i))
|
||||
pref = pref / (np.linalg.norm(pref) + 1e-9) * 1.34
|
||||
sim.setAgentPrefVelocity(i, tuple(pref))
|
||||
sim.doStep()
|
||||
```
|
||||
|
||||
### Trajectory prediction (PyTorch GNN, 2025-style)
|
||||
```python
|
||||
import torch, torch.nn as nn
|
||||
from torch_geometric.nn import GATv2Conv
|
||||
|
||||
class TrajectronLite(nn.Module):
|
||||
def __init__(self, hidden=64, future=12):
|
||||
super().__init__()
|
||||
self.encoder = nn.GRU(4, hidden, batch_first=True)
|
||||
self.gat = GATv2Conv(hidden, hidden, heads=4, concat=False)
|
||||
self.decoder = nn.GRU(hidden, hidden, batch_first=True)
|
||||
self.head = nn.Linear(hidden, 2)
|
||||
self.future = future
|
||||
|
||||
def forward(self, hist, edge_index):
|
||||
# hist: (N, T, 4) — (x, y, vx, vy)
|
||||
h, _ = self.encoder(hist)
|
||||
h = self.gat(h[:, -1], edge_index)
|
||||
h = h.unsqueeze(1).expand(-1, self.future, -1)
|
||||
out, _ = self.decoder(h)
|
||||
return self.head(out) # (N, future, 2)
|
||||
```
|
||||
|
||||
### SUMO foot traffic export
|
||||
```python
|
||||
import traci
|
||||
traci.start(["sumo", "-c", "station.sumocfg"])
|
||||
while traci.simulation.getMinExpectedNumber() > 0:
|
||||
traci.simulationStep()
|
||||
for pid in traci.person.getIDList():
|
||||
x, y = traci.person.getPosition(pid)
|
||||
v = traci.person.getSpeed(pid)
|
||||
log(pid, x, y, v)
|
||||
traci.close()
|
||||
```
|
||||
|
||||
### Density heatmap (post-hoc)
|
||||
```python
|
||||
import numpy as np, matplotlib.pyplot as plt
|
||||
from scipy.stats import gaussian_kde
|
||||
|
||||
xy = trajectories[:, :, :2].reshape(-1, 2).T # (2, N*T)
|
||||
kde = gaussian_kde(xy, bw_method=0.15)
|
||||
gx, gy = np.mgrid[0:50:200j, 0:50:200j]
|
||||
density = kde(np.vstack([gx.ravel(), gy.ravel()])).reshape(gx.shape)
|
||||
plt.imshow(density.T, origin="lower", extent=(0, 50, 0, 50), cmap="hot")
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Evacuation + dense crowd | Social Force (Helbing) |
|
||||
| Smooth navigation, robotics | ORCA / RVO2 |
|
||||
| Trajectory prediction (ML) | Trajectron++ / EqMotion |
|
||||
| Large-scale urban (10⁵+) | Macroscopic LWR / MATSim |
|
||||
| Discrete cell-based grid | Cellular Automata (Burstedde) |
|
||||
|
||||
**기본값**: Mesa 3.x + Social Force for simulation, RVO2 for robot integration.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Complex Systems]]
|
||||
- 변형: [[Cellular Automata]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: parameter sweep design, scenario script generation, calibration code 작성.
|
||||
**언제 X**: real-time inner-loop force computation — 매 numerical kernel은 Cython/Numba/CUDA.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Pseudo-uniform spawning**: 매 corner clustering 발생 — Poisson disk sampling 사용.
|
||||
- **Naive O(N²) social force**: 매 KD-tree neighborhood 로 cutoff (보통 5m).
|
||||
- **Validation skip**: 매 fundamental diagram (density vs flow) 와 비교 필수.
|
||||
- **dt too large**: 매 0.05–0.1s 권장; 매 그 이상 instability.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Helbing & Molnár 1995, Helbing et al. 2000 Nature, Mesa docs 3.x, RVO2 reference).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Social Force / ORCA / GNN trajectory FULL content |
|
||||
@@ -0,0 +1,177 @@
|
||||
---
|
||||
id: wiki-2026-0508-problem-solving-process
|
||||
title: Problem Solving Process
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Problem Solving, Polya Method, Engineering Problem Solving]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [cognition, engineering, methodology, debugging]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: multi
|
||||
framework: structured-problem-solving
|
||||
---
|
||||
|
||||
# Problem Solving Process
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 a problem well-stated is half-solved."**. 매 Polya 1945 *How to Solve It* 의 4단계 (understand → plan → carry out → look back) 가 매 modern engineering, debugging, AI agent design 의 backbone. 매 2026 LLM agent (Claude, OpenAI Operator) 의 ReAct/CoT 도 매 본질적으로 Polya 의 자동화.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 Polya 4 stages
|
||||
- **Understand**: 매 restate, 매 identify knowns/unknowns/constraints.
|
||||
- **Plan**: 매 decompose, 매 analogous problems, 매 work backwards.
|
||||
- **Carry Out**: 매 execute, 매 verify each step.
|
||||
- **Look Back**: 매 check, 매 generalize, 매 alternate methods.
|
||||
|
||||
### 매 strategies
|
||||
- **Decomposition**: 매 break into sub-problems (divide & conquer).
|
||||
- **Analogy**: 매 find similar solved problem (case-based reasoning).
|
||||
- **Inversion**: 매 work backwards from goal.
|
||||
- **Specialization**: 매 try simpler instance (n=1, n=2 first).
|
||||
- **Generalization**: 매 solve more general version sometimes easier.
|
||||
- **Symmetry / Invariants**: 매 find quantity that doesn't change.
|
||||
|
||||
### 매 응용
|
||||
1. Debugging: 매 reproduce → bisect → fix → verify → write test.
|
||||
2. System design: 매 understand requirements → decompose → component design.
|
||||
3. LLM agent: 매 ReAct loop = Polya in code.
|
||||
4. Math/algorithms: 매 examples → conjecture → prove → optimize.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: Debugging as Polya
|
||||
```python
|
||||
def debug(bug_report):
|
||||
# 1. UNDERSTAND
|
||||
repro = build_minimal_repro(bug_report)
|
||||
# 2. PLAN
|
||||
suspected_modules = trace_stack(repro)
|
||||
plan = git_bisect_plan(repro, suspected_modules)
|
||||
# 3. CARRY OUT
|
||||
bad_commit = git_bisect(plan)
|
||||
fix = author_fix(bad_commit)
|
||||
# 4. LOOK BACK
|
||||
add_regression_test(repro)
|
||||
update_runbook(bug_report.symptom)
|
||||
return fix
|
||||
```
|
||||
|
||||
### Pattern 2: ReAct LLM agent (Polya 자동화)
|
||||
```python
|
||||
SYSTEM = """For each task, follow:
|
||||
1. THOUGHT: restate the problem and constraints (UNDERSTAND).
|
||||
2. PLAN: decompose into 1-3 next actions.
|
||||
3. ACTION: call exactly one tool.
|
||||
4. OBSERVE: read result.
|
||||
5. REFLECT: did this advance? if not, revise plan (LOOK BACK).
|
||||
Repeat until done.
|
||||
"""
|
||||
```
|
||||
|
||||
### Pattern 3: Decomposition tree
|
||||
```python
|
||||
@dataclass
|
||||
class Problem:
|
||||
statement: str
|
||||
children: list["Problem"] = field(default_factory=list)
|
||||
solved: bool = False
|
||||
solution: Optional[str] = None
|
||||
|
||||
def solve(p: Problem):
|
||||
if can_solve_directly(p):
|
||||
p.solution = direct(p); p.solved = True; return
|
||||
p.children = decompose(p)
|
||||
for c in p.children: solve(c)
|
||||
p.solution = combine([c.solution for c in p.children])
|
||||
p.solved = all(c.solved for c in p.children)
|
||||
```
|
||||
|
||||
### Pattern 4: Five-Whys root cause
|
||||
```text
|
||||
Symptom: 매 dashboard p99 latency 5x baseline.
|
||||
Why? — 매 DB queries slow.
|
||||
Why? — 매 missing index.
|
||||
Why? — 매 migration didn't add it.
|
||||
Why? — 매 PR template doesn't require index check.
|
||||
Why? — 매 no automated linter.
|
||||
→ 매 Root: missing tooling, not "lazy engineer".
|
||||
```
|
||||
|
||||
### Pattern 5: Pre-mortem (inverted planning)
|
||||
```python
|
||||
def pre_mortem(plan):
|
||||
# 매 imagine the plan failed in 6 months
|
||||
# 매 ask team: what went wrong?
|
||||
failure_modes = team_brainstorm("It's 6mo from now. Project failed. Why?")
|
||||
return prioritize_mitigations(failure_modes)
|
||||
```
|
||||
|
||||
### Pattern 6: Working-memory checkpoint
|
||||
```markdown
|
||||
<!-- 매 problem_log.md while solving -->
|
||||
## 매 KNOWN
|
||||
- API returns 500 on POST /orders > 1000 items.
|
||||
## 매 UNKNOWN
|
||||
- Is it timeout, memory, or DB lock?
|
||||
## 매 TRIED
|
||||
- [x] Reproduce locally → reproduces at 1500.
|
||||
- [x] Add timing logs → DB INSERT is slow.
|
||||
- [ ] Check lock contention.
|
||||
## 매 NEXT
|
||||
- pg_stat_activity during repro.
|
||||
```
|
||||
|
||||
### Pattern 7: Solution generalization (look back)
|
||||
```python
|
||||
# 매 after fixing one instance — 매 ask: where else does this pattern occur?
|
||||
def generalize(fix):
|
||||
pattern = abstract(fix) # e.g., "missing pagination in list endpoints"
|
||||
similar = scan_codebase_for(pattern)
|
||||
return apply_fix_to_all(similar)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Strategy |
|
||||
|---|---|
|
||||
| 매 stuck at "understand" | Restate problem to rubber duck / LLM |
|
||||
| 매 plan unclear | Try simpler case (n=1) first |
|
||||
| 매 carry-out fails | Bisect; isolate variable |
|
||||
| 매 done — but is it right? | Look back; alt method; edge cases |
|
||||
| 매 recurring class of bugs | Generalize the fix; tooling |
|
||||
| 매 LLM agent loop stuck | Force REFLECT step; reduce action set |
|
||||
|
||||
**기본값**: 매 always do Look Back — 매 most engineers skip it; 매 90% of compounding leverage lives there.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Cognitive Psychology]]
|
||||
- 변형: [[Polya Method]] · [[Debugging]] · [[Root Cause Analysis]]
|
||||
- Adjacent: [[ReAct]] · [[Chain of Thought]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 system-prompt scaffolds, 매 incident runbooks, 매 onboarding docs, 매 interview prep.
|
||||
**언제 X**: 매 trivial 1-line tasks — 매 over-formalization slows.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Skip understanding**: 매 jump to coding → 매 wrong problem solved.
|
||||
- **Skip looking back**: 매 ship fix, never abstract → 매 same bug class returns.
|
||||
- **No working-memory log**: 매 forget what you tried.
|
||||
- **One strategy only**: 매 if decomposition fails, try inversion / analogy.
|
||||
- **LLM as oracle**: 매 use as plan-critic, not plan-author.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Polya 1945, Newell & Simon 1972, Yao et al. 2022 ReAct).
|
||||
- 신뢰도 A (foundational).
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Polya 4단계 + ReAct + 7 패턴 |
|
||||
@@ -0,0 +1,167 @@
|
||||
---
|
||||
id: wiki-2026-0508-program-comprehension-strategies
|
||||
title: Program Comprehension Strategies
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Code Reading, Code Comprehension, Mental Models of Code]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [software-engineering, cognition, code-review, onboarding]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: multi
|
||||
framework: cognitive-software-engineering
|
||||
---
|
||||
|
||||
# Program Comprehension Strategies
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 90% of programming is reading code, not writing it."**. 매 Brooks (1983), Pennington (1987), Soloway (1986) 의 cognitive software engineering 연구에서 출발한 매 분야 — 매 code → mental model 변환의 strategies. 매 2026 LLM 시대에는 매 Cursor/Claude Code 의 contextual indexing 이 매 human comprehension 을 augment.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 3대 strategy
|
||||
- **Top-down (Brooks)**: 매 hypothesis 형성 → code 로 verify. 매 domain expert 가 사용.
|
||||
- **Bottom-up (Pennington)**: 매 statement → control-flow → data-flow → program model. 매 novice 가 사용.
|
||||
- **Opportunistic (mixed)**: 매 expert programmer 의 실제 행동 — top-down 시작, beacon 발견 시 bottom-up 으로 dive.
|
||||
|
||||
### 매 cognitive constructs
|
||||
- **Beacons**: 매 recognizable patterns (e.g., `for(i=0; i<n; i++)` → 매 loop, `swap(a,b)` → 매 sort).
|
||||
- **Plans**: 매 stereotypical solutions (e.g., search plan, accumulator plan).
|
||||
- **Chunks**: 매 functionally cohesive code groups stored as 1 unit in working memory.
|
||||
|
||||
### 매 응용
|
||||
1. Code review: 매 reviewer 는 top-down — PR 의 의도 파악 후 specific changes 검증.
|
||||
2. Onboarding: 매 new dev 는 bottom-up — small fixes 로 시작, 점진적 chunking.
|
||||
3. AI-assisted reading: 매 LLM 에게 code summarization → human 이 hypothesis 생성.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: Top-down hypothesis-driven reading
|
||||
```python
|
||||
# 매 step 1: read README / docstring → 매 form hypothesis
|
||||
# 매 step 2: locate entry point (main, app.py)
|
||||
# 매 step 3: trace only the path that confirms/refutes hypothesis
|
||||
|
||||
def trace_hypothesis(repo, hypothesis):
|
||||
entry = find_entry_point(repo)
|
||||
call_graph = build_call_graph(entry)
|
||||
relevant = filter_by_keyword(call_graph, hypothesis.keywords)
|
||||
return relevant
|
||||
```
|
||||
|
||||
### Pattern 2: Beacon recognition (LLM-augmented)
|
||||
```python
|
||||
import anthropic
|
||||
client = anthropic.Anthropic()
|
||||
|
||||
def extract_beacons(code: str) -> list[str]:
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=1024,
|
||||
system="Identify recognizable code patterns (beacons) and name their plan.",
|
||||
messages=[{"role": "user", "content": f"```\n{code}\n```"}],
|
||||
)
|
||||
return parse_beacons(resp.content[0].text)
|
||||
```
|
||||
|
||||
### Pattern 3: Chunking via cohesion analysis
|
||||
```python
|
||||
def chunk_function(ast_node):
|
||||
"""매 group statements by 매 shared variables (cohesion)."""
|
||||
chunks, current = [], []
|
||||
last_vars = set()
|
||||
for stmt in ast_node.body:
|
||||
vars = extract_vars(stmt)
|
||||
if last_vars and not (vars & last_vars):
|
||||
chunks.append(current)
|
||||
current = []
|
||||
current.append(stmt)
|
||||
last_vars = vars
|
||||
if current:
|
||||
chunks.append(current)
|
||||
return chunks
|
||||
```
|
||||
|
||||
### Pattern 4: Cross-reference walking (bottom-up)
|
||||
```bash
|
||||
# 매 ripgrep + ctags-driven exploration
|
||||
rg -l "AuthService" --type ts | head -5
|
||||
rg "class AuthService" --type ts -A 30
|
||||
rg "new AuthService\(" --type ts # 매 callers
|
||||
```
|
||||
|
||||
### Pattern 5: LLM-driven code summarization
|
||||
```python
|
||||
# 매 Claude Code-style structured summary
|
||||
PROMPT = """Summarize this file with:
|
||||
1. 매 PURPOSE (1 sentence)
|
||||
2. 매 KEY DATA STRUCTURES
|
||||
3. 매 PUBLIC API
|
||||
4. 매 NON-OBVIOUS CONTRACTS / INVARIANTS
|
||||
5. 매 DEPENDENCIES (incoming + outgoing)
|
||||
"""
|
||||
|
||||
def summarize(file_path):
|
||||
code = open(file_path).read()
|
||||
return claude_call(PROMPT + f"\n```\n{code}\n```")
|
||||
```
|
||||
|
||||
### Pattern 6: Mental model checkpointing
|
||||
```markdown
|
||||
<!-- 매 personal-notes.md per repo while reading -->
|
||||
## Module: auth/
|
||||
- Purpose: JWT issuance & verification
|
||||
- Entry: `auth/router.ts:loginHandler`
|
||||
- Key invariant: tokens always include `iss=our-domain`
|
||||
- Open Q: where is refresh-token rotation?
|
||||
```
|
||||
|
||||
### Pattern 7: Diagram-first — produce dependency graph before reading
|
||||
```bash
|
||||
madge --image deps.svg src/
|
||||
# 매 visual chunking — see clusters before diving
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Strategy |
|
||||
|---|---|
|
||||
| 매 domain familiar, code new | Top-down |
|
||||
| 매 domain new, code small | Bottom-up |
|
||||
| 매 large unknown codebase | Opportunistic + diagram first |
|
||||
| 매 bug hunt | Bottom-up from stack trace |
|
||||
| 매 architecture review | Top-down from entry points |
|
||||
| 매 LLM augmentation | Summarize → form hypothesis → verify |
|
||||
|
||||
**기본값**: 매 opportunistic — 매 README + entry point 부터 시작, beacon 발견 시 dive.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Cognitive Psychology]]
|
||||
- 변형: [[Code Review]] · [[Onboarding]]
|
||||
- 응용: [[Refactoring_Best_Practices|Refactoring]]
|
||||
- Adjacent: [[Mental_Models|Mental Models]] · [[Working Memory]] · [[AST]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 onboarding new repo, 매 reviewing large PR, 매 understanding legacy code, 매 building mental model.
|
||||
**언제 X**: 매 1-line hot-fix 에 over-engineering 하지 마라.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Read everything linearly**: 매 working memory 초과 — chunking 없이 무너짐.
|
||||
- **Skip the README**: 매 hypothesis 없이 bottom-up 만 → 매 lost in details.
|
||||
- **No checkpointing**: 매 1시간 후 모두 잊음 — write down mental model.
|
||||
- **Trust LLM summary blindly**: 매 hallucination 위험 — 매 verify on key claims.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Brooks 1983, Pennington 1987, Soloway & Ehrlich 1984, Storey 2006 review).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — top-down/bottom-up/opportunistic + LLM augmentation |
|
||||
@@ -0,0 +1,219 @@
|
||||
---
|
||||
id: wiki-2026-0508-progressive-web-apps-pwas
|
||||
title: Progressive Web Apps (PWAs)
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [PWA, Installable Web Apps, Web App Manifest Apps]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [web, frontend, mobile, service-worker, offline-first]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: javascript
|
||||
framework: web-platform
|
||||
---
|
||||
|
||||
# Progressive Web Apps (PWAs)
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 the web with installability, offline, and push — without the app store tax."**. 매 Alex Russell 이 2015년 정립한 PWA 는 매 service worker + manifest + HTTPS 의 조합으로 매 web app 을 매 native-feel 으로 격상. 매 2026: iOS 17+/Safari 17+ 가 push notifications 와 매 home-screen install 을 정식 지원, 매 Project Fugu API 들 (file system, USB, Bluetooth) 까지 가능.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 3 pillars
|
||||
- **Service Worker**: 매 background script — 매 caching, 매 offline, 매 push.
|
||||
- **Web App Manifest**: 매 JSON — 매 install metadata (icon, name, display).
|
||||
- **HTTPS**: 매 mandatory transport (loopback exception for dev).
|
||||
|
||||
### 매 capabilities (2026)
|
||||
- 매 offline first via Cache + IndexedDB.
|
||||
- 매 background sync (eventual consistency).
|
||||
- 매 push notifications (iOS 17+ supports).
|
||||
- 매 file system access (Origin Private File System, OPFS).
|
||||
- 매 share target (receive shares from native).
|
||||
- 매 periodic background sync.
|
||||
- 매 WebGPU / WebTransport / WebCodecs.
|
||||
|
||||
### 매 응용
|
||||
1. Twitter, Pinterest, Starbucks Lite — 매 60-80% bundle reduction.
|
||||
2. 매 conference apps — 매 offline schedule + push.
|
||||
3. 매 internal enterprise tools — 매 install via QR, no MDM.
|
||||
4. 매 emerging-market apps — 매 low-bandwidth-friendly.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: Minimal manifest.json
|
||||
```json
|
||||
{
|
||||
"name": "Wiki Cleanup Tool",
|
||||
"short_name": "WikiClean",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#ffffff",
|
||||
"theme_color": "#0066cc",
|
||||
"icons": [
|
||||
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
|
||||
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 2: Service worker (cache-first for assets, network-first for API)
|
||||
```javascript
|
||||
// sw.js
|
||||
const CACHE = 'app-v3';
|
||||
const ASSETS = ['/', '/index.html', '/app.js', '/styles.css'];
|
||||
|
||||
self.addEventListener('install', (e) => {
|
||||
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(ASSETS)));
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (e) => {
|
||||
e.waitUntil(caches.keys().then((keys) =>
|
||||
Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))
|
||||
));
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (e) => {
|
||||
const url = new URL(e.request.url);
|
||||
if (url.pathname.startsWith('/api/')) {
|
||||
// network-first
|
||||
e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
|
||||
} else {
|
||||
// cache-first
|
||||
e.respondWith(caches.match(e.request).then((r) => r || fetch(e.request)));
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Pattern 3: Registration with update flow
|
||||
```javascript
|
||||
// app.js
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js').then((reg) => {
|
||||
reg.addEventListener('updatefound', () => {
|
||||
const sw = reg.installing;
|
||||
sw.addEventListener('statechange', () => {
|
||||
if (sw.state === 'installed' && navigator.serviceWorker.controller) {
|
||||
showUpdateToast(() => sw.postMessage({ type: 'SKIP_WAITING' }));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 4: Push notifications (2026 cross-platform)
|
||||
```javascript
|
||||
async function subscribe() {
|
||||
const reg = await navigator.serviceWorker.ready;
|
||||
const sub = await reg.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey: VAPID_PUBLIC_KEY,
|
||||
});
|
||||
await fetch('/api/save-sub', { method: 'POST', body: JSON.stringify(sub) });
|
||||
}
|
||||
|
||||
// sw.js
|
||||
self.addEventListener('push', (e) => {
|
||||
const { title, body, url } = e.data.json();
|
||||
e.waitUntil(self.registration.showNotification(title, { body, data: { url } }));
|
||||
});
|
||||
self.addEventListener('notificationclick', (e) => {
|
||||
e.notification.close();
|
||||
e.waitUntil(clients.openWindow(e.notification.data.url));
|
||||
});
|
||||
```
|
||||
|
||||
### Pattern 5: Background sync for offline writes
|
||||
```javascript
|
||||
// queue write when offline
|
||||
async function postWithSync(url, payload) {
|
||||
try {
|
||||
return await fetch(url, { method: 'POST', body: JSON.stringify(payload) });
|
||||
} catch {
|
||||
const reg = await navigator.serviceWorker.ready;
|
||||
await idbAdd('outbox', { url, payload });
|
||||
await reg.sync.register('flush-outbox');
|
||||
}
|
||||
}
|
||||
|
||||
// sw.js
|
||||
self.addEventListener('sync', (e) => {
|
||||
if (e.tag === 'flush-outbox') e.waitUntil(flushOutbox());
|
||||
});
|
||||
```
|
||||
|
||||
### Pattern 6: File System Access (2026 Fugu)
|
||||
```javascript
|
||||
async function saveDoc(content) {
|
||||
const handle = await window.showSaveFilePicker({
|
||||
types: [{ description: 'Markdown', accept: { 'text/markdown': ['.md'] } }],
|
||||
});
|
||||
const writable = await handle.createWritable();
|
||||
await writable.write(content);
|
||||
await writable.close();
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 7: Install prompt UX
|
||||
```javascript
|
||||
let deferred;
|
||||
window.addEventListener('beforeinstallprompt', (e) => {
|
||||
e.preventDefault();
|
||||
deferred = e;
|
||||
showCustomInstallButton();
|
||||
});
|
||||
|
||||
async function onInstallClick() {
|
||||
if (!deferred) return;
|
||||
deferred.prompt();
|
||||
const { outcome } = await deferred.userChoice;
|
||||
analytics.track('pwa_install', { outcome });
|
||||
deferred = null;
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 content-heavy site | PWA, no native |
|
||||
| 매 needs deep OS integration (BLE, NFC, telephony) | Native + Capacitor / native shell |
|
||||
| 매 cross-platform productivity | PWA with Fugu APIs |
|
||||
| 매 emerging-market reach | PWA — 매 small bundle, offline |
|
||||
| 매 game (heavy GPU) | Native or WebGPU PWA |
|
||||
| 매 enterprise behind SSO | PWA — 매 no app store distribution |
|
||||
|
||||
**기본값**: 매 start with PWA, 매 fall back to native shell only when blocked APIs needed.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Large_Frontend_Projects|Frontend Architecture]]
|
||||
- 변형: [[Service Worker]]
|
||||
- 응용: [[Offline-First]] · [[Push Notifications]]
|
||||
- Adjacent: [[WebGPU]] · [[Workbox]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 caching strategy design, 매 SW boilerplate, 매 update-flow patterns.
|
||||
**언제 X**: 매 native-only API needs (full BLE stack, deep telephony) — 매 use Capacitor / native.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Cache-everything**: 매 stale stale stale — 매 use versioned cache + activate cleanup.
|
||||
- **No update flow**: 매 user stuck on old SW forever.
|
||||
- **HTTPS skipped in staging**: 매 SW won't register — 매 broken parity.
|
||||
- **Manifest without maskable icons**: 매 ugly cropped icons on Android adaptive.
|
||||
- **Push spam**: 매 user opt-out + iOS revoke + reputation damage.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (W3C Service Worker spec, Web App Manifest spec, web.dev/learn/pwa).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — 3 pillars, 7 패턴, 2026 Fugu/iOS push 반영 |
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
id: wiki-2026-0508-pull-request-and-issue-tracking
|
||||
title: Pull Request and Issue Tracking
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [PR Workflow, Code Review, Issue Tracker]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [git, github, workflow, devops]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: yaml
|
||||
framework: github-gitlab
|
||||
---
|
||||
|
||||
# Pull Request and Issue Tracking
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 PR 의 unit of code change, 매 issue 의 unit of intent"**. GitHub (2008) 의 popularize, GitLab/Bitbucket/Gitea/Forgejo 의 follow. 매 2026 의 standard workflow 의 trunk-based + small PRs + automated checks + LLM-assisted review (CodeRabbit, GitHub Copilot Workspace, Claude Code).
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 PR Lifecycle
|
||||
1. **Branch** — 매 feature/fix branch 의 cut from main.
|
||||
2. **Commit** — 매 atomic change + descriptive message (Conventional Commits).
|
||||
3. **Open PR** — 매 description (what/why/how) + linked issue.
|
||||
4. **CI** — 매 lint, test, build, security scan.
|
||||
5. **Review** — 매 human + LLM-assist.
|
||||
6. **Merge** — 매 squash / rebase / merge commit.
|
||||
7. **Deploy** — 매 main 의 push 의 trigger CD.
|
||||
|
||||
### 매 Issue Types
|
||||
- **Bug** — 매 actual misbehavior + repro steps.
|
||||
- **Feature** — 매 user-facing capability request.
|
||||
- **Task** — 매 internal work (refactor, debt).
|
||||
- **Epic** — 매 multi-PR initiative.
|
||||
|
||||
### 매 Automation Surface
|
||||
- Branch protection (required reviews + checks).
|
||||
- Auto-assign reviewers (CODEOWNERS).
|
||||
- Auto-label / triage bots.
|
||||
- Stale issue cleanup.
|
||||
- Release notes (release-please).
|
||||
|
||||
### 매 응용
|
||||
1. Solo project — 매 PR 의 self 의 review 의 force structure.
|
||||
2. Team — 매 ownership boundary 의 CODEOWNERS.
|
||||
3. OSS — 매 issue triage 의 community signal.
|
||||
4. Compliance — 매 audit trail 의 SOC2/ISO 27001.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### PR template (`.github/PULL_REQUEST_TEMPLATE.md`)
|
||||
```markdown
|
||||
## What
|
||||
<one-liner>
|
||||
|
||||
## Why
|
||||
<motivation, linked issue: #123>
|
||||
|
||||
## How
|
||||
<technical approach summary>
|
||||
|
||||
## Test plan
|
||||
- [ ] Unit tests pass
|
||||
- [ ] Manual repro on staging
|
||||
- [ ] No new warnings
|
||||
|
||||
## Risk
|
||||
Low / Medium / High — explain.
|
||||
```
|
||||
|
||||
### Issue template (`.github/ISSUE_TEMPLATE/bug.yml`)
|
||||
```yaml
|
||||
name: Bug report
|
||||
description: File a bug
|
||||
labels: [bug, triage]
|
||||
body:
|
||||
- type: textarea
|
||||
id: repro
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
validations: { required: true }
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected behavior
|
||||
- type: input
|
||||
id: version
|
||||
attributes: { label: Version }
|
||||
```
|
||||
|
||||
### CODEOWNERS
|
||||
```
|
||||
# .github/CODEOWNERS
|
||||
*.py @backend-team
|
||||
/web/** @frontend-team
|
||||
/infra/** @platform @sre
|
||||
*.md @docs
|
||||
```
|
||||
|
||||
### CI gate (GitHub Actions)
|
||||
```yaml
|
||||
name: ci
|
||||
on: [pull_request]
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with: { node-version: 22 }
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
- run: npm test -- --coverage
|
||||
- uses: codecov/codecov-action@v4
|
||||
```
|
||||
|
||||
### Auto-merge after green
|
||||
```yaml
|
||||
name: auto-merge
|
||||
on: pull_request_review
|
||||
jobs:
|
||||
automerge:
|
||||
if: github.event.review.state == 'approved'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: pascalgn/automerge-action@v0.16.4
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
MERGE_METHOD: squash
|
||||
MERGE_LABELS: "automerge,!wip"
|
||||
```
|
||||
|
||||
### `gh` CLI workflow
|
||||
```bash
|
||||
# Create PR
|
||||
git checkout -b fix/null-deref
|
||||
git commit -am "fix: handle null user in checkout"
|
||||
gh pr create --fill --reviewer alice,bob
|
||||
|
||||
# Review queue
|
||||
gh pr list --search "is:open review-requested:@me"
|
||||
|
||||
# Triage
|
||||
gh issue list --label "needs-triage" --json number,title,createdAt
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Small change | Squash merge |
|
||||
| Long-lived feature | Merge commit (preserve history) |
|
||||
| Linear history fans | Rebase + fast-forward |
|
||||
| Many reviewers | CODEOWNERS auto-request |
|
||||
| OSS project | Issue templates + DCO |
|
||||
| Internal monorepo | Required checks + auto-merge |
|
||||
|
||||
**기본값**: small PRs (<400 LOC) + squash merge + Conventional Commits + required CI.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[CI CD]]
|
||||
- 응용: [[Code-Review]] · [[Trunk-Based-Development]]
|
||||
- Adjacent: [[Conventional-Commits]] · [[CODEOWNERS]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: PR description 의 generate, review 의 first-pass (style, obvious bugs), issue triage 의 label.
|
||||
**언제 X**: security-critical review — 매 human 의 final approve.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Mega-PR (5000+ LOC)**: 매 review 의 useless — 매 split 의 require.
|
||||
- **Empty description**: 매 reviewer 의 context-free.
|
||||
- **Force-push to shared branch**: 매 review history 의 destroy — feature branch 의 only.
|
||||
- **Self-merge without review**: 매 sole-maintainer except — 매 audit trail 의 weak.
|
||||
- **Issue 의 dump 의 chat**: 매 GitHub issue 의 single source of truth.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (GitHub Docs 2026, Conventional Commits v1.0).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — PR/issue templates + CI patterns + gh CLI |
|
||||
@@ -0,0 +1,147 @@
|
||||
---
|
||||
id: wiki-2026-0508-rule-of-three
|
||||
title: Rule of Three
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Three Strikes Rule, DRY Trigger, Triplication Rule]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [refactoring, dry, software-engineering, code-smell, abstraction]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: agnostic
|
||||
framework: refactoring
|
||||
---
|
||||
|
||||
# Rule of Three
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 첫 두 번의 중복은 참아라. 세 번째에 추상화하라"**. Martin Fowler 가 *Refactoring* (1999) 에서 codify 한 heuristic — 매 premature abstraction 의 cost 가 duplication 의 cost 보다 큰 까닭에, 매 세 번째 instance 에서 야 진짜 pattern 이 보인다는 pragmatic guideline. 매 2026 년 까지 매 senior eng 의 default mental model.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 origin (Don Roberts → Fowler)
|
||||
- Don Roberts 가 처음 articulate, Fowler 가 *Refactoring* (1999) book 에서 popularize.
|
||||
- 매 underlying principle: 매 abstraction 은 매 미래 의 use case 의 prediction. 매 N=2 일 때 prediction 의 sample size 부족. 매 N=3 에서 야 매 commonality 가 진짜 인지 vs 매 우연 인지 distinguishable.
|
||||
|
||||
### 매 trade-off
|
||||
- **매 abstraction cost**: 매 wrong abstraction 의 cost ≫ 매 duplication 의 cost (Sandi Metz 의 famous talk: "duplication is far cheaper than the wrong abstraction").
|
||||
- **매 cognitive load**: 매 abstraction 의 매 indirection 추가 → 매 reader 가 매 hop 따라 가야.
|
||||
- **매 lock-in**: 매 abstraction 일찍 commit 시 매 future divergence 시 매 rollback cost 큼.
|
||||
|
||||
### 매 응용
|
||||
1. **함수 추출**: 매 동일 logic 의 3 번째 copy 시 → extract function.
|
||||
2. **클래스 hierarchy**: 매 3 번째 subclass 의 emerging 시 → introduce base class.
|
||||
3. **Config / parameter**: 매 magic number 의 3 번째 occurrence 시 → constant 화.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: Duplication tolerated (N=2)
|
||||
```typescript
|
||||
// 매 OK — 매 2 번 만의 duplication. 매 abstraction X.
|
||||
function calcOrderTotal(items: Item[]) {
|
||||
return items.reduce((sum, i) => sum + i.price * i.qty, 0);
|
||||
}
|
||||
|
||||
function calcCartPreview(items: Item[]) {
|
||||
// 매 looks similar but 매 different context — leave it.
|
||||
return items.reduce((sum, i) => sum + i.price * i.qty, 0);
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 2: 3rd occurrence → extract
|
||||
```typescript
|
||||
// 매 3 번째 copy 등장 시 abstract.
|
||||
const sumLineItems = (items: Item[]) =>
|
||||
items.reduce((sum, i) => sum + i.price * i.qty, 0);
|
||||
|
||||
const calcOrderTotal = sumLineItems;
|
||||
const calcCartPreview = sumLineItems;
|
||||
const calcInvoiceTotal = sumLineItems; // 매 trigger
|
||||
```
|
||||
|
||||
### Pattern 3: Generic-too-early anti-example
|
||||
```typescript
|
||||
// 매 BAD — 매 N=1 에서 매 over-generalize.
|
||||
function processCollection<T, R>(
|
||||
data: T[],
|
||||
reducer: (acc: R, x: T) => R,
|
||||
initial: R,
|
||||
filter?: (x: T) => boolean,
|
||||
mapper?: (x: T) => T
|
||||
): R {
|
||||
// 매 future-proofing 의 환상. 매 actual 사용 = 매 1 case.
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 4: Sandi Metz 의 "prefer duplication"
|
||||
```ruby
|
||||
# 매 duplicate code 는 매 wrong abstraction 보다 매 fix easier.
|
||||
# 매 wrong abstraction = 매 매 caller refactor 필요.
|
||||
class OrderTotal
|
||||
def calculate(items)
|
||||
items.sum { |i| i.price * i.qty }
|
||||
end
|
||||
end
|
||||
|
||||
class CartPreview
|
||||
def calculate(items)
|
||||
items.sum { |i| i.price * i.qty } # 매 duplicate intentional until N=3
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
### Pattern 5: 매 React component 의 Rule of Three
|
||||
```tsx
|
||||
// 매 1st: inline.
|
||||
<button className="bg-blue-500 px-4 py-2 rounded">Save</button>
|
||||
|
||||
// 매 2nd: 그냥 copy.
|
||||
<button className="bg-blue-500 px-4 py-2 rounded">Cancel</button>
|
||||
|
||||
// 매 3rd: abstract.
|
||||
const PrimaryButton = ({ children, ...rest }) => (
|
||||
<button className="bg-blue-500 px-4 py-2 rounded" {...rest}>{children}</button>
|
||||
);
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 N=1 (one-off) | Inline. 매 abstraction X. |
|
||||
| 매 N=2 (duplication 등장) | Wait. 매 watch for 3rd. |
|
||||
| 매 N=3 (triplication) | Extract — 매 pattern crystallized. |
|
||||
| 매 cross-domain duplication (uncertain pattern) | Wait — 매 4-5 까지 도 OK. |
|
||||
| 매 critical bug-prone duplication | Extract early — 매 correctness ≫ 매 abstraction cost. |
|
||||
|
||||
**기본값**: 매 N=3 까지 wait. 매 doubt 시 duplicate.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[DRY Principle (Don't Repeat Yourself)]] · [[Refactoring_Best_Practices|Refactoring]]
|
||||
- 변형: [[YAGNI]]
|
||||
- 응용: [[Extract Function]] · [[Extract Class]]
|
||||
- Adjacent: [[Code Smell]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 codebase 의 duplication 매 detect → 매 N count 후 매 refactor 제안.
|
||||
**언제 X**: 매 N=2 에서 매 LLM 의 over-eager abstraction 제안 — reject.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **DRY 원리주의 (DRY zealotry)**: 매 N=1 에서 매 abstract → 매 wrong shape.
|
||||
- **Forever duplication**: 매 N=10 도 매 ignore — 매 maintenance disaster.
|
||||
- **Hasty generalization**: 매 surface similarity 만 보고 매 abstract — 매 underlying domain 의 different.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Fowler *Refactoring* 1st/2nd ed; Sandi Metz "All the Little Things" RailsConf 2014).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Rule of Three 의 origin/trade-off/patterns/Metz 의 "prefer duplication" 정리 |
|
||||
@@ -0,0 +1,184 @@
|
||||
---
|
||||
id: wiki-2026-0508-state
|
||||
title: State
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Application State, Program State, Stateful, State Management]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [state, programming, architecture, frontend, backend]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: typescript
|
||||
framework: agnostic
|
||||
---
|
||||
|
||||
# State
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 state = 매 program 의 매 time 의 매 snapshot"**. 매 변하는 모든 데이터 — 매 UI 의 input value, 매 server 의 user session, 매 game 의 entity transform 까지. 매 state management 가 매 software complexity 의 매 dominant source — Rich Hickey 의 famous "state is hard" quote (Strange Loop 2009).
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 분류
|
||||
- **Local / component state**: 매 React `useState`, 매 Vue `ref` — 매 single component scope.
|
||||
- **Shared / global state**: 매 Redux/Zustand/Pinia/Jotai — 매 multiple components share.
|
||||
- **Server state**: 매 React Query/TanStack Query/SWR — 매 server-of-truth 의 매 cache.
|
||||
- **URL state**: 매 query params, hash — 매 shareable / bookmarkable.
|
||||
- **Persistent state**: 매 localStorage, IndexedDB, DB — 매 across sessions.
|
||||
- **Derived state**: 매 computed from base state — 매 NOT stored separately (single source of truth).
|
||||
|
||||
### 매 state 의 trade-off
|
||||
- **매 mutable** vs **매 immutable**: 매 immutability → 매 reasoning easier, 매 time-travel debug 가능, 매 perf cost 일부.
|
||||
- **매 local** vs **매 global**: 매 global → 매 sharing easy, 매 coupling explosion.
|
||||
- **매 client** vs **매 server**: 매 client → 매 latency 0, 매 inconsistency. 매 server → 매 truth 1, 매 latency.
|
||||
- **매 fine-grained** vs **매 coarse**: 매 fine → 매 selective re-render, 매 bookkeeping cost.
|
||||
|
||||
### 매 modern (2026) frontend stack
|
||||
- **Local**: useState/useReducer (React 19), `$state` (Svelte 5 runes), `ref/computed` (Vue 3.5).
|
||||
- **Global**: Zustand (most popular React), Jotai (atomic), Pinia (Vue), Redux Toolkit (legacy-heavy).
|
||||
- **Server**: TanStack Query 5 (React/Solid/Svelte/Vue), SWR (Vercel), Apollo Client (GraphQL).
|
||||
- **URL**: TanStack Router, Next.js useSearchParams, nuqs.
|
||||
- **Form**: React Hook Form + Zod (de facto), TanStack Form.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern 1: Local state (React)
|
||||
```tsx
|
||||
import { useState } from "react";
|
||||
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0);
|
||||
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 2: Global state (Zustand)
|
||||
```typescript
|
||||
import { create } from "zustand";
|
||||
|
||||
interface CartState {
|
||||
items: { id: string; qty: number }[];
|
||||
add: (id: string) => void;
|
||||
remove: (id: string) => void;
|
||||
total: () => number;
|
||||
}
|
||||
|
||||
export const useCart = create<CartState>((set, get) => ({
|
||||
items: [],
|
||||
add: (id) => set(s => {
|
||||
const existing = s.items.find(i => i.id === id);
|
||||
if (existing) return { items: s.items.map(i => i.id === id ? { ...i, qty: i.qty + 1 } : i) };
|
||||
return { items: [...s.items, { id, qty: 1 }] };
|
||||
}),
|
||||
remove: (id) => set(s => ({ items: s.items.filter(i => i.id !== id) })),
|
||||
total: () => get().items.reduce((s, i) => s + i.qty, 0),
|
||||
}));
|
||||
```
|
||||
|
||||
### Pattern 3: Server state (TanStack Query)
|
||||
```tsx
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
function useUser(id: string) {
|
||||
return useQuery({
|
||||
queryKey: ["user", id],
|
||||
queryFn: () => fetch(`/api/users/${id}`).then(r => r.json()),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
function useUpdateUser() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: (u: User) => fetch(`/api/users/${u.id}`, { method: "PUT", body: JSON.stringify(u) }),
|
||||
onSuccess: (_, u) => qc.invalidateQueries({ queryKey: ["user", u.id] }),
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 4: URL state (nuqs)
|
||||
```tsx
|
||||
import { useQueryState, parseAsInteger } from "nuqs";
|
||||
|
||||
function ProductList() {
|
||||
const [page, setPage] = useQueryState("page", parseAsInteger.withDefault(1));
|
||||
const [sort, setSort] = useQueryState("sort", { defaultValue: "name" });
|
||||
// 매 URL = ?page=2&sort=price → 매 shareable, 매 back-button works.
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 5: Derived state (NEVER duplicate base)
|
||||
```tsx
|
||||
// 매 BAD — 매 fullName 의 매 별도 state.
|
||||
const [first, setFirst] = useState("");
|
||||
const [last, setLast] = useState("");
|
||||
const [fullName, setFullName] = useState(""); // 매 anti-pattern
|
||||
|
||||
// 매 GOOD — 매 derive on render.
|
||||
const fullName = `${first} ${last}`;
|
||||
|
||||
// 매 expensive case → useMemo.
|
||||
const expensiveResult = useMemo(() => heavyCompute(first, last), [first, last]);
|
||||
```
|
||||
|
||||
### Pattern 6: State machine (XState)
|
||||
```typescript
|
||||
import { setup } from "xstate";
|
||||
|
||||
const trafficLight = setup({}).createMachine({
|
||||
initial: "red",
|
||||
states: {
|
||||
red: { on: { TICK: "green" } },
|
||||
green: { on: { TICK: "yellow" } },
|
||||
yellow: { on: { TICK: "red" } },
|
||||
},
|
||||
});
|
||||
// 매 invalid transition 의 매 compile-time prevention.
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 component-local UI | useState |
|
||||
| 매 2-3 component shared | Lift state up / Context |
|
||||
| 매 app-wide global | Zustand / Jotai |
|
||||
| 매 server data | TanStack Query (NOT global state) |
|
||||
| 매 form | React Hook Form + Zod |
|
||||
| 매 URL-bound | nuqs / TanStack Router |
|
||||
| 매 complex transitions | XState (state machine) |
|
||||
| 매 persistent | Zustand persist middleware / IndexedDB |
|
||||
|
||||
**기본값**: 매 derive whenever possible. 매 store 만 base state. 매 server state 의 매 global state X (TanStack Query 사용).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[State Management]] · [[Architecture]]
|
||||
- 변형: [[Server State]]
|
||||
- 응용: [[React]] · [[Zustand]] · [[XState]]
|
||||
- Adjacent: [[Immutability]] · [[State Machine]] · [[Single Source of Truth (SSoT)]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 state shape 의 매 design 추천, 매 derived vs base 의 매 audit.
|
||||
**언제 X**: 매 LLM 의 매 over-eager Redux 추천 — 매 modern projects 에서 의 outdated.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **State duplication**: 매 derivable 의 매 별도 store — 매 sync bugs.
|
||||
- **Server state in global store**: 매 cache invalidation 손수 reimplement — 매 TanStack Query 사용.
|
||||
- **Prop drilling depth >3**: 매 Context / state lib 의 매 trigger.
|
||||
- **Premature global**: 매 1 component scope 의 매 Zustand store — 매 over-engineering.
|
||||
- **Mutable update**: 매 `state.items.push(x)` (Redux) — 매 React 의 매 re-render miss.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (React 19 docs, TanStack Query v5 docs, Zustand 4.x, XState v5 docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — State 의 분류, 2026 modern stack, useState/Zustand/TanStack Query/nuqs/XState 패턴 + 기본값 결정표 정리 |
|
||||
@@ -0,0 +1,165 @@
|
||||
---
|
||||
id: wiki-2026-0508-statistical-analysis
|
||||
title: Statistical Analysis
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Statistics, Inferential Statistics, Data Analysis]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [statistics, hypothesis-testing, regression, bayesian]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: Python / R
|
||||
framework: scipy / statsmodels / pymc / R-tidyverse
|
||||
---
|
||||
|
||||
# Statistical Analysis
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 데이터의 uncertainty 를 정량화"**. Fisher–Neyman frequentist framework 부터 Gelman 2020s Bayesian workflow까지, 2026 현재 표준은 statsmodels + PyMC 5.x + ArviZ pipeline 으로 reproducible inference를 빌드하는 것이다.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 두 paradigm
|
||||
- **Frequentist**: parameter 는 fixed, data 가 random. p-value, confidence interval, MLE.
|
||||
- **Bayesian**: parameter 도 random, prior + likelihood → posterior. Credible interval, posterior predictive.
|
||||
- **2026 합의**: 매 둘 다 도구 — small n / strong prior 면 Bayesian, large n / regulated 면 frequentist.
|
||||
|
||||
### 매 핵심 절차
|
||||
- **EDA**: distribution, missing, outlier, correlation matrix.
|
||||
- **Hypothesis test**: t-test, χ², Mann-Whitney, permutation. Effect size + CI 동봉.
|
||||
- **Regression**: OLS → GLM → mixed-effects → hierarchical Bayesian.
|
||||
- **Model checking**: residual diagnostics, posterior predictive checks, k-fold CV.
|
||||
|
||||
### 매 응용
|
||||
1. A/B test 분석 (web, ML model rollout).
|
||||
2. Clinical trial efficacy.
|
||||
3. Causal inference (DiD, IV, RDD, double ML).
|
||||
4. Risk modeling (insurance, finance).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Welch's t-test + effect size + CI (scipy 1.13+)
|
||||
```python
|
||||
import numpy as np
|
||||
from scipy import stats
|
||||
|
||||
def welch_with_effect(a, b):
|
||||
t, p = stats.ttest_ind(a, b, equal_var=False)
|
||||
n1, n2 = len(a), len(b)
|
||||
s1, s2 = a.var(ddof=1), b.var(ddof=1)
|
||||
pooled = np.sqrt(((n1-1)*s1 + (n2-1)*s2) / (n1+n2-2))
|
||||
cohen_d = (a.mean() - b.mean()) / pooled
|
||||
df = (s1/n1 + s2/n2)**2 / ((s1/n1)**2/(n1-1) + (s2/n2)**2/(n2-1))
|
||||
se = np.sqrt(s1/n1 + s2/n2)
|
||||
crit = stats.t.ppf(0.975, df)
|
||||
diff = a.mean() - b.mean()
|
||||
return dict(t=t, p=p, d=cohen_d, ci=(diff - crit*se, diff + crit*se))
|
||||
```
|
||||
|
||||
### OLS regression with diagnostics (statsmodels)
|
||||
```python
|
||||
import statsmodels.api as sm
|
||||
import statsmodels.formula.api as smf
|
||||
|
||||
model = smf.ols("y ~ x1 + x2 + C(group)", data=df).fit(cov_type="HC3")
|
||||
print(model.summary())
|
||||
|
||||
# diagnostics
|
||||
from statsmodels.stats.diagnostic import het_breuschpagan
|
||||
bp = het_breuschpagan(model.resid, model.model.exog)
|
||||
print("Breusch-Pagan p:", bp[1])
|
||||
```
|
||||
|
||||
### Hierarchical Bayesian (PyMC 5.x)
|
||||
```python
|
||||
import pymc as pm
|
||||
import arviz as az
|
||||
|
||||
with pm.Model() as hier:
|
||||
mu_a = pm.Normal("mu_a", 0, 5)
|
||||
sigma_a = pm.HalfNormal("sigma_a", 1)
|
||||
a = pm.Normal("a", mu_a, sigma_a, shape=n_groups)
|
||||
b = pm.Normal("b", 0, 1)
|
||||
sigma = pm.HalfNormal("sigma", 1)
|
||||
mu = a[group_idx] + b * x
|
||||
pm.Normal("y_obs", mu, sigma, observed=y)
|
||||
idata = pm.sample(2000, tune=1000, target_accept=0.95)
|
||||
|
||||
az.plot_trace(idata)
|
||||
az.summary(idata, var_names=["mu_a", "sigma_a", "b"])
|
||||
```
|
||||
|
||||
### Bootstrap CI
|
||||
```python
|
||||
import numpy as np
|
||||
def bootstrap_ci(data, stat=np.mean, n=10_000, alpha=0.05, rng=None):
|
||||
rng = rng or np.random.default_rng(42)
|
||||
boots = stat(rng.choice(data, size=(n, len(data)), replace=True), axis=1)
|
||||
lo, hi = np.quantile(boots, [alpha/2, 1-alpha/2])
|
||||
return stat(data), (lo, hi)
|
||||
```
|
||||
|
||||
### Multiple testing correction
|
||||
```python
|
||||
from statsmodels.stats.multitest import multipletests
|
||||
reject, pvals_corr, _, _ = multipletests(pvals, alpha=0.05, method="fdr_bh")
|
||||
```
|
||||
|
||||
### Causal inference: doubly robust (EconML / DoubleML)
|
||||
```python
|
||||
from econml.dml import LinearDML
|
||||
from sklearn.ensemble import GradientBoostingRegressor
|
||||
|
||||
dml = LinearDML(
|
||||
model_y=GradientBoostingRegressor(),
|
||||
model_t=GradientBoostingRegressor(),
|
||||
discrete_treatment=False,
|
||||
cv=5,
|
||||
)
|
||||
dml.fit(Y, T, X=X, W=W)
|
||||
print(dml.effect(X), dml.effect_interval(X))
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 2-group mean compare, normal-ish | Welch's t-test |
|
||||
| Non-parametric, small n | Mann-Whitney / permutation |
|
||||
| Multi-level data | Mixed-effects (lme4 / statsmodels) |
|
||||
| Strong prior, small n | Bayesian (PyMC) |
|
||||
| Causal effect from observational | DML / IV / RDD |
|
||||
| Many comparisons | FDR (BH), not Bonferroni unless ≤10 tests |
|
||||
|
||||
**기본값**: statsmodels for frequentist, PyMC 5 + ArviZ for Bayesian, EconML for causal.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Probability Theory]]
|
||||
- 변형: [[Bayesian_Inference|Bayesian Inference]] · [[Causal Inference]]
|
||||
- Adjacent: [[Machine Learning]] · [[Power Analysis]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: pipeline scaffolding, EDA narrative, model spec translation, plot 코드 생성.
|
||||
**언제 X**: numerical p-value computation 직접 — library 사용. 매 LLM의 hallucinated stat 의 X.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **p-hacking**: 매 multiple test 후 cherry-pick — pre-registration + correction 필수.
|
||||
- **CI vs PI 혼동**: confidence interval ≠ prediction interval. 매 명확히 구분.
|
||||
- **HARKing**: hypothesis after results — exploratory vs confirmatory 분리.
|
||||
- **Naive default prior**: PyMC `Normal(0, 100)` 의 X — domain-informed weakly-informative prior.
|
||||
- **n=30 rule**: 매 myth — distribution shape 기반 결정.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Wasserman "All of Statistics", Gelman BDA3, statsmodels docs 0.14+, PyMC 5.x docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — frequentist + Bayesian + causal patterns |
|
||||
@@ -0,0 +1,173 @@
|
||||
---
|
||||
id: wiki-2026-0508-typescript
|
||||
title: TypeScript
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [TS, Typed JavaScript]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [language, typescript, javascript, types]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: typescript
|
||||
framework: tsc-bun-deno
|
||||
---
|
||||
|
||||
# TypeScript
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 JavaScript 의 superset + structural type system + erasure compile"**. Microsoft 의 Anders Hejlsberg 의 lead, 2012 release. 매 2026 의 v5.6 (Q1) — TC39 Stage 3 type-annotation proposal 의 ECMAScript inclusion 의 progress, Bun/Deno 의 native runtime 의 TS 의 zero-config execution 의 standard.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 Type System
|
||||
- **Structural** (duck typing 의 formalize), nominal X.
|
||||
- **Gradual** — `any` / `unknown` escape hatch.
|
||||
- **Erasure** — runtime 의 zero overhead 의 strip.
|
||||
- **Inference** — 매 explicit annotation 의 minimize.
|
||||
|
||||
### 매 Key Constructs
|
||||
- `interface` / `type` — 매 interchangeable mostly.
|
||||
- `as const` — literal narrowing.
|
||||
- Generics — `<T>`, `extends`, `infer`.
|
||||
- Mapped types — `{[K in keyof T]: ...}`.
|
||||
- Conditional types — `T extends U ? X : Y`.
|
||||
- Template literal types — `` `prefix-${T}` ``.
|
||||
|
||||
### 매 Modern (5.x) Features
|
||||
- `const` type parameters (5.0).
|
||||
- `satisfies` operator (4.9).
|
||||
- Decorators stage 3 (5.0).
|
||||
- Stricter `unknown` in catch (4.4 default).
|
||||
- `using` declarations (5.2, ES2026 explicit resource management).
|
||||
|
||||
### 매 응용
|
||||
1. Frontend — React / Vue / Svelte 의 default.
|
||||
2. Backend — Node, Bun, Deno, Cloudflare Workers.
|
||||
3. Tooling — eslint plugins, build scripts.
|
||||
4. Schema — Zod / Valibot / ArkType 의 runtime validation.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Discriminated union
|
||||
```typescript
|
||||
type Shape =
|
||||
| { kind: "circle"; radius: number }
|
||||
| { kind: "square"; side: number };
|
||||
|
||||
function area(s: Shape): number {
|
||||
switch (s.kind) {
|
||||
case "circle": return Math.PI * s.radius ** 2;
|
||||
case "square": return s.side ** 2;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `satisfies` for literal-narrow + type-check
|
||||
```typescript
|
||||
const palette = {
|
||||
red: [255, 0, 0],
|
||||
green: "#00ff00",
|
||||
} satisfies Record<string, [number, number, number] | string>;
|
||||
|
||||
palette.red[0]; // ok, number
|
||||
palette.green.toUpperCase(); // ok, string
|
||||
```
|
||||
|
||||
### Generic constraint + `infer`
|
||||
```typescript
|
||||
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
|
||||
|
||||
function fetchUser() { return { id: 1, name: "Alice" }; }
|
||||
type User = ReturnType<typeof fetchUser>; // {id: number, name: string}
|
||||
```
|
||||
|
||||
### Branded types (nominal-ish)
|
||||
```typescript
|
||||
type Brand<T, B> = T & { __brand: B };
|
||||
type UserId = Brand<string, "UserId">;
|
||||
type OrderId = Brand<string, "OrderId">;
|
||||
|
||||
function getUser(id: UserId) { /* ... */ }
|
||||
const oid = "ord_42" as OrderId;
|
||||
// getUser(oid); // Error: OrderId not assignable to UserId
|
||||
```
|
||||
|
||||
### Zod schema → TS type
|
||||
```typescript
|
||||
import { z } from "zod";
|
||||
|
||||
const User = z.object({
|
||||
id: z.string().uuid(),
|
||||
email: z.string().email(),
|
||||
age: z.number().int().min(0),
|
||||
});
|
||||
|
||||
type User = z.infer<typeof User>;
|
||||
|
||||
const parsed = User.parse(JSON.parse(body)); // runtime + type
|
||||
```
|
||||
|
||||
### `using` (explicit resource cleanup, ES2026)
|
||||
```typescript
|
||||
class FileHandle implements Disposable {
|
||||
constructor(public path: string) { /* open */ }
|
||||
[Symbol.dispose]() { /* close */ }
|
||||
}
|
||||
|
||||
function read() {
|
||||
using fh = new FileHandle("/tmp/data");
|
||||
// ... auto-close at scope exit
|
||||
}
|
||||
```
|
||||
|
||||
### Bun/Deno direct TS run
|
||||
```bash
|
||||
bun run script.ts # native, no build
|
||||
deno run --allow-net app.ts # native + permissions
|
||||
node --experimental-strip-types script.ts # Node 22.6+
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Library API | strict mode + `interface` |
|
||||
| Internal app | `type` + Zod for boundaries |
|
||||
| Discriminated state | `kind` field + switch |
|
||||
| Runtime validation | Zod / Valibot / ArkType |
|
||||
| Avoid `any` | `unknown` + narrow |
|
||||
| Nominal IDs | branded types |
|
||||
|
||||
**기본값**: `tsconfig` strict, target ES2024, Bun/Deno runtime, Zod boundaries.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[JavaScript]]
|
||||
- 변형: [[Flow]]
|
||||
- 응용: [[React]] · [[Nodejs]] · [[Bun]] · [[Deno]]
|
||||
- Adjacent: [[Zod]] · [[ESLint]] · [[Vite]] · [[tsup]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: type 의 derive, generic constraint 의 design, error 의 explain.
|
||||
**언제 X**: very recent TS feature (LLM cutoff 의 newer) — 매 official release notes 의 verify.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **`any` 의 default**: 매 type system 의 disable.
|
||||
- **`as` cast 의 over-use**: 매 runtime mismatch 의 hide.
|
||||
- **`!` non-null assertion 의 abuse**: 매 narrow 의 effort 의 do.
|
||||
- **`interface` vs `type` 의 endless debate**: 매 either 의 fine, consistency 의 important.
|
||||
- **Decorator 의 prod 의 untested**: 매 stage 3 의 runtime 의 still 의 change.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (typescriptlang.org docs 5.6, TC39 type-annotations proposal).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — type system + 5.x features + Bun/Deno runtime |
|
||||
@@ -0,0 +1,171 @@
|
||||
---
|
||||
id: wiki-2026-0508-decisions
|
||||
title: Architecture Decision Records (ADR)
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [ADR, Decision Log, Architecture Decisions]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [adr, architecture, decisions, documentation, engineering]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: markdown
|
||||
framework: adr-tools
|
||||
---
|
||||
|
||||
# Architecture Decision Records (ADR)
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 immutable record of architectural choices, written in the moment of decision"**. Michael Nygard 가 2011 년 originally proposed; 2026 modern engineering org 의 standard practice — single ADR file per decision, append-only, version-controlled in repo alongside code.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 ADR file 구조
|
||||
- **Title**: short noun phrase (e.g., "Use PostgreSQL for transactional store").
|
||||
- **Status**: Proposed → Accepted → Deprecated → Superseded.
|
||||
- **Context**: forces 와 constraints 의 background.
|
||||
- **Decision**: what we will do — active voice, declarative.
|
||||
- **Consequences**: positive / negative / neutral trade-offs.
|
||||
|
||||
### 매 lifecycle
|
||||
- ADR 는 immutable — supersede 하려면 new ADR 작성, old 의 status 를 `Superseded by ADR-N` 로 update.
|
||||
- PR review 의 part — engineering team 의 collective signoff.
|
||||
- ADR-001 부터 sequential numbering, 절대 renumbering 안 함.
|
||||
|
||||
### 매 응용
|
||||
1. Microservices boundary 의 결정 (e.g., service split rationale).
|
||||
2. Data store / message queue 의 선택 (Postgres vs DynamoDB).
|
||||
3. Auth flow / API style (REST vs GraphQL vs gRPC).
|
||||
4. Build tooling / CI 의 stack lock-in.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Nygard ADR template (md)
|
||||
```markdown
|
||||
# ADR-007: Adopt PostgreSQL for primary OLTP
|
||||
|
||||
## Status
|
||||
Accepted (2026-05-08)
|
||||
|
||||
## Context
|
||||
We need an ACID-compliant store for orders.
|
||||
Read/write ratio is 3:1, peak 2k QPS.
|
||||
Team has Postgres ops experience; Aurora / RDS managed offering available.
|
||||
|
||||
## Decision
|
||||
We will use Amazon RDS for PostgreSQL 16 as the primary OLTP store.
|
||||
|
||||
## Consequences
|
||||
+ Strong consistency, mature ecosystem.
|
||||
+ Existing in-house expertise reduces ramp.
|
||||
- Vendor lock-in to AWS RDS.
|
||||
- Need to manage VACUUM tuning at >10M rows/table.
|
||||
```
|
||||
|
||||
### MADR template (richer variant)
|
||||
```markdown
|
||||
---
|
||||
status: accepted
|
||||
date: 2026-05-08
|
||||
deciders: [alice, bob, carol]
|
||||
consulted: [security-team]
|
||||
informed: [eng-all]
|
||||
---
|
||||
# Use Kafka for event bus
|
||||
|
||||
## Context and Problem Statement
|
||||
How do we propagate domain events across 8 microservices?
|
||||
|
||||
## Considered Options
|
||||
- Kafka
|
||||
- RabbitMQ
|
||||
- AWS SNS/SQS
|
||||
|
||||
## Decision Outcome
|
||||
Chosen: Kafka, because durable replay + partition ordering matter.
|
||||
|
||||
### Positive Consequences
|
||||
- Replayable history (compaction).
|
||||
- High throughput (>1M msg/s).
|
||||
|
||||
### Negative Consequences
|
||||
- Operational complexity (ZK / KRaft).
|
||||
```
|
||||
|
||||
### adr-tools CLI workflow
|
||||
```bash
|
||||
# Init in repo
|
||||
adr init doc/adr
|
||||
|
||||
# Create new ADR
|
||||
adr new "Use Postgres for OLTP"
|
||||
# -> doc/adr/0007-use-postgres-for-oltp.md
|
||||
|
||||
# Supersede old decision
|
||||
adr new -s 3 "Replace MongoDB with Postgres"
|
||||
# -> auto-marks ADR-0003 as Superseded
|
||||
```
|
||||
|
||||
### Lightweight in-PR ADR (modern variant)
|
||||
```markdown
|
||||
<!-- .github/PULL_REQUEST_TEMPLATE.md -->
|
||||
## Decision Record
|
||||
- **Choice**: <one sentence>
|
||||
- **Why now**: <trigger>
|
||||
- **Alternatives considered**: <list>
|
||||
- **Trade-offs accepted**: <list>
|
||||
```
|
||||
|
||||
### ADR index generation (CI script)
|
||||
```python
|
||||
# scripts/build_adr_index.py
|
||||
import re, pathlib
|
||||
adrs = sorted(pathlib.Path("doc/adr").glob("[0-9]*.md"))
|
||||
lines = ["# ADR Index\n"]
|
||||
for f in adrs:
|
||||
title = next(l[2:].strip() for l in f.read_text().splitlines() if l.startswith("# "))
|
||||
status = re.search(r"## Status\n(\w+)", f.read_text()).group(1)
|
||||
lines.append(f"- [{f.stem}]({f.name}) — {title} ({status})")
|
||||
pathlib.Path("doc/adr/README.md").write_text("\n".join(lines))
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Solo / prototype | Skip ADR — overhead > benefit |
|
||||
| Team ≥ 3, multi-quarter project | Nygard ADR mandatory |
|
||||
| Regulated env (FDA, SOC2) | MADR + sign-off metadata |
|
||||
| Very fast-moving startup | In-PR lightweight ADR |
|
||||
| Architecture review board | MADR with `consulted` / `informed` |
|
||||
|
||||
**기본값**: Nygard ADR in `doc/adr/`, accepted via PR review, supersession over deletion.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Software_Architecture_Patterns]] · [[소프트웨어 설계 원칙 및 디자인 패턴|Engineering_Principles]]
|
||||
- 응용: [[Microservices_Architecture]] · [[Codebase_Onboarding]]
|
||||
- Adjacent: [[Pull_Request_and_Issue_Tracking]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: Engineering team ≥ 3, decisions have multi-month consequences, onboarding context value matters.
|
||||
**언제 X**: Personal project, throwaway prototype, decisions reversible in <1 day.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Edit history erasure**: ADR 를 mutate — supersession chain 의 의도 가 lost.
|
||||
- **Decision-by-Slack**: ADR 없이 채팅 만 의 합의 — 6 개월 후 누구 도 rationale 모름.
|
||||
- **Over-documentation**: 매 trivial choice 의 ADR — signal-to-noise drops.
|
||||
- **Status drift**: Accepted ADR 가 production 의 actual state 와 diverge — periodic audit 필요.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Michael Nygard 2011 original post; ThoughtWorks Tech Radar "Adopt"; AWS / Spotify / GitHub public ADR repos).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full ADR taxonomy + Nygard/MADR templates + adr-tools workflow |
|
||||
@@ -0,0 +1,209 @@
|
||||
---
|
||||
id: wiki-2026-0508-project-profile
|
||||
title: Project Profile (Repo Metadata Document)
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Project Profile, Repo Profile, PROJECT.md]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [project-profile, onboarding, documentation, metadata, engineering]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: markdown
|
||||
framework: github-readme-spec
|
||||
---
|
||||
|
||||
# Project Profile (Repo Metadata Document)
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 single-page document that answers: what is this repo, who runs it, how do I run it, where is it deployed"**. 2026 modern engineering — replaces sprawling wiki tribal knowledge with a versioned, reviewable, machine-parseable PROJECT.md / project-profile.md at repo root, consumed by humans 와 LLM coding agents (Claude Code, Copilot Workspace) alike.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 mandatory sections
|
||||
- **Identity**: name, slug, owners (tech + product), Slack channel, on-call rotation.
|
||||
- **Purpose**: 1-paragraph "why this repo exists" — business problem, not implementation.
|
||||
- **Stack**: languages, frameworks, runtime versions, key dependencies.
|
||||
- **Run locally**: prereqs + 3-5 commands max to bootstrap dev env.
|
||||
- **Deploy**: target environments, deploy mechanism (CI workflow link), rollback procedure.
|
||||
|
||||
### 매 secondary sections
|
||||
- **Architecture diagram**: mermaid / draw.io link.
|
||||
- **Data flows**: what services this calls, who calls this.
|
||||
- **SLOs**: latency / availability targets.
|
||||
- **Runbooks**: links to incident-response docs.
|
||||
- **ADR index**: link to `doc/adr/README.md`.
|
||||
|
||||
### 매 LLM agent consumption
|
||||
- LLM coding agents (Claude Opus 4.7, GPT-5 Workspace) read PROJECT.md FIRST when entering a repo.
|
||||
- Frontmatter machine-parseable — agents pull tech_stack, owners, conventions.
|
||||
- Reduces hallucinated assumptions (wrong test runner, wrong deploy target, etc.).
|
||||
|
||||
### 매 응용
|
||||
1. New-hire onboarding (day-1 read).
|
||||
2. Incident response (on-call finds owner / runbook fast).
|
||||
3. LLM agent context-priming (agent reads profile → executes commands correctly).
|
||||
4. Cross-team integration (team A wants to consume team B's service — reads profile first).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Minimal profile (markdown)
|
||||
```markdown
|
||||
---
|
||||
name: orders-service
|
||||
slug: orders
|
||||
owners:
|
||||
tech: alice@acme.com
|
||||
product: bob@acme.com
|
||||
slack: "#orders-team"
|
||||
oncall: pagerduty.com/services/orders
|
||||
stack:
|
||||
language: go
|
||||
runtime: 1.23
|
||||
framework: chi
|
||||
db: postgres-16
|
||||
---
|
||||
|
||||
# orders-service
|
||||
|
||||
## Purpose
|
||||
Authoritative store for customer orders. Handles checkout, fulfillment events.
|
||||
|
||||
## Run locally
|
||||
```bash
|
||||
make dev
|
||||
curl localhost:8080/healthz
|
||||
```
|
||||
|
||||
## Deploy
|
||||
Auto-deploy on merge to `main` via `.github/workflows/deploy.yml`.
|
||||
Rollback: `gh workflow run rollback.yml -F sha=<prev>`.
|
||||
|
||||
## Architecture
|
||||
See [docs/architecture.md](docs/architecture.md).
|
||||
|
||||
## ADRs
|
||||
See [doc/adr/](doc/adr/).
|
||||
```
|
||||
|
||||
### Frontmatter spec (YAML, agent-readable)
|
||||
```yaml
|
||||
---
|
||||
name: <kebab-case>
|
||||
slug: <short>
|
||||
version: 1
|
||||
owners:
|
||||
tech: <email>
|
||||
product: <email>
|
||||
security: <email>
|
||||
slack: "#channel"
|
||||
oncall: <pagerduty-url>
|
||||
repo: github.com/acme/orders-service
|
||||
stack:
|
||||
language: <go|rust|python|ts>
|
||||
runtime: <version>
|
||||
framework: <name>
|
||||
db: <postgres-16|dynamo|...>
|
||||
deploy:
|
||||
prod: <url>
|
||||
staging: <url>
|
||||
ci: .github/workflows/deploy.yml
|
||||
slo:
|
||||
latency_p99_ms: 250
|
||||
availability: 99.9
|
||||
---
|
||||
```
|
||||
|
||||
### CI: profile schema validation
|
||||
```yaml
|
||||
# .github/workflows/profile-lint.yml
|
||||
name: profile-lint
|
||||
on: [pull_request]
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: pip install pyyaml jsonschema
|
||||
- run: python scripts/lint_profile.py PROJECT.md
|
||||
```
|
||||
|
||||
```python
|
||||
# scripts/lint_profile.py
|
||||
import sys, yaml, jsonschema
|
||||
schema = yaml.safe_load(open("schemas/project-profile.schema.yaml"))
|
||||
text = open(sys.argv[1]).read()
|
||||
fm = yaml.safe_load(text.split("---")[1])
|
||||
jsonschema.validate(fm, schema)
|
||||
print("ok")
|
||||
```
|
||||
|
||||
### Org-wide profile aggregator
|
||||
```python
|
||||
# tools/aggregate_profiles.py
|
||||
import requests, yaml, pathlib
|
||||
ORG = "acme"
|
||||
gh = requests.Session()
|
||||
repos = gh.get(f"https://api.github.com/orgs/{ORG}/repos").json()
|
||||
out = []
|
||||
for r in repos:
|
||||
raw = gh.get(f"https://raw.githubusercontent.com/{ORG}/{r['name']}/main/PROJECT.md")
|
||||
if raw.status_code == 200 and "---" in raw.text:
|
||||
out.append(yaml.safe_load(raw.text.split("---")[1]))
|
||||
pathlib.Path("catalog.yaml").write_text(yaml.dump(out))
|
||||
```
|
||||
|
||||
### Mermaid embed (architecture)
|
||||
```markdown
|
||||
## Architecture
|
||||
```mermaid
|
||||
flowchart LR
|
||||
client --> gateway
|
||||
gateway --> orders[orders-service]
|
||||
orders --> postgres[(postgres)]
|
||||
orders --> kafka[(kafka)]
|
||||
kafka --> fulfillment
|
||||
```
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Solo repo | Skip — README is enough |
|
||||
| Service in team org | Mandatory PROJECT.md w/ frontmatter |
|
||||
| Regulated org (SOC2, FDA) | Profile + ADR index + SLO doc |
|
||||
| Multi-team monorepo | One profile per service dir |
|
||||
| LLM-agent-heavy workflow | Frontmatter strict-schema validated in CI |
|
||||
|
||||
**기본값**: PROJECT.md at repo root, YAML frontmatter, CI lint, kept under 200 lines.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Codebase_Onboarding]] · [[소프트웨어 설계 원칙 및 디자인 패턴|Engineering_Principles]]
|
||||
- 변형: [[CODEOWNERS]]
|
||||
- 응용: [[decisions]]
|
||||
- Adjacent: [[Pull_Request_and_Issue_Tracking]] · [[GIT_PROTOCOL]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: Repo has > 1 contributor, repo is consumed by LLM coding agents, repo deploys to production.
|
||||
**언제 X**: Throwaway scratch repo, single-script gist, ephemeral demo.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Stale profile**: Owner left 6 months ago, still listed — periodic CODEOWNERS sync needed.
|
||||
- **Profile-as-novel**: 800-line PROJECT.md — split into ARCHITECTURE.md / RUNBOOK.md.
|
||||
- **No frontmatter**: Free-form prose only — LLM agents can't reliably extract.
|
||||
- **Docs-only, no CI lint**: Schema drift goes undetected for months.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Backstage Software Catalog spec; GitHub `.github/PROJECT.md` convention; Spotify Tech Radar; Anthropic Claude Code agent repo onboarding behavior 2026).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full Project Profile spec + frontmatter schema + CI lint patterns |
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
id: wiki-2026-0508-동적-분석-dynamic-analysis
|
||||
title: 동적 분석 Dynamic Analysis
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: dynamic-analysis
|
||||
duplicate_of: "[[Dynamic Analysis]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, security, testing]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 동적 분석 Dynamic Analysis
|
||||
|
||||
> **이 문서는 [[Dynamic Analysis]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- 실행 중 프로그램 행동 관찰 (runtime behavior observation).
|
||||
- DAST, fuzzing, taint tracking 의 기반.
|
||||
|
||||
## 🔗 Graph
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: wiki-2026-0508-반복적-리뷰iterative-review
|
||||
title: 반복적 리뷰Iterative Review
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: wiki-2026-0508-iterative-review
|
||||
duplicate_of: "[[Iterative Review]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, code-review, iteration, process]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 반복적 리뷰Iterative Review
|
||||
|
||||
> **이 문서는 [[Iterative Review]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약 (Korean-context aspects)
|
||||
- **반복적 리뷰**: 매 single big review 의 X — 매 small chunk 단위로 여러 번 review 하는 process.
|
||||
- **Stacked PR pattern**: 매 large feature 를 dependent 작은 PR sequence 로 분할 — 매 Graphite, Sapling 의 표준 workflow.
|
||||
- **한국 dev culture**: 매 Toss, Coupang, Naver — 매 dedicated review session + async PR 두 layer.
|
||||
- **2026 trend**: Claude Opus 4.7 1M context PR review (`claude review`) → human iterative reviewer pair.
|
||||
|
||||
## 🔗 Graph
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
id: wiki-2026-0508-방어-플랫폼-defense-platforms
|
||||
title: 방어 플랫폼(Defense Platforms)
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: defense-platforms
|
||||
duplicate_of: "[[Defense Platforms]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, security]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 방어 플랫폼(Defense Platforms)
|
||||
|
||||
> **이 문서는 [[Defense Platforms]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- 통합 보안 플랫폼 (XDR, SIEM, SOAR convergence).
|
||||
- 2026 modern: AI-driven detection + response.
|
||||
|
||||
## 🔗 Graph
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: wiki-2026-0508-아키텍처-드리프트-architectural-drift
|
||||
title: 아키텍처 드리프트 Architectural Drift
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: architectural-drift
|
||||
duplicate_of: "[[Architectural Drift]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, architecture, software-decay, governance]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 아키텍처 드리프트 Architectural Drift
|
||||
|
||||
> **이 문서는 [[Architectural Drift]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약 (Korean specialization)
|
||||
- "Drift" — 의도된 architecture 와 실제 구현 사이의 점진적 괴리.
|
||||
- 원인: ad-hoc 구현, time pressure, 부재된 ADR, 신규 멤버 onboarding 부족.
|
||||
- 측정: ArchUnit, Structurizr, dependency graph 분석으로 drift 정량화.
|
||||
|
||||
## 🔗 Graph
|
||||
- 관련: [[관심사의 분리 (Separation of Concerns)]] · [[Hexagonal_Architecture]]
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — Architectural Drift 로 redirect |
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
---
|
||||
id: wiki-2026-0508-의도-및-목적-지향적-설명-purpose-driven-ex
|
||||
title: 의도 및 목적 지향적 설명(Purpose-driven Explanation)
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Purpose-Driven Explanation, Intent-First Explanation, Why-First, 목적 우선 설명]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [communication, technical-writing, pedagogy, llm-prompting]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: markdown
|
||||
framework: technical-writing
|
||||
---
|
||||
|
||||
# 의도 및 목적 지향적 설명(Purpose-driven Explanation)
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 'WHAT' 매 의 의 시작 매 X — 매 'WHY' 의 의 의 시작"**. 매 Simon Sinek *Start with Why* (2009), 매 Heath brothers *Made to Stick*, 매 modern technical-writing (Diátaxis framework, Google docs style) 매 동일한 thesis — 매 reader / listener 매 purpose 의 의 의 의 의 detail 매 retain. 매 LLM prompting 매 동일 (intent-aware system prompt > capability list).
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 3-layer 매 explanation stack
|
||||
1. **매 WHY (purpose)**: 매 어떤 problem 의 solve? 매 어떤 audience 의 의 의 의?
|
||||
2. **매 WHAT (concept)**: 매 mechanism / definition / shape.
|
||||
3. **매 HOW (procedure)**: 매 step-by-step / 매 syntax / 매 implementation.
|
||||
|
||||
### 매 reverse pyramid 매 anti-pattern
|
||||
- 매 typical bad 의 docs: 매 syntax → 매 example → 매 (마지막에) 매 use case.
|
||||
- 매 improvement: 매 use case (intent) → 매 mechanism → 매 syntax.
|
||||
|
||||
### 매 Diátaxis quadrant alignment
|
||||
- **Tutorial**: 매 learning-by-doing → purpose = "skill 의 acquire".
|
||||
- **How-to**: 매 task-oriented → purpose = "specific outcome 의 reach".
|
||||
- **Reference**: 매 information-oriented → purpose = "lookup".
|
||||
- **Explanation**: 매 understanding-oriented → purpose = "build mental model".
|
||||
- 매 매 매 매 quadrant 매 different intent 의 의 의 매 match.
|
||||
|
||||
### 매 응용
|
||||
1. 매 API documentation: "이 endpoint 매 의 / 매 purpose / 매 use case" 의 의 의 의 시작.
|
||||
2. 매 commit message: 매 "why" > "what" (diff 매 의 의 의 what 의 visible).
|
||||
3. 매 LLM system prompt: 매 "당신 매 X 의 위해 매 user 의 의 의 의 X 의 의 의 의" 의 first.
|
||||
4. 매 onboarding doc: 매 "이 product 매 의 / 매 problem solve" 의 first paragraph.
|
||||
5. 매 ADR (Architecture Decision Record): 매 Context → Decision → Consequence (매 essentially purpose-first).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Pattern: function docstring (purpose-first)
|
||||
```python
|
||||
def normalize_embeddings(vectors: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Why: cosine similarity requires unit-length vectors; raw model
|
||||
outputs vary in magnitude and skew similarity scores.
|
||||
|
||||
What: scales each row to L2-norm = 1.
|
||||
|
||||
How: divides by np.linalg.norm(axis=1, keepdims=True) with
|
||||
epsilon guard for zero vectors.
|
||||
"""
|
||||
norms = np.linalg.norm(vectors, axis=1, keepdims=True)
|
||||
return vectors / np.maximum(norms, 1e-12)
|
||||
```
|
||||
|
||||
### Pattern: README opening
|
||||
```markdown
|
||||
# ProjectX
|
||||
|
||||
**For**: ML engineers running batch evaluation on 100k+ examples
|
||||
**Solves**: vendor-locked eval harnesses that don't support custom metrics
|
||||
**Not for**: real-time inference, single-example debugging
|
||||
|
||||
## Quick start
|
||||
...
|
||||
```
|
||||
|
||||
### Pattern: commit message
|
||||
```
|
||||
fix(auth): refresh token before expiry, not after
|
||||
|
||||
Why: users were seeing 401s mid-session because the refresh
|
||||
fired on next API call AFTER expiry, leaving a 200-500ms gap.
|
||||
|
||||
What: shifted refresh trigger to T-30s window.
|
||||
|
||||
How: added `expiresAt - 30_000` check in interceptor pre-hook.
|
||||
```
|
||||
|
||||
### Pattern: LLM system prompt
|
||||
```typescript
|
||||
const systemPrompt = `
|
||||
ROLE & PURPOSE
|
||||
You help backend engineers debug production incidents.
|
||||
Optimize for: minimum-time-to-hypothesis. The user is paged at 3am.
|
||||
|
||||
CONSTRAINTS
|
||||
- Lead with most likely root cause
|
||||
- Ask for logs/metrics ONLY if blocking
|
||||
- Suggest rollback before deep-fix when unclear
|
||||
`;
|
||||
```
|
||||
|
||||
### Pattern: ADR template
|
||||
```markdown
|
||||
# ADR 0042: Move from Postgres to ClickHouse for analytics
|
||||
|
||||
## Context (the WHY)
|
||||
Analytics queries hit 30-60s p95 on 2B-row events table.
|
||||
Product team needs sub-2s for dashboard interactivity.
|
||||
|
||||
## Decision (the WHAT)
|
||||
Adopt ClickHouse for the analytics read path; keep Postgres
|
||||
for transactional OLTP.
|
||||
|
||||
## Consequences (the HOW it plays out)
|
||||
+ p95 drops to ~200ms on tested queries
|
||||
- Dual-write complexity, 2nd ops surface
|
||||
- Eventual consistency between OLTP and analytics
|
||||
```
|
||||
|
||||
### Pattern: tutorial opening
|
||||
```markdown
|
||||
# Build a semantic search in 10 minutes
|
||||
|
||||
By the end you'll have:
|
||||
- A working semantic search over your own markdown files
|
||||
- An understanding of *why* embedding > keyword for fuzzy queries
|
||||
|
||||
You'll learn this by building it — not by reading theory.
|
||||
Prerequisites: Python 3.11, an OpenAI/Anthropic API key.
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| context | lead with |
|
||||
|---|---|
|
||||
| 매 docs landing page | audience + problem solved |
|
||||
| 매 function / class | why + when-to-use |
|
||||
| 매 commit / PR | why + what changed |
|
||||
| 매 LLM prompt | role + optimization target |
|
||||
| 매 meeting / pitch | problem + stakes |
|
||||
|
||||
**기본값**: 매 모든 explanation artifact 매 의 의 의 first 1-3 sentence 매 purpose 의 의 의 의 의 의 의 의 contain.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Technical Writing]]
|
||||
- 변형: [[BLUF (Bottom Line Up Front)]]
|
||||
- 응용: [[ADR]]
|
||||
- Adjacent: [[Pyramid Principle]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 docs / prompt / commit message / spec 의 의 write 시 매 의 의 의 항상.
|
||||
**언제 X**: 매 reference card / cheat-sheet — 매 lookup speed 매 priority 시 매 purpose 의 omit 매 가능.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **매 syntax-dump**: 매 use case 의 mention 매 X 매 raw API listing.
|
||||
- **매 buried lead**: 매 purpose 매 paragraph 5 매 의 의 의 hidden.
|
||||
- **매 fake why**: 매 marketing fluff ("revolutionary", "best-in-class") 매 의 의 의 actual purpose 의 의 의 의 substitute.
|
||||
- **매 over-justification**: 매 1-line task 매 5-paragraph rationale → 매 noise.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Sinek *Start With Why*, Diátaxis framework documentation, Google developer documentation style guide, ADR community).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — WHY/WHAT/HOW stack + Diátaxis alignment + 6 patterns |
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: wiki-2026-0508-코드-스멜-및-리팩토링-code-smells-and-ref
|
||||
title: 코드 스멜 및 리팩토링 (Code Smells and Refactoring)
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: code-smells-and-refactoring
|
||||
duplicate_of: "[[Code-Smells-and-Refactoring]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, code-smell, refactoring, programming]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 코드 스멜 및 리팩토링 (Code Smells and Refactoring)
|
||||
|
||||
> **이 문서는 [[Code-Smells-and-Refactoring]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- Fowler의 22 code smell 의 한국어 명명.
|
||||
- Long Method, Large Class, Feature Envy, Shotgun Surgery.
|
||||
- Refactoring catalog: 매 Extract/Inline/Move 의 의미.
|
||||
|
||||
## 🔗 Graph
|
||||
- 인접: [[SOLID 원칙]] · [[기본 타입에의 집착(Primitive Obsession)]]
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
id: wiki-2026-0508-크로스-플랫폼-cross-platform-아키텍처
|
||||
title: 크로스 플랫폼(Cross-Platform) 아키텍처
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: cross-platform-architecture
|
||||
duplicate_of: "[[Cross-Platform-Architecture]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, cross-platform, architecture]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 크로스 플랫폼(Cross-Platform) 아키텍처
|
||||
|
||||
> **이 문서는 [[Cross-Platform-Architecture]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- Mobile + PC + Console 동시 빌드 — single codebase + per-platform shim layer.
|
||||
- 매 abstraction layer (Unity/Unreal/Flutter) 의 한국어 설명.
|
||||
- Save/account sync, controller mapping, perf budget 차이.
|
||||
|
||||
## 🔗 Graph
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: wiki-2026-0508-풀-리퀘스트-및-이슈-트래커-pr-issue-tracker
|
||||
title: "풀 리퀘스트 및 이슈 트래커 (PR & Issue Tracker)"
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: pull-requests-and-issue-tracking
|
||||
duplicate_of: "[[Pull_Request_and_Issue_Tracking|Pull-Requests-and-Issue-Tracking]]"
|
||||
aliases: [PR Tracker]
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, pull-request, issue-tracker, devops]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 풀 리퀘스트 및 이슈 트래커 (PR & Issue Tracker)
|
||||
|
||||
> **이 문서는 [[Pull_Request_and_Issue_Tracking|Pull-Requests-and-Issue-Tracking]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- "트래커" 변형 — same canonical 문서의 한국어 alternate title.
|
||||
- GitHub Issues + Projects, Linear, Jira 의 매 standard stack.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Pull_Request_and_Issue_Tracking|Pull-Requests-and-Issue-Tracking]] (canonical)
|
||||
- 변형: [[풀_리퀘스트_및_이슈_트래킹_Pull_Requests_&_Issue_Tracking]]
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
---
|
||||
id: wiki-2026-0508-풀-리퀘스트-및-이슈-트래킹-pull-requests-is
|
||||
title: "풀 리퀘스트 및 이슈 트래킹 (Pull Requests & Issue Tracking)"
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: pull-requests-and-issue-tracking
|
||||
duplicate_of: "[[Pull_Request_and_Issue_Tracking|Pull-Requests-and-Issue-Tracking]]"
|
||||
aliases: [PR & Issues]
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, pull-request, issue-tracking, devops]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 풀 리퀘스트 및 이슈 트래킹 (Pull Requests & Issue Tracking)
|
||||
|
||||
> **이 문서는 [[Pull_Request_and_Issue_Tracking|Pull-Requests-and-Issue-Tracking]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- GitHub PR + Issues, Linear, Jira — 2026 standard stack.
|
||||
- Auto-link commit ↔ issue ↔ PR (GitFlow + Trunk-based).
|
||||
- LLM-augmented PR review (Claude Code, Codex).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Pull_Request_and_Issue_Tracking|Pull-Requests-and-Issue-Tracking]] (canonical)
|
||||
- 변형: [[풀_리퀘스트_및_이슈_트래커_PR_&_Issue_Tracker]]
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
Reference in New Issue
Block a user