chore(brain): ASTRA 성장 자산 동기화 — 기능 인벤토리·growth(약점프로필/학습큐)·일화기억·장기기억·회의록 원문
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
---
|
||||
id: wiki-2026-0508-analysis
|
||||
title: Analysis
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Data Analysis, Analytical Method]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [analysis, methodology, reasoning]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: pandas
|
||||
---
|
||||
|
||||
# Analysis
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 Analysis는 복잡한 whole를 component parts로 decompose하여 underlying structure를 understand하는 systematic process이다"**. Aristotle의 logical decomposition에서 시작하여, modern data science(2026)에서는 EDA, statistical inference, causal analysis까지 spectrum이 확장되었다. 매 핵심은 reduction 자체가 아니라, decomposition 후의 synthesis로 actionable insight를 도출하는 것.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 Analysis vs Synthesis
|
||||
- **Analysis**: top-down decomposition — whole → parts → relationships.
|
||||
- **Synthesis**: bottom-up integration — parts → whole.
|
||||
- 매 둘은 paired operation — analysis만 하면 fragmentation, synthesis만 하면 superficial generalization.
|
||||
|
||||
### 매 분석 dimensions
|
||||
- **Descriptive**: "무엇이 happened?" — summary statistics, distributions.
|
||||
- **Diagnostic**: "왜 happened?" — correlation, causal inference.
|
||||
- **Predictive**: "무엇이 happen할 것인가?" — forecasting models.
|
||||
- **Prescriptive**: "무엇을 해야 하나?" — optimization, decision theory.
|
||||
|
||||
### 매 응용
|
||||
1. EDA (Exploratory Data Analysis) — Tukey의 1977 framework, 매 modern DS의 first step.
|
||||
2. Root Cause Analysis — 5 Whys, fishbone, fault tree.
|
||||
3. Sensitivity Analysis — input perturbation으로 model robustness 측정.
|
||||
4. Failure Mode Analysis (FMEA) — engineering risk assessment.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### EDA quickstart (Polars 2026)
|
||||
```python
|
||||
import polars as pl
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
df = pl.read_parquet("data.parquet")
|
||||
print(df.schema)
|
||||
print(df.null_count())
|
||||
print(df.describe())
|
||||
|
||||
for col in df.select(pl.col(pl.NUMERIC_DTYPES)).columns:
|
||||
df[col].to_pandas().hist(bins=50)
|
||||
plt.title(col); plt.show()
|
||||
```
|
||||
|
||||
### Correlation matrix with significance
|
||||
```python
|
||||
import numpy as np
|
||||
from scipy import stats
|
||||
|
||||
def corr_with_pvalues(df):
|
||||
cols = df.select_dtypes(include=np.number).columns
|
||||
n = len(cols)
|
||||
corr = np.zeros((n, n)); pval = np.zeros((n, n))
|
||||
for i, a in enumerate(cols):
|
||||
for j, b in enumerate(cols):
|
||||
r, p = stats.pearsonr(df[a].dropna(), df[b].dropna())
|
||||
corr[i, j] = r; pval[i, j] = p
|
||||
return corr, pval
|
||||
```
|
||||
|
||||
### Causal analysis (DoWhy 2026)
|
||||
```python
|
||||
from dowhy import CausalModel
|
||||
|
||||
model = CausalModel(
|
||||
data=df,
|
||||
treatment="ad_spend",
|
||||
outcome="revenue",
|
||||
common_causes=["season", "channel", "brand"],
|
||||
)
|
||||
identified = model.identify_effect()
|
||||
estimate = model.estimate_effect(
|
||||
identified, method_name="backdoor.linear_regression"
|
||||
)
|
||||
refute = model.refute_estimate(
|
||||
identified, estimate, method_name="random_common_cause"
|
||||
)
|
||||
print(estimate.value, refute)
|
||||
```
|
||||
|
||||
### Sensitivity analysis (SALib)
|
||||
```python
|
||||
from SALib.sample import sobol
|
||||
from SALib.analyze import sobol as sobol_analyze
|
||||
|
||||
problem = {
|
||||
"num_vars": 3,
|
||||
"names": ["x1", "x2", "x3"],
|
||||
"bounds": [[0, 1]] * 3,
|
||||
}
|
||||
X = sobol.sample(problem, 1024)
|
||||
Y = np.array([model_fn(*x) for x in X])
|
||||
Si = sobol_analyze.analyze(problem, Y)
|
||||
print(Si["S1"], Si["ST"])
|
||||
```
|
||||
|
||||
### Failure Mode tabulation
|
||||
```python
|
||||
fmea = pl.DataFrame({
|
||||
"mode": ["timeout", "OOM", "race"],
|
||||
"severity": [7, 9, 8],
|
||||
"occurrence": [4, 2, 3],
|
||||
"detection": [5, 6, 9],
|
||||
})
|
||||
fmea = fmea.with_columns(
|
||||
(pl.col("severity") * pl.col("occurrence") * pl.col("detection")).alias("RPN")
|
||||
).sort("RPN", descending=True)
|
||||
```
|
||||
|
||||
### LLM-assisted analysis (Claude Opus 4.7)
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
|
||||
client = Anthropic()
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=2048,
|
||||
system="You are a senior data analyst. Output JSON: {findings, hypotheses, next_steps}.",
|
||||
messages=[{"role": "user", "content": f"Summary stats:\n{df.describe()}"}],
|
||||
)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| New dataset, no prior | EDA + descriptive |
|
||||
| Known outcome, want drivers | Diagnostic + causal |
|
||||
| Need forecast | Predictive ML |
|
||||
| Decision under uncertainty | Prescriptive + sensitivity |
|
||||
| Post-incident | Root cause + FMEA |
|
||||
|
||||
**기본값**: EDA first — 매 어떤 sophisticated method도 raw data 의 distribution 의 understanding 없이는 misleading하다.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Scientific Method]]
|
||||
- 변형: [[Exploratory Data Analysis]] · [[Causal Inference]] · [[Root Cause Analysis]]
|
||||
- 응용: [[Decision Making]] · [[Debugging]]
|
||||
- Adjacent: [[Synthesis]] · [[Statistics]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: hypothesis generation, summary narration, code scaffolding for analysis pipelines, anomaly explanation.
|
||||
**언제 X**: precise statistical inference (use proper tools), causal claims without proper identification, large-N numeric crunching (use pandas/polars not LLM).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Analysis paralysis**: 매 endless decomposition without synthesis — 의 decision 의 deferred.
|
||||
- **Confirmation bias**: 매 only analyzing data that supports prior hypothesis.
|
||||
- **Spurious correlation**: 매 correlation을 causation으로 confuse.
|
||||
- **Over-decomposition**: 매 component-level optimization 의 global suboptimum.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Tukey 1977 *Exploratory Data Analysis*; Pearl 2009 *Causality*).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content with 6 patterns + decision matrix |
|
||||
@@ -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,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 추가 |
|
||||
+195
@@ -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]] · [[Paged-Attention]]
|
||||
- 응용: [[LLM_Optimization_and_Deployment_Strategies|vLLM]]
|
||||
- Adjacent: [[Continuous-Batching]] · [[FlashAttention]]
|
||||
|
||||
## 🤖 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,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,140 @@
|
||||
---
|
||||
id: wiki-2026-0508-middle-out-thinking
|
||||
title: Middle Out Thinking
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Middle-Out Reasoning, Anchor-First Design]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [thinking, problem-solving, design]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: conceptual
|
||||
framework: methodology
|
||||
---
|
||||
|
||||
# Middle Out Thinking
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 problem-solving은 middle anchor에서 시작한다"**. 매 top-down (high-level vision)도 bottom-up (raw details)도 아닌, 매 가장 stable / well-understood 한 layer에서 양방향으로 expand 하는 reasoning approach. 매 Silicon Valley series 의 fictional compression 농담에서 시작해 매 product design / ML architecture / writing 의 real methodology 로 자리 잡았다.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 왜 middle 인가
|
||||
- Top-down: 매 vision 명확하지만 매 details 의 unknown 많음 → premature commitment.
|
||||
- Bottom-up: 매 details 견고하지만 매 coherence 부재 → integration hell.
|
||||
- Middle-out: 매 anchor (가장 잘 아는 layer) 부터 매 outward expansion → matched uncertainty.
|
||||
|
||||
### 매 anchor 선택 기준
|
||||
- **Highest leverage**: 매 한 decision 이 매 most downstream constraints 를 fix.
|
||||
- **Most certain**: 매 well-known domain / proven pattern.
|
||||
- **Bidirectional**: 매 위로 (abstraction)도 매 아래로 (implementation)도 expand 가능.
|
||||
|
||||
### 매 응용
|
||||
1. **Product**: MVP feature 매 core user job 부터 → upward (positioning), downward (UI tech).
|
||||
2. **ML architecture**: 매 backbone (e.g., Transformer block) 매 anchor → upward (training loop), downward (kernel ops).
|
||||
3. **Writing**: 매 thesis sentence 매 middle → upward (intro/conclusion), downward (evidence).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Anchor identification
|
||||
```python
|
||||
# Middle-out planning helper
|
||||
def identify_anchor(problem: dict) -> str:
|
||||
"""매 highest-leverage + most-certain layer 찾기."""
|
||||
candidates = problem["layers"]
|
||||
scored = [
|
||||
(layer, layer["leverage"] * layer["certainty"])
|
||||
for layer in candidates
|
||||
]
|
||||
scored.sort(key=lambda x: -x[1])
|
||||
return scored[0][0]["name"]
|
||||
```
|
||||
|
||||
### Bidirectional expansion
|
||||
```python
|
||||
def expand(anchor: str) -> dict:
|
||||
upward = derive_abstractions(anchor) # vision, goals
|
||||
downward = derive_implementations(anchor) # mechanisms
|
||||
return {"up": upward, "down": downward, "anchor": anchor}
|
||||
```
|
||||
|
||||
### Middle-out PR description
|
||||
```markdown
|
||||
## Anchor (middle)
|
||||
변경의 핵심: <one sentence>
|
||||
|
||||
## Up (why)
|
||||
- Business / product reason
|
||||
- User-facing impact
|
||||
|
||||
## Down (how)
|
||||
- Implementation detail 1
|
||||
- Implementation detail 2
|
||||
```
|
||||
|
||||
### Architecture sketch (ML)
|
||||
```python
|
||||
# Anchor: TransformerBlock
|
||||
class TransformerBlock(nn.Module):
|
||||
def __init__(self, d, h):
|
||||
super().__init__()
|
||||
self.attn = MultiHeadAttn(d, h)
|
||||
self.ff = FeedForward(d)
|
||||
def forward(self, x):
|
||||
return self.ff(self.attn(x))
|
||||
|
||||
# Up: stack into model
|
||||
# Down: choose attention kernel (FlashAttn vs naive)
|
||||
```
|
||||
|
||||
### Document outline tool
|
||||
```python
|
||||
def middle_out_outline(thesis: str):
|
||||
return {
|
||||
"thesis": thesis, # anchor
|
||||
"intro": "[derive from thesis]",
|
||||
"body": "[decompose thesis into 3 claims]",
|
||||
"conclusion": "[restate + extend]",
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 vision 명확, 매 details 의 unknown | Middle-out (anchor at known mid layer) |
|
||||
| 매 details 의 강제 (HW constraint) | Bottom-up |
|
||||
| 매 brand-new domain, 매 nothing known | Top-down + spike |
|
||||
| 매 refactor existing system | Middle-out (anchor at stable interface) |
|
||||
|
||||
**기본값**: Middle-out — 매 most realistic problems 에서 매 anchor 가 존재.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Problem_Solving|Problem-Solving]] · [[Design-Thinking]]
|
||||
- 변형: [[Top-Down-Design]] · [[Bottom-Up-Design]]
|
||||
- 응용: [[Minimal-Viable-Product]]
|
||||
- Adjacent: [[Pyramid-Principle]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 ambiguous spec 에서 매 LLM 에게 "what's the anchor?" 질문 → 매 most leveraged decision 부터 elaborate.
|
||||
**언제 X**: 매 trivial well-defined task — 매 직접 implementation 이 빠름.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Anchor too high**: 매 vision-level anchor → 매 bottom-up과 동일하게 details 폭발.
|
||||
- **Anchor too low**: 매 implementation-level anchor → 매 top-down 부재로 coherence 상실.
|
||||
- **Multiple anchors**: 매 simultaneous 의 multiple middle 선택 → 매 expansion conflict.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Pyramid Principle, Minto 1987; Architectural Decision Records practice).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — anchor-first reasoning methodology with bidirectional expansion |
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
---
|
||||
id: wiki-2026-0508-minimal-viable-product
|
||||
title: Minimal Viable Product
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [MVP, Minimum Viable Product]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [product, lean-startup, validation]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: conceptual
|
||||
framework: lean-startup
|
||||
---
|
||||
|
||||
# Minimal Viable Product (MVP)
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 학습 단위로서의 가장 작은 product"**. 매 Eric Ries (2011) 가 정의한 MVP 는 매 customer hypothesis 를 매 minimum effort 로 validate 하는 product version. 매 2026 의 MVP 는 매 AI-augmented prototyping (Claude Opus, Replit Agent) 으로 매 days-not-weeks scale.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 MVP 의 진짜 의미
|
||||
- **Minimum**: 매 build effort 의 minimization (X feature count).
|
||||
- **Viable**: 매 real user 의 real job 을 매 end-to-end 수행 가능.
|
||||
- **Product**: 매 learning vehicle — 매 metric capture 가능해야.
|
||||
|
||||
### 매 MVP 의 X
|
||||
- 매 buggy half-product (X — viable 아님).
|
||||
- 매 feature-complete v1 (X — minimum 아님).
|
||||
- 매 internal demo (X — product 아님, no users).
|
||||
|
||||
### 매 응용
|
||||
1. **Concierge MVP**: 매 manual backend, 매 user 는 magic UX 로 인식.
|
||||
2. **Wizard-of-Oz**: 매 fake automation, 매 human-in-loop.
|
||||
3. **Landing page**: 매 product X, 매 demand signal capture only.
|
||||
4. **Single-feature**: 매 one core job, 매 polished.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Hypothesis canvas
|
||||
```yaml
|
||||
mvp:
|
||||
hypothesis: "User X will pay $Y for solving Z"
|
||||
riskiest_assumption: "User X actually has problem Z"
|
||||
minimum_test:
|
||||
type: landing_page
|
||||
success_metric: "100 sign-ups in 7 days"
|
||||
kill_metric: "<10 sign-ups → pivot"
|
||||
```
|
||||
|
||||
### Concierge MVP scaffold
|
||||
```python
|
||||
# Fake the backend, learn from real users
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
@app.post("/recommend")
|
||||
async def recommend(user_query: str):
|
||||
# MVP: send query to founder's phone
|
||||
await sms_to_founder(user_query)
|
||||
# Founder manually crafts recommendation
|
||||
response = await wait_for_founder_reply()
|
||||
return {"recommendation": response}
|
||||
```
|
||||
|
||||
### Build-Measure-Learn loop
|
||||
```python
|
||||
class MVPCycle:
|
||||
def __init__(self, hypothesis):
|
||||
self.hypothesis = hypothesis
|
||||
def build(self): # smallest experiment
|
||||
return prototype(self.hypothesis)
|
||||
def measure(self, prototype, n_users=20):
|
||||
return collect_metrics(prototype, n_users)
|
||||
def learn(self, metrics):
|
||||
if metrics["activation"] > 0.4:
|
||||
return "persevere"
|
||||
return "pivot"
|
||||
```
|
||||
|
||||
### AI-augmented MVP (2026)
|
||||
```bash
|
||||
# Claude Code + Replit Agent stack
|
||||
claude-code "build MVP for <hypothesis>" --scaffold next.js
|
||||
# Days-not-weeks: AI generates 80% boilerplate
|
||||
```
|
||||
|
||||
### Kill criteria gate
|
||||
```python
|
||||
def should_kill(metrics: dict, kill_threshold: dict) -> bool:
|
||||
"""매 honest evaluation — sunk cost ignore."""
|
||||
return all(
|
||||
metrics[k] < kill_threshold[k]
|
||||
for k in kill_threshold
|
||||
)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | MVP type |
|
||||
|---|---|
|
||||
| 매 demand 의 unknown | Landing page |
|
||||
| 매 UX 의 unknown, backend 매 hard | Concierge / Wizard-of-Oz |
|
||||
| 매 demand 매 confirmed, 매 build feasible | Single-feature MVP |
|
||||
| 매 enterprise B2B | Design partner pilot (X cold MVP) |
|
||||
|
||||
**기본값**: Landing page → Concierge → Single-feature 의 progression.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Lean-Startup]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 hypothesis articulation, 매 riskiest assumption 의 surfacing, 매 MVP scaffold generation.
|
||||
**언제 X**: 매 already-validated product 의 v2 — MVP framing 의 X.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Feature creep MVP**: 매 minimum 무시 → 매 8주 build, 매 launch 실패.
|
||||
- **Vanity metrics**: 매 page views / signups 만 측정 → activation / retention X.
|
||||
- **No kill criteria**: 매 sunk cost trap.
|
||||
- **MVP = bad quality**: 매 minimum 은 scope, X quality.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Ries 2011 *The Lean Startup*; Blank *Four Steps to the Epiphany*).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — MVP types, build-measure-learn, AI-augmented 2026 stack |
|
||||
@@ -0,0 +1,144 @@
|
||||
---
|
||||
id: wiki-2026-0508-neuroergonomics
|
||||
title: Neuroergonomics
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Neuro-Ergonomics, Brain at Work, Cognitive Ergonomics]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [neuroergonomics, hci, cognitive-load, fnirs, eeg]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: mne-python
|
||||
---
|
||||
|
||||
# Neuroergonomics
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 brain at work — 매 neural signals 의 measure, 매 system 의 adapt"**. 매 2003 Parasuraman 의 coin, 매 fNIRS/EEG/eye-tracking 의 mature. 매 2026 의 closed-loop adaptive systems (cockpits, surgery, AR work) 의 deploy.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 measurement modalities
|
||||
- **EEG**: 매 ms-level temporal resolution. 매 cognitive load 의 alpha-suppression / theta-Fz 의 marker.
|
||||
- **fNIRS**: 매 cortex hemodynamics. 매 portable, motion-tolerant — 매 real-world 의 work.
|
||||
- **Eye tracking**: 매 fixation duration, pupil dilation — 매 mental effort 의 proxy.
|
||||
- **HRV / GSR**: 매 ANS arousal — 매 stress / engagement.
|
||||
|
||||
### 매 cognitive states 의 detect
|
||||
- **Workload**: 매 over-load → 매 error spike. 매 under-load → 매 vigilance drop.
|
||||
- **Vigilance / fatigue**: 매 P300 amplitude decline + theta increase.
|
||||
- **Engagement / flow**: 매 mid-frontal theta + alpha asymmetry.
|
||||
|
||||
### 매 응용
|
||||
1. 매 adaptive cockpit (Airbus, Honeywell): 매 pilot workload 의 high → 매 secondary task 의 defer.
|
||||
2. 매 surgical training: 매 trainee fNIRS prefrontal 의 over-activation = novice marker.
|
||||
3. 매 driver-state monitoring (Tesla v13, Mercedes Drive Pilot): 매 EEG drowsiness 의 detect.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### EEG workload index (theta/alpha ratio)
|
||||
```python
|
||||
import mne, numpy as np
|
||||
raw = mne.io.read_raw_brainvision('subj.vhdr', preload=True)
|
||||
raw.filter(1, 40)
|
||||
psd = raw.compute_psd(fmin=4, fmax=12, picks=['Fz', 'Pz'])
|
||||
freqs = psd.freqs
|
||||
power = psd.get_data() # (channels, freqs)
|
||||
theta = power[:, (freqs >= 4) & (freqs < 8)].mean(axis=1)
|
||||
alpha = power[:, (freqs >= 8) & (freqs < 13)].mean(axis=1)
|
||||
workload_index = theta / alpha # higher = more load
|
||||
```
|
||||
|
||||
### fNIRS prefrontal activation (MNE-NIRS)
|
||||
```python
|
||||
from mne_nirs.experimental_design import make_first_level_design_matrix
|
||||
from mne_nirs.statistics import run_glm
|
||||
raw_haemo = mne.preprocessing.nirs.beer_lambert_law(raw_od, ppf=0.1)
|
||||
design = make_first_level_design_matrix(raw_haemo, drift_model='cosine')
|
||||
glm = run_glm(raw_haemo, design)
|
||||
# beta for HbO in PFC channels = task-evoked activation
|
||||
pfc_activation = glm.to_dataframe().query("ch_name.str.contains('S1_D1') & Chroma=='hbo'")
|
||||
```
|
||||
|
||||
### Pupil-based effort (PsychoPy + Pupil Labs)
|
||||
```python
|
||||
import zmq, msgpack
|
||||
ctx = zmq.Context(); sub = ctx.socket(zmq.SUB)
|
||||
sub.connect('tcp://127.0.0.1:50020'); sub.setsockopt_string(zmq.SUBSCRIBE, 'pupil')
|
||||
while True:
|
||||
topic, payload = sub.recv_multipart()
|
||||
msg = msgpack.unpackb(payload)
|
||||
if msg['confidence'] > 0.8:
|
||||
diameter_mm = msg['diameter_3d']
|
||||
# baseline-corrected pupil dilation = effort proxy
|
||||
```
|
||||
|
||||
### Closed-loop adaptive UI (workload-triggered)
|
||||
```python
|
||||
class AdaptiveDashboard:
|
||||
def tick(self, workload_idx: float):
|
||||
if workload_idx > 1.5: # high load
|
||||
self.hide_secondary_widgets()
|
||||
self.enlarge_primary_alert()
|
||||
elif workload_idx < 0.6: # under-load → boredom
|
||||
self.inject_status_check()
|
||||
else:
|
||||
self.restore_default()
|
||||
```
|
||||
|
||||
### Drowsiness detector (real-time EEG)
|
||||
```python
|
||||
from scipy.signal import welch
|
||||
def is_drowsy(eeg_window, fs=256):
|
||||
f, P = welch(eeg_window, fs=fs, nperseg=fs*2)
|
||||
theta = P[(f>=4)&(f<8)].mean()
|
||||
beta = P[(f>=13)&(f<30)].mean()
|
||||
return (theta / beta) > 4.0 # KSS-validated threshold
|
||||
```
|
||||
|
||||
### NASA-TLX subjective + neural fusion
|
||||
```python
|
||||
def fused_workload(neural_idx: float, tlx_score: float) -> float:
|
||||
# weight neural higher when within-subject calibrated
|
||||
return 0.6 * neural_idx_z + 0.4 * (tlx_score / 100)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Lab, high precision needed | EEG (32-64ch) + eye-track |
|
||||
| Field / mobile work | fNIRS + wearable HRV |
|
||||
| Driver / pilot | Webcam-pupil + steering-entropy + PERCLOS |
|
||||
| Long shift fatigue | Actigraphy + HRV + PVT |
|
||||
|
||||
**기본값**: fNIRS + eye-tracking — 매 real-world ecological validity 의 best.
|
||||
|
||||
## 🔗 Graph
|
||||
- 변형: [[Affective-Computing]] · [[Brain-Computer-Interface]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 study design review, 매 GLM script generation, 매 multimodal-feature engineering, 매 paper synthesis.
|
||||
**언제 X**: 매 raw artifact rejection, 매 individual-subject calibration — 매 expert review 의 require.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Single-modality reliance**: 매 EEG-only 의 motion artifact 에 fragile. 매 fusion 의 require.
|
||||
- **No baseline**: 매 absolute power 의 between-subject 의 noisy. 매 within-subject z-score 의 use.
|
||||
- **Open-loop dashboard**: 매 measure-but-not-act → 매 value 의 zero. 매 closed-loop 의 design.
|
||||
- **No personalization**: 매 group-mean threshold 의 50% individuals 에 wrong.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Parasuraman & Rizzo 2007 *Neuroergonomics*; Ayaz & Dehais 2019).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — modalities + closed-loop adaptive patterns |
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
---
|
||||
id: wiki-2026-0508-neuroplasticity-in-addiction
|
||||
title: Neuroplasticity in Addiction
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Addiction Plasticity, Reward Learning Plasticity, Drug-Induced LTP]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [neuroplasticity, addiction, dopamine, ltp, mesolimbic]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: brian2-rl
|
||||
---
|
||||
|
||||
# Neuroplasticity in Addiction
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 reward 의 hijack — 매 mesolimbic LTP 의 maladaptive learning"**. 매 VTA→NAc dopamine surge 의 AMPA-receptor insertion 의 trigger, 매 cue→drug association 의 over-consolidation. 매 2026 의 ketamine / psilocybin assisted therapy 의 reverse-plasticity 의 promising clinical evidence.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 circuits
|
||||
- **Mesolimbic (VTA→NAc)**: 매 reward prediction error → 매 reinforcement.
|
||||
- **Mesocortical (VTA→mPFC)**: 매 craving, executive control 의 erode.
|
||||
- **Amygdala→NAc**: 매 cue-conditioning, withdrawal-anxiety.
|
||||
- **Hippocampus→NAc**: 매 contextual cues.
|
||||
|
||||
### 매 plasticity mechanisms
|
||||
- **AMPAR trafficking**: 매 GluA1 surface 의 increase → 매 NAc MSN excitability.
|
||||
- **Silent synapses**: 매 NMDAR-only 의 cocaine 후 의 unsilencing.
|
||||
- **Dendritic spines**: 매 stimulants → 매 spine density 의 increase. 매 opioids → 매 decrease.
|
||||
- **Epigenetic** (ΔFosB, HDAC5): 매 long-term gene-expression 의 lock-in.
|
||||
|
||||
### 매 응용
|
||||
1. 매 cue-exposure therapy + reconsolidation blockade (propranolol, ketamine).
|
||||
2. 매 TMS / DBS (NAc, sgACC) 의 craving reduction.
|
||||
3. 매 contingency management + digital phenotyping.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Q-learning model fit (drug-bias parameter)
|
||||
```python
|
||||
import numpy as np
|
||||
def q_learn_ll(choices, rewards, alpha=0.3, beta=5.0):
|
||||
Q = np.zeros(2); ll = 0.0
|
||||
for c, r in zip(choices, rewards):
|
||||
p = np.exp(beta*Q) / np.exp(beta*Q).sum()
|
||||
ll += np.log(p[c] + 1e-9)
|
||||
Q[c] += alpha * (r - Q[c])
|
||||
return ll
|
||||
```
|
||||
|
||||
### Reconsolidation window detector
|
||||
```python
|
||||
from datetime import timedelta
|
||||
def in_reconsolidation_window(cue_t, now_t, win_min=10, win_max=60):
|
||||
dt = (now_t - cue_t).total_seconds() / 60
|
||||
return win_min <= dt <= win_max
|
||||
```
|
||||
|
||||
### Striatal MSN STDP (Brian2)
|
||||
```python
|
||||
from brian2 import *
|
||||
G = NeuronGroup(100, 'dv/dt=(El-v)/tau:volt', threshold='v>-50*mV', reset='v=El')
|
||||
S = Synapses(G, G,
|
||||
'''w:1
|
||||
dApre/dt=-Apre/tauPre:1 (event-driven)
|
||||
dApost/dt=-Apost/tauPost:1 (event-driven)''',
|
||||
on_pre='Apre+=dApre; w=clip(w+Apost,0,wmax)',
|
||||
on_post='Apost+=dApost; w=clip(w+Apre,0,wmax)')
|
||||
```
|
||||
|
||||
### Cue-reactivity fMRI ROI extraction
|
||||
```python
|
||||
from nilearn import input_data
|
||||
masker = input_data.NiftiMasker(mask_img='nac_left.nii.gz', standardize=True)
|
||||
ts = masker.fit_transform('subject_task.nii.gz')
|
||||
craving_corr = np.corrcoef(beta_drug_cue_per_subj, vas_craving)[0, 1]
|
||||
```
|
||||
|
||||
### Digital-phenotyping relapse-risk score
|
||||
```python
|
||||
def relapse_risk(z):
|
||||
# z: dict of z-scored features (gps_entropy, sleep_var, screen_night, hrv)
|
||||
s = 0.4*z['gps_entropy'] + 0.3*z['sleep_var'] \
|
||||
+ 0.2*z['screen_night'] - 0.1*z['hrv']
|
||||
return 1 / (1 + np.exp(-s))
|
||||
```
|
||||
|
||||
### Ketamine plasticity-window dosing protocol stub
|
||||
```python
|
||||
from datetime import timedelta
|
||||
class KetamineProtocol:
|
||||
window_h = 24 # BDNF / mTOR peak
|
||||
def schedule_therapy(self, infusion_t):
|
||||
return infusion_t + timedelta(hours=2)
|
||||
```
|
||||
|
||||
### TMS dlPFC craving protocol
|
||||
```python
|
||||
def tms_session():
|
||||
return dict(target='left_dlPFC', frequency_hz=10,
|
||||
trains=20, pulses_per_train=50,
|
||||
inter_train_s=20, intensity_pct_rmt=110)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Intervention |
|
||||
|---|---|
|
||||
| Acute craving | TMS dlPFC 10 Hz |
|
||||
| Treatment-resistant | DBS NAc (case-by-case) |
|
||||
| Comorbid depression | Ketamine + therapy |
|
||||
| Stimulant-use disorder | Contingency management + counseling |
|
||||
| Opioid-use disorder | Buprenorphine + therapy |
|
||||
|
||||
**기본값**: CBT + medication + digital tools — 매 multimodal 의 best evidence.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Neuroplasticity]] · [[Addiction-Neuroscience]]
|
||||
- 변형: [[Reward-Prediction-Error]]
|
||||
- Adjacent: [[Mesolimbic-Pathway]] · [[Dopamine-System]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 mechanism teaching, 매 protocol scaffold, 매 patient-education content.
|
||||
**언제 X**: 매 clinical decision making — 매 licensed clinician 의 require.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Plasticity = bad**: 매 plasticity itself 의 healing 의 vehicle.
|
||||
- **Single-receptor focus**: 매 D2-only blockade 의 outcomes 의 weak. 매 circuit-level 의 think.
|
||||
- **Reconsolidation hype**: 매 window narrow, 매 boundary conditions 의 strict.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Lüscher & Malenka 2011 *Neuron*; Kalivas & Volkow 2005).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — circuits + reversal-therapy patterns |
|
||||
@@ -0,0 +1,181 @@
|
||||
---
|
||||
id: wiki-2026-0508-protocols
|
||||
title: Protocols
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Communication Protocols, Network Protocols, Wire Protocols]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [networking, protocols, systems, MCP]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: multi
|
||||
framework: HTTP-gRPC-MCP
|
||||
---
|
||||
|
||||
# Protocols
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 communicating parties 가 매 따라야 하는 rules 의 명시"**. 매 syntax (frame format), 매 semantics (meaning of fields), 매 timing (sequencing) 의 3 axes 로 정의. 매 2026 의 hot stack: HTTP/3 (QUIC), gRPC, MCP (Model Context Protocol), WebSocket, MQTT 5.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 protocol 의 layers
|
||||
- **Physical / Link**: Ethernet, Wi-Fi 7, 5G NR.
|
||||
- **Network**: IPv6 (default 2026), IPv4 legacy.
|
||||
- **Transport**: TCP, UDP, QUIC.
|
||||
- **Application**: HTTP/3, gRPC, MCP, MQTT, AMQP.
|
||||
|
||||
### 매 design dimensions
|
||||
- **Stateful vs stateless**: 매 server-side state 보관 여부.
|
||||
- **Sync vs async**: 매 request-response vs publish-subscribe.
|
||||
- **Push vs pull**: 매 server-initiated vs client-initiated.
|
||||
- **Text vs binary**: 매 human-readable vs efficient.
|
||||
- **Versioning**: 매 backward / forward compatibility 의 strategy.
|
||||
|
||||
### 매 응용
|
||||
1. **Web**: HTTP/3 over QUIC — 매 default.
|
||||
2. **AI tools**: MCP (Anthropic 2024) 매 LLM ↔ tool 의 universal.
|
||||
3. **Microservices**: gRPC 매 internal RPC.
|
||||
4. **IoT**: MQTT 5 매 lightweight pub-sub.
|
||||
5. **Realtime**: WebSocket / WebTransport.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### MCP server (Anthropic, 2026 standard)
|
||||
```python
|
||||
from mcp.server import Server
|
||||
from mcp.types import Tool, TextContent
|
||||
|
||||
server = Server("knowledge-base")
|
||||
|
||||
@server.list_tools()
|
||||
async def tools():
|
||||
return [Tool(
|
||||
name="query",
|
||||
description="Query the KB",
|
||||
inputSchema={
|
||||
"type": "object",
|
||||
"properties": {"q": {"type": "string"}},
|
||||
"required": ["q"],
|
||||
},
|
||||
)]
|
||||
|
||||
@server.call_tool()
|
||||
async def call(name, args):
|
||||
return [TextContent(type="text", text=search(args["q"]))]
|
||||
```
|
||||
|
||||
### gRPC service (.proto + Python)
|
||||
```protobuf
|
||||
// kb.proto
|
||||
syntax = "proto3";
|
||||
service KB {
|
||||
rpc Query(QueryRequest) returns (stream QueryChunk);
|
||||
}
|
||||
message QueryRequest { string q = 1; }
|
||||
message QueryChunk { string text = 1; bool done = 2; }
|
||||
```
|
||||
|
||||
```python
|
||||
# server.py
|
||||
import grpc, kb_pb2_grpc, kb_pb2
|
||||
|
||||
class KBServicer(kb_pb2_grpc.KBServicer):
|
||||
def Query(self, request, context):
|
||||
for chunk in stream_search(request.q):
|
||||
yield kb_pb2.QueryChunk(text=chunk, done=False)
|
||||
yield kb_pb2.QueryChunk(done=True)
|
||||
```
|
||||
|
||||
### HTTP/3 client (QUIC)
|
||||
```python
|
||||
# httpx + h2/h3
|
||||
import httpx
|
||||
|
||||
async with httpx.AsyncClient(http2=True, http3=True) as client:
|
||||
r = await client.get("https://api.example.com/v1/users")
|
||||
print(r.http_version) # "HTTP/3"
|
||||
```
|
||||
|
||||
### WebSocket realtime
|
||||
```python
|
||||
import asyncio
|
||||
import websockets
|
||||
|
||||
async def handler(ws):
|
||||
async for msg in ws:
|
||||
await ws.send(f"echo: {msg}")
|
||||
|
||||
async def main():
|
||||
async with websockets.serve(handler, "0.0.0.0", 8765):
|
||||
await asyncio.Future() # run forever
|
||||
```
|
||||
|
||||
### MQTT 5 pub-sub (IoT)
|
||||
```python
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
def on_message(client, userdata, msg):
|
||||
print(f"{msg.topic}: {msg.payload.decode()}")
|
||||
|
||||
client = mqtt.Client(protocol=mqtt.MQTTv5)
|
||||
client.on_message = on_message
|
||||
client.connect("broker.example.com", 1883)
|
||||
client.subscribe("sensors/+/temperature")
|
||||
client.loop_forever()
|
||||
```
|
||||
|
||||
### Protocol negotiation (capabilities handshake)
|
||||
```python
|
||||
# Common pattern: client sends supported versions, server picks highest mutual
|
||||
def negotiate(client_versions: set[str], server_versions: set[str]) -> str:
|
||||
common = client_versions & server_versions
|
||||
if not common:
|
||||
raise ProtocolError("no compatible version")
|
||||
return max(common, key=lambda v: tuple(map(int, v.split("."))))
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| Scenario | Protocol |
|
||||
|---|---|
|
||||
| 매 LLM ↔ tools | MCP |
|
||||
| 매 internal RPC, polyglot | gRPC over HTTP/2 |
|
||||
| 매 public web API | HTTP/3 + JSON / OpenAPI |
|
||||
| 매 realtime browser | WebSocket / WebTransport |
|
||||
| 매 IoT constrained | MQTT 5 / CoAP |
|
||||
| 매 message queue | AMQP 1.0 / Kafka |
|
||||
| 매 streaming chat | Server-Sent Events / WebSocket |
|
||||
|
||||
**기본값**: 매 public = HTTP/3 + JSON, 매 internal = gRPC, 매 LLM tools = MCP.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Distributed-Systems]]
|
||||
- 변형: [[HTTP]] · [[gRPC]] · [[MCP]]
|
||||
- 응용: [[API-Design]] · [[Microservices]] · [[클라우드_인프라_및_IaC_운영_표준|IoT]]
|
||||
- Adjacent: [[Interoperability]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 protocol selection, 매 wire format debugging, 매 backward-compat strategy review.
|
||||
**언제 X**: 매 single-process in-memory calls — 매 protocol 무용.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Custom snowflake protocol**: 매 in-house wire format 매 ecosystem 의 X.
|
||||
- **No version negotiation**: 매 deploy mismatch → cascade failure.
|
||||
- **Stateful with no session**: 매 load balancer 매 sticky session 강제 → scaling pain.
|
||||
- **Chatty protocols**: 매 N round trips 매 single op → latency.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (RFC 9114 HTTP/3, 9000 QUIC; gRPC.io; Anthropic MCP spec 2024; OASIS MQTT 5; OASIS AMQP 1.0).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — protocol layers + 2026 modern stack (MCP, HTTP/3, gRPC) |
|
||||
+190
@@ -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]] · [[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]]
|
||||
|
||||
## 🤖 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,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]] · [[Node-js]] · [[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,34 @@
|
||||
---
|
||||
id: wiki-2026-0508-메타-레이어-meta-layers
|
||||
title: 메타 레이어 (Meta Layers)
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: meta-layers
|
||||
duplicate_of: "[[Meta Layers]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, game-design, meta-game, systems]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 메타 레이어 (Meta Layers)
|
||||
|
||||
> **이 문서는 [[Meta Layers]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약 (specialization aspects)
|
||||
- 매 meta layer: core gameplay loop 위에 매 stacked progression/strategy systems — 매 long-term engagement 의 driver.
|
||||
- 매 examples: MMO seasons/expansions, MOBA patch meta, roguelike unlock trees, gacha banner rotations.
|
||||
- 매 design tension: meta refresh frequency ↔ player burnout, depth ↔ accessibility for new players.
|
||||
- 매 2026 trend: AI-generated dynamic meta (procedural balance shifts), live-ops-driven micro-metas.
|
||||
|
||||
## 🔗 Graph
|
||||
- 관련: [[Live Ops]] · [[Player Retention]]
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: wiki-2026-0508-모바일-퍼스트-인덱싱-mobile-first-indexin
|
||||
title: 모바일 퍼스트 인덱싱(Mobile-First Indexing)
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: mobile-first-indexing
|
||||
duplicate_of: "[[Mobile-First Indexing]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, seo, web]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 모바일 퍼스트 인덱싱(Mobile-First Indexing)
|
||||
|
||||
> **이 문서는 [[Mobile-First Indexing]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- Google 의 mobile 버전 사이트를 primary index source 로 사용 (2023 부터 default).
|
||||
- Mobile UX / Core Web Vitals (LCP, INP, CLS) 가 ranking 핵심 요소.
|
||||
- Responsive design + 동일 content (mobile = desktop) 가 권장 pattern.
|
||||
|
||||
## 🔗 Graph
|
||||
- Adjacent: [[Core Web Vitals Optimization (INP, LCP 개선)|Cumulative Layout Shift (CLS)]] · [[Core Web Vitals Optimization (INP, LCP 개선)|Core Web Vitals]]
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
---
|
||||
id: wiki-2026-0508-코드베이스-맵과-대화형-투어-codebase-maps-in
|
||||
title: "코드베이스 맵과 대화형 투어 (Codebase Maps & Interactive Tours)"
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: codebase-maps-and-interactive-tours
|
||||
duplicate_of: "[[Codebase-Maps-and-Interactive-Tours]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, codebase, onboarding, documentation]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 코드베이스 맵과 대화형 투어 (Codebase Maps & Interactive Tours)
|
||||
|
||||
> **이 문서는 [[Codebase-Maps-and-Interactive-Tours]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- Onboarding 가속: 매 new dev 의 module dependency 이해 단축.
|
||||
- CodeTour (VS Code), Sourcegraph, Cursor — 2026 tooling stack.
|
||||
- LLM-augmented walkthrough: Claude Opus 4.7 inline explanation.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Codebase-Maps-and-Interactive-Tours]] (canonical)
|
||||
- 인접: [[Pull_Request_and_Issue_Tracking|Pull-Requests-and-Issue-Tracking]]
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: wiki-2026-0508-텔레메트리-데이터-telemetry-data
|
||||
title: 텔레메트리 데이터 (Telemetry Data)
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: telemetry-data
|
||||
duplicate_of: "[[Telemetry-Data]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, telemetry, data, analytics]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 텔레메트리 데이터 (Telemetry Data)
|
||||
|
||||
> **이 문서는 [[Telemetry-Data]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- Event log: 매 client/server emission → analytics warehouse.
|
||||
- 매 funnel/cohort/retention 분석의 raw input.
|
||||
- ClickHouse, BigQuery, Snowflake — 2026 modern stack.
|
||||
|
||||
## 🔗 Graph
|
||||
- 변형: [[텔레메트리 (Telemetry).]] · [[텔레메트리(Telemetry) 데이터 분석]]
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
Reference in New Issue
Block a user