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,401 @@
|
|
|
1
|
+
# Evidence Aligner V2 Context
|
|
2
|
+
|
|
3
|
+
> **Version**: 2.0.0
|
|
4
|
+
> **Created**: 2026-01-31
|
|
5
|
+
|
|
6
|
+
## 1. 배경
|
|
7
|
+
|
|
8
|
+
### 1.1 LLM 오프셋 계산의 문제
|
|
9
|
+
|
|
10
|
+
LLM에게 텍스트 내 정확한 문자 위치(spanStart/spanEnd)를 계산하도록 요청하면:
|
|
11
|
+
|
|
12
|
+
```json
|
|
13
|
+
// LLM 출력 (문제 있음)
|
|
14
|
+
{
|
|
15
|
+
"quote": "JSONB 제거",
|
|
16
|
+
"spanStart": 142,
|
|
17
|
+
"spanEnd": 150
|
|
18
|
+
}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
**실제 문제**:
|
|
22
|
+
1. LLM은 토큰 기반으로 동작하여 문자 단위 계산이 부정확
|
|
23
|
+
2. 멀티바이트 문자(한글 등)에서 오프셋 계산 오류 빈번
|
|
24
|
+
3. 원문을 보지 않고 추측하는 경우 발생
|
|
25
|
+
|
|
26
|
+
### 1.2 Quote-only 방식의 장점
|
|
27
|
+
|
|
28
|
+
```json
|
|
29
|
+
// LLM 출력 (개선)
|
|
30
|
+
{
|
|
31
|
+
"messageIndex": 3,
|
|
32
|
+
"quote": "DuckDB의 JSONB를 JSON으로 변경"
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
**장점**:
|
|
37
|
+
1. LLM은 인용만 담당 (잘하는 것)
|
|
38
|
+
2. 정확한 위치 계산은 시스템이 담당
|
|
39
|
+
3. 검증 가능: quote가 원문에 없으면 즉시 탐지
|
|
40
|
+
|
|
41
|
+
## 2. Memo.txt 참고 사항
|
|
42
|
+
|
|
43
|
+
### 2.1 핵심 원칙 (섹션 2.4)
|
|
44
|
+
|
|
45
|
+
> **4. EvidenceSpan은 파이프라인이 확정**
|
|
46
|
+
> - LLM에게 spanStart/spanEnd 요구 금지
|
|
47
|
+
> - LLM은 quote만 제공 → aligner가 원문에서 찾아 span을 계산
|
|
48
|
+
|
|
49
|
+
### 2.2 Extractor 출력 스키마 (섹션 6.1)
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
{
|
|
53
|
+
"entries":[
|
|
54
|
+
{
|
|
55
|
+
"entryId":"ent_...",
|
|
56
|
+
"type":"fact",
|
|
57
|
+
"title":"DuckDB JSONB 제거",
|
|
58
|
+
"evidence":[{"messageIndex":3,"quote":"content JSONB → JSON"}]
|
|
59
|
+
}
|
|
60
|
+
]
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### 2.3 정렬 알고리즘 (섹션 6.2)
|
|
65
|
+
|
|
66
|
+
1. **exact substring match**
|
|
67
|
+
2. **normalize(공백/개행 collapse) 후 fuzzy match (최소 0.85 이상)** — optional
|
|
68
|
+
3. 실패 시 `evidenceAligned=false`로 표시하고, 해당 엔트리는 **Verified 승격 금지**
|
|
69
|
+
|
|
70
|
+
## 3. Idris2 영감 적용
|
|
71
|
+
|
|
72
|
+
### 3.1 Proof-Carrying Data
|
|
73
|
+
|
|
74
|
+
**Idris2 개념**:
|
|
75
|
+
```idris
|
|
76
|
+
-- 주장과 증거가 타입 수준에서 연결
|
|
77
|
+
data ProvenClaim : Type where
|
|
78
|
+
MkClaim : (claim : String) ->
|
|
79
|
+
(evidence : Span) ->
|
|
80
|
+
(proof : InSource evidence) -> -- 증거가 원문에 있다는 증명
|
|
81
|
+
ProvenClaim
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
**TypeScript 적용**:
|
|
85
|
+
```typescript
|
|
86
|
+
// 정렬 성공한 증거만 특정 타입으로
|
|
87
|
+
type AlignedEvidence = {
|
|
88
|
+
quote: string;
|
|
89
|
+
span: { start: number; end: number };
|
|
90
|
+
matchMethod: 'exact' | 'normalized' | 'fuzzy';
|
|
91
|
+
confidence: number; // matchMethod에 따라 범위 제한
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// 정렬 실패는 별도 타입
|
|
95
|
+
type FailedEvidence = {
|
|
96
|
+
quote: string;
|
|
97
|
+
failureReason: 'not_found' | 'below_threshold' | 'ambiguous';
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// Union으로 구분
|
|
101
|
+
type Evidence = AlignedEvidence | FailedEvidence;
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### 3.2 Confidence 불변식
|
|
105
|
+
|
|
106
|
+
```typescript
|
|
107
|
+
// Zod refinement로 불변식 검증
|
|
108
|
+
const AlignedEvidenceSchema = z.object({
|
|
109
|
+
matchMethod: z.enum(['exact', 'normalized', 'fuzzy']),
|
|
110
|
+
confidence: z.number()
|
|
111
|
+
}).refine(data => {
|
|
112
|
+
switch (data.matchMethod) {
|
|
113
|
+
case 'exact':
|
|
114
|
+
return data.confidence === 1.0;
|
|
115
|
+
case 'normalized':
|
|
116
|
+
return data.confidence >= 0.95 && data.confidence < 1.0;
|
|
117
|
+
case 'fuzzy':
|
|
118
|
+
return data.confidence >= 0.85 && data.confidence < 0.95;
|
|
119
|
+
}
|
|
120
|
+
}, { message: 'Confidence must match method' });
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## 4. 기존 코드와의 관계
|
|
124
|
+
|
|
125
|
+
### 4.1 현재 evidence-aligner.ts
|
|
126
|
+
|
|
127
|
+
```typescript
|
|
128
|
+
// 현재 구현 (src/core/evidence-aligner.ts)
|
|
129
|
+
export class EvidenceAligner {
|
|
130
|
+
align(claims: string[], sourceContent: string): AlignmentResult {
|
|
131
|
+
for (const claim of claims) {
|
|
132
|
+
const exactSpan = this.findExactMatch(claim, sourceContent);
|
|
133
|
+
if (exactSpan) {
|
|
134
|
+
spans.push(exactSpan);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
missingClaims.push(claim);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private findExactMatch(claim: string, source: string): EvidenceSpan | null {
|
|
142
|
+
const index = source.indexOf(claim);
|
|
143
|
+
if (index === -1) return null;
|
|
144
|
+
return { start: index, end: index + claim.length, ... };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
### 4.2 V2 확장 포인트
|
|
150
|
+
|
|
151
|
+
| 기존 | V2 확장 |
|
|
152
|
+
|-----|---------|
|
|
153
|
+
| claims: string[] | extractedJson with messageIndex |
|
|
154
|
+
| sourceContent: string | sessionMessages: string[] |
|
|
155
|
+
| exactMatch only | exact → normalized → fuzzy fallback |
|
|
156
|
+
| 반환: spans + missingClaims | 반환: AlignResult with details |
|
|
157
|
+
|
|
158
|
+
### 4.3 하위 호환성
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
// 기존 API 유지
|
|
162
|
+
class EvidenceAlignerV2 extends EvidenceAligner {
|
|
163
|
+
// 기존 메서드 오버라이드
|
|
164
|
+
align(claims: string[], sourceContent: string): AlignmentResult {
|
|
165
|
+
// V2 로직으로 처리 후 기존 형식으로 변환
|
|
166
|
+
const v2Result = this.alignV2([sourceContent], {
|
|
167
|
+
evidence: claims.map((c, i) => ({ quote: c, messageIndex: 0 }))
|
|
168
|
+
});
|
|
169
|
+
return this.convertToV1Result(v2Result);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// 새 API
|
|
173
|
+
alignV2(sessionMessages: string[], extractedJson: ExtractedData): AlignResult;
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## 5. 정규화 전략
|
|
178
|
+
|
|
179
|
+
### 5.1 공백 정규화
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
function normalizeWhitespace(text: string): string {
|
|
183
|
+
return text
|
|
184
|
+
.replace(/[\t\r]/g, ' ') // 탭, CR → 공백
|
|
185
|
+
.replace(/\n+/g, ' ') // 개행 → 공백
|
|
186
|
+
.replace(/ +/g, ' ') // 연속 공백 → 단일 공백
|
|
187
|
+
.trim();
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### 5.2 위치 역추적 문제
|
|
192
|
+
|
|
193
|
+
정규화 후 매칭 시, 원본 위치를 찾아야 함:
|
|
194
|
+
|
|
195
|
+
```typescript
|
|
196
|
+
// 원본: "Hello World\n\nTest"
|
|
197
|
+
// 정규화: "Hello World Test"
|
|
198
|
+
// 매칭: "World Test" at 6-16 (정규화)
|
|
199
|
+
// 역추적: 원본에서 "World\n\nTest" 찾기
|
|
200
|
+
|
|
201
|
+
function mapToOriginal(
|
|
202
|
+
original: string,
|
|
203
|
+
normalized: string,
|
|
204
|
+
normalizedStart: number,
|
|
205
|
+
normalizedEnd: number
|
|
206
|
+
): { start: number; end: number } {
|
|
207
|
+
// 각 문자 위치 매핑 테이블 생성
|
|
208
|
+
const posMap = buildPositionMap(original, normalized);
|
|
209
|
+
return {
|
|
210
|
+
start: posMap.normalizedToOriginal.get(normalizedStart)!,
|
|
211
|
+
end: posMap.normalizedToOriginal.get(normalizedEnd - 1)! + 1
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
### 5.3 유니코드 고려
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
// 한글, 이모지 등 멀티바이트 문자 처리
|
|
220
|
+
function normalizeUnicode(text: string): string {
|
|
221
|
+
return text
|
|
222
|
+
.normalize('NFKC') // 유니코드 정규화
|
|
223
|
+
.replace(/\p{Zs}/gu, ' ') // 모든 공백 문자 → 일반 공백
|
|
224
|
+
.replace(/\p{Cf}/gu, ''); // 보이지 않는 포맷 문자 제거
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## 6. Fuzzy Matching 전략
|
|
229
|
+
|
|
230
|
+
### 6.1 Levenshtein 거리
|
|
231
|
+
|
|
232
|
+
```typescript
|
|
233
|
+
function levenshteinDistance(a: string, b: string): number {
|
|
234
|
+
const m = a.length, n = b.length;
|
|
235
|
+
const dp: number[][] = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
|
|
236
|
+
|
|
237
|
+
for (let i = 0; i <= m; i++) dp[i][0] = i;
|
|
238
|
+
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
239
|
+
|
|
240
|
+
for (let i = 1; i <= m; i++) {
|
|
241
|
+
for (let j = 1; j <= n; j++) {
|
|
242
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
243
|
+
dp[i][j] = Math.min(
|
|
244
|
+
dp[i - 1][j] + 1, // 삭제
|
|
245
|
+
dp[i][j - 1] + 1, // 삽입
|
|
246
|
+
dp[i - 1][j - 1] + cost // 대체
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return dp[m][n];
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function similarity(a: string, b: string): number {
|
|
254
|
+
const dist = levenshteinDistance(a, b);
|
|
255
|
+
const maxLen = Math.max(a.length, b.length);
|
|
256
|
+
return 1 - dist / maxLen;
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
### 6.2 슬라이딩 윈도우 최적화
|
|
261
|
+
|
|
262
|
+
```typescript
|
|
263
|
+
function findBestMatch(
|
|
264
|
+
quote: string,
|
|
265
|
+
source: string,
|
|
266
|
+
threshold: number
|
|
267
|
+
): { start: number; end: number; score: number } | null {
|
|
268
|
+
const quoteLen = quote.length;
|
|
269
|
+
const windowSizes = [quoteLen, quoteLen * 1.1, quoteLen * 1.2]; // 다양한 윈도우
|
|
270
|
+
|
|
271
|
+
let best: { start: number; end: number; score: number } | null = null;
|
|
272
|
+
|
|
273
|
+
for (const windowSize of windowSizes) {
|
|
274
|
+
const size = Math.ceil(windowSize);
|
|
275
|
+
for (let i = 0; i <= source.length - size; i++) {
|
|
276
|
+
const window = source.slice(i, i + size);
|
|
277
|
+
const score = similarity(quote, window);
|
|
278
|
+
|
|
279
|
+
if (score >= threshold && (!best || score > best.score)) {
|
|
280
|
+
best = { start: i, end: i + size, score };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return best;
|
|
286
|
+
}
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
## 7. 에러 케이스 처리
|
|
290
|
+
|
|
291
|
+
### 7.1 messageIndex 범위 초과
|
|
292
|
+
|
|
293
|
+
```typescript
|
|
294
|
+
function validateEvidence(evidence: ExtractedEvidence, messageCount: number): ValidationResult {
|
|
295
|
+
if (evidence.messageIndex >= messageCount) {
|
|
296
|
+
return {
|
|
297
|
+
valid: false,
|
|
298
|
+
error: `messageIndex ${evidence.messageIndex} out of range (max: ${messageCount - 1})`
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
return { valid: true };
|
|
302
|
+
}
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
### 7.2 빈 quote
|
|
306
|
+
|
|
307
|
+
```typescript
|
|
308
|
+
if (!evidence.quote || evidence.quote.trim().length === 0) {
|
|
309
|
+
return {
|
|
310
|
+
aligned: false,
|
|
311
|
+
failureReason: 'empty_quote'
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
### 7.3 애매한 매칭 (여러 위치에서 발견)
|
|
317
|
+
|
|
318
|
+
```typescript
|
|
319
|
+
function handleAmbiguousMatch(
|
|
320
|
+
quote: string,
|
|
321
|
+
source: string
|
|
322
|
+
): AlignResult {
|
|
323
|
+
const matches = findAllMatches(quote, source);
|
|
324
|
+
|
|
325
|
+
if (matches.length > 1) {
|
|
326
|
+
// 첫 번째 매칭 사용, 단 애매함 표시
|
|
327
|
+
return {
|
|
328
|
+
...matches[0],
|
|
329
|
+
meta: { ambiguous: true, alternativeCount: matches.length - 1 }
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
return matches[0];
|
|
333
|
+
}
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
## 8. 성능 고려사항
|
|
337
|
+
|
|
338
|
+
### 8.1 캐싱
|
|
339
|
+
|
|
340
|
+
```typescript
|
|
341
|
+
// 정규화 결과 캐싱 (동일 소스 반복 사용 시)
|
|
342
|
+
const normalizeCache = new Map<string, { normalized: string; posMap: PositionMap }>();
|
|
343
|
+
|
|
344
|
+
function getCachedNormalized(source: string): { normalized: string; posMap: PositionMap } {
|
|
345
|
+
if (!normalizeCache.has(source)) {
|
|
346
|
+
const normalized = normalize(source);
|
|
347
|
+
const posMap = buildPositionMap(source, normalized);
|
|
348
|
+
normalizeCache.set(source, { normalized, posMap });
|
|
349
|
+
}
|
|
350
|
+
return normalizeCache.get(source)!;
|
|
351
|
+
}
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
### 8.2 조기 종료
|
|
355
|
+
|
|
356
|
+
```typescript
|
|
357
|
+
// Exact match 성공 시 fuzzy 시도 안 함
|
|
358
|
+
function align(quote: string, source: string): AlignedSpan | null {
|
|
359
|
+
// Step 1: Exact (가장 빠름)
|
|
360
|
+
const exact = exactMatch(quote, source);
|
|
361
|
+
if (exact) return exact;
|
|
362
|
+
|
|
363
|
+
// Step 2: Normalized (중간)
|
|
364
|
+
const normalized = normalizedMatch(quote, source);
|
|
365
|
+
if (normalized) return normalized;
|
|
366
|
+
|
|
367
|
+
// Step 3: Fuzzy (가장 느림, 필요할 때만)
|
|
368
|
+
return fuzzyMatch(quote, source, 0.85);
|
|
369
|
+
}
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
### 8.3 긴 텍스트 처리
|
|
373
|
+
|
|
374
|
+
```typescript
|
|
375
|
+
// 매우 긴 소스의 경우 분할 처리
|
|
376
|
+
const CHUNK_SIZE = 10000;
|
|
377
|
+
|
|
378
|
+
function alignLongSource(quote: string, source: string): AlignedSpan | null {
|
|
379
|
+
if (source.length <= CHUNK_SIZE) {
|
|
380
|
+
return align(quote, source);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// 청크 단위로 검색 (오버랩 적용)
|
|
384
|
+
const overlap = quote.length * 2;
|
|
385
|
+
for (let i = 0; i < source.length; i += CHUNK_SIZE - overlap) {
|
|
386
|
+
const chunk = source.slice(i, i + CHUNK_SIZE);
|
|
387
|
+
const result = align(quote, chunk);
|
|
388
|
+
if (result) {
|
|
389
|
+
return { ...result, start: result.start + i, end: result.end + i };
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return null;
|
|
393
|
+
}
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
## 9. 참고 자료
|
|
397
|
+
|
|
398
|
+
- **Memo.txt**: 섹션 6 - Evidence Align 구현 지시
|
|
399
|
+
- **현재 구현**: `src/core/evidence-aligner.ts`
|
|
400
|
+
- **타입 정의**: `src/core/types.ts` - EvidenceSpan
|
|
401
|
+
- **AXIOMMIND**: Principle 4 - 증거 범위 확정
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
# Evidence Aligner V2 Implementation Plan
|
|
2
|
+
|
|
3
|
+
> **Version**: 2.0.0
|
|
4
|
+
> **Status**: Draft
|
|
5
|
+
> **Created**: 2026-01-31
|
|
6
|
+
|
|
7
|
+
## Phase 1: Extractor 수정 (P0)
|
|
8
|
+
|
|
9
|
+
### 1.1 프롬프트 변경
|
|
10
|
+
|
|
11
|
+
**작업 항목**:
|
|
12
|
+
- [ ] LLM 프롬프트에서 spanStart/spanEnd 요구 제거
|
|
13
|
+
- [ ] quote 필드 필수로 변경
|
|
14
|
+
- [ ] quote 길이 가이드라인 추가 (30~200자)
|
|
15
|
+
|
|
16
|
+
**프롬프트 예시**:
|
|
17
|
+
```
|
|
18
|
+
각 entry에 대해 evidence를 제공하세요.
|
|
19
|
+
- messageIndex: 증거가 있는 메시지 인덱스 (0-based)
|
|
20
|
+
- quote: 원문에서 발췌한 텍스트 (30~200자)
|
|
21
|
+
|
|
22
|
+
중요: spanStart/spanEnd는 제공하지 마세요. 시스템이 자동으로 계산합니다.
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### 1.2 파서 수정
|
|
26
|
+
|
|
27
|
+
**파일**: `src/core/extractor.ts` (가정)
|
|
28
|
+
|
|
29
|
+
**작업 항목**:
|
|
30
|
+
- [ ] 출력 스키마에서 spanStart/spanEnd 제거
|
|
31
|
+
- [ ] quote 필수 검증 추가
|
|
32
|
+
- [ ] messageIndex 범위 검증
|
|
33
|
+
|
|
34
|
+
## Phase 2: Aligner 핵심 구현 (P0)
|
|
35
|
+
|
|
36
|
+
### 2.1 타입 정의
|
|
37
|
+
|
|
38
|
+
**파일**: `src/core/types.ts` 수정
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
// 추가할 타입들
|
|
42
|
+
export const AlignMethodSchema = z.enum(['exact', 'normalized', 'fuzzy', 'none']);
|
|
43
|
+
|
|
44
|
+
export const AlignedEvidenceSchema = z.object({
|
|
45
|
+
messageIndex: z.number().int().nonnegative(),
|
|
46
|
+
quote: z.string(),
|
|
47
|
+
quoteHash: z.string(),
|
|
48
|
+
spanStart: z.number().int().nonnegative(),
|
|
49
|
+
spanEnd: z.number().int().positive(),
|
|
50
|
+
confidence: z.number().min(0).max(1),
|
|
51
|
+
matchMethod: AlignMethodSchema
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**작업 항목**:
|
|
56
|
+
- [ ] AlignMethod 타입 추가
|
|
57
|
+
- [ ] AlignedEvidence 스키마 추가
|
|
58
|
+
- [ ] AlignResult 스키마 추가
|
|
59
|
+
- [ ] EvidenceAlignedEvent 타입 추가
|
|
60
|
+
|
|
61
|
+
### 2.2 Aligner 클래스 확장
|
|
62
|
+
|
|
63
|
+
**파일**: `src/core/evidence-aligner.ts` 수정
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
export class EvidenceAlignerV2 {
|
|
67
|
+
constructor(private config: AlignerConfig);
|
|
68
|
+
|
|
69
|
+
// 메인 정렬 함수
|
|
70
|
+
async align(
|
|
71
|
+
sessionMessages: string[],
|
|
72
|
+
extractedJson: ExtractedData
|
|
73
|
+
): Promise<AlignResult>;
|
|
74
|
+
|
|
75
|
+
// 단계별 매칭
|
|
76
|
+
private exactMatch(quote: string, source: string): AlignedSpan | null;
|
|
77
|
+
private normalizedMatch(quote: string, source: string): AlignedSpan | null;
|
|
78
|
+
private fuzzyMatch(quote: string, source: string, threshold: number): AlignedSpan | null;
|
|
79
|
+
|
|
80
|
+
// 헬퍼
|
|
81
|
+
private normalize(text: string): string;
|
|
82
|
+
private levenshteinSimilarity(a: string, b: string): number;
|
|
83
|
+
private mapToOriginal(source: string, normalized: string, start: number, length: number): Span;
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
**작업 항목**:
|
|
88
|
+
- [ ] exactMatch 메서드 구현
|
|
89
|
+
- [ ] normalize 함수 구현
|
|
90
|
+
- [ ] normalizedMatch 메서드 구현 (위치 역추적 포함)
|
|
91
|
+
- [ ] levenshteinSimilarity 함수 구현
|
|
92
|
+
- [ ] fuzzyMatch 메서드 구현 (슬라이딩 윈도우)
|
|
93
|
+
- [ ] align 메인 함수 구현 (3단계 폴백)
|
|
94
|
+
|
|
95
|
+
### 2.3 설정
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
interface AlignerConfig {
|
|
99
|
+
fuzzyThreshold: number; // default: 0.85
|
|
100
|
+
maxQuoteLength: number; // default: 500
|
|
101
|
+
enableFuzzy: boolean; // default: true
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Phase 3: 이벤트 연동 (P0)
|
|
106
|
+
|
|
107
|
+
### 3.1 이벤트 발행
|
|
108
|
+
|
|
109
|
+
**파일**: `src/core/event-store.ts` 수정
|
|
110
|
+
|
|
111
|
+
**작업 항목**:
|
|
112
|
+
- [ ] 'evidence_aligned' 이벤트 타입 추가
|
|
113
|
+
- [ ] payload 스키마 정의
|
|
114
|
+
|
|
115
|
+
### 3.2 Orchestrator 연동
|
|
116
|
+
|
|
117
|
+
**파일**: 파이프라인 연동 (graduation.ts 또는 신규)
|
|
118
|
+
|
|
119
|
+
```typescript
|
|
120
|
+
async function processSession(session: Session): Promise<void> {
|
|
121
|
+
// 1. session_ingested 이벤트
|
|
122
|
+
const ingestEvent = await eventStore.append({ eventType: 'session_ingested', ... });
|
|
123
|
+
|
|
124
|
+
// 2. LLM 추출
|
|
125
|
+
const extracted = await extractor.extract(session);
|
|
126
|
+
await eventStore.append({ eventType: 'memory_extracted', ... });
|
|
127
|
+
|
|
128
|
+
// 3. Evidence 정렬 (V2)
|
|
129
|
+
const alignResult = await aligner.align(session.messages, extracted);
|
|
130
|
+
await eventStore.append({
|
|
131
|
+
eventType: 'evidence_aligned',
|
|
132
|
+
content: JSON.stringify({
|
|
133
|
+
source_event_id: ingestEvent.eventId,
|
|
134
|
+
aligned_count: alignResult.alignedEvidence.length,
|
|
135
|
+
failed_count: alignResult.failedQuotes.length,
|
|
136
|
+
evidence: alignResult.alignedEvidence,
|
|
137
|
+
failed_quotes: alignResult.failedQuotes
|
|
138
|
+
})
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
// 4. Entry 저장 (alignResult 반영)
|
|
142
|
+
for (const entry of extracted.entries) {
|
|
143
|
+
const entryEvidence = alignResult.alignedEvidence.filter(
|
|
144
|
+
e => e.entryId === entry.entryId
|
|
145
|
+
);
|
|
146
|
+
entry.evidenceAligned = entryEvidence.every(e => e.matchMethod !== 'none');
|
|
147
|
+
// ...
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
**작업 항목**:
|
|
153
|
+
- [ ] process_session 흐름에 aligner 삽입
|
|
154
|
+
- [ ] evidence_aligned 이벤트 발행
|
|
155
|
+
- [ ] entry에 evidenceAligned 플래그 설정
|
|
156
|
+
|
|
157
|
+
## Phase 4: 승격 정책 적용 (P0)
|
|
158
|
+
|
|
159
|
+
### 4.1 Graduation 조건 수정
|
|
160
|
+
|
|
161
|
+
**파일**: `src/core/graduation.ts` 수정
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
async function promoteToVerified(entry: Entry): Promise<PromotionResult> {
|
|
165
|
+
// Evidence 정렬 확인
|
|
166
|
+
if (!entry.evidenceAligned) {
|
|
167
|
+
return {
|
|
168
|
+
success: false,
|
|
169
|
+
reason: 'Evidence alignment failed. Cannot promote to Verified.'
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 기타 조건 확인...
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
**작업 항목**:
|
|
178
|
+
- [ ] candidate → verified 승격 조건에 evidenceAligned 추가
|
|
179
|
+
- [ ] 실패 시 명확한 reason 제공
|
|
180
|
+
|
|
181
|
+
### 4.2 메타데이터 기록
|
|
182
|
+
|
|
183
|
+
**작업 항목**:
|
|
184
|
+
- [ ] entry.meta.promotionBlocked 플래그
|
|
185
|
+
- [ ] entry.meta.promotionBlockReason 기록
|
|
186
|
+
- [ ] entry.meta.failedQuotes 저장 (디버깅용)
|
|
187
|
+
|
|
188
|
+
## Phase 5: 유틸리티 및 테스트 (P1)
|
|
189
|
+
|
|
190
|
+
### 5.1 Levenshtein 구현
|
|
191
|
+
|
|
192
|
+
**파일**: `src/core/string-utils.ts` (신규)
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
export function levenshteinDistance(a: string, b: string): number;
|
|
196
|
+
export function levenshteinSimilarity(a: string, b: string): number;
|
|
197
|
+
export function findBestFuzzyMatch(
|
|
198
|
+
needle: string,
|
|
199
|
+
haystack: string,
|
|
200
|
+
threshold: number
|
|
201
|
+
): { start: number; end: number; score: number } | null;
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
**작업 항목**:
|
|
205
|
+
- [ ] Levenshtein 거리 함수
|
|
206
|
+
- [ ] 유사도 함수 (1 - distance / max_length)
|
|
207
|
+
- [ ] 슬라이딩 윈도우 최적 매칭
|
|
208
|
+
|
|
209
|
+
### 5.2 위치 역추적
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
// 정규화된 문자열에서 원본 문자열 위치 매핑
|
|
213
|
+
interface PositionMap {
|
|
214
|
+
normalizedToOriginal: Map<number, number>;
|
|
215
|
+
originalToNormalized: Map<number, number>;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function createPositionMap(original: string, normalized: string): PositionMap;
|
|
219
|
+
export function mapSpanToOriginal(map: PositionMap, normalizedSpan: Span): Span;
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
**작업 항목**:
|
|
223
|
+
- [ ] 위치 매핑 생성 함수
|
|
224
|
+
- [ ] span 역추적 함수
|
|
225
|
+
|
|
226
|
+
## 파일 목록
|
|
227
|
+
|
|
228
|
+
### 수정 파일
|
|
229
|
+
```
|
|
230
|
+
src/core/types.ts # 타입 추가
|
|
231
|
+
src/core/evidence-aligner.ts # V2 로직 추가
|
|
232
|
+
src/core/graduation.ts # 승격 조건 수정
|
|
233
|
+
src/core/event-store.ts # 이벤트 타입 추가
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
### 신규 파일
|
|
237
|
+
```
|
|
238
|
+
src/core/string-utils.ts # 문자열 유틸리티
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
## 테스트
|
|
242
|
+
|
|
243
|
+
### 필수 테스트 케이스
|
|
244
|
+
|
|
245
|
+
1. **Exact Match**
|
|
246
|
+
```typescript
|
|
247
|
+
// quote가 원문에 정확히 존재
|
|
248
|
+
const source = "DuckDB의 JSONB를 JSON으로 변경";
|
|
249
|
+
const quote = "JSONB를 JSON으로";
|
|
250
|
+
expect(aligner.exactMatch(quote, source)).toEqual({
|
|
251
|
+
spanStart: 7,
|
|
252
|
+
spanEnd: 18,
|
|
253
|
+
confidence: 1.0,
|
|
254
|
+
matchMethod: 'exact'
|
|
255
|
+
});
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
2. **Normalized Match**
|
|
259
|
+
```typescript
|
|
260
|
+
// 공백 차이만 있는 경우
|
|
261
|
+
const source = "JSONB를 JSON으로\n변경";
|
|
262
|
+
const quote = "JSONB를 JSON으로 변경";
|
|
263
|
+
expect(aligner.normalizedMatch(quote, source)).not.toBeNull();
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
3. **Fuzzy Match**
|
|
267
|
+
```typescript
|
|
268
|
+
// 약간의 오타/변형
|
|
269
|
+
const source = "DuckDB에서 JSONB 타입을 제거";
|
|
270
|
+
const quote = "DuckDB JSONB 타입 제거"; // 조사 누락
|
|
271
|
+
const result = aligner.fuzzyMatch(quote, source, 0.85);
|
|
272
|
+
expect(result?.confidence).toBeGreaterThanOrEqual(0.85);
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
4. **No Match**
|
|
276
|
+
```typescript
|
|
277
|
+
// 원문에 없는 내용
|
|
278
|
+
const source = "벡터 검색을 구현합니다";
|
|
279
|
+
const quote = "JSONB를 제거";
|
|
280
|
+
expect(aligner.align([source], { evidence: [{ quote }] })).toEqual({
|
|
281
|
+
evidenceAligned: false,
|
|
282
|
+
failedQuotes: ["JSONB를 제거"]
|
|
283
|
+
});
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
5. **승격 거부**
|
|
287
|
+
```typescript
|
|
288
|
+
const entry = { evidenceAligned: false, stage: 'candidate' };
|
|
289
|
+
const result = await graduation.promoteToVerified(entry);
|
|
290
|
+
expect(result.success).toBe(false);
|
|
291
|
+
expect(result.reason).toContain('Evidence alignment failed');
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
## 마일스톤
|
|
295
|
+
|
|
296
|
+
| 단계 | 완료 기준 |
|
|
297
|
+
|------|----------|
|
|
298
|
+
| M1 | 타입 정의 완료 |
|
|
299
|
+
| M2 | exactMatch + normalizedMatch 동작 |
|
|
300
|
+
| M3 | fuzzyMatch 동작 (Levenshtein) |
|
|
301
|
+
| M4 | evidence_aligned 이벤트 발행 |
|
|
302
|
+
| M5 | Graduation 승격 조건 적용 |
|
|
303
|
+
| M6 | 테스트 통과 |
|