claude-memory-layer 1.0.11 → 1.0.12

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.
Files changed (99) hide show
  1. package/AGENTS.md +60 -0
  2. package/README.md +166 -2
  3. package/bootstrap-kb/decisions/decisions.md +244 -0
  4. package/bootstrap-kb/glossary/glossary.md +46 -0
  5. package/bootstrap-kb/modules/.claude-plugin.md +22 -0
  6. package/bootstrap-kb/modules/agents.md.md +15 -0
  7. package/bootstrap-kb/modules/claude.md.md +15 -0
  8. package/bootstrap-kb/modules/context.md.md +15 -0
  9. package/bootstrap-kb/modules/docs.md +18 -0
  10. package/bootstrap-kb/modules/handoff.md.md +15 -0
  11. package/bootstrap-kb/modules/package-lock.json.md +15 -0
  12. package/bootstrap-kb/modules/package.json.md +15 -0
  13. package/bootstrap-kb/modules/plan.md.md +15 -0
  14. package/bootstrap-kb/modules/readme.md.md +15 -0
  15. package/bootstrap-kb/modules/scripts.md +26 -0
  16. package/bootstrap-kb/modules/spec.md.md +15 -0
  17. package/bootstrap-kb/modules/specs.md +20 -0
  18. package/bootstrap-kb/modules/src.md +51 -0
  19. package/bootstrap-kb/modules/tests.md +42 -0
  20. package/bootstrap-kb/modules/tsconfig.json.md +15 -0
  21. package/bootstrap-kb/modules/vitest.config.ts.md +15 -0
  22. package/bootstrap-kb/overview/overview.md +40 -0
  23. package/bootstrap-kb/sources/manifest.json +950 -0
  24. package/bootstrap-kb/sources/manifest.md +227 -0
  25. package/bootstrap-kb/timeline/timeline.md +57 -0
  26. package/d.sh +3 -0
  27. package/deploy.sh +3 -0
  28. package/dist/cli/index.js +2389 -286
  29. package/dist/cli/index.js.map +4 -4
  30. package/dist/core/index.js +1017 -132
  31. package/dist/core/index.js.map +4 -4
  32. package/dist/hooks/post-tool-use.js +1347 -202
  33. package/dist/hooks/post-tool-use.js.map +4 -4
  34. package/dist/hooks/session-end.js +1339 -194
  35. package/dist/hooks/session-end.js.map +4 -4
  36. package/dist/hooks/session-start.js +1343 -198
  37. package/dist/hooks/session-start.js.map +4 -4
  38. package/dist/hooks/stop.js +1351 -206
  39. package/dist/hooks/stop.js.map +4 -4
  40. package/dist/hooks/user-prompt-submit.js +1347 -202
  41. package/dist/hooks/user-prompt-submit.js.map +4 -4
  42. package/dist/server/api/index.js +1436 -211
  43. package/dist/server/api/index.js.map +4 -4
  44. package/dist/server/index.js +1445 -220
  45. package/dist/server/index.js.map +4 -4
  46. package/dist/services/memory-service.js +1345 -199
  47. package/dist/services/memory-service.js.map +4 -4
  48. package/dist/ui/app.js +69 -2
  49. package/dist/ui/index.html +8 -0
  50. package/docs/MCP_MEMORY_SERVICE_COMPARATIVE_REVIEW.md +271 -0
  51. package/docs/MEMU_ADOPTION.md +40 -0
  52. package/memory/.claude-plugin/commands/2026-02-25.md +263 -0
  53. package/memory/_index.md +405 -0
  54. package/memory/default/uncategorized/2026-02-25.md +4839 -0
  55. package/memory/specs/20260207-dashboard-upgrade/2026-02-25.md +142 -0
  56. package/memory/specs/citations-system/2026-02-25.md +1121 -0
  57. package/memory/specs/endless-mode/2026-02-25.md +1392 -0
  58. package/memory/specs/entity-edge-model/2026-02-25.md +1263 -0
  59. package/memory/specs/evidence-aligner-v2/2026-02-25.md +1028 -0
  60. package/memory/specs/mcp-desktop-integration/2026-02-25.md +1334 -0
  61. package/memory/specs/post-tool-use-hook/2026-02-25.md +1164 -0
  62. package/memory/specs/private-tags/2026-02-25.md +1057 -0
  63. package/memory/specs/progressive-disclosure/2026-02-25.md +1436 -0
  64. package/memory/specs/task-entity-system/2026-02-25.md +924 -0
  65. package/memory/specs/vector-outbox-v2/2026-02-25.md +1510 -0
  66. package/memory/specs/web-viewer-ui/2026-02-25.md +1709 -0
  67. package/package.json +2 -1
  68. package/scripts/build.ts +6 -0
  69. package/src/cli/index.ts +281 -2
  70. package/src/core/consolidated-store.ts +63 -1
  71. package/src/core/consolidation-worker.ts +115 -6
  72. package/src/core/event-store.ts +14 -0
  73. package/src/core/index.ts +1 -0
  74. package/src/core/ingest-interceptor.ts +80 -0
  75. package/src/core/markdown-mirror.ts +70 -0
  76. package/src/core/md-mirror.ts +92 -0
  77. package/src/core/mongo-sync-config.ts +165 -0
  78. package/src/core/mongo-sync-worker.ts +381 -0
  79. package/src/core/retriever.ts +540 -150
  80. package/src/core/sqlite-event-store.ts +350 -1
  81. package/src/core/tag-taxonomy.ts +51 -0
  82. package/src/core/types.ts +28 -0
  83. package/src/server/api/health.ts +53 -0
  84. package/src/server/api/index.ts +3 -1
  85. package/src/server/api/stats.ts +46 -1
  86. package/src/services/bootstrap-organizer.ts +443 -0
  87. package/src/services/codex-session-history-importer.ts +474 -0
  88. package/src/services/memory-service.ts +373 -68
  89. package/src/ui/app.js +69 -2
  90. package/src/ui/index.html +8 -0
  91. package/tests/bootstrap-organizer.test.ts +111 -0
  92. package/tests/consolidation-worker.test.ts +75 -0
  93. package/tests/ingest-interceptor.test.ts +38 -0
  94. package/tests/markdown-mirror.test.ts +85 -0
  95. package/tests/md-mirror.test.ts +50 -0
  96. package/tests/retriever-fallback-chain.test.ts +223 -0
  97. package/tests/retriever-strategy-scope.test.ts +97 -0
  98. package/tests/retriever.memu-adoption.test.ts +122 -0
  99. package/tests/sqlite-event-store-replication.test.ts +92 -0
@@ -0,0 +1,1121 @@
1
+
2
+ ## 2026-02-25T12:31:26.220Z | 5f1e6336-dbdb-4bd2-96ea-d6f683c03325
3
+ - type: session_summary
4
+ - session: import:organized
5
+ # Citations System Context
6
+
7
+ > **Version**: 1.0.0
8
+ > **Created**: 2026-02-01
9
+
10
+ ## 1. 배경
11
+
12
+ ### 1.1 claude-mem의 접근 방식
13
+
14
+ claude-mem은 observation에 ID를 부여하여 참조 가능하게 함:
15
+
16
+ ```
17
+ [mem:abc123] 에서 참조한 정보입니다.
18
+ ```
19
+
20
+ **특징**:
21
+ - 모든 observation에 고유 ID
22
+ - 검색 결과에 ID 표시
23
+ - ID로 원본 조회 가능
24
+
25
+ ### 1.2 현재 code-memory의 상황
26
+
27
+ 현재 이벤트 ID는 존재하지만 인용 시스템 없음:
28
+
29
+ ```typescript
30
+ // 현재 검색 결과
31
+ {
32
+ eventId: "evt_abc123def456...", // 긴 UUID
33
+ content: "...",
34
+ score: 0.9
35
+ }
36
+ ```
37
+
38
+ **문제**:
39
+ 1. eventId가 너무 길어서 참조하기 불편
40
+ 2. 컨텍스트에 인용 표시 없음
41
+ 3. 출처 확인 어려움
42
+
43
+ ### 1.3 인용의 가치
44
+
45
+ | 인용 없음 | 인용 있음 |
46
+ |----------|----------|
47
+ | 출처 불명 | 명확한 출처 |
48
+ | 검증 불가 | 원본 확인 가능 |
49
+ | 맥락 손실 | 전후 관계 파악 |
50
+ | 신뢰도 낮음 | 신뢰도 높음 |
51
+
52
+ ## 2. ID 설계
53
+
54
+ ### 2.1 고려사항
55
+
56
+ | 요소 | 요구사항 |
57
+ |------|----------|
58
+ | 길이 | 짧고 기억하기 쉬움 |
59
+ | 고유성 | 충돌 확률 낮음 |
60
+ | 가독성 | 쉽게 읽고 말할 수 있음 |
61
+ | 생성 | 빠르고 결정적 |
62
+
63
+ ### 2.2 옵션 비교
64
+
65
+ | 옵션 | 예시 | 조합 수 | 장점 | 단점 |
66
+ |------|------|--------|------|------|
67
+ | 4자 base62 | a7Bc | 14.7M | 매우 짧음 | 충돌 위험 |
68
+ | **6자 base62** | a7Bc3x | 56.8B | 균형 | - |
69
+ | 8자 base62 | a7Bc3xYz | 218T | 충돌 없음 | 다소 김 |
70
+ | 8자 hex | ab12cd34 | 4.3B | 익숙함 | 효율 낮음 |
71
+
72
+ **선택**: 6자 base62 (56.8억 조합)
73
+ - 1000만 이벤트에서 충돌 확률 < 0.0001%
74
+
75
+ ### 2.3 생성 알고리즘
76
+
77
+ ```typescript
78
+ // SHA256 해시 기반 (결정적, 빠름)
79
+ function generateCitationId(eventId: string): string {
80
+ const hash = crypto.createHash('sha256').update(eventId).digest();
81
+
82
+ // base62 인코딩
83
+ const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
84
+ let id = '';
85
+ for (let i = 0; i < 6; i++) {
86
+ id += charset[hash[i] % 62];
87
+ }
88
+ return id;
89
+ }
90
+ ```
91
+
92
+ ## 3. 기존 코드와의 관계
93
+
94
+ ### 3.1 event-store.ts
95
+
96
+ 인용 테이블 추가:
97
+
98
+ ```sql
99
+ -- events 테이블과 1:1 관계
100
+ CREATE TABLE citations (
101
+ citation_id VARCHAR(8) PRIMARY KEY,
102
+ event_id VARCHAR NOT NULL UNIQUE REFERENCES events(event_id)
103
+ );
104
+ ```
105
+
106
+ ### 3.2 retriever.ts
107
+
108
+ 검색 결과에 인용 포함:
109
+
110
+ ```typescript
111
+ // 현재
112
+ async search(query): Promise<SearchResult[]>
113
+
114
+ // 확장
115
+ async searchWithCitations(query): Promise<CitedSearchResult[]>
116
+ ```
117
+
118
+ ### 3.3 context-formatter.ts
119
+
120
+ 인용 표시 포맷:
121
+
122
+ ```typescript
123
+ // 현재
124
+ > DuckDB를 사용하여...
125
+
126
+ // 확장
127
+ > DuckDB를 사용하여...
128
+ >
129
+ > [mem:a7Bc3x] - 2026-01-30, Session abc123
130
+ ```
131
+
132
+ ## 4. 설계 결정 사항
133
+
134
+ ### 4.1 생성 시점
135
+
136
+ **옵션 1: 이벤트 저장 시 즉시 생성**
137
+ - 장점: 항상 인용 ID 존재
138
+ - 단점: 저장 오버헤드
139
+
140
+ **옵션 2: 검색 시 지연 생성**
141
+ - 장점: 필요할 때만 생성
142
+ - 단점: 첫 검색 약간 느림
143
+
144
+ **선택**: 지연 생성 (getOrCreate 패턴)
145
+ - 저장 시 오버헤드 없음
146
+ - 대부분 이벤트는 검색되지 않음
147
+
148
+ ### 4.2 인용 포맷
149
+
150
+ **옵션들**:
151
+ 1. `[mem:a7Bc3x]` - 명확하고 검색 가능
152
+ 2. `(ref: a7Bc3x)` - 간결
153
+ 3. `¹` (각주 스타일) - 학술적
154
+ 4. `<a7Bc3x>` - 태그 스타일
155
+
156
+ **선택**: `[mem:a7Bc3x]`
157
+ - `mem:` 접두사로 명확한 의미
158
+ - 대괄호로 시각적 구분
159
+ - 검색/복사 용이
160
+
161
+ ### 4.3 컨텍스트 포함 방식
162
+
163
+ **인라인 방식** (선택):
164
+ ```markdown
165
+ > 내용...
166
+ > [mem:a7Bc3x] - 2026-01-30
167
+ ```
168
+
169
+ **각주 방식**:
170
+ ```markdown
171
+ DuckDB를 사용[1]...
172
+
173
+ ---
174
+ [1] mem:a7Bc3x - 2026-01-30
175
+ ```
176
+
177
+ **참조 방식**:
178
+ ```markdown
179
+ ## Content
180
+ DuckDB를 사용...
181
+
182
+ ## References
183
+ - [mem:a7Bc3x] Session abc123, 2026-01-30
184
+ ```
185
+
186
+ ## 5. 사용 추적
187
+
188
+ ### 5.1 목적
189
+
190
+ - 인기 있는 메모리 파악
191
+ - 자주 참조되는 지식 식별
192
+ - graduation 우선순위 결정
193
+
194
+ ### 5.2 추적 데이터
195
+
196
+ ```sql
197
+ CREATE TABLE citation_usages (
198
+ usage_id VARCHAR PRIMARY KEY,
199
+ citation_id VARCHAR NOT NULL,
200
+ session_id VARCHAR NOT NULL,
201
+ used_at TIMESTAMP,
202
+ context VARCHAR -- 검색 쿼리
203
+ );
204
+ ```
205
+
206
+ ### 5.3 통계 활용
207
+
208
+ ```typescript
209
+ // 인기 인용 → graduation 우선순위
210
+ async function graduationCandidates(): Promise<Event[]> {
211
+ const popular = await getPopularCitations({ limit: 100 });
212
+ return popular.filter(c => c.usageCount >= 5);
213
+ }
214
+ ```
215
+
216
+ ## 6. 성능 고려사항
217
+
218
+ ### 6.1 ID 생성
219
+
220
+ - SHA256 해시: ~1µs
221
+ - DB 조회 (exists): ~1ms
222
+ - 충돌 시 재시도: 드묾
223
+
224
+ ### 6.2 인덱스
225
+
226
+ ```sql
227
+ -- 빠른 조회를 위한 인덱스
228
+ CREATE INDEX idx_citations_event ON citations(event_id);
229
+ CREATE INDEX idx_usages_citation ON citation_usages(citation_id);
230
+ ```
231
+
232
+ ### 6.3 캐싱
233
+
234
+ ```typescript
235
+ // 최근 사용된 인용 캐싱
236
+ const citationCache = new LRUCache<string, Citation>({
237
+ max: 1000,
238
+ ttl: 3600000 // 1시간
239
+ });
240
+ ```
241
+
242
+ ## 7. 참고 자료
243
+
244
+ - **claude-mem**: Citation system with observation IDs
245
+ - **학술 인용**: APA, MLA 스타일
246
+ - **GitHub**: Issue/PR 참조 (#123)
247
+ - **Notion**: 블록 ID 참조 시스템
248
+
249
+ ## 2026-02-25T12:31:26.227Z | ed4343cd-9ae7-4b7a-ba31-e9b3a5a048da
250
+ - type: session_summary
251
+ - session: import:organized
252
+ # Citations System Implementation Plan
253
+
254
+ > **Version**: 1.0.0
255
+ > **Status**: Draft
256
+ > **Created**: 2026-02-01
257
+
258
+ ## Phase 1: 인용 저장소 (P0)
259
+
260
+ ### 1.1 스키마 정의
261
+
262
+ **파일**: `src/core/types.ts` 수정
263
+
264
+ ```typescript
265
+ export const CitationSchema = z.object({
266
+ citationId: z.string().length(6),
267
+ eventId: z.string(),
268
+ createdAt: z.date()
269
+ });
270
+
271
+ export type Citation = z.infer<typeof CitationSchema>;
272
+
273
+ export const CitationUsageSchema = z.object({
274
+ usageId: z.string(),
275
+ citationId: z.string(),
276
+ sessionId: z.string(),
277
+ usedAt: z.date(),
278
+ context: z.string().optional()
279
+ });
280
+
281
+ export type CitationUsage = z.infer<typeof CitationUsageSchema>;
282
+ ```
283
+
284
+ **작업 항목**:
285
+ - [ ] Citation 스키마 추가
286
+ - [ ] CitationUsage 스키마 추가
287
+ - [ ] 설정 스키마 확장
288
+
289
+ ### 1.2 DB 테이블
290
+
291
+ **파일**: `src/core/event-store.ts` 수정
292
+
293
+ ```typescript
294
+ private async initSchema(): Promise<void> {
295
+ // 기존 테이블...
296
+
297
+ // 인용 테이블
298
+ await this.db.exec(`
299
+ CREATE TABLE IF NOT EXISTS citations (
300
+ citation_id VARCHAR(8) PRIMARY KEY,
301
+ event_id VARCHAR NOT NULL,
302
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
303
+ UNIQUE(event_id)
304
+ );
305
+
306
+ CREATE INDEX IF NOT EXISTS idx_citations_event ON citations(event_id);
307
+ `);
308
+
309
+ // 사용 로그 테이블
310
+ await this.db.exec(`
311
+ CREATE TABLE IF NOT EXISTS citation_usages (
312
+ usage_id VARCHAR PRIMARY KEY,
313
+ citation_id VARCHAR NOT NULL,
314
+ session_id VARCHAR NOT NULL,
315
+ used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
316
+ context VARCHAR
317
+ );
318
+
319
+ CREATE INDEX IF NOT EXISTS idx_usages_citation ON citation_usages(citation_id);
320
+ `);
321
+ }
322
+ ```
323
+
324
+ **작업 항목**:
325
+ - [ ] citations 테이블 생성
326
+ - [ ] citation_usages 테이블 생성
327
+ - [ ] 인덱스 생성
328
+
329
+ ## Phase 2: 인용 ID 생성 (P0)
330
+
331
+ ### 2.1 ID 생성기
332
+
333
+ **파일**: `src/core/citation-generator.ts` (신규)
334
+
335
+ ```typescript
336
+ import { createHash } from 'crypto';
337
+
338
+ const ID_LENGTH = 6;
339
+ const CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
340
+
341
+ export function generateCitationId(eventId: string): string {
342
+ const hash = createHash('sha256')
343
+ .update(eventId)
344
+ .digest();
345
+
346
+ let id = '';
347
+ for (let i = 0; i < ID_LENGTH; i++) {
348
+ id += CHARSET[hash[i] % CHARSET.length];
349
+ }
350
+
351
+ return id;
352
+ }
353
+
354
+ // 충돌 처리 (드문 경우)
355
+ export async function generateUniqueCitationId(
356
+ eventId: string,
357
+ store: CitationStore
358
+ ): Promise<string> {
359
+ let id = generateCitationId(eventId);
360
+ let attempt = 0;
361
+
362
+ while (await store.exists(id) && attempt < 10) {
363
+ // 솔트 추가하여 재생성
364
+ id = generateCitationId(`${eventId}:${attempt}`);
365
+ attempt++;
366
+ }
367
+
368
+ if (attempt >= 10) {
369
+ throw new Error('Failed to generate unique citation ID');
370
+ }
371
+
372
+ return id;
373
+ }
374
+ ```
375
+
376
+ **작업 항목**:
377
+ - [ ] generateCitationId 함수 구현
378
+ - [ ] 충돌 처리 로직
379
+ - [ ] 유닛 테스트
380
+
381
+ ### 2.2 인용 저장소
382
+
383
+ **파일**: `src/core/citation-store.ts` (신규)
384
+
385
+ ```typescript
386
+ export class CitationStore {
387
+ constructor(private db: Database) {}
388
+
389
+ async create(citation: CitationInput): Promise<Citation> {
390
+ await this.db.run(`
391
+ INSERT INTO citations (citation_id, event_id, created_at)
392
+ VALUES (?, ?, ?)
393
+ `, [citation.citationId, citation.eventId, new Date()]);
394
+
395
+ return { ...citation, createdAt: new Date() };
396
+ }
397
+
398
+ async findById(citationId: string): Promise<Citation | null> {
399
+ return this.db.get(`
400
+ SELECT * FROM citations WHERE citation_id = ?
401
+ `, [citationId]);
402
+ }
403
+
404
+ async findByEventId(eventId: string): Promise<Citation | null> {
405
+ return this.db.get(`
406
+ SELECT * FROM citations WHERE event_id = ?
407
+ `, [eventId]);
408
+ }
409
+
410
+ async exists(citationId: string): Promise<boolean> {
411
+ const result = await this.db.get(`
412
+ SELECT 1 FROM citations WHERE citation_id = ?
413
+ `, [citationId]);
414
+ return !!result;
415
+ }
416
+
417
+ async getOrCreate(eventId: string): Promise<Citation> {
418
+ const existing = await this.findByEventId(eventId);
419
+ if (existing) return existing;
420
+
421
+ const citationId = await generateUniqueCitationId(eventId, this);
422
+ return this.create({ citationId, eventId });
423
+ }
424
+ }
425
+ ```
426
+
427
+ **작업 항목**:
428
+ - [ ] CitationStore 클래스 구현
429
+ - [ ] CRUD 메서드
430
+ - [ ] getOrCreate 패턴
431
+
432
+ ## Phase 3: 컨텍스트 통합 (P0)
433
+
434
+ ### 3.1 인용 포함 검색
435
+
436
+ **파일**: `src/core/retriever.ts` 수정
437
+
438
+ ```typescript
439
+ export interface CitedSearchResult {
440
+ event: Event;
441
+ citation: Citation;
442
+ score: number;
443
+ }
444
+
445
+ export class Retriever {
446
+ async searchWithCitations(
447
+ query: string,
448
+ options?: SearchOptions
449
+ ): Promise<CitedSearchResult[]> {
450
+ const results = await this.search(query, options);
451
+
452
+ return Promise.all(
453
+ results.map(async (result) => {
454
+ const citation = await this.citationStore.getOrCreate(result.eventId);
455
+ return {
456
+ event: result,
457
+ citation,
458
+ score: result.score
459
+ };
460
+ })
461
+ );
462
+ }
463
+ }
464
+ ```
465
+
466
+ **작업 항목**:
467
+ - [ ] searchWithCitations 메서드 추가
468
+ - [ ] 인용 자동 생성/조회
469
+
470
+ ### 3.2 컨텍스트 포맷터 수정
471
+
472
+ **파일**: `src/core/context-formatter.ts` 수정
473
+
474
+ ```typescript
475
+ export function formatContextWithCitations(
476
+ results: CitedSearchResult[],
477
+ options?: FormatOptions
478
+ ): string {
479
+ const format = options?.format ?? 'inline';
480
+
481
+ switch (format) {
482
+ case 'inline':
483
+ return formatInline(results);
484
+ case 'footnote':
485
+ return formatFootnote(results);
486
+ case 'reference':
487
+ return formatReference(results);
488
+ }
489
+ }
490
+
491
+ function formatInline(results: CitedSearchResult[]): string {
492
+ return results.map(r => {
493
+ const date = r.event.timestamp.toLocaleDateString();
494
+ const session = r.event.sessionId.slice(0, 6);
495
+
496
+ return [
497
+ `> ${r.event.payload.content}`,
498
+ `>`,
499
+ `> [mem:${r.citation.citationId}] - ${date}, Session ${session}`
500
+ ].join('\n');
501
+ }).join('\n\n---\n\n');
502
+ }
503
+ ```
504
+
505
+ **작업 항목**:
506
+ - [ ] 인라인 포맷 구현
507
+ - [ ] 각주 포맷 구현
508
+ - [ ] 참조 포맷 구현
509
+
510
+ ## Phase 4: 조회 인터페이스 (P0)
511
+
512
+ ### 4.1 CLI 명령
513
+
514
+ **파일**: `src/cli/commands/show.ts` (신규)
515
+
516
+ ```typescript
517
+ import { Command } from 'commander';
518
+
519
+ export const showCommand = new Command('show')
520
+ .argument('<citation>', 'Citation ID (e.g., mem:a7Bc3x or just a7Bc3x)')
521
+ .description('Show full content of a cited memory')
522
+ .action(async (citation: string) => {
523
+ const memoryService = await MemoryService.getInstance();
524
+
525
+ // mem: 접두사 제거
526
+ const citationId = citation.replace(/^mem:/, '');
527
+
528
+ const result = await memoryService.getCitedMemory(citationId);
529
+
530
+ if (!result) {
531
+ console.log(chalk.red(`Citation not found: ${citationId}`));
532
+ return;
533
+ }
534
+
535
+ // 출력 포맷팅
536
+ console.log(chalk.bold(`📄 Memory Citation: ${citationId}`));
537
+ console.log();
538
+ console.log(`Session: ${result.event.sessionId}`);
539
+ console.log(`Date: ${result.event.timestamp.toLocaleString()}`);
540
+ console.log(`Type: ${result.event.eventType}`);
541
+ console.log();
542
+ console.log('Content:');
543
+ console.log('─'.repeat(40));
544
+ console.log(result.event.payload.content);
545
+ console.log('─'.repeat(40));
546
+
547
+ if (result.related) {
548
+ console.log();
549
+ console.log('Related:');
550
+ if (result.related.previous) {
551
+ console.log(` Previous: [mem:${result.related.previous.citationId}]`);
552
+ }
553
+ if (result.related.next) {
554
+ console.log(` Next: [mem:${result.related.next.citationId}]`);
555
+ }
556
+ }
557
+ });
558
+ ```
559
+
560
+ **작업 항목**:
561
+ - [ ] show 명령 구현
562
+ - [ ] 출력 포맷팅
563
+ - [ ] 관련 인용 표시
564
+
565
+ ### 4.2 API 엔드포인트
566
+
567
+ **파일**: `src/server/api/citations.ts` (신규)
568
+
569
+ ```typescript
570
+ import { Hono } from 'hono';
571
+
572
+ export const citationsRouter = new Hono();
573
+
574
+ // GET /api/citations/:id
575
+ citationsRouter.get('/:id', async (c) => {
576
+ const { id } = c.req.param();
577
+ const memoryService = await MemoryService.getInstance();
578
+
579
+ const result = await memoryService.getCitedMemory(id);
580
+
581
+ if (!result) {
582
+ return c.json({ error: 'Citation not found' }, 404);
583
+ }
584
+
585
+ return c.json(result);
586
+ });
587
+
588
+ // GET /api/citations/:id/related
589
+ citationsRouter.get('/:id/related', async (c) => {
590
+ const { id } = c.req.param();
591
+ const memoryService = await MemoryService.getInstance();
592
+
593
+ const related = await memoryService.getRelatedCitations(id);
594
+
595
+ return c.json({ related });
596
+ });
597
+ ```
598
+
599
+ **작업 항목**:
600
+ - [ ] 인용 조회 API
601
+ - [ ] 관련 인용 API
602
+ - [ ] 에러 처리
603
+
604
+ ## Phase 5: 사용 추적 (P1)
605
+
606
+ ### 5.1 사용 로깅
607
+
608
+ **파일**: `src/core/citation-store.ts` 수정
609
+
610
+ ```typescript
611
+ export class CitationStore {
612
+ async logUsage(
613
+ citationId: string,
614
+ sessionId: string,
615
+ context?: string
616
+ ): Promise<void> {
617
+ const usageId = crypto.randomUUID();
618
+
619
+ await this.db.run(`
620
+ INSERT INTO citation_usages (usage_id, citation_id, session_id, used_at, context)
621
+ VALUES (?, ?, ?, ?, ?)
622
+ `, [usageId, citationId, sessionId, new Date(), context]);
623
+ }
624
+
625
+ async getUsageStats(citationId: string): Promise<CitationStats> {
626
+ const result = await this.db.get(`
627
+ SELECT
628
+ COUNT(*) as usage_count,
629
+ MAX(used_at) as last_used
630
+ FROM citation_usages
631
+ WHERE citation_id = ?
632
+ `, [citationId]);
633
+
634
+ return {
635
+ usageCount: result.usage_count,
636
+ lastUsed: result.last_used ? new Date(result.last_used) : null
637
+ };
638
+ }
639
+ }
640
+ ```
641
+
642
+ **작업 항목**:
643
+ - [ ] 사용 로깅 구현
644
+ - [ ] 통계 조회
645
+ - [ ] user-prompt-submit 훅에서 로깅
646
+
647
+ ### 5.2 인기 인용 통계
648
+
649
+ ```typescript
650
+ async getPopularCitations(options?: { limit?: number; days?: number }): Promise<PopularCitation[]> {
651
+ const { limit = 10, days = 30 } = options || {};
652
+
653
+ return this.db.query(`
654
+ SELECT
655
+ c.citation_id,
656
+ e.event_type,
657
+ SUBSTR(JSON_EXTRACT(e.payload_json, '$.content'), 1, 100) as preview,
658
+ COUNT(u.usage_id) as usage_count,
659
+ MAX(u.used_at) as last_used
660
+ FROM citations c
661
+ JOIN events e ON c.event_id = e.event_id
662
+ LEFT JOIN citation_usages u ON c.citation_id = u.citation_id
663
+ AND u.used_at > datetime('now', '-${days} days')
664
+ GROUP BY c.citation_id
665
+ ORDER BY usage_count DESC
666
+ LIMIT ?
667
+ `, [limit]);
668
+ }
669
+ ```
670
+
671
+ **작업 항목**:
672
+ - [ ] 인기 인용 조회
673
+ - [ ] 기간별 필터링
674
+ - [ ] Stats API에 추가
675
+
676
+ ## 파일 목록
677
+
678
+ ### 신규 파일
679
+ ```
680
+ src/core/citation-generator.ts # ID 생성
681
+ src/core/citation-store.ts # 인용 저장소
682
+ src/cli/commands/show.ts # show 명령
683
+ src/server/api/citations.ts # 인용 API
684
+ ```
685
+
686
+ ### 수정 파일
687
+ ```
688
+ src/core/types.ts # 스키마 추가
689
+ src/core/event-store.ts # 테이블 추가
690
+ src/core/retriever.ts # 인용 포함 검색
691
+ src/core/context-formatter.ts # 인용 포맷
692
+ src/hooks/user-prompt-submit.ts # 사용 로깅
693
+ src/cli/index.ts # show 명령 등록
694
+ src/server/api/index.ts # citations 라우터 추가
695
+ ```
696
+
697
+ ## 테스트
698
+
699
+ ### 필수 테스트 케이스
700
+
701
+ 1. **ID 생성**
702
+ ```typescript
703
+ test('should generate 6-char citation ID', () => {
704
+ const id = generateCitationId('event_123');
705
+ expect(id.length).toBe(6);
706
+ expect(/^[A-Za-z0-9]+$/.test(id)).toBe(true);
707
+ });
708
+ ```
709
+
710
+ 2. **충돌 처리**
711
+ ```typescript
712
+ test('should handle ID collision', async () => {
713
+ // 첫 번째 이벤트 저장
714
+ await store.create({ citationId: 'abc123', eventId: 'event_1' });
715
+
716
+ // 충돌 시 다른 ID 생성
717
+ const id = await generateUniqueCitationId('event_2', store);
718
+ expect(id).not.toBe('abc123');
719
+ });
720
+ ```
721
+
722
+ 3. **컨텍스트 포맷**
723
+ ```typescript
724
+ test('should format context with citations', () => {
725
+ const formatted = formatContextWithCitations([{
726
+ event: mockEvent,
727
+ citation: { citationId: 'a7Bc3x', ... },
728
+ score: 0.9
729
+ }]);
730
+
731
+ expect(formatted).toContain('[mem:a7Bc3x]');
732
+ });
733
+ ```
734
+
735
+ ## 마일스톤
736
+
737
+ | 단계 | 완료 기준 |
738
+ |------|----------|
739
+ | M1 | 스키마 및 테이블 생성 |
740
+ | M2 | ID 생성기 구현 |
741
+ | M3 | CitationStore 구현 |
742
+ | M4 | 검색에 인용 통합 |
743
+ | M5 | CLI show 명령 |
744
+ | M6 | API 엔드포인트 |
745
+ | M7 | 사용 추적 |
746
+ | M8 | 테스트 통과 |
747
+
748
+ ## 2026-02-25T12:31:26.235Z | 291960d8-18b8-42ca-b47d-8e822fb68b05
749
+ - type: session_summary
750
+ - session: import:organized
751
+ # Citations System Specification
752
+
753
+ > **Version**: 1.0.0
754
+ > **Status**: Draft
755
+ > **Created**: 2026-02-01
756
+ > **Reference**: claude-mem (thedotmack/claude-mem)
757
+
758
+ ## 1. 개요
759
+
760
+ ### 1.1 문제 정의
761
+
762
+ 현재 시스템에서 메모리 출처 추적이 어려움:
763
+
764
+ 1. **출처 불명확**: 검색 결과가 어느 세션에서 왔는지 즉시 파악 어려움
765
+ 2. **검증 불가**: AI가 참조한 정보의 원본 확인 어려움
766
+ 3. **맥락 손실**: 인용된 정보의 전후 맥락 파악 어려움
767
+
768
+ ### 1.2 해결 방향
769
+
770
+ **Citations (인용) 시스템**:
771
+ - 모든 메모리에 고유 인용 ID 부여
772
+ - 컨텍스트 주입 시 인용 표시
773
+ - 클릭/명령으로 원본 조회 가능
774
+
775
+ ## 2. 핵심 개념
776
+
777
+ ### 2.1 인용 형식
778
+
779
+ ```
780
+ [mem:abc123] 에서 참조한 정보입니다.
781
+ ```
782
+
783
+ ### 2.2 인용 구조
784
+
785
+ ```typescript
786
+ interface Citation {
787
+ // 식별
788
+ id: string; // 짧은 인용 ID (6-8자)
789
+ eventId: string; // 전체 이벤트 ID
790
+
791
+ // 출처 정보
792
+ sessionId: string;
793
+ timestamp: Date;
794
+ eventType: 'prompt' | 'response' | 'tool' | 'insight';
795
+
796
+ // 메타데이터
797
+ preview: string; // 50자 미리보기
798
+ confidence: number; // 매칭 신뢰도
799
+ relevanceScore: number; // 검색 관련성 점수
800
+ }
801
+ ```
802
+
803
+ ### 2.3 인용 ID 생성
804
+
805
+ ```typescript
806
+ // 짧고 읽기 쉬운 ID
807
+ function generateCitationId(eventId: string): string {
808
+ // eventId의 해시에서 6자 추출
809
+ const hash = crypto.createHash('sha256')
810
+ .update(eventId)
811
+ .digest('base64url')
812
+ .slice(0, 6);
813
+
814
+ return hash; // 예: "a7Bc3x"
815
+ }
816
+ ```
817
+
818
+ ## 3. 데이터 스키마
819
+
820
+ ### 3.1 인용 테이블
821
+
822
+ ```sql
823
+ CREATE TABLE citations (
824
+ citation_id VARCHAR(8) PRIMARY KEY,
825
+ event_id VARCHAR NOT NULL REFERENCES events(event_id),
826
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
827
+
828
+ -- 인덱스
829
+ UNIQUE(event_id)
830
+ );
831
+
832
+ CREATE INDEX idx_citations_event ON citations(event_id);
833
+ ```
834
+
835
+ ### 3.2 이벤트 확장
836
+
837
+ ```typescript
838
+ const EventSchema = z.object({
839
+ eventId: z.string(),
840
+ // ... 기존 필드
841
+
842
+ // 인용 정보 추가
843
+ citationId: z.string().optional(), // 생성된 인용 ID
844
+ });
845
+ ```
846
+
847
+ ## 4. 인용 생성 흐름
848
+
849
+ ### 4.1 자동 생성
850
+
851
+ ```typescript
852
+ // 이벤트 저장 시 자동으로 인용 ID 생성
853
+ async function storeEventWithCitation(event: Event): Promise<string> {
854
+ const eventId = await eventStore.append(event);
855
+
856
+ // 인용 ID 생성 및 저장
857
+ const citationId = generateCitationId(eventId);
858
+ await citationStore.create({
859
+ citationId,
860
+ eventId,
861
+ createdAt: new Date()
862
+ });
863
+
864
+ return eventId;
865
+ }
866
+ ```
867
+
868
+ ### 4.2 지연 생성
869
+
870
+ ```typescript
871
+ // 검색 시 필요할 때만 인용 ID 생성
872
+ async function getCitationId(eventId: string): Promise<string> {
873
+ // 기존 인용 확인
874
+ const existing = await citationStore.findByEventId(eventId);
875
+ if (existing) {
876
+ return existing.citationId;
877
+ }
878
+
879
+ // 새로 생성
880
+ const citationId = generateCitationId(eventId);
881
+ await citationStore.create({ citationId, eventId });
882
+ return citationId;
883
+ }
884
+ ```
885
+
886
+ ## 5. 컨텍스트 주입
887
+
888
+ ### 5.1 인용 포함 포맷
889
+
890
+ ```markdown
891
+ ## Relevant Context
892
+
893
+ Based on previous conversations:
894
+
895
+ > DuckDB를 사용하여 이벤트 소싱 패턴을 구현하는 것이 좋습니다.
896
+ > 이벤트는 불변이어야 하며, append-only 방식으로 저장합니다.
897
+ >
898
+ > [mem:a7Bc3x] - 2026-01-30, Session abc123
899
+
900
+ ---
901
+
902
+ > 타입 안전성을 위해 Zod 스키마를 사용하세요.
903
+ >
904
+ > [mem:x9Yz2w] - 2026-01-29, Session def456
905
+ ```
906
+
907
+ ### 5.2 포맷터 구현
908
+
909
+ ```typescript
910
+ interface CitedMemory {
911
+ content: string;
912
+ citation: Citation;
913
+ }
914
+
915
+ function formatCitedContext(memories: CitedMemory[]): string {
916
+ const parts = memories.map(m => {
917
+ const lines = [
918
+ `> ${m.content}`,
919
+ `>`,
920
+ `> [mem:${m.citation.id}] - ${formatDate(m.citation.timestamp)}, ` +
921
+ `Session ${m.citation.sessionId.slice(0, 6)}`
922
+ ];
923
+ return lines.join('\n');
924
+ });
925
+
926
+ return [
927
+ '## Relevant Context',
928
+ '',
929
+ 'Based on previous conversations:',
930
+ '',
931
+ parts.join('\n\n---\n\n')
932
+ ].join('\n');
933
+ }
934
+ ```
935
+
936
+ ## 6. 인용 조회
937
+
938
+ ### 6.1 CLI 명령
939
+
940
+ ```bash
941
+ # 인용 ID로 원본 조회
942
+ $ code-memory show mem:a7Bc3x
943
+
944
+ 📄 Memory Citation: a7Bc3x
945
+
946
+ Session: abc123
947
+ Date: 2026-01-30 14:05
948
+ Type: assistant_response
949
+
950
+ Content:
951
+ ────────────────────────────────────────
952
+ DuckDB를 사용하여 이벤트 소싱 패턴을 구현하는 것이 좋습니다.
953
+ 이벤트는 불변이어야 하며, append-only 방식으로 저장합니다.
954
+
955
+ 스키마 예시:
956
+ ```sql
957
+ CREATE TABLE events (
958
+ event_id VARCHAR PRIMARY KEY,
959
+ ...
960
+ );
961
+ ```
962
+ ────────────────────────────────────────
963
+
964
+ Related:
965
+ Previous: [mem:b8Xc2y] - User question about DB design
966
+ Next: [mem:c9Yd3z] - Follow-up on indexing
967
+ ```
968
+
969
+ ### 6.2 API 엔드포인트
970
+
971
+ ```typescript
972
+ // GET /api/citations/:id
973
+ router.get('/citations/:id', async (c) => {
974
+ const { id } = c.req.param();
975
+
976
+ const citation = await citationStore.findById(id);
977
+ if (!citation) {
978
+ return c.json({ error: 'Citation not found' }, 404);
979
+ }
980
+
981
+ const event = await eventStore.findById(citation.eventId);
982
+ const related = await getRelatedEvents(citation.eventId);
983
+
984
+ return c.json({
985
+ citation,
986
+ event,
987
+ related
988
+ });
989
+ });
990
+ ```
991
+
992
+ ### 6.3 슬래시 명령
993
+
994
+ ```
995
+ User: /show a7Bc3x
996
+
997
+ ---
998
+ 이 메모리의 전체 내용을 보여드립니다:
999
+
1000
+ [원본 내용 표시]
1001
+ ---
1002
+ ```
1003
+
1004
+ ## 7. 인용 검색
1005
+
1006
+ ### 7.1 인용 ID로 검색
1007
+
1008
+ ```typescript
1009
+ async function searchByCitation(citationId: string): Promise<Event | null> {
1010
+ const citation = await citationStore.findById(citationId);
1011
+ if (!citation) return null;
1012
+
1013
+ return eventStore.findById(citation.eventId);
1014
+ }
1015
+ ```
1016
+
1017
+ ### 7.2 역참조 검색
1018
+
1019
+ ```typescript
1020
+ // 특정 이벤트를 인용한 세션들 조회
1021
+ async function findCitingSession(citationId: string): Promise<string[]> {
1022
+ // 인용 사용 로그에서 검색
1023
+ const usages = await citationUsageStore.findByCitationId(citationId);
1024
+ return [...new Set(usages.map(u => u.sessionId))];
1025
+ }
1026
+ ```
1027
+
1028
+ ## 8. 인용 사용 추적
1029
+
1030
+ ### 8.1 사용 로그
1031
+
1032
+ ```sql
1033
+ CREATE TABLE citation_usages (
1034
+ usage_id VARCHAR PRIMARY KEY,
1035
+ citation_id VARCHAR NOT NULL,
1036
+ session_id VARCHAR NOT NULL,
1037
+ used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1038
+ context VARCHAR -- 어떤 쿼리에서 사용됐는지
1039
+ );
1040
+
1041
+ CREATE INDEX idx_usages_citation ON citation_usages(citation_id);
1042
+ CREATE INDEX idx_usages_session ON citation_usages(session_id);
1043
+ ```
1044
+
1045
+ ### 8.2 인기 인용 통계
1046
+
1047
+ ```typescript
1048
+ async function getPopularCitations(limit: number = 10): Promise<CitationStats[]> {
1049
+ return db.query(`
1050
+ SELECT
1051
+ c.citation_id,
1052
+ COUNT(u.usage_id) as usage_count,
1053
+ MAX(u.used_at) as last_used
1054
+ FROM citations c
1055
+ LEFT JOIN citation_usages u ON c.citation_id = u.citation_id
1056
+ GROUP BY c.citation_id
1057
+ ORDER BY usage_count DESC
1058
+ LIMIT ?
1059
+ `, [limit]);
1060
+ }
1061
+ ```
1062
+
1063
+ ## 9. UI 표시
1064
+
1065
+ ### 9.1 CLI
1066
+
1067
+ ```
1068
+ $ code-memory search "DuckDB"
1069
+
1070
+ 🔍 Search Results:
1071
+
1072
+ #1 [mem:a7Bc3x] (score: 0.94)
1073
+ "DuckDB를 사용하여 이벤트 소싱 패턴을..."
1074
+ 📅 2026-01-30 | 🔗 Session abc123
1075
+
1076
+ #2 [mem:d4Ef5g] (score: 0.87)
1077
+ "DuckDB의 인덱싱 전략..."
1078
+ 📅 2026-01-29 | 🔗 Session def456
1079
+
1080
+ 💡 Use "code-memory show mem:a7Bc3x" for full content
1081
+ ```
1082
+
1083
+ ### 9.2 Web Viewer
1084
+
1085
+ ```html
1086
+ <div class="search-result">
1087
+ <div class="result-header">
1088
+ <span class="citation-badge" title="Click to copy">
1089
+ [mem:a7Bc3x]
1090
+ </span>
1091
+ <span class="score">0.94</span>
1092
+ </div>
1093
+ <p class="preview">DuckDB를 사용하여 이벤트 소싱 패턴을...</p>
1094
+ <div class="metadata">
1095
+ <span>📅 2026-01-30</span>
1096
+ <a href="/sessions/abc123">🔗 Session abc123</a>
1097
+ </div>
1098
+ <button onclick="showCitation('a7Bc3x')">View Full</button>
1099
+ </div>
1100
+ ```
1101
+
1102
+ ## 10. 설정
1103
+
1104
+ ```typescript
1105
+ const CitationsConfigSchema = z.object({
1106
+ enabled: z.boolean().default(true),
1107
+ idLength: z.number().default(6), // 인용 ID 길이
1108
+ includeInContext: z.boolean().default(true), // 컨텍스트에 포함
1109
+ trackUsage: z.boolean().default(true), // 사용 추적
1110
+ format: z.enum(['inline', 'footnote', 'reference']).default('inline')
1111
+ });
1112
+ ```
1113
+
1114
+ ## 11. 성공 기준
1115
+
1116
+ - [ ] 모든 이벤트에 인용 ID 자동 생성
1117
+ - [ ] 컨텍스트 주입 시 인용 표시
1118
+ - [ ] `code-memory show mem:xxx` 명령 동작
1119
+ - [ ] Web Viewer에서 인용 클릭 시 원본 표시
1120
+ - [ ] 인용 사용 통계 수집
1121
+ - [ ] 인용 ID 충돌 없음 (6자, 64^6 = 687억 조합)