docs: architecture.md Purpose 섹션 최신화

v2.2.158 기준 — 자동 scan 섹션은 이미 최신 (395 files, 25 modules).
Purpose 섹션 (사용자 편집 영역) 을 _TODO_ → 실제 내용으로:

- Top-level 동작 흐름 다이어그램 (User → webview → chatHandlers →
  AgentExecutor → handlePrompt phases / executeActions / LLM I/O)
- 8개 핵심 디자인 패턴 (god-file 분해, 대화 연속성, slash 시스템,
  Stocks feature, 5-Layer Memory, Company 모드, Context budget,
  Cloud LLM routing)
- 진입 파일 5개 + 활성 작업 (2026-05) 정리

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
g1nation
2026-05-25 10:03:12 +09:00
parent 0a97324f1b
commit fc2bf0d74e
+78 -1
View File
@@ -343,4 +343,81 @@ _Last auto-scan: 2026-05-25T00:59:03.313Z · signature `fca24b52`_
<!-- ASTRA:AUTO-END -->
## Purpose
_TODO_
Astra (g1nation) — **로컬 LLM 기반의 개인 지능형 운영 레이어**. VS Code 확장으로 LM Studio / Ollama 와 채팅하면서 *프로젝트 컨텍스트 / 메모리 / 작업 자동화* 를 단일 UI 에서 처리. 100% 로컬 (cloud LLM 은 opt-in 라우팅).
### Top-level 동작 흐름
```
User ↘ ↗ webview (chat UI)
sidebar.html / sidebar.js ←—— chatHandlers
│ │
│ ├─ slash router (/research /youtube /stocks 등)
│ │
↓ ↓
SidebarChatProvider ──→ AgentExecutor (agent.ts, 1,529 lines)
┌──────────────────────┴──────────────────────┐
↓ ↓ ↓
handlePrompt phases executeActions (8 그룹) LLM I/O (agent/llm)
(agent/handlePrompt) (agent/actions) createStreamingRequest
streamChatOnce
callNonStreaming
[PRIOR TURN CONCLUSION] ← 대화 연속성 anchor
+ Mode Bridge + Context Blocks + System Prompt + Budget
```
### 핵심 디자인 패턴
**1. God-file 분해 (R50R59, 2026-05).** `agent.ts` 2731→1529 lines, `extension.ts` 1145→349 lines. 25개 신규 모듈 (`src/agent/**`, `src/extension/**`). 패턴:
- *Pure free functions + deps object* — `this.X` 의존성을 callback dep 으로 명시 (e.g. `callNonStreaming(deps, params)`)
- *Thin wrappers on the class* — AgentExecutor 의 메서드는 deps 묶어서 free function 으로 위임. 외부 caller signature 보존.
- Action handlers (15+ tags) 는 `HandlerContext` 공유 ctx 객체로 통일 — 8개 그룹 (file/run/list/brain/calendar/sheets/tasks).
- handlePrompt 1,100줄 → 7 phase 모듈 (buildTurnContextBlocks / buildModeBridgeContext / build{Agent,Astra}ModeSystemPrompt / computeBudgetedRequest / processFinalAnswer / applyAutoContinuation).
**2. 대화 연속성 (v2.2.150~157).** 작은 로컬 모델 (gemma 4B 등) 이 follow-up 정정/보강 turn 에 echo/parrot 하는 문제 해결:
- `[PRIOR TURN CONCLUSION]` block — 직전 assistant 답변의 첫 문장을 system prompt 에 anchor
- `[CONVERSATION CONTINUITY & REVISION]` rule — echo 금지, 최소 3-5 문장 구조 강제
- *Thin follow-up classifier* (`isThinFollowUp`) — 짧은 follow-up turn 에서 Guard 의 4-section boilerplate (`## 요청 요약` 등) suppress
- *Slash 결과 chatHistory mirror* — slash 명령 결과를 webview *와 함께* agent.chatHistory 에 push (capture wrapper). 다음 turn LLM 이 직전 명령 출력 인식. `getHistory()` 가 filtered copy 반환하는 silent bug fix 포함.
**3. Slash 명령 시스템.** `src/features/datacollect/slashRouter.ts` 의 registry. 등록된 명령: `/research /benchmark /youtube /blog /wikify /meet /stocks`. webview 의 `/` 자동완성 dropdown 으로 노출. 각 명령은 `(arg, view, context) => Promise<boolean>` 시그니처 통일.
**4. Stocks feature (v2.2.152~158).** 새 도메인 — 한국 주식 모니터링/발굴:
- `.astra/stocks.json` 저장소 (workspace root)
- Yahoo Finance 현재가 갱신, `g1nation.stocks.spreadsheetId` 로 Google Sheets 동기화 (calendar OAuth scope 재사용)
- KST 09:00 / 15:00 watcher 자동 트리거 → Telegram 보고서
- **8 키워드 자동 필터** (ROE/성장성/유동성/수익성/영업효율/기술력/안정성/PBR) — `llmJudge.ts``stockDiscovery.ts` 가 동일 임계값 공유
- `/stocks discover` — Naver 비공식 JSON API (`m.stock.naver.com/api/...`) 로 시가총액 페이지 + 펀더멘털 (ROE/영업이익률/유보율) 크롤 후 8 키워드 필터 → 통과한 종목 → LLM Top 5 매력도 분석 → Telegram 자동 발송
- `/stocks judge <symbol>` — LLM 으로 4-criteria 필터 자동 판정 + JSON 업데이트
**5. 5-Layer Cognitive Memory.** `src/memory/`:
- Short-Term (대화 단기) / Long-Term (Second Brain) / Project (프로젝트 기록) / Procedural (스킬) / Episodic (세션 요약)
- TF-IDF + 한/영 이중 토크나이저 (`src/retrieval/scoring.ts`)
- 옵션: embedding hybrid (`g1nation.embeddingModel` 설정 시 dense+sparse blend)
- Knowledge Mix policy — Second Brain 의존도 (0-100) 사용자 조절 가능
**6. 1인 기업 모드 (Company Mode).** `src/features/company/`:
- 가상 회사 — 사용자 = CEO, 에이전트 = 직원. 명령 분류기 → dispatcher → 직군별 specialist → CEO 검수 → 산출물
- 각 turn 은 session directory 에 `_brief.md / _report.md / 에이전트별 산출물` 영구 기록
- LLM 호출 인터페이스: `IAIService.chat({system, user})` (mock 가능 → `tests/helpers/mockLLMClient.ts`)
**7. Context budget (`src/lib/contextManager.ts`).** 매 turn 마다 system + history + input 의 토큰 예산 계산, output 상한 동적 조절. `smallModelContextCap` 옵션으로 ≤3B 모델의 EOS-first 환각 회피.
**8. Cloud LLM routing (`src/features/providers/`).** `openrouter:` / `anthropic:` / `gemini:` prefix 가 model id 에 있으면 자동 cloud SDK 라우팅. SSE 응답은 OpenAI 호환 형식으로 normalize → 로컬 path 와 동일 consumer.
### 진입 파일 (학습 순서)
1. **`src/extension.ts`** — activation, 모든 wiring (사이드바 / approval / telegram / stocks watcher / slash router)
2. **`src/sidebarProvider.ts`** — webview lifecycle, message dispatch (chatHandlers / settings)
3. **`src/agent.ts`** — AgentExecutor (thin wrappers + chatHistory 상태)
4. **`src/agent/handlePrompt/`** — 한 turn 의 7-phase pipeline
5. **`src/features/stocks/`** — 최근 새 도메인 사례 (slash + watcher + LLM + Telegram 통합)
### 활성 작업 (2026-05)
- *완료*: god-file 분해 R50R59, Stocks feature 전체 파이프라인, 대화 연속성 fix
- *진행 가능 (paused)*: `/stocks discover` 의 시가총액 범위 자동 유도 (사용자 드롭 요청)
- *남은 큰 영역*: `slashRouter.ts` (1,127 lines), `dispatcher.ts` (1,364 lines), `sidebarProvider.ts` (3,194 lines) — 별도 god-file 분해 대상이나 ROI 검토 필요