claude-memory-layer 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/commands/memory-forget.md +42 -0
- package/.claude-plugin/commands/memory-history.md +34 -0
- package/.claude-plugin/commands/memory-import.md +56 -0
- package/.claude-plugin/commands/memory-list.md +37 -0
- package/.claude-plugin/commands/memory-search.md +36 -0
- package/.claude-plugin/commands/memory-stats.md +34 -0
- package/.claude-plugin/hooks.json +59 -0
- package/.claude-plugin/plugin.json +24 -0
- package/.history/package_20260201112328.json +45 -0
- package/.history/package_20260201113602.json +45 -0
- package/.history/package_20260201113713.json +45 -0
- package/.history/package_20260201114110.json +45 -0
- package/Memo.txt +558 -0
- package/README.md +520 -0
- package/context.md +636 -0
- package/dist/.claude-plugin/commands/memory-forget.md +42 -0
- package/dist/.claude-plugin/commands/memory-history.md +34 -0
- package/dist/.claude-plugin/commands/memory-import.md +56 -0
- package/dist/.claude-plugin/commands/memory-list.md +37 -0
- package/dist/.claude-plugin/commands/memory-search.md +36 -0
- package/dist/.claude-plugin/commands/memory-stats.md +34 -0
- package/dist/.claude-plugin/hooks.json +59 -0
- package/dist/.claude-plugin/plugin.json +24 -0
- package/dist/cli/index.js +3539 -0
- package/dist/cli/index.js.map +7 -0
- package/dist/core/index.js +4408 -0
- package/dist/core/index.js.map +7 -0
- package/dist/hooks/session-end.js +2971 -0
- package/dist/hooks/session-end.js.map +7 -0
- package/dist/hooks/session-start.js +2969 -0
- package/dist/hooks/session-start.js.map +7 -0
- package/dist/hooks/stop.js +3123 -0
- package/dist/hooks/stop.js.map +7 -0
- package/dist/hooks/user-prompt-submit.js +2960 -0
- package/dist/hooks/user-prompt-submit.js.map +7 -0
- package/dist/services/memory-service.js +2931 -0
- package/dist/services/memory-service.js.map +7 -0
- package/package.json +45 -0
- package/plan.md +1642 -0
- package/scripts/build.ts +102 -0
- package/spec.md +624 -0
- package/specs/citations-system/context.md +243 -0
- package/specs/citations-system/plan.md +495 -0
- package/specs/citations-system/spec.md +371 -0
- package/specs/endless-mode/context.md +305 -0
- package/specs/endless-mode/plan.md +620 -0
- package/specs/endless-mode/spec.md +455 -0
- package/specs/entity-edge-model/context.md +401 -0
- package/specs/entity-edge-model/plan.md +459 -0
- package/specs/entity-edge-model/spec.md +391 -0
- package/specs/evidence-aligner-v2/context.md +401 -0
- package/specs/evidence-aligner-v2/plan.md +303 -0
- package/specs/evidence-aligner-v2/spec.md +312 -0
- package/specs/mcp-desktop-integration/context.md +278 -0
- package/specs/mcp-desktop-integration/plan.md +550 -0
- package/specs/mcp-desktop-integration/spec.md +494 -0
- package/specs/post-tool-use-hook/context.md +319 -0
- package/specs/post-tool-use-hook/plan.md +469 -0
- package/specs/post-tool-use-hook/spec.md +364 -0
- package/specs/private-tags/context.md +288 -0
- package/specs/private-tags/plan.md +412 -0
- package/specs/private-tags/spec.md +345 -0
- package/specs/progressive-disclosure/context.md +346 -0
- package/specs/progressive-disclosure/plan.md +663 -0
- package/specs/progressive-disclosure/spec.md +415 -0
- package/specs/task-entity-system/context.md +297 -0
- package/specs/task-entity-system/plan.md +301 -0
- package/specs/task-entity-system/spec.md +314 -0
- package/specs/vector-outbox-v2/context.md +470 -0
- package/specs/vector-outbox-v2/plan.md +562 -0
- package/specs/vector-outbox-v2/spec.md +466 -0
- package/specs/web-viewer-ui/context.md +384 -0
- package/specs/web-viewer-ui/plan.md +797 -0
- package/specs/web-viewer-ui/spec.md +516 -0
- package/src/cli/index.ts +570 -0
- package/src/core/canonical-key.ts +186 -0
- package/src/core/citation-generator.ts +63 -0
- package/src/core/consolidated-store.ts +279 -0
- package/src/core/consolidation-worker.ts +384 -0
- package/src/core/context-formatter.ts +276 -0
- package/src/core/continuity-manager.ts +336 -0
- package/src/core/edge-repo.ts +324 -0
- package/src/core/embedder.ts +124 -0
- package/src/core/entity-repo.ts +342 -0
- package/src/core/event-store.ts +672 -0
- package/src/core/evidence-aligner.ts +635 -0
- package/src/core/graduation.ts +365 -0
- package/src/core/index.ts +32 -0
- package/src/core/matcher.ts +210 -0
- package/src/core/metadata-extractor.ts +203 -0
- package/src/core/privacy/filter.ts +179 -0
- package/src/core/privacy/index.ts +20 -0
- package/src/core/privacy/tag-parser.ts +145 -0
- package/src/core/progressive-retriever.ts +415 -0
- package/src/core/retriever.ts +235 -0
- package/src/core/task/blocker-resolver.ts +325 -0
- package/src/core/task/index.ts +9 -0
- package/src/core/task/task-matcher.ts +238 -0
- package/src/core/task/task-projector.ts +345 -0
- package/src/core/task/task-resolver.ts +414 -0
- package/src/core/types.ts +841 -0
- package/src/core/vector-outbox.ts +295 -0
- package/src/core/vector-store.ts +182 -0
- package/src/core/vector-worker.ts +488 -0
- package/src/core/working-set-store.ts +244 -0
- package/src/hooks/post-tool-use.ts +127 -0
- package/src/hooks/session-end.ts +78 -0
- package/src/hooks/session-start.ts +57 -0
- package/src/hooks/stop.ts +78 -0
- package/src/hooks/user-prompt-submit.ts +54 -0
- package/src/mcp/handlers.ts +212 -0
- package/src/mcp/index.ts +47 -0
- package/src/mcp/tools.ts +78 -0
- package/src/server/api/citations.ts +101 -0
- package/src/server/api/events.ts +101 -0
- package/src/server/api/index.ts +18 -0
- package/src/server/api/search.ts +98 -0
- package/src/server/api/sessions.ts +111 -0
- package/src/server/api/stats.ts +97 -0
- package/src/server/index.ts +91 -0
- package/src/services/memory-service.ts +626 -0
- package/src/services/session-history-importer.ts +367 -0
- package/tests/canonical-key.test.ts +101 -0
- package/tests/evidence-aligner.test.ts +152 -0
- package/tests/matcher.test.ts +112 -0
- package/tsconfig.json +24 -0
- package/vitest.config.ts +15 -0
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
# Vector Outbox V2 Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **Version**: 2.0.0
|
|
4
|
+
> **Status**: Draft
|
|
5
|
+
> **Created**: 2026-01-31
|
|
6
|
+
|
|
7
|
+
## Phase 1: 스키마 및 타입 (P0)
|
|
8
|
+
|
|
9
|
+
### 1.1 타입 정의
|
|
10
|
+
|
|
11
|
+
**파일**: `src/core/types.ts` 수정
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
// 추가할 타입들
|
|
15
|
+
export const ItemKindSchema = z.enum(['entry', 'task_title', 'session_summary']);
|
|
16
|
+
export type ItemKind = z.infer<typeof ItemKindSchema>;
|
|
17
|
+
|
|
18
|
+
export const OutboxStatusSchema = z.enum(['pending', 'processing', 'done', 'failed']);
|
|
19
|
+
export type OutboxStatus = z.infer<typeof OutboxStatusSchema>;
|
|
20
|
+
|
|
21
|
+
export const OutboxJobSchema = z.object({
|
|
22
|
+
jobId: z.string(),
|
|
23
|
+
itemKind: ItemKindSchema,
|
|
24
|
+
itemId: z.string(),
|
|
25
|
+
embeddingVersion: z.string(),
|
|
26
|
+
status: OutboxStatusSchema,
|
|
27
|
+
retryCount: z.number().int().nonnegative(),
|
|
28
|
+
error: z.string().optional(),
|
|
29
|
+
createdAt: z.date(),
|
|
30
|
+
updatedAt: z.date()
|
|
31
|
+
});
|
|
32
|
+
export type OutboxJob = z.infer<typeof OutboxJobSchema>;
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
**작업 항목**:
|
|
36
|
+
- [ ] ItemKind 스키마 추가
|
|
37
|
+
- [ ] OutboxStatus 스키마 추가
|
|
38
|
+
- [ ] OutboxJob 스키마 추가
|
|
39
|
+
- [ ] EnqueueResult, ProcessResult 타입 추가
|
|
40
|
+
|
|
41
|
+
### 1.2 DB 스키마
|
|
42
|
+
|
|
43
|
+
**파일**: 마이그레이션 스크립트
|
|
44
|
+
|
|
45
|
+
```sql
|
|
46
|
+
-- 기존 outbox 테이블이 있다면 백업 후 마이그레이션
|
|
47
|
+
-- 신규 vector_outbox 테이블
|
|
48
|
+
|
|
49
|
+
CREATE TABLE vector_outbox (
|
|
50
|
+
job_id VARCHAR PRIMARY KEY,
|
|
51
|
+
item_kind VARCHAR NOT NULL,
|
|
52
|
+
item_id VARCHAR NOT NULL,
|
|
53
|
+
embedding_version VARCHAR NOT NULL,
|
|
54
|
+
status VARCHAR NOT NULL DEFAULT 'pending',
|
|
55
|
+
retry_count INTEGER DEFAULT 0,
|
|
56
|
+
error VARCHAR,
|
|
57
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
58
|
+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
59
|
+
UNIQUE(item_kind, item_id, embedding_version)
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
CREATE INDEX idx_outbox_status ON vector_outbox(status);
|
|
63
|
+
CREATE INDEX idx_outbox_created ON vector_outbox(created_at);
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
**작업 항목**:
|
|
67
|
+
- [ ] vector_outbox 테이블 DDL
|
|
68
|
+
- [ ] 인덱스 생성
|
|
69
|
+
- [ ] UNIQUE 제약 추가
|
|
70
|
+
- [ ] 기존 데이터 마이그레이션 스크립트 (필요시)
|
|
71
|
+
|
|
72
|
+
## Phase 2: VectorOutbox 클래스 (P0)
|
|
73
|
+
|
|
74
|
+
### 2.1 Enqueue 구현
|
|
75
|
+
|
|
76
|
+
**파일**: `src/core/vector-outbox.ts` (신규)
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
export class VectorOutbox {
|
|
80
|
+
constructor(private db: Database);
|
|
81
|
+
|
|
82
|
+
async enqueue(input: OutboxEnqueueInput): Promise<EnqueueResult> {
|
|
83
|
+
const jobId = uuidv4();
|
|
84
|
+
|
|
85
|
+
try {
|
|
86
|
+
await this.db.run(`
|
|
87
|
+
INSERT INTO vector_outbox
|
|
88
|
+
(job_id, item_kind, item_id, embedding_version, status)
|
|
89
|
+
VALUES (?, ?, ?, ?, 'pending')
|
|
90
|
+
ON CONFLICT (item_kind, item_id, embedding_version)
|
|
91
|
+
DO NOTHING
|
|
92
|
+
`, [jobId, input.itemKind, input.itemId, input.embeddingVersion]);
|
|
93
|
+
|
|
94
|
+
// 삽입 성공 여부 확인
|
|
95
|
+
const inserted = await this.db.query(`
|
|
96
|
+
SELECT job_id FROM vector_outbox
|
|
97
|
+
WHERE item_kind = ? AND item_id = ? AND embedding_version = ?
|
|
98
|
+
`, [input.itemKind, input.itemId, input.embeddingVersion]);
|
|
99
|
+
|
|
100
|
+
const isNew = inserted[0]?.job_id === jobId;
|
|
101
|
+
return { success: true, jobId: inserted[0].job_id, isNew };
|
|
102
|
+
|
|
103
|
+
} catch (error) {
|
|
104
|
+
return { success: false, error: error.message };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**작업 항목**:
|
|
111
|
+
- [ ] enqueue() 메서드 (중복 처리 포함)
|
|
112
|
+
- [ ] enqueueBatch() 배치 메서드
|
|
113
|
+
- [ ] ON CONFLICT DO NOTHING 처리
|
|
114
|
+
|
|
115
|
+
### 2.2 조회 메서드
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
async getPendingJobs(limit: number = 100): Promise<OutboxJob[]> {
|
|
119
|
+
return this.db.query(`
|
|
120
|
+
SELECT * FROM vector_outbox
|
|
121
|
+
WHERE status = 'pending'
|
|
122
|
+
ORDER BY created_at ASC
|
|
123
|
+
LIMIT ?
|
|
124
|
+
`, [limit]);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async getJobById(jobId: string): Promise<OutboxJob | null> {
|
|
128
|
+
const rows = await this.db.query(`
|
|
129
|
+
SELECT * FROM vector_outbox WHERE job_id = ?
|
|
130
|
+
`, [jobId]);
|
|
131
|
+
return rows[0] || null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async getMetrics(): Promise<OutboxMetrics> {
|
|
135
|
+
// 상태별 통계 조회
|
|
136
|
+
}
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
**작업 항목**:
|
|
140
|
+
- [ ] getPendingJobs() 메서드
|
|
141
|
+
- [ ] getJobById() 메서드
|
|
142
|
+
- [ ] getMetrics() 통계 메서드
|
|
143
|
+
|
|
144
|
+
## Phase 3: VectorWorker V2 (P0)
|
|
145
|
+
|
|
146
|
+
### 3.1 Worker 기본 구현
|
|
147
|
+
|
|
148
|
+
**파일**: `src/core/vector-worker.ts` 수정
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
export class VectorWorkerV2 {
|
|
152
|
+
constructor(
|
|
153
|
+
private outbox: VectorOutbox,
|
|
154
|
+
private embedder: Embedder,
|
|
155
|
+
private vectorStore: VectorStore,
|
|
156
|
+
private db: Database
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
// Job claiming with lock
|
|
160
|
+
async claimJobs(limit: number): Promise<OutboxJob[]> {
|
|
161
|
+
// 트랜잭션으로 pending → processing 변경
|
|
162
|
+
return this.db.transaction(async (tx) => {
|
|
163
|
+
const jobs = await tx.query(`
|
|
164
|
+
SELECT * FROM vector_outbox
|
|
165
|
+
WHERE status = 'pending'
|
|
166
|
+
ORDER BY created_at ASC
|
|
167
|
+
LIMIT ?
|
|
168
|
+
FOR UPDATE -- DuckDB에서 지원 시
|
|
169
|
+
`, [limit]);
|
|
170
|
+
|
|
171
|
+
if (jobs.length === 0) return [];
|
|
172
|
+
|
|
173
|
+
const jobIds = jobs.map(j => j.job_id);
|
|
174
|
+
await tx.run(`
|
|
175
|
+
UPDATE vector_outbox
|
|
176
|
+
SET status = 'processing', updated_at = CURRENT_TIMESTAMP
|
|
177
|
+
WHERE job_id IN (${jobIds.map(() => '?').join(',')})
|
|
178
|
+
`, jobIds);
|
|
179
|
+
|
|
180
|
+
return jobs.map(j => ({ ...j, status: 'processing' as const }));
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
**작업 항목**:
|
|
187
|
+
- [ ] claimJobs() 락 처리
|
|
188
|
+
- [ ] markDone() 메서드
|
|
189
|
+
- [ ] markFailed() 메서드
|
|
190
|
+
|
|
191
|
+
### 3.2 Process 루프
|
|
192
|
+
|
|
193
|
+
```typescript
|
|
194
|
+
async processAll(): Promise<ProcessResult> {
|
|
195
|
+
const result: ProcessResult = {
|
|
196
|
+
processed: 0,
|
|
197
|
+
succeeded: 0,
|
|
198
|
+
failed: 0,
|
|
199
|
+
errors: []
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const BATCH_SIZE = 50;
|
|
203
|
+
|
|
204
|
+
while (true) {
|
|
205
|
+
const jobs = await this.claimJobs(BATCH_SIZE);
|
|
206
|
+
if (jobs.length === 0) break;
|
|
207
|
+
|
|
208
|
+
for (const job of jobs) {
|
|
209
|
+
try {
|
|
210
|
+
await this.processJob(job);
|
|
211
|
+
await this.markDone(job.jobId);
|
|
212
|
+
result.succeeded++;
|
|
213
|
+
} catch (error) {
|
|
214
|
+
await this.markFailed(job.jobId, error.message);
|
|
215
|
+
result.failed++;
|
|
216
|
+
result.errors.push({ jobId: job.jobId, error: error.message });
|
|
217
|
+
}
|
|
218
|
+
result.processed++;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return result;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private async processJob(job: OutboxJob): Promise<void> {
|
|
226
|
+
// 1. 콘텐츠 조회
|
|
227
|
+
const content = await this.getContent(job.itemKind, job.itemId);
|
|
228
|
+
if (!content) {
|
|
229
|
+
throw new Error(`Content not found: ${job.itemKind}:${job.itemId}`);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// 2. 임베딩 생성
|
|
233
|
+
const embedding = await this.embedder.embed(content);
|
|
234
|
+
|
|
235
|
+
// 3. LanceDB upsert
|
|
236
|
+
await this.vectorStore.upsert({
|
|
237
|
+
id: `${job.itemKind}:${job.itemId}`,
|
|
238
|
+
vector: embedding,
|
|
239
|
+
content,
|
|
240
|
+
metadata: {
|
|
241
|
+
itemKind: job.itemKind,
|
|
242
|
+
embeddingVersion: job.embeddingVersion,
|
|
243
|
+
indexedAt: new Date().toISOString()
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
**작업 항목**:
|
|
250
|
+
- [ ] processAll() 메인 루프
|
|
251
|
+
- [ ] processJob() 단일 job 처리
|
|
252
|
+
- [ ] getContent() 콘텐츠 조회 (itemKind별)
|
|
253
|
+
|
|
254
|
+
### 3.3 Reconcile
|
|
255
|
+
|
|
256
|
+
```typescript
|
|
257
|
+
async reconcileFailed(maxRetries: number = 3): Promise<number> {
|
|
258
|
+
const result = await this.db.run(`
|
|
259
|
+
UPDATE vector_outbox
|
|
260
|
+
SET status = 'pending',
|
|
261
|
+
retry_count = retry_count + 1,
|
|
262
|
+
updated_at = CURRENT_TIMESTAMP
|
|
263
|
+
WHERE status = 'failed'
|
|
264
|
+
AND retry_count < ?
|
|
265
|
+
`, [maxRetries]);
|
|
266
|
+
|
|
267
|
+
return result.changes;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async recoverStuck(stuckThresholdMs: number = 5 * 60 * 1000): Promise<number> {
|
|
271
|
+
const threshold = new Date(Date.now() - stuckThresholdMs);
|
|
272
|
+
const result = await this.db.run(`
|
|
273
|
+
UPDATE vector_outbox
|
|
274
|
+
SET status = 'pending',
|
|
275
|
+
updated_at = CURRENT_TIMESTAMP
|
|
276
|
+
WHERE status = 'processing'
|
|
277
|
+
AND updated_at < ?
|
|
278
|
+
`, [threshold.toISOString()]);
|
|
279
|
+
|
|
280
|
+
return result.changes;
|
|
281
|
+
}
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
**작업 항목**:
|
|
285
|
+
- [ ] reconcileFailed() 재시도 메서드
|
|
286
|
+
- [ ] recoverStuck() stuck 복구 메서드
|
|
287
|
+
- [ ] cleanupDone() 정리 메서드
|
|
288
|
+
|
|
289
|
+
## Phase 4: VectorStore Upsert (P0)
|
|
290
|
+
|
|
291
|
+
### 4.1 Upsert 메서드
|
|
292
|
+
|
|
293
|
+
**파일**: `src/core/vector-store.ts` 수정
|
|
294
|
+
|
|
295
|
+
```typescript
|
|
296
|
+
// 기존 add() 메서드 외에 upsert() 추가
|
|
297
|
+
async upsert(record: VectorRecord): Promise<void> {
|
|
298
|
+
const table = await this.getOrCreateTable();
|
|
299
|
+
|
|
300
|
+
// 기존 레코드 확인
|
|
301
|
+
const existing = await table
|
|
302
|
+
.search([0]) // dummy
|
|
303
|
+
.filter(`id = '${record.id}'`)
|
|
304
|
+
.limit(1)
|
|
305
|
+
.toArray();
|
|
306
|
+
|
|
307
|
+
if (existing.length > 0) {
|
|
308
|
+
// 삭제 후 재삽입 (LanceDB upsert 패턴)
|
|
309
|
+
await table.delete(`id = '${record.id}'`);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
await table.add([{
|
|
313
|
+
id: record.id,
|
|
314
|
+
vector: record.vector,
|
|
315
|
+
content: record.content,
|
|
316
|
+
timestamp: record.timestamp,
|
|
317
|
+
...record.metadata
|
|
318
|
+
}]);
|
|
319
|
+
}
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
**작업 항목**:
|
|
323
|
+
- [ ] upsert() 메서드 구현
|
|
324
|
+
- [ ] delete + add 패턴 적용
|
|
325
|
+
- [ ] 기존 add()와 구분
|
|
326
|
+
|
|
327
|
+
### 4.2 테이블 버전 관리
|
|
328
|
+
|
|
329
|
+
```typescript
|
|
330
|
+
// 임베딩 모델 버전별 테이블
|
|
331
|
+
private getTableName(itemKind: ItemKind, version: string): string {
|
|
332
|
+
const versionSlug = version.replace(/[^a-z0-9]/gi, '_').toLowerCase();
|
|
333
|
+
return `${itemKind}_vectors_${versionSlug}`;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async getOrCreateTable(itemKind: ItemKind, version: string): Promise<Table> {
|
|
337
|
+
const tableName = this.getTableName(itemKind, version);
|
|
338
|
+
|
|
339
|
+
try {
|
|
340
|
+
return await this.db.openTable(tableName);
|
|
341
|
+
} catch {
|
|
342
|
+
// 테이블 생성
|
|
343
|
+
return await this.db.createTable(tableName, [
|
|
344
|
+
{ id: '', vector: [], content: '', timestamp: '' }
|
|
345
|
+
]);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
**작업 항목**:
|
|
351
|
+
- [ ] getTableName() 버전별 테이블명
|
|
352
|
+
- [ ] getOrCreateTable() lazy 생성
|
|
353
|
+
|
|
354
|
+
## Phase 5: 통합 및 트리거 (P0)
|
|
355
|
+
|
|
356
|
+
### 5.1 Entry 저장 시 자동 enqueue
|
|
357
|
+
|
|
358
|
+
**파일**: Graduation 또는 Entry 저장 로직
|
|
359
|
+
|
|
360
|
+
```typescript
|
|
361
|
+
async function materializeEntry(entry: Entry): Promise<void> {
|
|
362
|
+
// 1. Entry 저장
|
|
363
|
+
await entryRepo.create(entry);
|
|
364
|
+
|
|
365
|
+
// 2. Outbox에 자동 enqueue
|
|
366
|
+
await outbox.enqueue({
|
|
367
|
+
itemKind: 'entry',
|
|
368
|
+
itemId: entry.entry_id,
|
|
369
|
+
embeddingVersion: config.embedding.version
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
**작업 항목**:
|
|
375
|
+
- [ ] Entry 저장 후 outbox.enqueue() 호출
|
|
376
|
+
- [ ] Task 생성 시 task_title enqueue
|
|
377
|
+
- [ ] Session 종료 시 session_summary enqueue
|
|
378
|
+
|
|
379
|
+
### 5.2 단일 Writer 보장
|
|
380
|
+
|
|
381
|
+
**파일**: `src/core/worker-lock.ts` (신규)
|
|
382
|
+
|
|
383
|
+
```typescript
|
|
384
|
+
export class WorkerLock {
|
|
385
|
+
private lockFile: string;
|
|
386
|
+
|
|
387
|
+
constructor(lockPath: string = '/tmp/vector-worker.lock');
|
|
388
|
+
|
|
389
|
+
acquire(): boolean {
|
|
390
|
+
if (fs.existsSync(this.lockFile)) {
|
|
391
|
+
const pid = parseInt(fs.readFileSync(this.lockFile, 'utf8'));
|
|
392
|
+
if (this.isProcessRunning(pid)) {
|
|
393
|
+
return false; // 다른 worker 실행 중
|
|
394
|
+
}
|
|
395
|
+
// stale lock file 제거
|
|
396
|
+
fs.unlinkSync(this.lockFile);
|
|
397
|
+
}
|
|
398
|
+
fs.writeFileSync(this.lockFile, process.pid.toString());
|
|
399
|
+
return true;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
release(): void {
|
|
403
|
+
if (fs.existsSync(this.lockFile)) {
|
|
404
|
+
fs.unlinkSync(this.lockFile);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
**작업 항목**:
|
|
411
|
+
- [ ] WorkerLock 클래스
|
|
412
|
+
- [ ] acquire/release 메서드
|
|
413
|
+
- [ ] stale lock 처리
|
|
414
|
+
|
|
415
|
+
## Phase 6: CLI 및 모니터링 (P1)
|
|
416
|
+
|
|
417
|
+
### 6.1 CLI 커맨드
|
|
418
|
+
|
|
419
|
+
**파일**: `src/cli/index.ts` 수정
|
|
420
|
+
|
|
421
|
+
```typescript
|
|
422
|
+
// 벡터 워커 실행
|
|
423
|
+
program
|
|
424
|
+
.command('vector-worker')
|
|
425
|
+
.description('Process pending vector jobs')
|
|
426
|
+
.option('--once', 'Process once and exit')
|
|
427
|
+
.option('--reconcile', 'Also reconcile failed jobs')
|
|
428
|
+
.action(async (options) => {
|
|
429
|
+
const lock = new WorkerLock();
|
|
430
|
+
if (!lock.acquire()) {
|
|
431
|
+
console.log('Another worker is running');
|
|
432
|
+
process.exit(0);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
try {
|
|
436
|
+
if (options.reconcile) {
|
|
437
|
+
const recovered = await worker.reconcileFailed(3);
|
|
438
|
+
console.log(`Recovered ${recovered} failed jobs`);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const result = await worker.processAll();
|
|
442
|
+
console.log(`Processed: ${result.processed}, Succeeded: ${result.succeeded}, Failed: ${result.failed}`);
|
|
443
|
+
|
|
444
|
+
if (!options.once) {
|
|
445
|
+
// 주기적 실행
|
|
446
|
+
setInterval(async () => {
|
|
447
|
+
await worker.processAll();
|
|
448
|
+
}, 10000);
|
|
449
|
+
}
|
|
450
|
+
} finally {
|
|
451
|
+
lock.release();
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
**작업 항목**:
|
|
457
|
+
- [ ] `cli vector-worker` 커맨드
|
|
458
|
+
- [ ] `cli vector-status` 통계 조회
|
|
459
|
+
- [ ] `cli vector-reconcile` 수동 복구
|
|
460
|
+
|
|
461
|
+
### 6.2 상태 조회
|
|
462
|
+
|
|
463
|
+
```typescript
|
|
464
|
+
program
|
|
465
|
+
.command('vector-status')
|
|
466
|
+
.description('Show vector outbox status')
|
|
467
|
+
.action(async () => {
|
|
468
|
+
const metrics = await outbox.getMetrics();
|
|
469
|
+
console.log('Vector Outbox Status:');
|
|
470
|
+
console.log(` Pending: ${metrics.pendingCount}`);
|
|
471
|
+
console.log(` Processing: ${metrics.processingCount}`);
|
|
472
|
+
console.log(` Done: ${metrics.doneCount}`);
|
|
473
|
+
console.log(` Failed: ${metrics.failedCount}`);
|
|
474
|
+
console.log(` Last sync: ${metrics.lastProcessedAt || 'Never'}`);
|
|
475
|
+
});
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
**작업 항목**:
|
|
479
|
+
- [ ] 상태 조회 커맨드
|
|
480
|
+
- [ ] 테이블 형식 출력
|
|
481
|
+
|
|
482
|
+
## 파일 목록
|
|
483
|
+
|
|
484
|
+
### 신규 파일
|
|
485
|
+
```
|
|
486
|
+
src/core/vector-outbox.ts # Outbox 관리
|
|
487
|
+
src/core/worker-lock.ts # 단일 worker 락
|
|
488
|
+
```
|
|
489
|
+
|
|
490
|
+
### 수정 파일
|
|
491
|
+
```
|
|
492
|
+
src/core/types.ts # 타입 추가
|
|
493
|
+
src/core/vector-worker.ts # V2 로직 추가
|
|
494
|
+
src/core/vector-store.ts # upsert 추가
|
|
495
|
+
src/cli/index.ts # CLI 커맨드 추가
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
## 테스트
|
|
499
|
+
|
|
500
|
+
### 필수 테스트 케이스
|
|
501
|
+
|
|
502
|
+
1. **Idempotent Enqueue**
|
|
503
|
+
```typescript
|
|
504
|
+
await outbox.enqueue({ itemKind: 'entry', itemId: 'e1', embeddingVersion: 'v1' });
|
|
505
|
+
await outbox.enqueue({ itemKind: 'entry', itemId: 'e1', embeddingVersion: 'v1' });
|
|
506
|
+
// 두 번째는 isNew: false
|
|
507
|
+
const count = await db.query('SELECT COUNT(*) FROM vector_outbox');
|
|
508
|
+
expect(count[0].count).toBe(1);
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
2. **Process All**
|
|
512
|
+
```typescript
|
|
513
|
+
await outbox.enqueue({ itemKind: 'entry', itemId: 'e1', ... });
|
|
514
|
+
await outbox.enqueue({ itemKind: 'entry', itemId: 'e2', ... });
|
|
515
|
+
const result = await worker.processAll();
|
|
516
|
+
expect(result.processed).toBe(2);
|
|
517
|
+
expect(result.succeeded).toBe(2);
|
|
518
|
+
```
|
|
519
|
+
|
|
520
|
+
3. **Reconcile Failed**
|
|
521
|
+
```typescript
|
|
522
|
+
// 실패한 job 생성
|
|
523
|
+
await db.run(`
|
|
524
|
+
INSERT INTO vector_outbox (job_id, item_kind, item_id, embedding_version, status, retry_count)
|
|
525
|
+
VALUES ('j1', 'entry', 'e1', 'v1', 'failed', 1)
|
|
526
|
+
`);
|
|
527
|
+
const recovered = await worker.reconcileFailed(3);
|
|
528
|
+
expect(recovered).toBe(1);
|
|
529
|
+
// status가 pending으로 변경됨
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
4. **LanceDB Upsert**
|
|
533
|
+
```typescript
|
|
534
|
+
await vectorStore.upsert({ id: 'e1', vector: [0.1, 0.2], ... });
|
|
535
|
+
await vectorStore.upsert({ id: 'e1', vector: [0.3, 0.4], ... });
|
|
536
|
+
// 중복 없이 최신 벡터만 존재
|
|
537
|
+
const results = await vectorStore.search([0.3, 0.4], 10);
|
|
538
|
+
expect(results.filter(r => r.id === 'e1').length).toBe(1);
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
5. **Single Writer Lock**
|
|
542
|
+
```typescript
|
|
543
|
+
const lock1 = new WorkerLock();
|
|
544
|
+
const lock2 = new WorkerLock();
|
|
545
|
+
expect(lock1.acquire()).toBe(true);
|
|
546
|
+
expect(lock2.acquire()).toBe(false);
|
|
547
|
+
lock1.release();
|
|
548
|
+
expect(lock2.acquire()).toBe(true);
|
|
549
|
+
```
|
|
550
|
+
|
|
551
|
+
## 마일스톤
|
|
552
|
+
|
|
553
|
+
| 단계 | 완료 기준 |
|
|
554
|
+
|------|----------|
|
|
555
|
+
| M1 | 타입 정의 + vector_outbox 테이블 |
|
|
556
|
+
| M2 | VectorOutbox enqueue/getPending |
|
|
557
|
+
| M3 | VectorWorkerV2 claimJobs/markDone |
|
|
558
|
+
| M4 | VectorStore upsert |
|
|
559
|
+
| M5 | processAll() 전체 루프 |
|
|
560
|
+
| M6 | reconcile + recoverStuck |
|
|
561
|
+
| M7 | CLI 커맨드 |
|
|
562
|
+
| M8 | 테스트 통과 |
|