[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
@@ -2,109 +2,166 @@
id: wiki-2026-0508-program-comprehension-strategies
title: Program Comprehension Strategies
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Code Reading, Code Comprehension, Mental Models of Code]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [software-engineering, cognition, code-review, onboarding]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: multi
framework: cognitive-software-engineering
---
# Program Comprehension Strategies (프로그램 이해 전략)
# Program Comprehension Strategies
## 📌 한 줄 통찰 (The Karpathy Summary)
프로그램 이해 전략(Program Comprehension Strategies)은 개발자가 기존 소스 코드를 유지보수하거나 확장하기 위해 코드를 읽고 그 논리적 구조와 설계 의도를 파악하는 인지적 과정(Cognitive Process)을 정의한 방법론입니다 [1-3]. 이 과정은 단순히 구문을 읽는 행위를 넘어, 코드라는 외부 표현을 개발자의 내면화된 '정신 모델(Mental Model)'로 매핑하는 고도의 지적 활동입니다 [1, 4]. 개발자는 코드의 익숙함과 전문성에 따라 하향식(Top-Down), 상향식(Bottom-Up), 그리고 이들을 유연하게 혼합한 통합적/기회주의적(Opportunistic) 전략을 선택적으로 사용합니다 [6-9].
## 한 줄
> **"매 90% of programming is reading code, not writing it."**. 매 Brooks (1983), Pennington (1987), Soloway (1986) 의 cognitive software engineering 연구에서 출발한 매 분야 — 매 code → mental model 변환의 strategies. 매 2026 LLM 시대에는 매 Cursor/Claude Code 의 contextual indexing 이 매 human comprehension 을 augment.
## 📖 구조화된 지식 (Synthesized Content)
프로그램 이해 모델은 개발자가 코드에서 '무엇(What)', '어떻게(How)', '왜(Why)'를 추출하는 방식을 체계화한 3대 핵심 프레임워크로 구성됩니다.
## 매 핵심
* **하향식 이해 모델 (Top-Down Models - Brooks, Soloway & Ehrlich):**
* **전제 조건:** 개발자가 시스템 아키텍처나 도메인 지식에 익숙할 때 주로 사용합니다 [19-21].
* **메커니즘:** 시스템의 전체 목적에 대한 가설(Hypothesis)을 먼저 세우고, 코드 내에서 이를 뒷받침하는 단서인 '비컨(Beacons)'과 전형적인 구조인 '프로그래밍 계획(Programming Plans)'을 찾아 가설을 검증하며 하위 수준으로 구체화합니다 [21-23].
* **상향식 이해 모델 (Bottom-Up Models - Pennington, Shneiderman):**
* **전제 조건:** 코드가 낯설거나 새로운 언어/프레임워크를 접할 때 사용합니다 [24, 25].
* **메커니즘:** 개별 구문과 제어 흐름(마이크로 구조)을 먼저 읽어 '프로그램 모델(Program Model)'을 구축한 후, 이를 기능적 의미가 담긴 '상황 모델(Situation Model)'로 '청킹(Chunking)'하여 상향식으로 결합합니다 [25-28].
* **통합 및 기회주의적 전략 (Integrated/Opportunistic Models - Letovsky, Mayrhauser & Vans):**
* **전제 조건:** 실제 복잡한 대규모 레거시 시스템 유지보수 환경에서 사용됩니다 [29-31].
* **메커니즘:** 개발자는 고정된 방향 없이 가설 검증과 세부 구현 파악을 수시로 오가며(Cross-referencing), 필요한 정보만 발췌하여 이해를 확장합니다 [30-32]. 이는 인지 부하를 최소화하면서 당면한 과제(Task-relevant)를 해결하는 데 최적화된 방식입니다.
### 매 3대 strategy
- **Top-down (Brooks)**: 매 hypothesis 형성 → code 로 verify. 매 domain expert 가 사용.
- **Bottom-up (Pennington)**: 매 statement → control-flow → data-flow → program model. 매 novice 가 사용.
- **Opportunistic (mixed)**: 매 expert programmer 의 실제 행동 — top-down 시작, beacon 발견 시 bottom-up 으로 dive.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **효율성 vs 정확성의 딜레마:** 하향식 전략은 아키텍처를 빠르게 파악할 수 있으나, '확증 편향'으로 인해 비전형적인(Unplan-like) 코드에서 발생하는 미세한 버그나 보안 취약점을 간과할 위험이 큽니다 [6, 11]. 반대로 상향식은 정확도가 높지만, 막대한 인지 부하를 유발하며 전체 맥락(Big Picture)을 놓칠 수 있습니다 [6].
* **비전형적 코드(Unplan-like)의 위험:** 코드가 관례를 벗어나거나 독창적이지만 가독성이 낮은 구조로 작성된 경우, 전문가의 하향식 가설 검증이 실패(Dangling Purpose)하게 되어 인지 비용이 기하급수적으로 증가합니다 [18, 38].
* **단일 진입점 부재:** 현대의 이벤트 기반 아키텍처나 마이크로서비스에서는 전통적인 `main()` 함수와 같은 명확한 이해의 출발점이 부재하여, 기회주의적 전략에 의존해야 하며 이로 인해 멘탈 모델이 파편화될 위험이 상존합니다 [6, 39].
### 매 cognitive constructs
- **Beacons**: 매 recognizable patterns (e.g., `for(i=0; i<n; i++)` → 매 loop, `swap(a,b)` → 매 sort).
- **Plans**: 매 stereotypical solutions (e.g., search plan, accumulator plan).
- **Chunks**: 매 functionally cohesive code groups stored as 1 unit in working memory.
## 🔗 지식 연결 (Graph)
### Related Concepts
- [[Cognitive Load & Mental Models]]: 프로그램 이해 과정에서 발생하는 인지적 병목과 청킹 메커니즘을 다룹니다.
- Beacons & Programming Plans: 하향식 가설 생성을 돕는 코드 내 단서와 전형적인 패턴에 대한 상세입니다.
- Clean Architecture vs Traceable Code: 인지 부하를 줄이기 위한 설계적 선택과 추적 가능성 사이의 균형을 논의합니다.
### 매 응용
1. Code review: 매 reviewer 는 top-down — PR 의 의도 파악 후 specific changes 검증.
2. Onboarding: 매 new dev 는 bottom-up — small fixes 로 시작, 점진적 chunking.
3. AI-assisted reading: 매 LLM 에게 code summarization → human 이 hypothesis 생성.
### Deeper Research Questions
- 대규모 분산 아키텍처 환경에서 고전적 이해 모델(Brooks, Pennington)의 한계를 보완하기 위한 현대적 인지 보조 도구는 무엇인가?
- 비전형적 코드를 마주했을 때 발생하는 '인지적 불일치'를 정적 분석 도구와 AI 어시스턴트로 어떻게 해소할 수 있는가?
- '상황 모델(의도)'과 '프로그램 모델(구현)' 사이의 괴리를 코드 리뷰 과정에서 시스템적으로 감지하는 방법은?
## 💻 패턴
### Practical Application Contexts
- **Implementation:** 명확한 함수명과 디자인 패턴을 '비컨'으로 제공하여 동료의 가설 검증 비용을 줄여야 합니다 [18, 38].
- **Maintenance:** 무작정 코드를 읽기보다 Git 히스토리와 PR 논의(Context)를 먼저 파악하여 하향식 가설을 먼저 세우는 것이 효율적입니다 [47, 48].
- **Onboarding:** 신규 입사자에게 비즈니스 도메인(Situation Model)을 먼저 교육한 후, 실제 구현부(Program Model)로 안내하는 하향식 지식 전달이 효과적입니다 [25, 27].
### Pattern 1: Top-down hypothesis-driven reading
```python
# 매 step 1: read README / docstring → 매 form hypothesis
# 매 step 2: locate entry point (main, app.py)
# 매 step 3: trace only the path that confirms/refutes hypothesis
---
*Last updated: 2026-05-02*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def trace_hypothesis(repo, hypothesis):
entry = find_entry_point(repo)
call_graph = build_call_graph(entry)
relevant = filter_by_keyword(call_graph, hypothesis.keywords)
return relevant
```
## 🤔 의사결정 기준 (Decision Criteria)
### Pattern 2: Beacon recognition (LLM-augmented)
```python
import anthropic
client = anthropic.Anthropic()
**선택 A를 써야 할 때:**
- *(TODO)*
def extract_beacons(code: str) -> list[str]:
resp = client.messages.create(
model="claude-opus-4-7",
max_tokens=1024,
system="Identify recognizable code patterns (beacons) and name their plan.",
messages=[{"role": "user", "content": f"```\n{code}\n```"}],
)
return parse_beacons(resp.content[0].text)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Pattern 3: Chunking via cohesion analysis
```python
def chunk_function(ast_node):
"""매 group statements by 매 shared variables (cohesion)."""
chunks, current = [], []
last_vars = set()
for stmt in ast_node.body:
vars = extract_vars(stmt)
if last_vars and not (vars & last_vars):
chunks.append(current)
current = []
current.append(stmt)
last_vars = vars
if current:
chunks.append(current)
return chunks
```
**기본값:**
> *(TODO)*
### Pattern 4: Cross-reference walking (bottom-up)
```bash
# 매 ripgrep + ctags-driven exploration
rg -l "AuthService" --type ts | head -5
rg "class AuthService" --type ts -A 30
rg "new AuthService\(" --type ts # 매 callers
```
## ❌ 안티패턴 (Anti-Patterns)
### Pattern 5: LLM-driven code summarization
```python
# 매 Claude Code-style structured summary
PROMPT = """Summarize this file with:
1. 매 PURPOSE (1 sentence)
2. 매 KEY DATA STRUCTURES
3. 매 PUBLIC API
4. 매 NON-OBVIOUS CONTRACTS / INVARIANTS
5. 매 DEPENDENCIES (incoming + outgoing)
"""
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def summarize(file_path):
code = open(file_path).read()
return claude_call(PROMPT + f"\n```\n{code}\n```")
```
### Pattern 6: Mental model checkpointing
```markdown
<!-- 매 personal-notes.md per repo while reading -->
## Module: auth/
- Purpose: JWT issuance & verification
- Entry: `auth/router.ts:loginHandler`
- Key invariant: tokens always include `iss=our-domain`
- Open Q: where is refresh-token rotation?
```
### Pattern 7: Diagram-first — produce dependency graph before reading
```bash
madge --image deps.svg src/
# 매 visual chunking — see clusters before diving
```
## 매 결정 기준
| 상황 | Strategy |
|---|---|
| 매 domain familiar, code new | Top-down |
| 매 domain new, code small | Bottom-up |
| 매 large unknown codebase | Opportunistic + diagram first |
| 매 bug hunt | Bottom-up from stack trace |
| 매 architecture review | Top-down from entry points |
| 매 LLM augmentation | Summarize → form hypothesis → verify |
**기본값**: 매 opportunistic — 매 README + entry point 부터 시작, beacon 발견 시 dive.
## 🔗 Graph
- 부모: [[Software Engineering]] · [[Cognitive Psychology]]
- 변형: [[Code Review]] · [[Onboarding]]
- 응용: [[Refactoring]] · [[Bug Localization]] · [[LLM-assisted Coding]]
- Adjacent: [[Mental Models]] · [[Working Memory]] · [[AST]]
## 🤖 LLM 활용
**언제**: 매 onboarding new repo, 매 reviewing large PR, 매 understanding legacy code, 매 building mental model.
**언제 X**: 매 1-line hot-fix 에 over-engineering 하지 마라.
## ❌ 안티패턴
- **Read everything linearly**: 매 working memory 초과 — chunking 없이 무너짐.
- **Skip the README**: 매 hypothesis 없이 bottom-up 만 → 매 lost in details.
- **No checkpointing**: 매 1시간 후 모두 잊음 — write down mental model.
- **Trust LLM summary blindly**: 매 hallucination 위험 — 매 verify on key claims.
## 🧪 검증 / 중복
- Verified (Brooks 1983, Pennington 1987, Soloway & Ehrlich 1984, Storey 2006 review).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — top-down/bottom-up/opportunistic + LLM augmentation |