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,495 @@
|
|
|
1
|
+
# Citations System Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **Version**: 1.0.0
|
|
4
|
+
> **Status**: Draft
|
|
5
|
+
> **Created**: 2026-02-01
|
|
6
|
+
|
|
7
|
+
## Phase 1: 인용 저장소 (P0)
|
|
8
|
+
|
|
9
|
+
### 1.1 스키마 정의
|
|
10
|
+
|
|
11
|
+
**파일**: `src/core/types.ts` 수정
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
export const CitationSchema = z.object({
|
|
15
|
+
citationId: z.string().length(6),
|
|
16
|
+
eventId: z.string(),
|
|
17
|
+
createdAt: z.date()
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
export type Citation = z.infer<typeof CitationSchema>;
|
|
21
|
+
|
|
22
|
+
export const CitationUsageSchema = z.object({
|
|
23
|
+
usageId: z.string(),
|
|
24
|
+
citationId: z.string(),
|
|
25
|
+
sessionId: z.string(),
|
|
26
|
+
usedAt: z.date(),
|
|
27
|
+
context: z.string().optional()
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export type CitationUsage = z.infer<typeof CitationUsageSchema>;
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
**작업 항목**:
|
|
34
|
+
- [ ] Citation 스키마 추가
|
|
35
|
+
- [ ] CitationUsage 스키마 추가
|
|
36
|
+
- [ ] 설정 스키마 확장
|
|
37
|
+
|
|
38
|
+
### 1.2 DB 테이블
|
|
39
|
+
|
|
40
|
+
**파일**: `src/core/event-store.ts` 수정
|
|
41
|
+
|
|
42
|
+
```typescript
|
|
43
|
+
private async initSchema(): Promise<void> {
|
|
44
|
+
// 기존 테이블...
|
|
45
|
+
|
|
46
|
+
// 인용 테이블
|
|
47
|
+
await this.db.exec(`
|
|
48
|
+
CREATE TABLE IF NOT EXISTS citations (
|
|
49
|
+
citation_id VARCHAR(8) PRIMARY KEY,
|
|
50
|
+
event_id VARCHAR NOT NULL,
|
|
51
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
52
|
+
UNIQUE(event_id)
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
CREATE INDEX IF NOT EXISTS idx_citations_event ON citations(event_id);
|
|
56
|
+
`);
|
|
57
|
+
|
|
58
|
+
// 사용 로그 테이블
|
|
59
|
+
await this.db.exec(`
|
|
60
|
+
CREATE TABLE IF NOT EXISTS citation_usages (
|
|
61
|
+
usage_id VARCHAR PRIMARY KEY,
|
|
62
|
+
citation_id VARCHAR NOT NULL,
|
|
63
|
+
session_id VARCHAR NOT NULL,
|
|
64
|
+
used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
65
|
+
context VARCHAR
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
CREATE INDEX IF NOT EXISTS idx_usages_citation ON citation_usages(citation_id);
|
|
69
|
+
`);
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
**작업 항목**:
|
|
74
|
+
- [ ] citations 테이블 생성
|
|
75
|
+
- [ ] citation_usages 테이블 생성
|
|
76
|
+
- [ ] 인덱스 생성
|
|
77
|
+
|
|
78
|
+
## Phase 2: 인용 ID 생성 (P0)
|
|
79
|
+
|
|
80
|
+
### 2.1 ID 생성기
|
|
81
|
+
|
|
82
|
+
**파일**: `src/core/citation-generator.ts` (신규)
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
import { createHash } from 'crypto';
|
|
86
|
+
|
|
87
|
+
const ID_LENGTH = 6;
|
|
88
|
+
const CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
89
|
+
|
|
90
|
+
export function generateCitationId(eventId: string): string {
|
|
91
|
+
const hash = createHash('sha256')
|
|
92
|
+
.update(eventId)
|
|
93
|
+
.digest();
|
|
94
|
+
|
|
95
|
+
let id = '';
|
|
96
|
+
for (let i = 0; i < ID_LENGTH; i++) {
|
|
97
|
+
id += CHARSET[hash[i] % CHARSET.length];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return id;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// 충돌 처리 (드문 경우)
|
|
104
|
+
export async function generateUniqueCitationId(
|
|
105
|
+
eventId: string,
|
|
106
|
+
store: CitationStore
|
|
107
|
+
): Promise<string> {
|
|
108
|
+
let id = generateCitationId(eventId);
|
|
109
|
+
let attempt = 0;
|
|
110
|
+
|
|
111
|
+
while (await store.exists(id) && attempt < 10) {
|
|
112
|
+
// 솔트 추가하여 재생성
|
|
113
|
+
id = generateCitationId(`${eventId}:${attempt}`);
|
|
114
|
+
attempt++;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (attempt >= 10) {
|
|
118
|
+
throw new Error('Failed to generate unique citation ID');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return id;
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
**작업 항목**:
|
|
126
|
+
- [ ] generateCitationId 함수 구현
|
|
127
|
+
- [ ] 충돌 처리 로직
|
|
128
|
+
- [ ] 유닛 테스트
|
|
129
|
+
|
|
130
|
+
### 2.2 인용 저장소
|
|
131
|
+
|
|
132
|
+
**파일**: `src/core/citation-store.ts` (신규)
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
export class CitationStore {
|
|
136
|
+
constructor(private db: Database) {}
|
|
137
|
+
|
|
138
|
+
async create(citation: CitationInput): Promise<Citation> {
|
|
139
|
+
await this.db.run(`
|
|
140
|
+
INSERT INTO citations (citation_id, event_id, created_at)
|
|
141
|
+
VALUES (?, ?, ?)
|
|
142
|
+
`, [citation.citationId, citation.eventId, new Date()]);
|
|
143
|
+
|
|
144
|
+
return { ...citation, createdAt: new Date() };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async findById(citationId: string): Promise<Citation | null> {
|
|
148
|
+
return this.db.get(`
|
|
149
|
+
SELECT * FROM citations WHERE citation_id = ?
|
|
150
|
+
`, [citationId]);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async findByEventId(eventId: string): Promise<Citation | null> {
|
|
154
|
+
return this.db.get(`
|
|
155
|
+
SELECT * FROM citations WHERE event_id = ?
|
|
156
|
+
`, [eventId]);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async exists(citationId: string): Promise<boolean> {
|
|
160
|
+
const result = await this.db.get(`
|
|
161
|
+
SELECT 1 FROM citations WHERE citation_id = ?
|
|
162
|
+
`, [citationId]);
|
|
163
|
+
return !!result;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async getOrCreate(eventId: string): Promise<Citation> {
|
|
167
|
+
const existing = await this.findByEventId(eventId);
|
|
168
|
+
if (existing) return existing;
|
|
169
|
+
|
|
170
|
+
const citationId = await generateUniqueCitationId(eventId, this);
|
|
171
|
+
return this.create({ citationId, eventId });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
**작업 항목**:
|
|
177
|
+
- [ ] CitationStore 클래스 구현
|
|
178
|
+
- [ ] CRUD 메서드
|
|
179
|
+
- [ ] getOrCreate 패턴
|
|
180
|
+
|
|
181
|
+
## Phase 3: 컨텍스트 통합 (P0)
|
|
182
|
+
|
|
183
|
+
### 3.1 인용 포함 검색
|
|
184
|
+
|
|
185
|
+
**파일**: `src/core/retriever.ts` 수정
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
export interface CitedSearchResult {
|
|
189
|
+
event: Event;
|
|
190
|
+
citation: Citation;
|
|
191
|
+
score: number;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export class Retriever {
|
|
195
|
+
async searchWithCitations(
|
|
196
|
+
query: string,
|
|
197
|
+
options?: SearchOptions
|
|
198
|
+
): Promise<CitedSearchResult[]> {
|
|
199
|
+
const results = await this.search(query, options);
|
|
200
|
+
|
|
201
|
+
return Promise.all(
|
|
202
|
+
results.map(async (result) => {
|
|
203
|
+
const citation = await this.citationStore.getOrCreate(result.eventId);
|
|
204
|
+
return {
|
|
205
|
+
event: result,
|
|
206
|
+
citation,
|
|
207
|
+
score: result.score
|
|
208
|
+
};
|
|
209
|
+
})
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
**작업 항목**:
|
|
216
|
+
- [ ] searchWithCitations 메서드 추가
|
|
217
|
+
- [ ] 인용 자동 생성/조회
|
|
218
|
+
|
|
219
|
+
### 3.2 컨텍스트 포맷터 수정
|
|
220
|
+
|
|
221
|
+
**파일**: `src/core/context-formatter.ts` 수정
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
export function formatContextWithCitations(
|
|
225
|
+
results: CitedSearchResult[],
|
|
226
|
+
options?: FormatOptions
|
|
227
|
+
): string {
|
|
228
|
+
const format = options?.format ?? 'inline';
|
|
229
|
+
|
|
230
|
+
switch (format) {
|
|
231
|
+
case 'inline':
|
|
232
|
+
return formatInline(results);
|
|
233
|
+
case 'footnote':
|
|
234
|
+
return formatFootnote(results);
|
|
235
|
+
case 'reference':
|
|
236
|
+
return formatReference(results);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function formatInline(results: CitedSearchResult[]): string {
|
|
241
|
+
return results.map(r => {
|
|
242
|
+
const date = r.event.timestamp.toLocaleDateString();
|
|
243
|
+
const session = r.event.sessionId.slice(0, 6);
|
|
244
|
+
|
|
245
|
+
return [
|
|
246
|
+
`> ${r.event.payload.content}`,
|
|
247
|
+
`>`,
|
|
248
|
+
`> [mem:${r.citation.citationId}] - ${date}, Session ${session}`
|
|
249
|
+
].join('\n');
|
|
250
|
+
}).join('\n\n---\n\n');
|
|
251
|
+
}
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
**작업 항목**:
|
|
255
|
+
- [ ] 인라인 포맷 구현
|
|
256
|
+
- [ ] 각주 포맷 구현
|
|
257
|
+
- [ ] 참조 포맷 구현
|
|
258
|
+
|
|
259
|
+
## Phase 4: 조회 인터페이스 (P0)
|
|
260
|
+
|
|
261
|
+
### 4.1 CLI 명령
|
|
262
|
+
|
|
263
|
+
**파일**: `src/cli/commands/show.ts` (신규)
|
|
264
|
+
|
|
265
|
+
```typescript
|
|
266
|
+
import { Command } from 'commander';
|
|
267
|
+
|
|
268
|
+
export const showCommand = new Command('show')
|
|
269
|
+
.argument('<citation>', 'Citation ID (e.g., mem:a7Bc3x or just a7Bc3x)')
|
|
270
|
+
.description('Show full content of a cited memory')
|
|
271
|
+
.action(async (citation: string) => {
|
|
272
|
+
const memoryService = await MemoryService.getInstance();
|
|
273
|
+
|
|
274
|
+
// mem: 접두사 제거
|
|
275
|
+
const citationId = citation.replace(/^mem:/, '');
|
|
276
|
+
|
|
277
|
+
const result = await memoryService.getCitedMemory(citationId);
|
|
278
|
+
|
|
279
|
+
if (!result) {
|
|
280
|
+
console.log(chalk.red(`Citation not found: ${citationId}`));
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// 출력 포맷팅
|
|
285
|
+
console.log(chalk.bold(`📄 Memory Citation: ${citationId}`));
|
|
286
|
+
console.log();
|
|
287
|
+
console.log(`Session: ${result.event.sessionId}`);
|
|
288
|
+
console.log(`Date: ${result.event.timestamp.toLocaleString()}`);
|
|
289
|
+
console.log(`Type: ${result.event.eventType}`);
|
|
290
|
+
console.log();
|
|
291
|
+
console.log('Content:');
|
|
292
|
+
console.log('─'.repeat(40));
|
|
293
|
+
console.log(result.event.payload.content);
|
|
294
|
+
console.log('─'.repeat(40));
|
|
295
|
+
|
|
296
|
+
if (result.related) {
|
|
297
|
+
console.log();
|
|
298
|
+
console.log('Related:');
|
|
299
|
+
if (result.related.previous) {
|
|
300
|
+
console.log(` Previous: [mem:${result.related.previous.citationId}]`);
|
|
301
|
+
}
|
|
302
|
+
if (result.related.next) {
|
|
303
|
+
console.log(` Next: [mem:${result.related.next.citationId}]`);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
**작업 항목**:
|
|
310
|
+
- [ ] show 명령 구현
|
|
311
|
+
- [ ] 출력 포맷팅
|
|
312
|
+
- [ ] 관련 인용 표시
|
|
313
|
+
|
|
314
|
+
### 4.2 API 엔드포인트
|
|
315
|
+
|
|
316
|
+
**파일**: `src/server/api/citations.ts` (신규)
|
|
317
|
+
|
|
318
|
+
```typescript
|
|
319
|
+
import { Hono } from 'hono';
|
|
320
|
+
|
|
321
|
+
export const citationsRouter = new Hono();
|
|
322
|
+
|
|
323
|
+
// GET /api/citations/:id
|
|
324
|
+
citationsRouter.get('/:id', async (c) => {
|
|
325
|
+
const { id } = c.req.param();
|
|
326
|
+
const memoryService = await MemoryService.getInstance();
|
|
327
|
+
|
|
328
|
+
const result = await memoryService.getCitedMemory(id);
|
|
329
|
+
|
|
330
|
+
if (!result) {
|
|
331
|
+
return c.json({ error: 'Citation not found' }, 404);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
return c.json(result);
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
// GET /api/citations/:id/related
|
|
338
|
+
citationsRouter.get('/:id/related', async (c) => {
|
|
339
|
+
const { id } = c.req.param();
|
|
340
|
+
const memoryService = await MemoryService.getInstance();
|
|
341
|
+
|
|
342
|
+
const related = await memoryService.getRelatedCitations(id);
|
|
343
|
+
|
|
344
|
+
return c.json({ related });
|
|
345
|
+
});
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
**작업 항목**:
|
|
349
|
+
- [ ] 인용 조회 API
|
|
350
|
+
- [ ] 관련 인용 API
|
|
351
|
+
- [ ] 에러 처리
|
|
352
|
+
|
|
353
|
+
## Phase 5: 사용 추적 (P1)
|
|
354
|
+
|
|
355
|
+
### 5.1 사용 로깅
|
|
356
|
+
|
|
357
|
+
**파일**: `src/core/citation-store.ts` 수정
|
|
358
|
+
|
|
359
|
+
```typescript
|
|
360
|
+
export class CitationStore {
|
|
361
|
+
async logUsage(
|
|
362
|
+
citationId: string,
|
|
363
|
+
sessionId: string,
|
|
364
|
+
context?: string
|
|
365
|
+
): Promise<void> {
|
|
366
|
+
const usageId = crypto.randomUUID();
|
|
367
|
+
|
|
368
|
+
await this.db.run(`
|
|
369
|
+
INSERT INTO citation_usages (usage_id, citation_id, session_id, used_at, context)
|
|
370
|
+
VALUES (?, ?, ?, ?, ?)
|
|
371
|
+
`, [usageId, citationId, sessionId, new Date(), context]);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async getUsageStats(citationId: string): Promise<CitationStats> {
|
|
375
|
+
const result = await this.db.get(`
|
|
376
|
+
SELECT
|
|
377
|
+
COUNT(*) as usage_count,
|
|
378
|
+
MAX(used_at) as last_used
|
|
379
|
+
FROM citation_usages
|
|
380
|
+
WHERE citation_id = ?
|
|
381
|
+
`, [citationId]);
|
|
382
|
+
|
|
383
|
+
return {
|
|
384
|
+
usageCount: result.usage_count,
|
|
385
|
+
lastUsed: result.last_used ? new Date(result.last_used) : null
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
**작업 항목**:
|
|
392
|
+
- [ ] 사용 로깅 구현
|
|
393
|
+
- [ ] 통계 조회
|
|
394
|
+
- [ ] user-prompt-submit 훅에서 로깅
|
|
395
|
+
|
|
396
|
+
### 5.2 인기 인용 통계
|
|
397
|
+
|
|
398
|
+
```typescript
|
|
399
|
+
async getPopularCitations(options?: { limit?: number; days?: number }): Promise<PopularCitation[]> {
|
|
400
|
+
const { limit = 10, days = 30 } = options || {};
|
|
401
|
+
|
|
402
|
+
return this.db.query(`
|
|
403
|
+
SELECT
|
|
404
|
+
c.citation_id,
|
|
405
|
+
e.event_type,
|
|
406
|
+
SUBSTR(JSON_EXTRACT(e.payload_json, '$.content'), 1, 100) as preview,
|
|
407
|
+
COUNT(u.usage_id) as usage_count,
|
|
408
|
+
MAX(u.used_at) as last_used
|
|
409
|
+
FROM citations c
|
|
410
|
+
JOIN events e ON c.event_id = e.event_id
|
|
411
|
+
LEFT JOIN citation_usages u ON c.citation_id = u.citation_id
|
|
412
|
+
AND u.used_at > datetime('now', '-${days} days')
|
|
413
|
+
GROUP BY c.citation_id
|
|
414
|
+
ORDER BY usage_count DESC
|
|
415
|
+
LIMIT ?
|
|
416
|
+
`, [limit]);
|
|
417
|
+
}
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
**작업 항목**:
|
|
421
|
+
- [ ] 인기 인용 조회
|
|
422
|
+
- [ ] 기간별 필터링
|
|
423
|
+
- [ ] Stats API에 추가
|
|
424
|
+
|
|
425
|
+
## 파일 목록
|
|
426
|
+
|
|
427
|
+
### 신규 파일
|
|
428
|
+
```
|
|
429
|
+
src/core/citation-generator.ts # ID 생성
|
|
430
|
+
src/core/citation-store.ts # 인용 저장소
|
|
431
|
+
src/cli/commands/show.ts # show 명령
|
|
432
|
+
src/server/api/citations.ts # 인용 API
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
### 수정 파일
|
|
436
|
+
```
|
|
437
|
+
src/core/types.ts # 스키마 추가
|
|
438
|
+
src/core/event-store.ts # 테이블 추가
|
|
439
|
+
src/core/retriever.ts # 인용 포함 검색
|
|
440
|
+
src/core/context-formatter.ts # 인용 포맷
|
|
441
|
+
src/hooks/user-prompt-submit.ts # 사용 로깅
|
|
442
|
+
src/cli/index.ts # show 명령 등록
|
|
443
|
+
src/server/api/index.ts # citations 라우터 추가
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
## 테스트
|
|
447
|
+
|
|
448
|
+
### 필수 테스트 케이스
|
|
449
|
+
|
|
450
|
+
1. **ID 생성**
|
|
451
|
+
```typescript
|
|
452
|
+
test('should generate 6-char citation ID', () => {
|
|
453
|
+
const id = generateCitationId('event_123');
|
|
454
|
+
expect(id.length).toBe(6);
|
|
455
|
+
expect(/^[A-Za-z0-9]+$/.test(id)).toBe(true);
|
|
456
|
+
});
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
2. **충돌 처리**
|
|
460
|
+
```typescript
|
|
461
|
+
test('should handle ID collision', async () => {
|
|
462
|
+
// 첫 번째 이벤트 저장
|
|
463
|
+
await store.create({ citationId: 'abc123', eventId: 'event_1' });
|
|
464
|
+
|
|
465
|
+
// 충돌 시 다른 ID 생성
|
|
466
|
+
const id = await generateUniqueCitationId('event_2', store);
|
|
467
|
+
expect(id).not.toBe('abc123');
|
|
468
|
+
});
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
3. **컨텍스트 포맷**
|
|
472
|
+
```typescript
|
|
473
|
+
test('should format context with citations', () => {
|
|
474
|
+
const formatted = formatContextWithCitations([{
|
|
475
|
+
event: mockEvent,
|
|
476
|
+
citation: { citationId: 'a7Bc3x', ... },
|
|
477
|
+
score: 0.9
|
|
478
|
+
}]);
|
|
479
|
+
|
|
480
|
+
expect(formatted).toContain('[mem:a7Bc3x]');
|
|
481
|
+
});
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
## 마일스톤
|
|
485
|
+
|
|
486
|
+
| 단계 | 완료 기준 |
|
|
487
|
+
|------|----------|
|
|
488
|
+
| M1 | 스키마 및 테이블 생성 |
|
|
489
|
+
| M2 | ID 생성기 구현 |
|
|
490
|
+
| M3 | CitationStore 구현 |
|
|
491
|
+
| M4 | 검색에 인용 통합 |
|
|
492
|
+
| M5 | CLI show 명령 |
|
|
493
|
+
| M6 | API 엔드포인트 |
|
|
494
|
+
| M7 | 사용 추적 |
|
|
495
|
+
| M8 | 테스트 통과 |
|