[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
+159 -42
View File
@@ -2,66 +2,183 @@
id: wiki-2026-0508-inversion
title: Inversion
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-INVE-001]
aliases: [Inversion of Control, Invert Thinking, Negative Visualization]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-reinforced, inversion, Mental-Models, Problem-Solving, carl-jacobi, Strategy]
confidence_score: 0.85
verification_status: applied
tags: [thinking-model, ioc, di, mental-model, design]
raw_sources: []
last_reinforced: 2026-04-20
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: typescript
framework: nestjs
---
# [[Inversion|Inversion]]
# Inversion
## 📌 한 줄 통찰 (The Karpathy Summary)
> "거꾸로 생각하기: '어떻게 하면 성공할까?' 대신 '어떻게 하면 확실히 망할까?'를 먼저 물어봄으로써, 뒤집힌 관점을 통해 숨겨진 리스크를 찾아내고 실패의 요인을 사전에 제거하는 지적 소거법."
## 한 줄
> **"매 problem 의 reverse 매 stating — '매 fail 하는 방법' 의 enumerate, '매 control 의 누가 가지나' 의 flip"**. 매 Carl Jacobi "invert, always invert", 매 Charlie Munger 의 mental model, 매 software IoC/DI 의 design principle.
## 📖 구조화된 지식 (Synthesized Content)
인버전(Inversion)은 문제를 해결하기 위해 그 반대의 상황을 가정하는 사고 기법입니다. (카를 야코비의 "항상 거꾸로 생각하라"에서 기원)
## 매 핵심
1. **전술적 이점**:
* **Risk Mitigation**: 성공 전략은 수만 가지일 수 있지만, 실패 요인은 명확한 경우가 많음 (소거법).
* **Anti-[[goal|goal]] Setting**: 도달하고 싶은 곳이 아니라, 절대 가서는 안 될 곳을 설정하여 행동의 범위를 제약.
* **Cognitive [[Shift|Shift]]**: 뇌의 고착된 사고 회로를 강제로 뒤집어 새로운 통찰 유도.
2. **사례**:
* **Pre-mortem**: 프로젝트 시작 전 "망했다"고 가정하고 그 이유를 찾아보기.
* **Security**: "어떻게 하면 이 철통 보안을 뚫을 수 있을까?" 고민하는 화이트 해커의 시각.
### 매 Inversion 3 layer
- **Cognitive**: "매 success" 대신 "매 failure 의 path" 을 enumerate.
- **Architectural (IoC)**: caller 가 control 하던 것을 framework 가 control.
- **Dependency (DI)**: hard-coded `new Foo()` 대신 inject.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌**: 과거에는 긍정적인 확신 정책(Positive Thinking)만이 강조되었으나, 현대 정책은 최악의 상황 정책(Worst-case Scenario)을 먼저 관리하여 생존 가능성 정책을 높이는 인버전 정책이 더 강건하다고 평가함(RL Update). ([[Fault-Tolerance|Fault-Tolerance]]와 연결)
- **정책 변화(RL Update)**: 소프트웨어 개발 정책에서 'GOTO'를 금기시하고 구조화된 제어 정책을 쓰는 이유 역시, 디버깅 시 코드의 흐름을 거꾸로 추적(Inversion)하기 쉽게 만들기 위한 노력의 일환임. ([[Logic|Logic]]와 연결)
### 매 IoC 의 forms
- **DI**: constructor/setter inject.
- **Service Locator**: registry lookup.
- **Events/Hooks**: publish-subscribe.
- **Template Method**: framework 의 skeleton, user 의 fill-in.
## 🔗 지식 연결 (Graph)
- [[Logic|Logic]], [[Fault-Tolerance|Fault-Tolerance]], [[Complexity Theory|Complexity Theory]], [[Decision Theory|Decision Theory]], [[Cognitive Biases|Cognitive Biases]]
- **Modern Tech/Tools**: Charlie Munger's [[Mental Models|Mental Models]], Pre-mortem [[Analysis|Analysis]], Test-driven development (TDD).
---
### 매 응용
1. Design review: failure mode enumeration.
2. Testability: mock injection.
3. Decision making: 매 worst case 의 list, 매 avoid.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### NestJS DI
```ts
@Injectable()
export class UserRepo {
findById(id: string) { /* ... */ }
}
**언제 쓰면 안 되는가:**
- *(TODO)*
@Injectable()
export class UserService {
// 매 instance 매 직접 만들지 않음 — framework 의 inject
constructor(private readonly repo: UserRepo) {}
async profile(id: string) { return this.repo.findById(id); }
}
## 🧪 검증 상태 (Validation)
@Module({ providers: [UserRepo, UserService], exports: [UserService] })
export class UserModule {}
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Manual DI (no framework)
```ts
type Deps = { db: Database; cache: Cache; logger: Logger };
export const makeUserService = ({ db, cache, logger }: Deps) => ({
async findById(id: string) {
const cached = await cache.get(id);
if (cached) return cached;
logger.debug('cache miss', id);
return db.users.findUnique({ where: { id } });
}
});
```
## 🧬 중복 검사 (Duplicate Check)
### Premortem (failure inversion)
```ts
// scripts/premortem.ts
const failureModes = [
{ mode: 'DB connection lost', mitigation: 'retry + circuit breaker' },
{ mode: 'Cache stampede', mitigation: 'singleflight + jitter' },
{ mode: 'Memory leak in handler', mitigation: 'memray weekly + RSS alert' },
{ mode: 'Auth token expired mid-flow', mitigation: 'refresh interceptor' }
];
console.table(failureModes);
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Test seam via inversion
```ts
// 매 hard-coded fetch 대신 inject — testable
type Fetcher = (url: string) => Promise<Response>;
export const makeApi = (fetcher: Fetcher = fetch) => ({
async get(path: string) {
const r = await fetcher(`https://api.acme.com${path}`);
return r.json();
}
});
## 🕓 변경 이력 (Changelog)
// test
const fakeFetch: Fetcher = async () => new Response(JSON.stringify({ ok: true }));
expect(await makeApi(fakeFetch).get('/x')).toEqual({ ok: true });
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Hook-based extension (template inversion)
```ts
// framework 의 lifecycle, user 의 hook 의 plug
type Plugin = {
beforeRequest?: (req: Request) => Request;
afterResponse?: (res: Response) => Response;
};
export class Server {
private plugins: Plugin[] = [];
use(p: Plugin) { this.plugins.push(p); }
async handle(req: Request) {
for (const p of this.plugins) req = p.beforeRequest?.(req) ?? req;
let res = await this.process(req);
for (const p of this.plugins) res = p.afterResponse?.(res) ?? res;
return res;
}
}
```
### Inverted error handling (Result type)
```ts
// 매 throw 대신 매 return 으로 invert — caller 의 forced handle
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
export async function fetchUser(id: string): Promise<Result<User>> {
try {
const u = await db.users.findUniqueOrThrow({ where: { id } });
return { ok: true, value: u };
} catch (e) {
return { ok: false, error: e as Error };
}
}
```
### Decision premortem prompt
```ts
// 매 launch 전 self-question
const premortem = `
1. 매 launch 6 month 후, 이 기능 매 fail 했다고 가정.
2. 매 가장 가능한 5 failure cause 매 무엇?
3. 매 매 cause 의 mitigation 매 무엇?
`;
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Module 매 testable 만들기 | DI |
| Framework 의 design | IoC + plugin hooks |
| Decision making | Premortem (failure inversion) |
| Error handling | Result type (return invert) |
**기본값**: constructor DI + premortem 매 architecture review 시.
## 🔗 Graph
- 부모: [[Mental Models]] · [[Software Design Principles]]
- 변형: [[Dependency Injection]] · [[Inversion of Control]] · [[Premortem]]
- 응용: [[NestJS]] · [[Result Type]] · [[Plugin Architecture]]
- Adjacent: [[Encapsulation-via-Access-Modifiers]] · [[Testability]]
## 🤖 LLM 활용
**언제**: 매 design 의 failure mode 의 brainstorm, IoC refactor 의 candidate 식별.
**언제 X**: 매 trivial pure function 의 매 over-DI X — 매 simplicity 가 우선.
## ❌ 안티패턴
- **DI everywhere**: simple value 도 inject → 매 boilerplate explosion.
- **Service locator hell**: global registry 의 hidden dependency.
- **No premortem**: 매 ship 후에야 매 failure 발견.
- **Inversion theater**: interface 매 single impl 만 — 의 wrap 의 무의미.
## 🧪 검증 / 중복
- Verified (Charlie Munger "Poor Charlie's Almanack", Martin Fowler "IoC Containers").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — cognitive + IoC + DI inversion 통합 |