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.
Files changed (127) hide show
  1. package/.claude-plugin/commands/memory-forget.md +42 -0
  2. package/.claude-plugin/commands/memory-history.md +34 -0
  3. package/.claude-plugin/commands/memory-import.md +56 -0
  4. package/.claude-plugin/commands/memory-list.md +37 -0
  5. package/.claude-plugin/commands/memory-search.md +36 -0
  6. package/.claude-plugin/commands/memory-stats.md +34 -0
  7. package/.claude-plugin/hooks.json +59 -0
  8. package/.claude-plugin/plugin.json +24 -0
  9. package/.history/package_20260201112328.json +45 -0
  10. package/.history/package_20260201113602.json +45 -0
  11. package/.history/package_20260201113713.json +45 -0
  12. package/.history/package_20260201114110.json +45 -0
  13. package/Memo.txt +558 -0
  14. package/README.md +520 -0
  15. package/context.md +636 -0
  16. package/dist/.claude-plugin/commands/memory-forget.md +42 -0
  17. package/dist/.claude-plugin/commands/memory-history.md +34 -0
  18. package/dist/.claude-plugin/commands/memory-import.md +56 -0
  19. package/dist/.claude-plugin/commands/memory-list.md +37 -0
  20. package/dist/.claude-plugin/commands/memory-search.md +36 -0
  21. package/dist/.claude-plugin/commands/memory-stats.md +34 -0
  22. package/dist/.claude-plugin/hooks.json +59 -0
  23. package/dist/.claude-plugin/plugin.json +24 -0
  24. package/dist/cli/index.js +3539 -0
  25. package/dist/cli/index.js.map +7 -0
  26. package/dist/core/index.js +4408 -0
  27. package/dist/core/index.js.map +7 -0
  28. package/dist/hooks/session-end.js +2971 -0
  29. package/dist/hooks/session-end.js.map +7 -0
  30. package/dist/hooks/session-start.js +2969 -0
  31. package/dist/hooks/session-start.js.map +7 -0
  32. package/dist/hooks/stop.js +3123 -0
  33. package/dist/hooks/stop.js.map +7 -0
  34. package/dist/hooks/user-prompt-submit.js +2960 -0
  35. package/dist/hooks/user-prompt-submit.js.map +7 -0
  36. package/dist/services/memory-service.js +2931 -0
  37. package/dist/services/memory-service.js.map +7 -0
  38. package/package.json +45 -0
  39. package/plan.md +1642 -0
  40. package/scripts/build.ts +102 -0
  41. package/spec.md +624 -0
  42. package/specs/citations-system/context.md +243 -0
  43. package/specs/citations-system/plan.md +495 -0
  44. package/specs/citations-system/spec.md +371 -0
  45. package/specs/endless-mode/context.md +305 -0
  46. package/specs/endless-mode/plan.md +620 -0
  47. package/specs/endless-mode/spec.md +455 -0
  48. package/specs/entity-edge-model/context.md +401 -0
  49. package/specs/entity-edge-model/plan.md +459 -0
  50. package/specs/entity-edge-model/spec.md +391 -0
  51. package/specs/evidence-aligner-v2/context.md +401 -0
  52. package/specs/evidence-aligner-v2/plan.md +303 -0
  53. package/specs/evidence-aligner-v2/spec.md +312 -0
  54. package/specs/mcp-desktop-integration/context.md +278 -0
  55. package/specs/mcp-desktop-integration/plan.md +550 -0
  56. package/specs/mcp-desktop-integration/spec.md +494 -0
  57. package/specs/post-tool-use-hook/context.md +319 -0
  58. package/specs/post-tool-use-hook/plan.md +469 -0
  59. package/specs/post-tool-use-hook/spec.md +364 -0
  60. package/specs/private-tags/context.md +288 -0
  61. package/specs/private-tags/plan.md +412 -0
  62. package/specs/private-tags/spec.md +345 -0
  63. package/specs/progressive-disclosure/context.md +346 -0
  64. package/specs/progressive-disclosure/plan.md +663 -0
  65. package/specs/progressive-disclosure/spec.md +415 -0
  66. package/specs/task-entity-system/context.md +297 -0
  67. package/specs/task-entity-system/plan.md +301 -0
  68. package/specs/task-entity-system/spec.md +314 -0
  69. package/specs/vector-outbox-v2/context.md +470 -0
  70. package/specs/vector-outbox-v2/plan.md +562 -0
  71. package/specs/vector-outbox-v2/spec.md +466 -0
  72. package/specs/web-viewer-ui/context.md +384 -0
  73. package/specs/web-viewer-ui/plan.md +797 -0
  74. package/specs/web-viewer-ui/spec.md +516 -0
  75. package/src/cli/index.ts +570 -0
  76. package/src/core/canonical-key.ts +186 -0
  77. package/src/core/citation-generator.ts +63 -0
  78. package/src/core/consolidated-store.ts +279 -0
  79. package/src/core/consolidation-worker.ts +384 -0
  80. package/src/core/context-formatter.ts +276 -0
  81. package/src/core/continuity-manager.ts +336 -0
  82. package/src/core/edge-repo.ts +324 -0
  83. package/src/core/embedder.ts +124 -0
  84. package/src/core/entity-repo.ts +342 -0
  85. package/src/core/event-store.ts +672 -0
  86. package/src/core/evidence-aligner.ts +635 -0
  87. package/src/core/graduation.ts +365 -0
  88. package/src/core/index.ts +32 -0
  89. package/src/core/matcher.ts +210 -0
  90. package/src/core/metadata-extractor.ts +203 -0
  91. package/src/core/privacy/filter.ts +179 -0
  92. package/src/core/privacy/index.ts +20 -0
  93. package/src/core/privacy/tag-parser.ts +145 -0
  94. package/src/core/progressive-retriever.ts +415 -0
  95. package/src/core/retriever.ts +235 -0
  96. package/src/core/task/blocker-resolver.ts +325 -0
  97. package/src/core/task/index.ts +9 -0
  98. package/src/core/task/task-matcher.ts +238 -0
  99. package/src/core/task/task-projector.ts +345 -0
  100. package/src/core/task/task-resolver.ts +414 -0
  101. package/src/core/types.ts +841 -0
  102. package/src/core/vector-outbox.ts +295 -0
  103. package/src/core/vector-store.ts +182 -0
  104. package/src/core/vector-worker.ts +488 -0
  105. package/src/core/working-set-store.ts +244 -0
  106. package/src/hooks/post-tool-use.ts +127 -0
  107. package/src/hooks/session-end.ts +78 -0
  108. package/src/hooks/session-start.ts +57 -0
  109. package/src/hooks/stop.ts +78 -0
  110. package/src/hooks/user-prompt-submit.ts +54 -0
  111. package/src/mcp/handlers.ts +212 -0
  112. package/src/mcp/index.ts +47 -0
  113. package/src/mcp/tools.ts +78 -0
  114. package/src/server/api/citations.ts +101 -0
  115. package/src/server/api/events.ts +101 -0
  116. package/src/server/api/index.ts +18 -0
  117. package/src/server/api/search.ts +98 -0
  118. package/src/server/api/sessions.ts +111 -0
  119. package/src/server/api/stats.ts +97 -0
  120. package/src/server/index.ts +91 -0
  121. package/src/services/memory-service.ts +626 -0
  122. package/src/services/session-history-importer.ts +367 -0
  123. package/tests/canonical-key.test.ts +101 -0
  124. package/tests/evidence-aligner.test.ts +152 -0
  125. package/tests/matcher.test.ts +112 -0
  126. package/tsconfig.json +24 -0
  127. package/vitest.config.ts +15 -0
@@ -0,0 +1,364 @@
1
+ # PostToolUse Hook Specification
2
+
3
+ > **Version**: 1.0.0
4
+ > **Status**: Draft
5
+ > **Created**: 2026-02-01
6
+ > **Reference**: claude-mem (thedotmack/claude-mem)
7
+
8
+ ## 1. 개요
9
+
10
+ ### 1.1 문제 정의
11
+
12
+ 현재 시스템에서 도구 사용 결과가 메모리에 저장되지 않음:
13
+
14
+ 1. **도구 실행 컨텍스트 손실**: 파일 읽기/쓰기 결과가 별도로 기록되지 않음
15
+ 2. **작업 패턴 학습 불가**: 어떤 도구를 어떤 상황에서 사용했는지 추적 불가
16
+ 3. **세션 재구성 어려움**: 과거 세션의 실제 작업 내용 파악 어려움
17
+
18
+ ### 1.2 해결 방향
19
+
20
+ **PostToolUse 훅 추가**:
21
+ - 도구 실행 직후 호출되는 훅
22
+ - 도구 이름, 입력 파라미터, 출력 결과를 캡처
23
+ - EventStore에 `tool_observation` 이벤트로 저장
24
+
25
+ ## 2. 핵심 개념
26
+
27
+ ### 2.1 훅 라이프사이클
28
+
29
+ ```
30
+ ┌─────────────────────────────────────────────────────────────┐
31
+ │ Claude Code Session │
32
+ ├─────────────────────────────────────────────────────────────┤
33
+ │ │
34
+ │ session-start ────────────────────────────────────────────▶│
35
+ │ │ │
36
+ │ ▼ │
37
+ │ user-prompt-submit ◀──────────────────────────────────────┐│
38
+ │ │ ││
39
+ │ ▼ ││
40
+ │ [Agent Processing] ││
41
+ │ │ ││
42
+ │ ├── Tool Execution ─────┐ ││
43
+ │ │ ▼ ││
44
+ │ │ post-tool-use (NEW) ││
45
+ │ │ │ ││
46
+ │ │◀──────────────────────┘ ││
47
+ │ │ ││
48
+ │ ▼ ││
49
+ │ stop ───────────────────────────────────────────────────┘│
50
+ │ │ │
51
+ │ ▼ │
52
+ │ session-end │
53
+ │ │
54
+ └─────────────────────────────────────────────────────────────┘
55
+ ```
56
+
57
+ ### 2.2 캡처할 데이터
58
+
59
+ | 필드 | 타입 | 설명 |
60
+ |------|------|------|
61
+ | tool_name | string | 실행된 도구 이름 (Read, Write, Bash 등) |
62
+ | tool_input | object | 도구에 전달된 파라미터 |
63
+ | tool_output | string | 도구 실행 결과 (truncated) |
64
+ | duration_ms | number | 실행 시간 |
65
+ | success | boolean | 성공/실패 여부 |
66
+ | error_message | string? | 실패 시 에러 메시지 |
67
+
68
+ ### 2.3 지원 도구 목록
69
+
70
+ ```typescript
71
+ type SupportedTool =
72
+ | 'Read' // 파일 읽기
73
+ | 'Write' // 파일 쓰기
74
+ | 'Edit' // 파일 편집
75
+ | 'Bash' // 명령 실행
76
+ | 'Glob' // 파일 검색
77
+ | 'Grep' // 내용 검색
78
+ | 'WebFetch' // 웹 요청
79
+ | 'WebSearch' // 웹 검색
80
+ | 'Task' // 서브에이전트
81
+ | 'NotebookEdit'; // 노트북 편집
82
+ ```
83
+
84
+ ## 3. 이벤트 스키마
85
+
86
+ ### 3.1 ToolObservation 이벤트
87
+
88
+ ```typescript
89
+ const ToolObservationEventSchema = z.object({
90
+ eventId: z.string().uuid(),
91
+ eventType: z.literal('tool_observation'),
92
+ sessionId: z.string(),
93
+ timestamp: z.date(),
94
+ payload: z.object({
95
+ toolName: z.string(),
96
+ toolInput: z.record(z.unknown()),
97
+ toolOutput: z.string().max(10000), // 10KB 제한
98
+ durationMs: z.number(),
99
+ success: z.boolean(),
100
+ errorMessage: z.string().optional(),
101
+
102
+ // 컨텍스트
103
+ promptIndex: z.number(), // 몇 번째 프롬프트에서 실행됐는지
104
+ toolIndex: z.number(), // 해당 프롬프트 내 몇 번째 도구인지
105
+
106
+ // 메타데이터 (도구별 특화)
107
+ metadata: z.object({
108
+ // Read/Write/Edit
109
+ filePath: z.string().optional(),
110
+ fileType: z.string().optional(),
111
+ lineCount: z.number().optional(),
112
+
113
+ // Bash
114
+ command: z.string().optional(),
115
+ exitCode: z.number().optional(),
116
+
117
+ // Grep/Glob
118
+ pattern: z.string().optional(),
119
+ matchCount: z.number().optional(),
120
+
121
+ // WebFetch
122
+ url: z.string().optional(),
123
+ statusCode: z.number().optional()
124
+ }).optional()
125
+ })
126
+ });
127
+ ```
128
+
129
+ ### 3.2 도구별 메타데이터 예시
130
+
131
+ ```typescript
132
+ // Read 도구
133
+ {
134
+ toolName: 'Read',
135
+ toolInput: { file_path: '/src/core/types.ts' },
136
+ toolOutput: '// Type definitions...', // truncated
137
+ metadata: {
138
+ filePath: '/src/core/types.ts',
139
+ fileType: 'typescript',
140
+ lineCount: 547
141
+ }
142
+ }
143
+
144
+ // Bash 도구
145
+ {
146
+ toolName: 'Bash',
147
+ toolInput: { command: 'npm test' },
148
+ toolOutput: 'All 42 tests passed',
149
+ metadata: {
150
+ command: 'npm test',
151
+ exitCode: 0
152
+ }
153
+ }
154
+
155
+ // Grep 도구
156
+ {
157
+ toolName: 'Grep',
158
+ toolInput: { pattern: 'async function', path: '/src' },
159
+ toolOutput: 'Found 15 matches in 8 files',
160
+ metadata: {
161
+ pattern: 'async function',
162
+ matchCount: 15
163
+ }
164
+ }
165
+ ```
166
+
167
+ ## 4. 훅 인터페이스
168
+
169
+ ### 4.1 훅 입력
170
+
171
+ ```typescript
172
+ interface PostToolUseHookInput {
173
+ // Claude Code에서 전달하는 데이터
174
+ tool_name: string;
175
+ tool_input: Record<string, unknown>;
176
+ tool_output: string;
177
+ tool_error?: string;
178
+
179
+ // 세션 컨텍스트
180
+ session_id: string;
181
+ conversation_id: string;
182
+
183
+ // 타이밍 정보
184
+ started_at: string;
185
+ ended_at: string;
186
+ }
187
+ ```
188
+
189
+ ### 4.2 훅 출력
190
+
191
+ ```typescript
192
+ interface PostToolUseHookOutput {
193
+ // 저장 결과
194
+ stored: boolean;
195
+ event_id?: string;
196
+
197
+ // 선택적 피드백 (Claude에게 전달)
198
+ feedback?: string;
199
+
200
+ // 에러
201
+ error?: string;
202
+ }
203
+ ```
204
+
205
+ ## 5. 프라이버시 필터링
206
+
207
+ ### 5.1 민감 정보 마스킹
208
+
209
+ ```typescript
210
+ const SENSITIVE_PATTERNS = [
211
+ /password\s*[:=]\s*['"]?[^\s'"]+/gi,
212
+ /api[_-]?key\s*[:=]\s*['"]?[^\s'"]+/gi,
213
+ /secret\s*[:=]\s*['"]?[^\s'"]+/gi,
214
+ /token\s*[:=]\s*['"]?[^\s'"]+/gi,
215
+ /bearer\s+[a-zA-Z0-9\-_.]+/gi,
216
+ /-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi
217
+ ];
218
+
219
+ function maskSensitiveData(content: string): string {
220
+ let masked = content;
221
+ for (const pattern of SENSITIVE_PATTERNS) {
222
+ masked = masked.replace(pattern, '[REDACTED]');
223
+ }
224
+ return masked;
225
+ }
226
+ ```
227
+
228
+ ### 5.2 제외할 도구
229
+
230
+ ```typescript
231
+ const EXCLUDED_TOOLS = [
232
+ 'TodoWrite', // 내부 상태 관리
233
+ 'TodoRead',
234
+ ];
235
+
236
+ function shouldStore(toolName: string): boolean {
237
+ return !EXCLUDED_TOOLS.includes(toolName);
238
+ }
239
+ ```
240
+
241
+ ## 6. 출력 압축
242
+
243
+ ### 6.1 크기 제한
244
+
245
+ ```typescript
246
+ const OUTPUT_LIMITS = {
247
+ maxLength: 10000, // 10KB
248
+ maxLines: 100, // 100줄
249
+ truncationMarker: '\n...[TRUNCATED]...\n'
250
+ };
251
+
252
+ function truncateOutput(output: string): string {
253
+ const lines = output.split('\n');
254
+
255
+ if (lines.length > OUTPUT_LIMITS.maxLines) {
256
+ const head = lines.slice(0, 50);
257
+ const tail = lines.slice(-50);
258
+ return head.join('\n') + OUTPUT_LIMITS.truncationMarker + tail.join('\n');
259
+ }
260
+
261
+ if (output.length > OUTPUT_LIMITS.maxLength) {
262
+ return output.slice(0, OUTPUT_LIMITS.maxLength / 2) +
263
+ OUTPUT_LIMITS.truncationMarker +
264
+ output.slice(-OUTPUT_LIMITS.maxLength / 2);
265
+ }
266
+
267
+ return output;
268
+ }
269
+ ```
270
+
271
+ ### 6.2 도구별 압축 전략
272
+
273
+ | 도구 | 압축 전략 |
274
+ |------|----------|
275
+ | Read | 첫 50줄 + 마지막 50줄, 파일 타입 보존 |
276
+ | Bash | 전체 출력, exitCode 보존 |
277
+ | Grep | 매칭된 파일 목록만, 전체 내용 제외 |
278
+ | Glob | 파일 경로 목록만 |
279
+ | WebFetch | 첫 500자 요약 |
280
+
281
+ ## 7. 벡터 임베딩 연동
282
+
283
+ ### 7.1 임베딩 대상
284
+
285
+ ```typescript
286
+ function createEmbeddingContent(observation: ToolObservation): string {
287
+ const parts: string[] = [];
288
+
289
+ // 도구 이름
290
+ parts.push(`Tool: ${observation.toolName}`);
291
+
292
+ // 주요 입력
293
+ if (observation.metadata?.filePath) {
294
+ parts.push(`File: ${observation.metadata.filePath}`);
295
+ }
296
+ if (observation.metadata?.command) {
297
+ parts.push(`Command: ${observation.metadata.command}`);
298
+ }
299
+ if (observation.metadata?.pattern) {
300
+ parts.push(`Pattern: ${observation.metadata.pattern}`);
301
+ }
302
+
303
+ // 결과 요약
304
+ parts.push(`Result: ${observation.success ? 'Success' : 'Failed'}`);
305
+
306
+ return parts.join('\n');
307
+ }
308
+ ```
309
+
310
+ ### 7.2 Outbox 연동
311
+
312
+ ```typescript
313
+ // tool_observation도 Outbox에 추가하여 벡터화
314
+ await eventStore.append({
315
+ eventType: 'tool_observation',
316
+ payload: observation
317
+ });
318
+
319
+ // VectorWorker가 배치 처리
320
+ // embedding content: "Tool: Read\nFile: /src/types.ts\nResult: Success"
321
+ ```
322
+
323
+ ## 8. 검색 활용
324
+
325
+ ### 8.1 도구 사용 이력 검색
326
+
327
+ ```sql
328
+ -- 특정 파일 관련 도구 사용 이력
329
+ SELECT * FROM events
330
+ WHERE event_type = 'tool_observation'
331
+ AND JSON_EXTRACT(payload_json, '$.metadata.filePath') LIKE '%types.ts%'
332
+ ORDER BY timestamp DESC
333
+ LIMIT 10;
334
+
335
+ -- 실패한 도구 실행 조회
336
+ SELECT * FROM events
337
+ WHERE event_type = 'tool_observation'
338
+ AND JSON_EXTRACT(payload_json, '$.success') = false
339
+ ORDER BY timestamp DESC;
340
+ ```
341
+
342
+ ### 8.2 컨텍스트 주입 활용
343
+
344
+ ```typescript
345
+ // user-prompt-submit에서 활용
346
+ async function getRelevantToolHistory(query: string): Promise<ToolObservation[]> {
347
+ // 벡터 검색으로 관련 도구 사용 이력 조회
348
+ const results = await vectorStore.search(query, {
349
+ filter: { eventType: 'tool_observation' },
350
+ topK: 5
351
+ });
352
+
353
+ return results.map(r => r.payload as ToolObservation);
354
+ }
355
+ ```
356
+
357
+ ## 9. 성공 기준
358
+
359
+ - [ ] PostToolUse 훅이 모든 도구 실행 후 호출됨
360
+ - [ ] tool_observation 이벤트가 EventStore에 저장됨
361
+ - [ ] 민감 정보가 마스킹됨
362
+ - [ ] 출력이 크기 제한 내로 압축됨
363
+ - [ ] 벡터 임베딩이 생성됨
364
+ - [ ] 도구 사용 이력 검색이 가능함
@@ -0,0 +1,288 @@
1
+ # Private Tags Context
2
+
3
+ > **Version**: 1.0.0
4
+ > **Created**: 2026-02-01
5
+
6
+ ## 1. 배경
7
+
8
+ ### 1.1 claude-mem의 접근 방식
9
+
10
+ claude-mem은 `<private>` 태그를 통한 명시적 프라이버시 제어 지원:
11
+
12
+ ```markdown
13
+ <private>
14
+ API_KEY=sk-xxxx
15
+ </private>
16
+ ```
17
+
18
+ **특징**:
19
+ - 사용자가 직접 비공개 영역 지정
20
+ - 태그 내 내용은 저장되지 않음
21
+ - 간단하고 직관적인 문법
22
+
23
+ ### 1.2 현재 code-memory의 상황
24
+
25
+ 현재 패턴 기반 필터링만 지원:
26
+
27
+ ```typescript
28
+ const config = {
29
+ privacy: {
30
+ excludePatterns: ['password', 'secret', 'api_key']
31
+ }
32
+ };
33
+ ```
34
+
35
+ **한계**:
36
+ 1. 고정된 패턴만 감지
37
+ 2. 컨텍스트 무시 (실제 비밀번호 아닌 "password"도 필터링)
38
+ 3. 사용자 의도 반영 불가
39
+
40
+ ### 1.3 두 접근법 비교
41
+
42
+ | 패턴 기반 | 태그 기반 |
43
+ |----------|----------|
44
+ | 자동 감지 | 명시적 지정 |
45
+ | False positive 가능 | 정확한 제어 |
46
+ | 설정 필요 | 즉시 사용 |
47
+ | 패턴 외 누락 가능 | 사용자 책임 |
48
+
49
+ **결론**: 두 방식 병행이 최선
50
+
51
+ ## 2. 태그 문법 선택
52
+
53
+ ### 2.1 고려한 옵션들
54
+
55
+ | 옵션 | 예시 | 장점 | 단점 |
56
+ |------|------|------|------|
57
+ | XML 스타일 | `<private>...</private>` | 직관적, 중첩 가능 | Markdown과 충돌 가능 |
58
+ | 대괄호 | `[private]...[/private]` | Markdown 친화적 | 덜 직관적 |
59
+ | HTML 주석 | `<!-- private -->` | 렌더링 안 됨 | 복잡함 |
60
+ | 펜스 스타일 | `:::private\n...\n:::` | Markdown 확장 스타일 | 비표준 |
61
+
62
+ ### 2.2 선택: XML 스타일 + 대안 지원
63
+
64
+ ```typescript
65
+ // 기본: XML 스타일
66
+ <private>...</private>
67
+
68
+ // 대안 1: 대괄호 (Markdown 문서용)
69
+ [private]...[/private]
70
+
71
+ // 대안 2: HTML 주석 (렌더링 방지)
72
+ <!-- private -->...<!-- /private -->
73
+ ```
74
+
75
+ ### 2.3 claude-mem과의 호환성
76
+
77
+ claude-mem이 `<private>` 태그를 사용하므로 동일한 문법을 기본으로 채택하여 사용자 경험 일관성 유지.
78
+
79
+ ## 3. 기존 코드와의 관계
80
+
81
+ ### 3.1 types.ts
82
+
83
+ 현재 Privacy 관련 타입:
84
+
85
+ ```typescript
86
+ // 현재
87
+ export const PrivacyConfigSchema = z.object({
88
+ excludePatterns: z.array(z.string()),
89
+ anonymize: z.boolean()
90
+ });
91
+
92
+ // 확장
93
+ export const PrivacyConfigSchema = z.object({
94
+ excludePatterns: z.array(z.string()),
95
+ anonymize: z.boolean(),
96
+ privateTags: PrivateTagsConfigSchema // 추가
97
+ });
98
+ ```
99
+
100
+ ### 3.2 훅 연동
101
+
102
+ 영향받는 훅:
103
+ - `user-prompt-submit.ts`: 사용자 입력 필터링
104
+ - `stop.ts`: AI 응답 필터링
105
+ - `post-tool-use.ts`: 도구 출력 필터링
106
+
107
+ ```typescript
108
+ // 모든 훅에서 동일한 필터 사용
109
+ const filtered = applyPrivacyFilter(content, config.privacy);
110
+ ```
111
+
112
+ ### 3.3 검색 영향
113
+
114
+ - **벡터 검색**: `[PRIVATE]` 마커가 임베딩에 포함되지만, 원본 내용은 검색 불가
115
+ - **전문 검색**: 마커는 검색 가능, 원본 내용 불가
116
+
117
+ ## 4. 설계 결정 사항
118
+
119
+ ### 4.1 마커 선택
120
+
121
+ **옵션들**:
122
+ 1. `[PRIVATE]` - 명확하고 검색 가능
123
+ 2. `[REDACTED]` - 일반적인 검열 용어
124
+ 3. `""` (빈 문자열) - 흔적 없이 제거
125
+ 4. `[...]` - 간결하지만 모호
126
+
127
+ **선택**: `[PRIVATE]`
128
+ - 명확한 의미 전달
129
+ - 검색/필터링 가능
130
+ - 설정으로 변경 가능
131
+
132
+ ### 4.2 코드 블록 처리
133
+
134
+ **문제**: 코드 블록 내 `<private>` 태그를 리터럴로 취급해야 함
135
+
136
+ ```markdown
137
+ ```xml
138
+ <private>이것은 예시 코드입니다</private>
139
+ ```
140
+ ```
141
+
142
+ **해결**: 코드 블록을 먼저 추출하고 보호
143
+
144
+ ```typescript
145
+ // 1. 코드 블록 임시 치환
146
+ // 2. private 태그 파싱
147
+ // 3. 코드 블록 복원
148
+ ```
149
+
150
+ ### 4.3 불완전한 태그 처리
151
+
152
+ **시나리오**:
153
+ ```markdown
154
+ <private>
155
+ 시작은 있지만 끝이 없음...
156
+ (사용자가 실수로 닫지 않음)
157
+ ```
158
+
159
+ **옵션**:
160
+ 1. 끝까지 private로 처리 → 데이터 손실 위험
161
+ 2. 무시 (원본 유지) → 보수적, 안전
162
+
163
+ **선택**: 무시 (보수적 접근)
164
+ - 데이터 손실 방지
165
+ - 사용자에게 경고 표시 가능
166
+
167
+ ### 4.4 중첩 태그 처리
168
+
169
+ ```markdown
170
+ <private>
171
+ 외부
172
+ <private>내부</private>
173
+ 외부 계속
174
+ </private>
175
+ ```
176
+
177
+ **선택**: 중첩 지원하지 않음
178
+ - 외부 태그만 처리
179
+ - 복잡도 감소
180
+ - 실용적 케이스 드묾
181
+
182
+ ## 5. 성능 고려사항
183
+
184
+ ### 5.1 정규식 성능
185
+
186
+ ```typescript
187
+ // 비효율적 (매번 새 정규식)
188
+ for (const format of formats) {
189
+ const regex = new RegExp(...); // 매번 생성
190
+ }
191
+
192
+ // 효율적 (캐싱)
193
+ const TAG_PATTERNS = {
194
+ xml: /<private>[\s\S]*?<\/private>/gi,
195
+ // ...
196
+ };
197
+ ```
198
+
199
+ ### 5.2 대용량 텍스트
200
+
201
+ 긴 텍스트의 경우:
202
+ - 정규식 `[\s\S]*?` 사용 (non-greedy)
203
+ - 스트리밍 파싱 고려 (향후)
204
+
205
+ ### 5.3 캐싱
206
+
207
+ ```typescript
208
+ // 동일 입력에 대한 결과 캐싱
209
+ const filterCache = new LRUCache<string, FilterResult>({
210
+ max: 100,
211
+ ttl: 60000
212
+ });
213
+ ```
214
+
215
+ ## 6. 보안 고려사항
216
+
217
+ ### 6.1 태그 우회 시도
218
+
219
+ ```markdown
220
+ <!-- 공격자가 태그를 깨뜨리려는 시도 -->
221
+ <private
222
+ >secret</private>
223
+
224
+ <pri
225
+ vate>secret</private>
226
+ ```
227
+
228
+ **대응**: 엄격한 정규식 매칭 (정확한 `<private>` 패턴만)
229
+
230
+ ### 6.2 메모리 내 노출
231
+
232
+ - 파싱 중 원본 내용이 메모리에 일시적으로 존재
233
+ - 디스크에는 저장되지 않음
234
+ - 로그에 원본 출력 금지
235
+
236
+ ```typescript
237
+ // 안전하지 않음
238
+ console.log(`Parsing: ${content}`);
239
+
240
+ // 안전
241
+ console.log(`Parsing content of length ${content.length}`);
242
+ ```
243
+
244
+ ## 7. 사용자 경험
245
+
246
+ ### 7.1 문서화
247
+
248
+ ```markdown
249
+ ## Privacy Tags
250
+
251
+ Wrap sensitive content in `<private>` tags to prevent storage:
252
+
253
+ \`\`\`
254
+ <private>
255
+ Your sensitive data here
256
+ </private>
257
+ \`\`\`
258
+
259
+ Content inside these tags will NOT be stored in memory.
260
+ ```
261
+
262
+ ### 7.2 피드백
263
+
264
+ ```typescript
265
+ // 훅에서 사용자에게 피드백
266
+ if (filterResult.metadata.privateTagCount > 0) {
267
+ return {
268
+ message: `🔒 ${filterResult.metadata.privateTagCount} private section(s) excluded from memory`
269
+ };
270
+ }
271
+ ```
272
+
273
+ ### 7.3 경고
274
+
275
+ ```typescript
276
+ // 불완전한 태그 감지
277
+ if (hasUnmatchedOpenTag(content)) {
278
+ return {
279
+ warning: '⚠️ Unclosed <private> tag detected. Content was NOT filtered.'
280
+ };
281
+ }
282
+ ```
283
+
284
+ ## 8. 참고 자료
285
+
286
+ - **claude-mem README**: Privacy controls using `<private>` tags
287
+ - **OWASP**: Sensitive Data Exposure guidelines
288
+ - **GDPR**: Right to erasure (잊혀질 권리)