Files
2nd/10_Wiki/Topic_Programming/DevOps_and_Security/Inversion.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

5.5 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-inversion Inversion 10_Wiki/Topics verified self
Inversion of Control
Invert Thinking
Negative Visualization
none A 0.85 applied
thinking-model
ioc
di
mental-model
design
2026-05-10 pending
language framework
typescript nestjs

Inversion

매 한 줄

"매 problem 의 reverse 매 stating — '매 fail 하는 방법' 의 enumerate, '매 control 의 누가 가지나' 의 flip". 매 Carl Jacobi "invert, always invert", 매 Charlie Munger 의 mental model, 매 software IoC/DI 의 design principle.

매 핵심

매 Inversion 3 layer

  • Cognitive: "매 success" 대신 "매 failure 의 path" 을 enumerate.
  • Architectural (IoC): caller 가 control 하던 것을 framework 가 control.
  • Dependency (DI): hard-coded new Foo() 대신 inject.

매 IoC 의 forms

  • DI: constructor/setter inject.
  • Service Locator: registry lookup.
  • Events/Hooks: publish-subscribe.
  • Template Method: framework 의 skeleton, user 의 fill-in.

매 응용

  1. Design review: failure mode enumeration.
  2. Testability: mock injection.
  3. Decision making: 매 worst case 의 list, 매 avoid.

💻 패턴

NestJS DI

@Injectable()
export class UserRepo {
  findById(id: string) { /* ... */ }
}

@Injectable()
export class UserService {
  // 매 instance 매 직접 만들지 않음 — framework 의 inject
  constructor(private readonly repo: UserRepo) {}
  async profile(id: string) { return this.repo.findById(id); }
}

@Module({ providers: [UserRepo, UserService], exports: [UserService] })
export class UserModule {}

Manual DI (no framework)

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 } });
  }
});

Premortem (failure inversion)

// 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);

Test seam via inversion

// 매 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();
  }
});

// test
const fakeFetch: Fetcher = async () => new Response(JSON.stringify({ ok: true }));
expect(await makeApi(fakeFetch).get('/x')).toEqual({ ok: true });

Hook-based extension (template inversion)

// 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)

// 매 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

// 매 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

🤖 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 통합