feat(engine): implement self-reflection (reflector) stage in multi-agent pipeline

- Added ReflectorAgent for meta-cognition and critical review between Research and Writing
- Updated WriterAgent to explicitly address reflection critiques
- Introduced 'g1nation.enableReflection' configuration setting
- Added comprehensive integration tests for the self-reflection stage
- Documented design decisions in ADR-0010 and related discussion records
This commit is contained in:
g1nation
2026-05-14 01:47:28 +09:00
parent e075779635
commit 8da9532ca1
18 changed files with 610 additions and 124 deletions
+46 -41
View File
@@ -3,23 +3,23 @@
<!-- ASTRA:AUTO-START -->
## Snapshot
- **Workspace**: `ConnectAI` `v2.0.2` _(absolute path varies by environment; resolved from the active VS Code workspace)_
- **Workspace**: `ConnectAI` `v2.0.9` _(absolute path varies by environment; resolved from the active VS Code workspace)_
- **Description**: The personal intelligence layer for Antigravity and VS Code. A private cognitive partner for deep project context, memory, and proactive strategic decision-making.
- **Stack**: TypeScript, Node.js, VS Code Extension, LM Studio SDK, Test runner
- **Stats**: 184 source files, ~31,651 lines across 5 top-level modules.
- **Stats**: 201 source files, ~35,737 lines across 5 top-level modules.
## Last Refresh
- **Time**: 2026-05-13T13:48:21.458Z
- **Files newly analysed**: 3
- **Files reused from cache**: 181
- **Time**: 2026-05-13T16:44:14.023Z
- **Files newly analysed**: 8
- **Files reused from cache**: 193
## Directory Map
```mermaid
mindmap
root((ConnectAI))
src/
core/
features/
core/
memory/
retrieval/
docs/
@@ -37,11 +37,11 @@ mindmap
> Arrows: which top-level module imports from which.
```mermaid
flowchart LR
src["src/<br/>85 files"]
src["src/<br/>100 files"]
media["media/<br/>6 files"]
tests["tests/<br/>27 files"]
core_py["core_py/<br/>6 files"]
docs["docs/<br/>60 files"]
docs["docs/<br/>62 files"]
tests --> src
```
@@ -53,78 +53,78 @@ flowchart LR
## Hub Files
> Imported by many other files — touching these has wide blast radius.
- `src/utils.ts` — referenced by **37** files
- `src/config.ts` — referenced by **11** files
- `src/utils.ts` — referenced by **43** files
- `src/config.ts` — referenced by **12** files
- `src/lib/paths.ts` — referenced by **10** files
- `src/features/company/types.ts` — referenced by **9** files · Type definitions for the 1인 기업 (One-Person Company) mode. The mode turns the user into a virtual CEO that dispatches work to a roster of specialist agents. Each turn produces a session directory conta
- `src/features/company/agents.ts` — referenced by **7** files · The 9-agent roster for 1인 기업 모드. Each entry is a static description — persona, role, specialty — used to build the specialist's system prompt at dispatch time. The set was adopted from Connectorigin's
- `src/skills/agentKnowledgeMap.ts` — referenced by **6** files
- `src/lib/engine.ts` — referenced by **6** files
- `src/sidebarProvider.ts` — referenced by **6** files
- `src/retrieval/scoring.ts` — referenced by **6** files · Scoring Engine — TF-IDF + Bilingual Tokenizer 단순 includes() 키워드 매칭을 넘어서, TF-IDF 가중치 기반의 문서 스코어링을 제공합니다. 한국어/영어 양국어 토크나이저를 포함합니다.
- `src/memory/types.ts` — referenced by **6** files · Memory Type Definitions (메모리 타입 정의) Astra의 5-Layer Cognitive Memory System의 모든 타입을 정의합니다. ① Short-Term ② Long-Term ③ Project ④ Procedural ⑤ Episodic
- `src/retrieval/lessonHelpers.ts` — referenced by **5** files · Lesson / Experience Memory — pure helpers (no vscode dependency) "Lesson" = a markdown file in the active brain that captures a past mistake/risk and how to avoid repeating it. Identified by a lessons
- `src/core/services.ts` — referenced by **6** files
## Modules
### `src/` — 85 files, ~20,591 lines
### `src/` — 100 files, ~23,711 lines
**Sub-directories**
- `src/features/` (28) — The 9-agent roster for 1인 기업 모드. Each entry is a static description — persona, role, specialty — used to build the speci
- `src/core/` (15) — Astra Path Resolver (경로 해결기) Astra의 모든 데이터 파일(.astra 디렉토리)의 경로를 중앙에서 관리합니다. 확장 프로그램의 설치 경로(extensionUri) 기반으로 .astra 디렉토
- `src/features/` (14) — Project Architecture Context (Feature 2) Builds a markdown document that captures the durable facts about a project — it
- `src/memory/` (8) — Episodic Memory (일화 기억) 과거 대화/회의/결정의 맥락 흐름을 저장합니다. 세션 종료 시 자동으로 에피소드를 요약하여 저장합니다. "왜 이렇게 결정했는지", "어떤 흐름으로 진행했는지" 기록. 저장
- `src/retrieval/` (8) — Brain Index — persistent, mtime-keyed tokenized cache of the Second Brain RAG 검색은 매 질의마다 브레인의 모든 .md 파일을 읽고 토크나이즈해서 TF-I
- `src/docs/` (6) — src Chronicle Records
- `src/lib/` (6) — Context Manager (컨텍스트 한계 관리) "context length = 132k" 는 "답변을 132k 토큰까지 생성해도 된다" 가 아닙니다. 시스템 프롬프트 + 대화 기록 + 입력 문서 + 생성될 답변
- `src/integrations/` (4) — Per-chat conversation history for the Telegram bot. Why this exists: the previous bot was stateless — every inbound mess
- `src/lmstudio/` (4) — 4 files (.ts)
- `src/sidebar/` (4) — 4 files (.ts)
- `src/skills/` (4) — 4 files (.ts)
- `src/integrations/` (3) — Subset of the Telegram Bot API types we actually consume. Source: https://core.telegram.org/bots/api Only fields the bot
- `src/agents/` (2) — 2 files (.ts)
- `src/scaffolder/` (2) — Scaffolder template catalog. Templates are pure data — (projectName) => { [relativePath]: contents }. New templates are
**Key files**
- `src/utils.ts` (268 lines)
- `src/config.ts` (209 lines)
- `src/config.ts` (216 lines)
- `src/features/company/types.ts` (150 lines) — Type definitions for the 1인 기업 (One-Person Company) mode. The mode turns the user into a virtual CEO that dispatches work to a roster of specialist agents. Each turn produces a session directory conta
- `src/lib/paths.ts` (151 lines)
- `src/sidebarProvider.ts` (2603 lines)
- `src/sidebarProvider.ts` (2934 lines)
- `src/features/company/agents.ts` (136 lines) — The 9-agent roster for 1인 기업 모드. Each entry is a static description — persona, role, specialty — used to build the specialist's system prompt at dispatch time. The set was adopted from Connectorigin's
- `src/memory/types.ts` (126 lines) — Memory Type Definitions (메모리 타입 정의) Astra의 5-Layer Cognitive Memory System의 모든 타입을 정의합니다. ① Short-Term ② Long-Term ③ Project ④ Procedural ⑤ Episodic
- `src/retrieval/scoring.ts` (518 lines) — Scoring Engine — TF-IDF + Bilingual Tokenizer 단순 includes() 키워드 매칭을 넘어서, TF-IDF 가중치 기반의 문서 스코어링을 제공합니다. 한국어/영어 양국어 토크나이저를 포함합니다.
- `src/skills/agentKnowledgeMap.ts` (374 lines)
- `src/agent.ts` (3207 lines)
- `src/core/services.ts` (164 lines)
- `src/agent.ts` (3232 lines)
- `src/features/company/companyConfig.ts` (330 lines) — State + config plumbing for 1인 기업 모드. Two surfaces: - CompanyState (runtime data: enabled flag, company name, which agents are active, per-agent model overrides). Persisted in VS Code's globalState so
- `src/retrieval/lessonHelpers.ts` (325 lines) — Lesson / Experience Memory — pure helpers (no vscode dependency) "Lesson" = a markdown file in the active brain that captures a past mistake/risk and how to avoid repeating it. Identified by a lessons
- `src/lib/engine.ts` (849 lines)
- `src/lib/engine.ts` (880 lines)
- `src/features/approval/approvalQueue.ts` (129 lines)
- `src/integrations/telegram/telegramClient.ts` (154 lines)
- `src/features/projectArchitecture/scanner.ts` (644 lines) — Deep static analyser for the Project Architecture Context generator. Walks the project tree (skipping the usual nodemodules / out / dist noise), pulls the role of each interesting file from its leadin
- `src/lib/contextManager.ts` (275 lines) — Context Manager (컨텍스트 한계 관리) "context length = 132k" 는 "답변을 132k 토큰까지 생성해도 된다" 가 아닙니다. 시스템 프롬프트 + 대화 기록 + 입력 문서 + 생성될 답변 + 여유분 ≤ context length 이 모듈은 요청을 보내기 전에 입력 토큰을 추정하고, - 동적으로 출력 상한(maxTokens)을 계
- `src/core/astraPath.ts` (50 lines) — Astra Path Resolver (경로 해결기) Astra의 모든 데이터 파일(.astra 디렉토리)의 경로를 중앙에서 관리합니다. 확장 프로그램의 설치 경로(extensionUri) 기반으로 .astra 디렉토리를 해결하여, 사용자 프로젝트 루트가 아닌 ConnectAI 패키지 내부에 데이터를 저장합니다. 이 모듈은 AAL(Astra Autonomou
- `src/extension.ts` (945 lines)
- `src/features/projectChronicle/types.ts` (118 lines)
- `src/integrations/telegram/telegramClient.ts` (154 lines)
- `src/lmstudio/client.ts` (147 lines)
- `src/retrieval/brainIndex.ts` (325 lines) — Brain Index — persistent, mtime-keyed tokenized cache of the Second Brain RAG 검색은 매 질의마다 브레인의 모든 .md 파일을 읽고 토크나이즈해서 TF-IDF 점수를 계산했습니다 — 파일 수가 많아지면 그게 병목입니다. 이 모듈은 <brainPath>/.astra/brain-index.json 에
- `src/extension.ts` (757 lines)
- `src/features/projectArchitecture/index.ts` (515 lines) — Project Architecture Context (Feature 2) Builds a markdown document that captures the durable facts about a project — its purpose, modules, key files, constraints, decisions — so Astra can attach it t
- `src/lmstudio/activityTracker.ts` (19 lines)
- `src/memory/EpisodicMemory.ts` (278 lines) — Episodic Memory (일화 기억) 과거 대화/회의/결정의 맥락 흐름을 저장합니다. 세션 종료 시 자동으로 에피소드를 요약하여 저장합니다. "왜 이렇게 결정했는지", "어떤 흐름으로 진행했는지" 기록. 저장 위치: {brainPath}/memory/episodes/.json
- `src/memory/LongTermMemory.ts` (243 lines) — Long-Term Memory (장기 기억) 사용자의 취향, 프로젝트 목표, 반복 규칙, 과거 결정 사항을 영구적으로 저장하고 관리합니다. 저장 위치: {brainPath}/memory/longterm.json
- `src/memory/ProjectMemory.ts` (212 lines) — Project Memory (프로젝트 기억) 프로젝트별 요구사항, 코드 구조, 아키텍처 결정, 버그 기록 등을 Astra 확장 프로그램 내부에 저장하고 관리합니다. 저장 위치: {ConnectAI}/.astra/projectmemory.json (기존: {projectRoot}/.astra/ → 변경됨)
- `src/retrieval/index.ts` (514 lines) — RetrievalOrchestrator — Unified RAG Pipeline Astra의 모든 검색 소스를 통합 관리하는 오케스트레이터입니다. 검색 흐름: ① Query Planning — 의도 분류 + 검색 전략 결정 ② Parallel Search — Brain + Memory + Project + Episode 동시 검색 ③ Result Fusio
- `src/features/company/promptBuilder.ts` (202 lines) — System-prompt construction for company-mode agents. Each specialist needs a prompt that includes: - Their identity (name, role, specialty) + optional persona. - The action-tag contract (<createfile>,
- `src/features/company/sessionStore.ts` (231 lines) — Disk persistence for company-mode session artefacts. Each company turn produces a timestamped directory: <workspaceRoot>/.astra/company/sessions/2026-05-13T21-29/ ├─ brief.md ← CEO's task decompositio
### `media/` — 6 files, ~3,304 lines
### `media/` — 6 files, ~4,099 lines
**Key files**
- `media/sidebar.css` (987 lines) — Stylesheet
- `media/sidebar.js` (1388 lines)
- `media/sidebar.css` (1225 lines) — Stylesheet
- `media/sidebar.js` (1874 lines)
- `media/sidebar.html` (356 lines) — Astra
- `media/settings-panel.css` (210 lines) — Stylesheet
- `media/sidebar.html` (285 lines) — Astra
- `media/settings-panel.html` (164 lines) — Astra Settings
- `media/settings-panel.js` (270 lines)
### `tests/` — 27 files, ~4,802 lines
### `tests/` — 27 files, ~4,932 lines
*Depends on*: `src/`
**Sub-directories**
- `tests/mocks/` (1) — 1 files (.js)
**Key files**
- `tests/agentEngine.test.ts` (646 lines) — AgentEngine Integration Tests & Performance Benchmarks 검증 대상: 1. ErrorClassifier — 오류 유형(Transient/Permanent/Abort) 자동 분류 2. ErrorRecoveryMatrix — 각 규칙이 의도한 대응 전략으로 매핑되는지 검증 3. resilientExecute — 지수 백
- `tests/agentEngine.test.ts` (776 lines) — AgentEngine Integration Tests & Performance Benchmarks 검증 대상: 1. ErrorClassifier — 오류 유형(Transient/Permanent/Abort) 자동 분류 2. ErrorRecoveryMatrix — 각 규칙이 의도한 대응 전략으로 매핑되는지 검증 3. resilientExecute — 지수 백
- `tests/lmStudioLifecycle.test.ts` (318 lines) — Unit tests for ModelLifecycleManager. Strategy: inject mock ILMStudioClient and a simple in-memory IActivityTracker. No real LM Studio or SDK is touched — the manager file does not import the SDK dire
- `tests/telegramBot.test.ts` (363 lines) — Unit tests for TelegramBot + truncateForTelegram. Strategy: - TelegramBot is driven by an injected ITelegramClient stub. We script getUpdates to return queued batches and assert that: - the offset cur
- `tests/lmStudioStreamer.test.ts` (220 lines) — Unit tests for LMStudioStreamer. Strategy: inject a fake ILMStudioClient that returns a fake model handle whose respond() yields a controllable async iterable. No real SDK or WebSocket touched.
@@ -160,10 +160,10 @@ flowchart LR
- `core_py/optimizer.py` (55 lines)
- `core_py/queue_worker.py` (82 lines)
### `docs/` — 60 files, ~2,545 lines
### `docs/` — 62 files, ~2,586 lines
**Sub-directories**
- `docs/records/` (48) — Astra Project Chronicle Records
- `docs/records/` (50) — Astra Project Chronicle Records
- `docs/docs/` (5) — docs Chronicle Records
**Key files**
@@ -172,7 +172,7 @@ flowchart LR
- `docs/EXPERIENCE_MEMORY_PLAN.md` (122 lines) — Experience Memory (Mistake / Lesson Loop) — Implementation Plan
- `docs/records/ConnectAI/development/2026-05-02_connectai_project_knowledge_overview.md` (121 lines) — Astra Project Knowledge Overview
- `docs/records/ConnectAI/development/2026-05-03_connectai_project_knowledge_overview.md` (121 lines) — Astra Project Knowledge Overview
- `docs/records/ConnectAI/timeline.md` (116 lines) — Project Timeline
- `docs/records/ConnectAI/timeline.md` (122 lines) — Project Timeline
- `docs/Advanced_Features_Implementation_Guide.md` (40 lines) — Advanced Features Implementation Guide
- `docs/PROJECT_CHRONICLE_GUARD_ROADMAP.md` (43 lines) — Project Chronicle Guard: Search Engine Roadmap
- `docs/UX_UI_Consistency_Guidelines.md` (44 lines) — UX/UI Consistency Guidelines
@@ -196,7 +196,7 @@ flowchart LR
## VS Code Extension Surface
- **Extension ID**: `g1nation.astra`
- **Activation events**: `onStartupFinished`
- **Commands** (19):
- **Commands** (23):
- `g1nation.newChat` — Astra: New Chat
- `g1nation.exportChat` — Astra: Export Chat as Markdown
- `g1nation.explainSelection` — Astra: Explain Selected Code
@@ -215,8 +215,12 @@ flowchart LR
- `g1nation.lesson.manage` — Astra: Browse / Manage Lessons
- `g1nation.architecture.refresh` — Astra: Refresh Project Architecture Context
- `g1nation.architecture.detach` — Astra: Detach Project Architecture Context
- `g1nation.architecture.attach` — Astra: Attach Project Architecture Context
- `g1nation.architecture.open` — Astra: Open Project Architecture Doc
- **Configuration** (38 settings):
- `g1nation.company.toggle` — Astra: Toggle 1인 기업 Mode
- `g1nation.company.manage` — Astra: Manage 1인 기업 Agents
- `g1nation.company.openSessions` — Astra: Open 1인 기업 Sessions Folder
- **Configuration** (39 settings):
- `g1nation.multiAgentEnabled` *(boolean)* _(default: `false`)_ — Enable Multi-Agent Workflow (Planner -> Researcher -> Writer) for complex tasks.
- `g1nation.memoryEnabled` *(boolean)* _(default: `true`)_ — Enable layered memory injection before each model response.
- `g1nation.memoryShortTermMessages` *(number)* _(default: `8`)_ — Number of recent conversation messages included as short-term memory.
@@ -255,6 +259,7 @@ flowchart LR
- `g1nation.embeddingModel` *(string)* _(default: `""`)_ — Embedding model registered in LM Studio / Ollama (e.g. 'text-embedding-bge-small-en-v1.5', 'nomic-embed-text', 'multilingual-e5-small'). When empty, Astra uses TF-IDF only. When set, the brain is embe
- `g1nation.embeddingBlendAlpha` *(number)* _(default: `0.5`)_ — Hybrid score blend: 0 = pure TF-IDF (sparse / keyword), 1 = pure embedding cosine (dense / semantic), 0.5 = balanced. Only used when g1nation.embeddingModel is set. Default 0.5.
- `g1nation.knowledgeMix.secondBrainWeight` *(number)* _(default: `50`)_ — Knowledge Mix (0100): how heavily the assistant should lean on Second Brain evidence vs. its own general knowledge. 0 = Second Brain disabled (model knowledge only). 50 = balanced (legacy default). 1
- `g1nation.enableReflection` *(boolean)* _(default: `true`)_ — Insert a Self-Reflection (Reflector) stage between Researcher and Writer in the multi-agent workflow. The Reflector critically reviews the plan and research output (gaps, contradictions, unsupported c
## Dependencies
- **Runtime** (2): `@lmstudio/sdk`, `pdf-parse`
@@ -302,7 +307,7 @@ Astra는 대표님의 명시적인 승인 하에 로컬 시스템의 강력한
**Designed for High-Performance Decision Making.**
Copyright (C) **g1nation**. All rights reserved.
_Last auto-scan: 2026-05-13T13:48:21.458Z · signature `fefc8c65`_
_Last auto-scan: 2026-05-13T16:44:14.023Z · signature `c63276ae`_
<!-- ASTRA:AUTO-END -->
## Purpose