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,663 @@
|
|
|
1
|
+
# Progressive Disclosure 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
|
+
// Layer 1: 검색 인덱스
|
|
15
|
+
export const SearchIndexItemSchema = z.object({
|
|
16
|
+
id: z.string(),
|
|
17
|
+
summary: z.string().max(100),
|
|
18
|
+
score: z.number(),
|
|
19
|
+
type: z.enum(['prompt', 'response', 'tool', 'insight']),
|
|
20
|
+
timestamp: z.date(),
|
|
21
|
+
sessionId: z.string()
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// Layer 2: 타임라인
|
|
25
|
+
export const TimelineItemSchema = z.object({
|
|
26
|
+
id: z.string(),
|
|
27
|
+
timestamp: z.date(),
|
|
28
|
+
type: z.enum(['prompt', 'response', 'tool', 'insight']),
|
|
29
|
+
preview: z.string().max(200),
|
|
30
|
+
isTarget: z.boolean()
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// Layer 3: 상세
|
|
34
|
+
export const FullDetailSchema = z.object({
|
|
35
|
+
id: z.string(),
|
|
36
|
+
content: z.string(),
|
|
37
|
+
type: z.enum(['prompt', 'response', 'tool', 'insight']),
|
|
38
|
+
timestamp: z.date(),
|
|
39
|
+
sessionId: z.string(),
|
|
40
|
+
metadata: z.object({
|
|
41
|
+
tokenCount: z.number(),
|
|
42
|
+
hasCode: z.boolean(),
|
|
43
|
+
files: z.array(z.string()).optional(),
|
|
44
|
+
tools: z.array(z.string()).optional()
|
|
45
|
+
}),
|
|
46
|
+
relations: z.object({
|
|
47
|
+
parentId: z.string().optional(),
|
|
48
|
+
childIds: z.array(z.string()),
|
|
49
|
+
relatedIds: z.array(z.string())
|
|
50
|
+
}).optional()
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**작업 항목**:
|
|
55
|
+
- [ ] SearchIndexItemSchema 추가
|
|
56
|
+
- [ ] TimelineItemSchema 추가
|
|
57
|
+
- [ ] FullDetailSchema 추가
|
|
58
|
+
- [ ] ProgressiveSearchResultSchema 추가
|
|
59
|
+
|
|
60
|
+
### 1.2 설정 스키마 확장
|
|
61
|
+
|
|
62
|
+
**파일**: `src/core/types.ts` 수정
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
export const ProgressiveDisclosureConfigSchema = z.object({
|
|
66
|
+
enabled: z.boolean().default(true),
|
|
67
|
+
layer1: z.object({
|
|
68
|
+
topK: z.number().default(10),
|
|
69
|
+
minScore: z.number().default(0.7)
|
|
70
|
+
}),
|
|
71
|
+
autoExpand: z.object({
|
|
72
|
+
enabled: z.boolean().default(true),
|
|
73
|
+
highConfidenceThreshold: z.number().default(0.92),
|
|
74
|
+
scoreGapThreshold: z.number().default(0.1),
|
|
75
|
+
maxAutoExpandCount: z.number().default(3)
|
|
76
|
+
}),
|
|
77
|
+
tokenBudget: z.object({
|
|
78
|
+
maxTotalTokens: z.number().default(2000),
|
|
79
|
+
layer1PerItem: z.number().default(50),
|
|
80
|
+
layer2PerItem: z.number().default(40),
|
|
81
|
+
layer3PerItem: z.number().default(500)
|
|
82
|
+
}),
|
|
83
|
+
cache: z.object({
|
|
84
|
+
layer1Ttl: z.number().default(60000),
|
|
85
|
+
layer2Ttl: z.number().default(300000),
|
|
86
|
+
layer3Ttl: z.number().default(1800000)
|
|
87
|
+
})
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**작업 항목**:
|
|
92
|
+
- [ ] ProgressiveDisclosureConfigSchema 추가
|
|
93
|
+
- [ ] ConfigSchema에 progressiveDisclosure 필드 추가
|
|
94
|
+
|
|
95
|
+
## Phase 2: ProgressiveRetriever 구현 (P0)
|
|
96
|
+
|
|
97
|
+
### 2.1 기본 클래스 구조
|
|
98
|
+
|
|
99
|
+
**파일**: `src/core/progressive-retriever.ts` (신규)
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
export class ProgressiveRetriever {
|
|
103
|
+
constructor(
|
|
104
|
+
private eventStore: EventStore,
|
|
105
|
+
private vectorStore: VectorStore,
|
|
106
|
+
private config: ProgressiveDisclosureConfig
|
|
107
|
+
) {}
|
|
108
|
+
|
|
109
|
+
// Layer 1: 검색 인덱스
|
|
110
|
+
async searchIndex(
|
|
111
|
+
query: string,
|
|
112
|
+
options?: { topK?: number; filter?: SearchFilter }
|
|
113
|
+
): Promise<SearchIndexItem[]> {
|
|
114
|
+
const { topK = this.config.layer1.topK } = options || {};
|
|
115
|
+
|
|
116
|
+
// 벡터 검색
|
|
117
|
+
const vectorResults = await this.vectorStore.search(query, { topK });
|
|
118
|
+
|
|
119
|
+
// 요약 생성 및 변환
|
|
120
|
+
return vectorResults.map(r => ({
|
|
121
|
+
id: r.id,
|
|
122
|
+
summary: this.generateSummary(r.content),
|
|
123
|
+
score: r.score,
|
|
124
|
+
type: r.metadata.type,
|
|
125
|
+
timestamp: r.metadata.timestamp,
|
|
126
|
+
sessionId: r.metadata.sessionId
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Layer 2: 타임라인
|
|
131
|
+
async getTimeline(
|
|
132
|
+
targetIds: string[],
|
|
133
|
+
options?: { windowSize?: number }
|
|
134
|
+
): Promise<TimelineItem[]> {
|
|
135
|
+
const { windowSize = 3 } = options || {};
|
|
136
|
+
|
|
137
|
+
const items: TimelineItem[] = [];
|
|
138
|
+
|
|
139
|
+
for (const targetId of targetIds) {
|
|
140
|
+
const event = await this.eventStore.findById(targetId);
|
|
141
|
+
if (!event) continue;
|
|
142
|
+
|
|
143
|
+
// 주변 이벤트 조회
|
|
144
|
+
const surrounding = await this.eventStore.findSurrounding(
|
|
145
|
+
event.sessionId,
|
|
146
|
+
event.timestamp,
|
|
147
|
+
windowSize
|
|
148
|
+
);
|
|
149
|
+
|
|
150
|
+
items.push(...surrounding.map(e => ({
|
|
151
|
+
id: e.eventId,
|
|
152
|
+
timestamp: e.timestamp,
|
|
153
|
+
type: e.eventType,
|
|
154
|
+
preview: this.generatePreview(e.payload),
|
|
155
|
+
isTarget: e.eventId === targetId
|
|
156
|
+
})));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return this.deduplicateTimeline(items);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Layer 3: 상세 정보
|
|
163
|
+
async getDetails(ids: string[]): Promise<FullDetail[]> {
|
|
164
|
+
const details: FullDetail[] = [];
|
|
165
|
+
|
|
166
|
+
for (const id of ids) {
|
|
167
|
+
const event = await this.eventStore.findById(id);
|
|
168
|
+
if (!event) continue;
|
|
169
|
+
|
|
170
|
+
details.push({
|
|
171
|
+
id: event.eventId,
|
|
172
|
+
content: event.payload.content,
|
|
173
|
+
type: event.eventType,
|
|
174
|
+
timestamp: event.timestamp,
|
|
175
|
+
sessionId: event.sessionId,
|
|
176
|
+
metadata: this.extractMetadata(event),
|
|
177
|
+
relations: await this.getRelations(event)
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return details;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
**작업 항목**:
|
|
187
|
+
- [ ] searchIndex 메서드 구현
|
|
188
|
+
- [ ] getTimeline 메서드 구현
|
|
189
|
+
- [ ] getDetails 메서드 구현
|
|
190
|
+
- [ ] generateSummary 헬퍼 구현
|
|
191
|
+
- [ ] generatePreview 헬퍼 구현
|
|
192
|
+
|
|
193
|
+
### 2.2 스마트 검색 구현
|
|
194
|
+
|
|
195
|
+
**파일**: `src/core/progressive-retriever.ts` 계속
|
|
196
|
+
|
|
197
|
+
```typescript
|
|
198
|
+
async smartSearch(
|
|
199
|
+
query: string,
|
|
200
|
+
options?: SmartSearchOptions
|
|
201
|
+
): Promise<ProgressiveSearchResult> {
|
|
202
|
+
const config = { ...this.config, ...options };
|
|
203
|
+
|
|
204
|
+
// Layer 1: 항상 실행
|
|
205
|
+
const index = await this.searchIndex(query, {
|
|
206
|
+
topK: config.layer1.topK,
|
|
207
|
+
filter: options?.filter
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
const result: ProgressiveSearchResult = {
|
|
211
|
+
index,
|
|
212
|
+
meta: {
|
|
213
|
+
totalMatches: index.length,
|
|
214
|
+
expandedCount: 0,
|
|
215
|
+
estimatedTokens: this.estimateTokens(index, 'layer1')
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
// 자동 확장 결정
|
|
220
|
+
if (config.autoExpand.enabled) {
|
|
221
|
+
const decision = this.shouldAutoExpand(index, config);
|
|
222
|
+
|
|
223
|
+
if (decision.expandTimeline && decision.ids) {
|
|
224
|
+
result.timeline = await this.getTimeline(decision.ids);
|
|
225
|
+
result.meta.estimatedTokens += this.estimateTokens(result.timeline, 'layer2');
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (decision.expandDetails && decision.ids) {
|
|
229
|
+
// 토큰 예산 체크
|
|
230
|
+
const remainingBudget = config.tokenBudget.maxTotalTokens - result.meta.estimatedTokens;
|
|
231
|
+
const idsToExpand = this.selectWithinBudget(decision.ids, remainingBudget);
|
|
232
|
+
|
|
233
|
+
result.details = await this.getDetails(idsToExpand);
|
|
234
|
+
result.meta.expandedCount = idsToExpand.length;
|
|
235
|
+
result.meta.estimatedTokens += this.estimateTokens(result.details, 'layer3');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
result.meta.expansionReason = decision.reason;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
**작업 항목**:
|
|
246
|
+
- [ ] smartSearch 메서드 구현
|
|
247
|
+
- [ ] shouldAutoExpand 로직 구현
|
|
248
|
+
- [ ] selectWithinBudget 토큰 예산 관리
|
|
249
|
+
|
|
250
|
+
### 2.3 확장 규칙 엔진
|
|
251
|
+
|
|
252
|
+
**파일**: `src/core/expansion-rules.ts` (신규)
|
|
253
|
+
|
|
254
|
+
```typescript
|
|
255
|
+
interface ExpansionDecision {
|
|
256
|
+
expand: boolean;
|
|
257
|
+
expandTimeline?: boolean;
|
|
258
|
+
expandDetails?: boolean;
|
|
259
|
+
ids?: string[];
|
|
260
|
+
reason: string;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function shouldAutoExpand(
|
|
264
|
+
results: SearchIndexItem[],
|
|
265
|
+
config: ProgressiveDisclosureConfig
|
|
266
|
+
): ExpansionDecision {
|
|
267
|
+
if (results.length === 0) {
|
|
268
|
+
return { expand: false, reason: 'no_results' };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const topScore = results[0].score;
|
|
272
|
+
|
|
273
|
+
// Rule 1: 높은 신뢰도 단일 결과
|
|
274
|
+
if (topScore >= config.autoExpand.highConfidenceThreshold && results.length === 1) {
|
|
275
|
+
return {
|
|
276
|
+
expand: true,
|
|
277
|
+
expandTimeline: true,
|
|
278
|
+
expandDetails: true,
|
|
279
|
+
ids: [results[0].id],
|
|
280
|
+
reason: 'high_confidence_single'
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Rule 2: 명확한 1등
|
|
285
|
+
if (results.length >= 2) {
|
|
286
|
+
const gap = results[0].score - results[1].score;
|
|
287
|
+
if (topScore >= 0.85 && gap >= config.autoExpand.scoreGapThreshold) {
|
|
288
|
+
return {
|
|
289
|
+
expand: true,
|
|
290
|
+
expandTimeline: true,
|
|
291
|
+
expandDetails: true,
|
|
292
|
+
ids: [results[0].id],
|
|
293
|
+
reason: 'clear_winner'
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// Rule 3: 모호한 결과 → 타임라인만
|
|
299
|
+
const highScoreCount = results.filter(r => r.score >= 0.8).length;
|
|
300
|
+
if (highScoreCount >= 3) {
|
|
301
|
+
return {
|
|
302
|
+
expand: true,
|
|
303
|
+
expandTimeline: true,
|
|
304
|
+
expandDetails: false,
|
|
305
|
+
ids: results.slice(0, 3).map(r => r.id),
|
|
306
|
+
reason: 'ambiguous_multiple_high'
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// Rule 4: 낮은 점수
|
|
311
|
+
return { expand: false, reason: 'low_confidence' };
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
**작업 항목**:
|
|
316
|
+
- [ ] 확장 규칙 함수 구현
|
|
317
|
+
- [ ] 규칙별 테스트 케이스
|
|
318
|
+
|
|
319
|
+
## Phase 3: 요약 및 미리보기 생성 (P0)
|
|
320
|
+
|
|
321
|
+
### 3.1 요약 생성기
|
|
322
|
+
|
|
323
|
+
**파일**: `src/core/summarizer.ts` (신규)
|
|
324
|
+
|
|
325
|
+
```typescript
|
|
326
|
+
export function generateSummary(content: string, maxLength: number = 100): string {
|
|
327
|
+
// 1. 코드 블록 제거
|
|
328
|
+
const withoutCode = content.replace(/```[\s\S]*?```/g, '[code]');
|
|
329
|
+
|
|
330
|
+
// 2. 첫 문장 추출
|
|
331
|
+
const firstSentence = withoutCode.match(/^[^.!?]+[.!?]/)?.[0] || '';
|
|
332
|
+
|
|
333
|
+
// 3. 길이 제한
|
|
334
|
+
if (firstSentence.length <= maxLength) {
|
|
335
|
+
return firstSentence.trim();
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// 4. 단어 경계에서 자르기
|
|
339
|
+
return withoutCode.slice(0, maxLength).replace(/\s+\S*$/, '') + '...';
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export function generatePreview(content: string, maxLength: number = 200): string {
|
|
343
|
+
// 1. 코드 블록 축약
|
|
344
|
+
const withCodeSummary = content.replace(
|
|
345
|
+
/```(\w+)[\s\S]*?```/g,
|
|
346
|
+
(_, lang) => `[${lang} code]`
|
|
347
|
+
);
|
|
348
|
+
|
|
349
|
+
// 2. 줄바꿈 정리
|
|
350
|
+
const singleLine = withCodeSummary.replace(/\n+/g, ' ').trim();
|
|
351
|
+
|
|
352
|
+
// 3. 길이 제한
|
|
353
|
+
if (singleLine.length <= maxLength) {
|
|
354
|
+
return singleLine;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
return singleLine.slice(0, maxLength).replace(/\s+\S*$/, '') + '...';
|
|
358
|
+
}
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
**작업 항목**:
|
|
362
|
+
- [ ] generateSummary 함수 구현
|
|
363
|
+
- [ ] generatePreview 함수 구현
|
|
364
|
+
- [ ] 코드 블록 처리 로직
|
|
365
|
+
- [ ] 특수 문자 처리
|
|
366
|
+
|
|
367
|
+
### 3.2 토큰 추정기
|
|
368
|
+
|
|
369
|
+
**파일**: `src/core/token-estimator.ts` (신규)
|
|
370
|
+
|
|
371
|
+
```typescript
|
|
372
|
+
// 간단한 토큰 추정 (GPT tokenizer 근사)
|
|
373
|
+
export function estimateTokens(text: string): number {
|
|
374
|
+
// 평균적으로 4자 = 1토큰
|
|
375
|
+
return Math.ceil(text.length / 4);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export function estimateLayerTokens(
|
|
379
|
+
items: unknown[],
|
|
380
|
+
layer: 'layer1' | 'layer2' | 'layer3',
|
|
381
|
+
config: ProgressiveDisclosureConfig
|
|
382
|
+
): number {
|
|
383
|
+
switch (layer) {
|
|
384
|
+
case 'layer1':
|
|
385
|
+
return items.length * config.tokenBudget.layer1PerItem;
|
|
386
|
+
case 'layer2':
|
|
387
|
+
return items.length * config.tokenBudget.layer2PerItem;
|
|
388
|
+
case 'layer3':
|
|
389
|
+
// Layer 3는 실제 콘텐츠 기반
|
|
390
|
+
return (items as FullDetail[]).reduce(
|
|
391
|
+
(sum, item) => sum + estimateTokens(item.content),
|
|
392
|
+
0
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
**작업 항목**:
|
|
399
|
+
- [ ] estimateTokens 함수 구현
|
|
400
|
+
- [ ] estimateLayerTokens 함수 구현
|
|
401
|
+
|
|
402
|
+
## Phase 4: 캐싱 (P1)
|
|
403
|
+
|
|
404
|
+
### 4.1 캐시 매니저
|
|
405
|
+
|
|
406
|
+
**파일**: `src/core/cache-manager.ts` (신규)
|
|
407
|
+
|
|
408
|
+
```typescript
|
|
409
|
+
import { LRUCache } from 'lru-cache';
|
|
410
|
+
|
|
411
|
+
export class ProgressiveCache {
|
|
412
|
+
private layer1Cache: LRUCache<string, SearchIndexItem[]>;
|
|
413
|
+
private layer2Cache: LRUCache<string, TimelineItem[]>;
|
|
414
|
+
private layer3Cache: LRUCache<string, FullDetail>;
|
|
415
|
+
|
|
416
|
+
constructor(config: ProgressiveDisclosureConfig) {
|
|
417
|
+
this.layer1Cache = new LRUCache({
|
|
418
|
+
max: 100,
|
|
419
|
+
ttl: config.cache.layer1Ttl
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
this.layer2Cache = new LRUCache({
|
|
423
|
+
max: 500,
|
|
424
|
+
ttl: config.cache.layer2Ttl
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
this.layer3Cache = new LRUCache({
|
|
428
|
+
max: 200,
|
|
429
|
+
ttl: config.cache.layer3Ttl
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// Layer 1 캐시
|
|
434
|
+
getLayer1(query: string, options: SearchOptions): SearchIndexItem[] | undefined {
|
|
435
|
+
const key = this.buildLayer1Key(query, options);
|
|
436
|
+
return this.layer1Cache.get(key);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
setLayer1(query: string, options: SearchOptions, results: SearchIndexItem[]): void {
|
|
440
|
+
const key = this.buildLayer1Key(query, options);
|
|
441
|
+
this.layer1Cache.set(key, results);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// ... Layer 2, 3 유사 구현
|
|
445
|
+
}
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
**작업 항목**:
|
|
449
|
+
- [ ] ProgressiveCache 클래스 구현
|
|
450
|
+
- [ ] Layer별 캐시 키 생성
|
|
451
|
+
- [ ] TTL 및 크기 제한 적용
|
|
452
|
+
|
|
453
|
+
## Phase 5: 포맷터 (P0)
|
|
454
|
+
|
|
455
|
+
### 5.1 컨텍스트 포맷터
|
|
456
|
+
|
|
457
|
+
**파일**: `src/core/context-formatter.ts` (신규)
|
|
458
|
+
|
|
459
|
+
```typescript
|
|
460
|
+
export class ContextFormatter {
|
|
461
|
+
formatProgressiveResult(result: ProgressiveSearchResult): string {
|
|
462
|
+
const parts: string[] = [];
|
|
463
|
+
|
|
464
|
+
// Layer 1: 항상 포함
|
|
465
|
+
parts.push(this.formatLayer1(result.index));
|
|
466
|
+
|
|
467
|
+
// Layer 2: 타임라인
|
|
468
|
+
if (result.timeline) {
|
|
469
|
+
parts.push(this.formatLayer2(result.timeline));
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// Layer 3: 상세
|
|
473
|
+
if (result.details) {
|
|
474
|
+
parts.push(this.formatLayer3(result.details));
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// 메타 정보
|
|
478
|
+
parts.push(this.formatMeta(result.meta));
|
|
479
|
+
|
|
480
|
+
return parts.join('\n\n');
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
private formatLayer1(items: SearchIndexItem[]): string {
|
|
484
|
+
const header = `## Related Memories (${items.length} matches)\n`;
|
|
485
|
+
const table = items.map((item, i) =>
|
|
486
|
+
`${i + 1}. [${item.id}] ${item.summary} (score: ${item.score.toFixed(2)})`
|
|
487
|
+
).join('\n');
|
|
488
|
+
|
|
489
|
+
return header + table;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
private formatLayer2(items: TimelineItem[]): string {
|
|
493
|
+
const header = '## Timeline Context\n';
|
|
494
|
+
const timeline = items.map(item => {
|
|
495
|
+
const marker = item.isTarget ? '**→**' : ' ';
|
|
496
|
+
const time = item.timestamp.toLocaleTimeString();
|
|
497
|
+
return `${marker} ${time}: ${item.preview}`;
|
|
498
|
+
}).join('\n');
|
|
499
|
+
|
|
500
|
+
return header + timeline;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
private formatLayer3(items: FullDetail[]): string {
|
|
504
|
+
return items.map(item => {
|
|
505
|
+
const header = `## Detail: ${item.id}\n`;
|
|
506
|
+
const meta = `*Session: ${item.sessionId} | ${item.timestamp.toLocaleDateString()}*\n`;
|
|
507
|
+
return header + meta + '\n' + item.content;
|
|
508
|
+
}).join('\n\n---\n\n');
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
**작업 항목**:
|
|
514
|
+
- [ ] ContextFormatter 클래스 구현
|
|
515
|
+
- [ ] Layer별 포맷 함수
|
|
516
|
+
- [ ] Markdown 출력 최적화
|
|
517
|
+
|
|
518
|
+
## Phase 6: 통합 (P0)
|
|
519
|
+
|
|
520
|
+
### 6.1 Retriever 교체
|
|
521
|
+
|
|
522
|
+
**파일**: `src/core/retriever.ts` 수정
|
|
523
|
+
|
|
524
|
+
```typescript
|
|
525
|
+
export class Retriever {
|
|
526
|
+
private progressiveRetriever: ProgressiveRetriever;
|
|
527
|
+
|
|
528
|
+
constructor(/* ... */) {
|
|
529
|
+
this.progressiveRetriever = new ProgressiveRetriever(
|
|
530
|
+
this.eventStore,
|
|
531
|
+
this.vectorStore,
|
|
532
|
+
config.progressiveDisclosure
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// 기존 메서드를 progressive로 위임
|
|
537
|
+
async search(query: string): Promise<SearchResult[]> {
|
|
538
|
+
if (this.config.progressiveDisclosure?.enabled) {
|
|
539
|
+
const result = await this.progressiveRetriever.smartSearch(query);
|
|
540
|
+
return this.convertToLegacyFormat(result);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// 기존 로직 유지 (fallback)
|
|
544
|
+
return this.legacySearch(query);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// 새로운 progressive 검색
|
|
548
|
+
async progressiveSearch(query: string, options?: SmartSearchOptions): Promise<ProgressiveSearchResult> {
|
|
549
|
+
return this.progressiveRetriever.smartSearch(query, options);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
**작업 항목**:
|
|
555
|
+
- [ ] Retriever에 progressiveRetriever 통합
|
|
556
|
+
- [ ] 기존 API 호환성 유지
|
|
557
|
+
- [ ] 새 API 추가
|
|
558
|
+
|
|
559
|
+
### 6.2 user-prompt-submit 훅 수정
|
|
560
|
+
|
|
561
|
+
**파일**: `src/hooks/user-prompt-submit.ts` 수정
|
|
562
|
+
|
|
563
|
+
```typescript
|
|
564
|
+
async function handleUserPromptSubmit(input: UserPromptInput): Promise<HookOutput> {
|
|
565
|
+
const memoryService = await MemoryService.getInstance();
|
|
566
|
+
const config = memoryService.getConfig();
|
|
567
|
+
|
|
568
|
+
// Progressive 검색 사용
|
|
569
|
+
const searchResult = await memoryService.progressiveSearch(input.prompt, {
|
|
570
|
+
maxTotalTokens: config.retrieval.maxTokens
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
// 포맷팅
|
|
574
|
+
const formatter = new ContextFormatter();
|
|
575
|
+
const context = formatter.formatProgressiveResult(searchResult);
|
|
576
|
+
|
|
577
|
+
return {
|
|
578
|
+
context,
|
|
579
|
+
meta: {
|
|
580
|
+
matchCount: searchResult.meta.totalMatches,
|
|
581
|
+
expandedCount: searchResult.meta.expandedCount,
|
|
582
|
+
estimatedTokens: searchResult.meta.estimatedTokens
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
```
|
|
587
|
+
|
|
588
|
+
**작업 항목**:
|
|
589
|
+
- [ ] 훅에서 progressive 검색 사용
|
|
590
|
+
- [ ] 메타 정보 반환
|
|
591
|
+
|
|
592
|
+
## 파일 목록
|
|
593
|
+
|
|
594
|
+
### 신규 파일
|
|
595
|
+
```
|
|
596
|
+
src/core/progressive-retriever.ts # 메인 검색 클래스
|
|
597
|
+
src/core/expansion-rules.ts # 확장 규칙 엔진
|
|
598
|
+
src/core/summarizer.ts # 요약/미리보기 생성
|
|
599
|
+
src/core/token-estimator.ts # 토큰 추정
|
|
600
|
+
src/core/cache-manager.ts # 캐시 관리
|
|
601
|
+
src/core/context-formatter.ts # 출력 포맷팅
|
|
602
|
+
```
|
|
603
|
+
|
|
604
|
+
### 수정 파일
|
|
605
|
+
```
|
|
606
|
+
src/core/types.ts # 스키마 추가
|
|
607
|
+
src/core/retriever.ts # Progressive 통합
|
|
608
|
+
src/hooks/user-prompt-submit.ts # 검색 방식 변경
|
|
609
|
+
src/services/memory-service.ts # 서비스 메서드 추가
|
|
610
|
+
```
|
|
611
|
+
|
|
612
|
+
## 테스트
|
|
613
|
+
|
|
614
|
+
### 필수 테스트 케이스
|
|
615
|
+
|
|
616
|
+
1. **Layer 1 검색**
|
|
617
|
+
```typescript
|
|
618
|
+
test('should return index with summaries', async () => {
|
|
619
|
+
const result = await retriever.searchIndex('DuckDB 스키마');
|
|
620
|
+
expect(result[0]).toHaveProperty('summary');
|
|
621
|
+
expect(result[0].summary.length).toBeLessThanOrEqual(100);
|
|
622
|
+
});
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
2. **자동 확장 규칙**
|
|
626
|
+
```typescript
|
|
627
|
+
test('should expand on high confidence', async () => {
|
|
628
|
+
const result = await retriever.smartSearch('unique term');
|
|
629
|
+
expect(result.details).toBeDefined();
|
|
630
|
+
expect(result.meta.expansionReason).toBe('high_confidence_single');
|
|
631
|
+
});
|
|
632
|
+
```
|
|
633
|
+
|
|
634
|
+
3. **토큰 예산**
|
|
635
|
+
```typescript
|
|
636
|
+
test('should respect token budget', async () => {
|
|
637
|
+
const result = await retriever.smartSearch('query', { maxTotalTokens: 500 });
|
|
638
|
+
expect(result.meta.estimatedTokens).toBeLessThanOrEqual(500);
|
|
639
|
+
});
|
|
640
|
+
```
|
|
641
|
+
|
|
642
|
+
4. **캐싱**
|
|
643
|
+
```typescript
|
|
644
|
+
test('should use cache on repeat query', async () => {
|
|
645
|
+
await retriever.searchIndex('test');
|
|
646
|
+
const start = Date.now();
|
|
647
|
+
await retriever.searchIndex('test');
|
|
648
|
+
expect(Date.now() - start).toBeLessThan(10);
|
|
649
|
+
});
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
## 마일스톤
|
|
653
|
+
|
|
654
|
+
| 단계 | 완료 기준 |
|
|
655
|
+
|------|----------|
|
|
656
|
+
| M1 | 타입 정의 완료 |
|
|
657
|
+
| M2 | ProgressiveRetriever 기본 구현 |
|
|
658
|
+
| M3 | 확장 규칙 엔진 |
|
|
659
|
+
| M4 | 요약/미리보기 생성 |
|
|
660
|
+
| M5 | 토큰 예산 관리 |
|
|
661
|
+
| M6 | 캐싱 구현 |
|
|
662
|
+
| M7 | 포맷터 및 통합 |
|
|
663
|
+
| M8 | 테스트 통과 |
|