claude-memory-layer 1.0.11 → 1.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +60 -0
- package/README.md +166 -2
- package/bootstrap-kb/decisions/decisions.md +244 -0
- package/bootstrap-kb/glossary/glossary.md +46 -0
- package/bootstrap-kb/modules/.claude-plugin.md +22 -0
- package/bootstrap-kb/modules/agents.md.md +15 -0
- package/bootstrap-kb/modules/claude.md.md +15 -0
- package/bootstrap-kb/modules/context.md.md +15 -0
- package/bootstrap-kb/modules/docs.md +18 -0
- package/bootstrap-kb/modules/handoff.md.md +15 -0
- package/bootstrap-kb/modules/package-lock.json.md +15 -0
- package/bootstrap-kb/modules/package.json.md +15 -0
- package/bootstrap-kb/modules/plan.md.md +15 -0
- package/bootstrap-kb/modules/readme.md.md +15 -0
- package/bootstrap-kb/modules/scripts.md +26 -0
- package/bootstrap-kb/modules/spec.md.md +15 -0
- package/bootstrap-kb/modules/specs.md +20 -0
- package/bootstrap-kb/modules/src.md +51 -0
- package/bootstrap-kb/modules/tests.md +42 -0
- package/bootstrap-kb/modules/tsconfig.json.md +15 -0
- package/bootstrap-kb/modules/vitest.config.ts.md +15 -0
- package/bootstrap-kb/overview/overview.md +40 -0
- package/bootstrap-kb/sources/manifest.json +950 -0
- package/bootstrap-kb/sources/manifest.md +227 -0
- package/bootstrap-kb/timeline/timeline.md +57 -0
- package/d.sh +3 -0
- package/deploy.sh +3 -0
- package/dist/cli/index.js +2389 -286
- package/dist/cli/index.js.map +4 -4
- package/dist/core/index.js +1017 -132
- package/dist/core/index.js.map +4 -4
- package/dist/hooks/post-tool-use.js +1347 -202
- package/dist/hooks/post-tool-use.js.map +4 -4
- package/dist/hooks/session-end.js +1339 -194
- package/dist/hooks/session-end.js.map +4 -4
- package/dist/hooks/session-start.js +1343 -198
- package/dist/hooks/session-start.js.map +4 -4
- package/dist/hooks/stop.js +1351 -206
- package/dist/hooks/stop.js.map +4 -4
- package/dist/hooks/user-prompt-submit.js +1347 -202
- package/dist/hooks/user-prompt-submit.js.map +4 -4
- package/dist/server/api/index.js +1436 -211
- package/dist/server/api/index.js.map +4 -4
- package/dist/server/index.js +1445 -220
- package/dist/server/index.js.map +4 -4
- package/dist/services/memory-service.js +1345 -199
- package/dist/services/memory-service.js.map +4 -4
- package/dist/ui/app.js +69 -2
- package/dist/ui/index.html +8 -0
- package/docs/MCP_MEMORY_SERVICE_COMPARATIVE_REVIEW.md +271 -0
- package/docs/MEMU_ADOPTION.md +40 -0
- package/memory/.claude-plugin/commands/2026-02-25.md +263 -0
- package/memory/_index.md +405 -0
- package/memory/default/uncategorized/2026-02-25.md +4839 -0
- package/memory/specs/20260207-dashboard-upgrade/2026-02-25.md +142 -0
- package/memory/specs/citations-system/2026-02-25.md +1121 -0
- package/memory/specs/endless-mode/2026-02-25.md +1392 -0
- package/memory/specs/entity-edge-model/2026-02-25.md +1263 -0
- package/memory/specs/evidence-aligner-v2/2026-02-25.md +1028 -0
- package/memory/specs/mcp-desktop-integration/2026-02-25.md +1334 -0
- package/memory/specs/post-tool-use-hook/2026-02-25.md +1164 -0
- package/memory/specs/private-tags/2026-02-25.md +1057 -0
- package/memory/specs/progressive-disclosure/2026-02-25.md +1436 -0
- package/memory/specs/task-entity-system/2026-02-25.md +924 -0
- package/memory/specs/vector-outbox-v2/2026-02-25.md +1510 -0
- package/memory/specs/web-viewer-ui/2026-02-25.md +1709 -0
- package/package.json +2 -1
- package/scripts/build.ts +6 -0
- package/src/cli/index.ts +281 -2
- package/src/core/consolidated-store.ts +63 -1
- package/src/core/consolidation-worker.ts +115 -6
- package/src/core/event-store.ts +14 -0
- package/src/core/index.ts +1 -0
- package/src/core/ingest-interceptor.ts +80 -0
- package/src/core/markdown-mirror.ts +70 -0
- package/src/core/md-mirror.ts +92 -0
- package/src/core/mongo-sync-config.ts +165 -0
- package/src/core/mongo-sync-worker.ts +381 -0
- package/src/core/retriever.ts +540 -150
- package/src/core/sqlite-event-store.ts +350 -1
- package/src/core/tag-taxonomy.ts +51 -0
- package/src/core/types.ts +28 -0
- package/src/server/api/health.ts +53 -0
- package/src/server/api/index.ts +3 -1
- package/src/server/api/stats.ts +46 -1
- package/src/services/bootstrap-organizer.ts +443 -0
- package/src/services/codex-session-history-importer.ts +474 -0
- package/src/services/memory-service.ts +373 -68
- package/src/ui/app.js +69 -2
- package/src/ui/index.html +8 -0
- package/tests/bootstrap-organizer.test.ts +111 -0
- package/tests/consolidation-worker.test.ts +75 -0
- package/tests/ingest-interceptor.test.ts +38 -0
- package/tests/markdown-mirror.test.ts +85 -0
- package/tests/md-mirror.test.ts +50 -0
- package/tests/retriever-fallback-chain.test.ts +223 -0
- package/tests/retriever-strategy-scope.test.ts +97 -0
- package/tests/retriever.memu-adoption.test.ts +122 -0
- package/tests/sqlite-event-store-replication.test.ts +92 -0
|
@@ -0,0 +1,1164 @@
|
|
|
1
|
+
|
|
2
|
+
## 2026-02-25T12:31:26.351Z | 1fc39ce6-94c1-4ee0-92cd-87b88d81f552
|
|
3
|
+
- type: session_summary
|
|
4
|
+
- session: import:organized
|
|
5
|
+
# PostToolUse Hook Context
|
|
6
|
+
|
|
7
|
+
> **Version**: 1.0.0
|
|
8
|
+
> **Created**: 2026-02-01
|
|
9
|
+
|
|
10
|
+
## 1. 배경
|
|
11
|
+
|
|
12
|
+
### 1.1 claude-mem의 접근 방식
|
|
13
|
+
|
|
14
|
+
claude-mem 프로젝트는 5개의 라이프사이클 훅을 사용:
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
SessionStart → UserPromptSubmit → PostToolUse → Stop → SessionEnd
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
**PostToolUse 훅의 역할** (claude-mem):
|
|
21
|
+
- 모든 도구 실행 결과를 "observation"으로 캡처
|
|
22
|
+
- SQLite + Chroma에 저장하여 검색 가능하게 함
|
|
23
|
+
- 세션 간 도구 사용 패턴 학습
|
|
24
|
+
|
|
25
|
+
**주요 특징**:
|
|
26
|
+
- 웹 뷰어에서 실시간 observation 스트림 표시
|
|
27
|
+
- 도구별로 다른 압축 전략 적용
|
|
28
|
+
- `<private>` 태그로 민감 정보 제외
|
|
29
|
+
|
|
30
|
+
### 1.2 현재 code-memory의 상황
|
|
31
|
+
|
|
32
|
+
현재 4개 훅만 구현:
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
SessionStart → UserPromptSubmit → Stop → SessionEnd
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
**부족한 점**:
|
|
39
|
+
1. 도구 실행 결과가 Stop 훅에서 응답 전체로만 저장됨
|
|
40
|
+
2. 개별 도구 실행의 입력/출력 분리 불가
|
|
41
|
+
3. "어떤 도구를 어떻게 사용했는지" 패턴 학습 불가
|
|
42
|
+
|
|
43
|
+
### 1.3 도입 필요성
|
|
44
|
+
|
|
45
|
+
| 현재 상황 | PostToolUse 도입 후 |
|
|
46
|
+
|----------|-------------------|
|
|
47
|
+
| 응답 전체만 저장 | 도구별 개별 저장 |
|
|
48
|
+
| 파일 경로 추출 어려움 | 메타데이터로 즉시 조회 |
|
|
49
|
+
| 성공/실패 구분 없음 | success 플래그로 분리 |
|
|
50
|
+
| 검색 시 노이즈 많음 | 도구 타입별 필터링 가능 |
|
|
51
|
+
|
|
52
|
+
## 2. Claude Code 훅 시스템
|
|
53
|
+
|
|
54
|
+
### 2.1 지원되는 훅 이벤트
|
|
55
|
+
|
|
56
|
+
Claude Code가 지원하는 훅 이벤트 목록:
|
|
57
|
+
|
|
58
|
+
```typescript
|
|
59
|
+
type HookEvent =
|
|
60
|
+
| 'session-start' // 세션 시작
|
|
61
|
+
| 'user-prompt-submit' // 사용자 프롬프트 제출
|
|
62
|
+
| 'post-tool-use' // 도구 사용 후 (NEW)
|
|
63
|
+
| 'stop' // 에이전트 응답 완료
|
|
64
|
+
| 'session-end'; // 세션 종료
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 2.2 post-tool-use 훅 입력 형식
|
|
68
|
+
|
|
69
|
+
Claude Code가 전달하는 데이터:
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
interface PostToolUseHookInput {
|
|
73
|
+
// 도구 정보
|
|
74
|
+
tool_name: string; // "Read", "Write", "Bash" 등
|
|
75
|
+
tool_input: object; // 도구에 전달된 파라미터
|
|
76
|
+
tool_output: string; // 도구 실행 결과
|
|
77
|
+
tool_error?: string; // 에러 발생 시 메시지
|
|
78
|
+
|
|
79
|
+
// 세션 정보
|
|
80
|
+
session_id: string;
|
|
81
|
+
conversation_id: string;
|
|
82
|
+
|
|
83
|
+
// 타이밍
|
|
84
|
+
started_at: string; // ISO 8601 형식
|
|
85
|
+
ended_at: string;
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### 2.3 훅 등록 방법
|
|
90
|
+
|
|
91
|
+
`.claude-plugin/hooks.json`:
|
|
92
|
+
|
|
93
|
+
```json
|
|
94
|
+
{
|
|
95
|
+
"hooks": [
|
|
96
|
+
{
|
|
97
|
+
"event": "post-tool-use",
|
|
98
|
+
"script": "node dist/hooks/post-tool-use.js",
|
|
99
|
+
"timeout": 5000
|
|
100
|
+
}
|
|
101
|
+
]
|
|
102
|
+
}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## 3. 참고 구현
|
|
106
|
+
|
|
107
|
+
### 3.1 claude-mem의 observation 저장
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
// claude-mem의 접근 방식 (추정)
|
|
111
|
+
interface Observation {
|
|
112
|
+
id: string;
|
|
113
|
+
session_id: string;
|
|
114
|
+
tool_name: string;
|
|
115
|
+
input: object;
|
|
116
|
+
output: string;
|
|
117
|
+
timestamp: Date;
|
|
118
|
+
|
|
119
|
+
// 검색을 위한 필드
|
|
120
|
+
summary: string; // LLM으로 생성한 요약
|
|
121
|
+
embedding: number[]; // 벡터 임베딩
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### 3.2 도구별 처리 차이
|
|
126
|
+
|
|
127
|
+
| 도구 | 저장 내용 | 요약 생성 |
|
|
128
|
+
|------|----------|----------|
|
|
129
|
+
| Read | 파일 경로, 첫 N줄 | "Read {path}: {first_line}..." |
|
|
130
|
+
| Write | 파일 경로, 변경 내용 요약 | "Wrote {lines} lines to {path}" |
|
|
131
|
+
| Bash | 명령어, exit code | "Ran `{cmd}`: {status}" |
|
|
132
|
+
| Grep | 패턴, 매칭 파일 수 | "Found {n} matches for {pattern}" |
|
|
133
|
+
|
|
134
|
+
### 3.3 Progressive Disclosure 활용
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
// 검색 시 observation을 3단계로 반환
|
|
138
|
+
interface ObservationSearchResult {
|
|
139
|
+
// Layer 1: ID + 요약 (최소 토큰)
|
|
140
|
+
layer1: { id: string; summary: string }[];
|
|
141
|
+
|
|
142
|
+
// Layer 2: 타임라인 컨텍스트
|
|
143
|
+
layer2: (ids: string[]) => {
|
|
144
|
+
id: string;
|
|
145
|
+
tool_name: string;
|
|
146
|
+
timestamp: Date;
|
|
147
|
+
}[];
|
|
148
|
+
|
|
149
|
+
// Layer 3: 전체 내용
|
|
150
|
+
layer3: (ids: string[]) => Observation[];
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
## 4. 기존 코드와의 관계
|
|
155
|
+
|
|
156
|
+
### 4.1 event-store.ts
|
|
157
|
+
|
|
158
|
+
현재 EventStore 스키마:
|
|
159
|
+
|
|
160
|
+
```sql
|
|
161
|
+
CREATE TABLE events (
|
|
162
|
+
event_id VARCHAR PRIMARY KEY,
|
|
163
|
+
event_type VARCHAR NOT NULL,
|
|
164
|
+
session_id VARCHAR NOT NULL,
|
|
165
|
+
timestamp TIMESTAMP NOT NULL,
|
|
166
|
+
payload_json JSON NOT NULL
|
|
167
|
+
);
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
**확장 필요 없음** - `event_type = 'tool_observation'`으로 저장 가능
|
|
171
|
+
|
|
172
|
+
### 4.2 types.ts
|
|
173
|
+
|
|
174
|
+
추가해야 할 타입:
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
// 기존 EventType
|
|
178
|
+
export const EventTypeSchema = z.enum([
|
|
179
|
+
'user_prompt',
|
|
180
|
+
'assistant_response',
|
|
181
|
+
'session_start',
|
|
182
|
+
'session_end',
|
|
183
|
+
'tool_observation' // 추가
|
|
184
|
+
]);
|
|
185
|
+
|
|
186
|
+
// ToolObservationPayload 추가
|
|
187
|
+
export const ToolObservationPayloadSchema = z.object({
|
|
188
|
+
toolName: z.string(),
|
|
189
|
+
toolInput: z.record(z.unknown()),
|
|
190
|
+
toolOutput: z.string(),
|
|
191
|
+
// ...
|
|
192
|
+
});
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### 4.3 embedder.ts
|
|
196
|
+
|
|
197
|
+
현재 임베딩 대상:
|
|
198
|
+
|
|
199
|
+
```typescript
|
|
200
|
+
function getEmbeddingContent(event: Event): string {
|
|
201
|
+
switch (event.eventType) {
|
|
202
|
+
case 'user_prompt':
|
|
203
|
+
return event.payload.content;
|
|
204
|
+
case 'assistant_response':
|
|
205
|
+
return event.payload.content;
|
|
206
|
+
// tool_observation 추가 필요
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### 4.4 retriever.ts
|
|
212
|
+
|
|
213
|
+
검색 인터페이스 확장:
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
// 기존
|
|
217
|
+
async search(query: string): Promise<SearchResult[]>;
|
|
218
|
+
|
|
219
|
+
// 추가
|
|
220
|
+
async searchToolHistory(query: string): Promise<ToolObservation[]>;
|
|
221
|
+
async getToolsForFile(filePath: string): Promise<ToolObservation[]>;
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
## 5. 설계 결정 사항
|
|
225
|
+
|
|
226
|
+
### 5.1 왜 별도 이벤트 타입인가?
|
|
227
|
+
|
|
228
|
+
**대안 1: assistant_response에 포함**
|
|
229
|
+
```json
|
|
230
|
+
{
|
|
231
|
+
"eventType": "assistant_response",
|
|
232
|
+
"payload": {
|
|
233
|
+
"content": "...",
|
|
234
|
+
"tools_used": [{ "name": "Read", "output": "..." }]
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
- 단점: 도구별 검색 어려움, 출력이 커짐
|
|
239
|
+
|
|
240
|
+
**대안 2: 별도 테이블**
|
|
241
|
+
```sql
|
|
242
|
+
CREATE TABLE tool_observations (...);
|
|
243
|
+
```
|
|
244
|
+
- 단점: 스키마 변경 필요, 일관성 관리 복잡
|
|
245
|
+
|
|
246
|
+
**선택: 기존 events 테이블에 새 event_type**
|
|
247
|
+
- 장점: 스키마 변경 없음
|
|
248
|
+
- 장점: 기존 쿼리 패턴 재사용
|
|
249
|
+
- 장점: 벡터 임베딩 파이프라인 공유
|
|
250
|
+
|
|
251
|
+
### 5.2 출력 압축 전략
|
|
252
|
+
|
|
253
|
+
**문제**: 도구 출력이 매우 클 수 있음 (대용량 파일 읽기)
|
|
254
|
+
|
|
255
|
+
**해결**:
|
|
256
|
+
1. 크기 제한 (10KB)
|
|
257
|
+
2. 줄 수 제한 (100줄)
|
|
258
|
+
3. Head + Tail 방식 (앞 50줄 + 뒤 50줄)
|
|
259
|
+
4. 도구별 특화 압축 (Grep은 파일 목록만)
|
|
260
|
+
|
|
261
|
+
### 5.3 민감 정보 처리
|
|
262
|
+
|
|
263
|
+
**현재 privacy.excludePatterns 활용**:
|
|
264
|
+
```typescript
|
|
265
|
+
const patterns = config.privacy.excludePatterns;
|
|
266
|
+
// ['password', 'secret', 'api_key']
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
**추가 필요**:
|
|
270
|
+
- 정규식 기반 마스킹
|
|
271
|
+
- 환경 변수 값 감지
|
|
272
|
+
- Bearer 토큰 패턴
|
|
273
|
+
|
|
274
|
+
### 5.4 임베딩 vs 저장만
|
|
275
|
+
|
|
276
|
+
**질문**: 모든 tool_observation을 임베딩해야 하나?
|
|
277
|
+
|
|
278
|
+
**결론**: 선택적 임베딩
|
|
279
|
+
- Read/Write: 파일 경로 + 첫 줄만 임베딩
|
|
280
|
+
- Bash: 명령어만 임베딩
|
|
281
|
+
- 전체 출력은 검색되지 않음 (너무 노이즈가 많음)
|
|
282
|
+
|
|
283
|
+
## 6. 성능 고려사항
|
|
284
|
+
|
|
285
|
+
### 6.1 훅 실행 시간
|
|
286
|
+
|
|
287
|
+
**제약**: 훅은 빨리 반환되어야 함 (Claude 응답 지연 방지)
|
|
288
|
+
|
|
289
|
+
**해결**:
|
|
290
|
+
```typescript
|
|
291
|
+
// 비동기 저장 (fire-and-forget)
|
|
292
|
+
async function handlePostToolUse(input: PostToolUseInput): Promise<void> {
|
|
293
|
+
// 바로 반환, 저장은 백그라운드
|
|
294
|
+
setImmediate(async () => {
|
|
295
|
+
await storeObservation(input);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
### 6.2 저장 빈도
|
|
301
|
+
|
|
302
|
+
**문제**: 대화 중 수십 개의 도구가 실행될 수 있음
|
|
303
|
+
|
|
304
|
+
**해결**:
|
|
305
|
+
1. 배치 저장 (10개씩 모아서)
|
|
306
|
+
2. 중복 제거 (같은 파일 연속 Read)
|
|
307
|
+
3. 샘플링 (Glob 결과는 요약만)
|
|
308
|
+
|
|
309
|
+
### 6.3 벡터 저장소 크기
|
|
310
|
+
|
|
311
|
+
**문제**: tool_observation이 많아지면 벡터 DB 비대
|
|
312
|
+
|
|
313
|
+
**해결**:
|
|
314
|
+
1. TTL 적용 (30일 후 삭제)
|
|
315
|
+
2. 자주 사용되는 것만 임베딩 유지
|
|
316
|
+
3. graduation 적용 (L0에서 L4로 승급하는 것만 유지)
|
|
317
|
+
|
|
318
|
+
## 7. 참고 자료
|
|
319
|
+
|
|
320
|
+
- **claude-mem README**: 5 lifecycle hooks, observation storage
|
|
321
|
+
- **Claude Code Hooks**: 공식 훅 이벤트 문서
|
|
322
|
+
- **AXIOMMIND**: Principle 2 (Append-Only)
|
|
323
|
+
- **기존 specs**: entity-edge-model, vector-outbox-v2
|
|
324
|
+
|
|
325
|
+
## 2026-02-25T12:31:26.359Z | cc90cab1-b7d8-4780-9709-42f1f868ed94
|
|
326
|
+
- type: session_summary
|
|
327
|
+
- session: import:organized
|
|
328
|
+
# PostToolUse Hook Implementation Plan
|
|
329
|
+
|
|
330
|
+
> **Version**: 1.0.0
|
|
331
|
+
> **Status**: Draft
|
|
332
|
+
> **Created**: 2026-02-01
|
|
333
|
+
|
|
334
|
+
## Phase 1: 타입 정의 (P0)
|
|
335
|
+
|
|
336
|
+
### 1.1 이벤트 스키마 추가
|
|
337
|
+
|
|
338
|
+
**파일**: `src/core/types.ts` 수정
|
|
339
|
+
|
|
340
|
+
```typescript
|
|
341
|
+
// 추가할 타입들
|
|
342
|
+
export const ToolObservationPayloadSchema = z.object({
|
|
343
|
+
toolName: z.string(),
|
|
344
|
+
toolInput: z.record(z.unknown()),
|
|
345
|
+
toolOutput: z.string(),
|
|
346
|
+
durationMs: z.number(),
|
|
347
|
+
success: z.boolean(),
|
|
348
|
+
errorMessage: z.string().optional(),
|
|
349
|
+
promptIndex: z.number(),
|
|
350
|
+
toolIndex: z.number(),
|
|
351
|
+
metadata: z.object({
|
|
352
|
+
filePath: z.string().optional(),
|
|
353
|
+
fileType: z.string().optional(),
|
|
354
|
+
lineCount: z.number().optional(),
|
|
355
|
+
command: z.string().optional(),
|
|
356
|
+
exitCode: z.number().optional(),
|
|
357
|
+
pattern: z.string().optional(),
|
|
358
|
+
matchCount: z.number().optional(),
|
|
359
|
+
url: z.string().optional(),
|
|
360
|
+
statusCode: z.number().optional()
|
|
361
|
+
}).optional()
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
export type ToolObservationPayload = z.infer<typeof ToolObservationPayloadSchema>;
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
**작업 항목**:
|
|
368
|
+
- [ ] ToolObservationPayloadSchema 추가
|
|
369
|
+
- [ ] EventType에 'tool_observation' 추가
|
|
370
|
+
- [ ] EventPayload union에 ToolObservationPayload 추가
|
|
371
|
+
|
|
372
|
+
### 1.2 설정 스키마 확장
|
|
373
|
+
|
|
374
|
+
**파일**: `src/core/types.ts` 수정
|
|
375
|
+
|
|
376
|
+
```typescript
|
|
377
|
+
// 설정에 tool observation 옵션 추가
|
|
378
|
+
export const ConfigSchema = z.object({
|
|
379
|
+
// ... 기존 설정
|
|
380
|
+
toolObservation: z.object({
|
|
381
|
+
enabled: z.boolean().default(true),
|
|
382
|
+
excludedTools: z.array(z.string()).default(['TodoWrite', 'TodoRead']),
|
|
383
|
+
maxOutputLength: z.number().default(10000),
|
|
384
|
+
maxOutputLines: z.number().default(100),
|
|
385
|
+
storeOnlyOnSuccess: z.boolean().default(false)
|
|
386
|
+
}).optional()
|
|
387
|
+
});
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
**작업 항목**:
|
|
391
|
+
- [ ] toolObservation 설정 스키마 추가
|
|
392
|
+
- [ ] 기본값 정의
|
|
393
|
+
|
|
394
|
+
## Phase 2: 훅 구현 (P0)
|
|
395
|
+
|
|
396
|
+
### 2.1 PostToolUse 훅 파일 생성
|
|
397
|
+
|
|
398
|
+
**파일**: `src/hooks/post-tool-use.ts` (신규)
|
|
399
|
+
|
|
400
|
+
```typescript
|
|
401
|
+
import { MemoryService } from '../services/memory-service';
|
|
402
|
+
import { maskSensitiveData, truncateOutput } from '../core/privacy';
|
|
403
|
+
|
|
404
|
+
interface PostToolUseInput {
|
|
405
|
+
tool_name: string;
|
|
406
|
+
tool_input: Record<string, unknown>;
|
|
407
|
+
tool_output: string;
|
|
408
|
+
tool_error?: string;
|
|
409
|
+
session_id: string;
|
|
410
|
+
started_at: string;
|
|
411
|
+
ended_at: string;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export async function handlePostToolUse(input: PostToolUseInput): Promise<void> {
|
|
415
|
+
const memoryService = await MemoryService.getInstance();
|
|
416
|
+
const config = await memoryService.getConfig();
|
|
417
|
+
|
|
418
|
+
// 1. 제외 도구 체크
|
|
419
|
+
if (config.toolObservation?.excludedTools?.includes(input.tool_name)) {
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// 2. 실패 시 저장 스킵 옵션
|
|
424
|
+
const success = !input.tool_error;
|
|
425
|
+
if (!success && config.toolObservation?.storeOnlyOnSuccess) {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// 3. 민감 정보 마스킹
|
|
430
|
+
const maskedOutput = maskSensitiveData(input.tool_output);
|
|
431
|
+
const maskedInput = maskSensitiveInput(input.tool_input);
|
|
432
|
+
|
|
433
|
+
// 4. 출력 압축
|
|
434
|
+
const truncatedOutput = truncateOutput(maskedOutput, {
|
|
435
|
+
maxLength: config.toolObservation?.maxOutputLength,
|
|
436
|
+
maxLines: config.toolObservation?.maxOutputLines
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
// 5. 메타데이터 추출
|
|
440
|
+
const metadata = extractMetadata(input.tool_name, maskedInput, success);
|
|
441
|
+
|
|
442
|
+
// 6. 이벤트 저장
|
|
443
|
+
await memoryService.storeToolObservation({
|
|
444
|
+
toolName: input.tool_name,
|
|
445
|
+
toolInput: maskedInput,
|
|
446
|
+
toolOutput: truncatedOutput,
|
|
447
|
+
durationMs: calculateDuration(input.started_at, input.ended_at),
|
|
448
|
+
success,
|
|
449
|
+
errorMessage: input.tool_error,
|
|
450
|
+
metadata
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
**작업 항목**:
|
|
456
|
+
- [ ] handlePostToolUse 함수 구현
|
|
457
|
+
- [ ] 제외 도구 체크 로직
|
|
458
|
+
- [ ] 성공/실패 필터링 로직
|
|
459
|
+
- [ ] 메타데이터 추출 함수
|
|
460
|
+
|
|
461
|
+
### 2.2 프라이버시 유틸리티
|
|
462
|
+
|
|
463
|
+
**파일**: `src/core/privacy.ts` (신규 또는 확장)
|
|
464
|
+
|
|
465
|
+
```typescript
|
|
466
|
+
const SENSITIVE_PATTERNS = [
|
|
467
|
+
/password\s*[:=]\s*['"]?[^\s'"]+/gi,
|
|
468
|
+
/api[_-]?key\s*[:=]\s*['"]?[^\s'"]+/gi,
|
|
469
|
+
/secret\s*[:=]\s*['"]?[^\s'"]+/gi,
|
|
470
|
+
/token\s*[:=]\s*['"]?[^\s'"]+/gi,
|
|
471
|
+
/bearer\s+[a-zA-Z0-9\-_.]+/gi,
|
|
472
|
+
];
|
|
473
|
+
|
|
474
|
+
export function maskSensitiveData(content: string): string {
|
|
475
|
+
let masked = content;
|
|
476
|
+
for (const pattern of SENSITIVE_PATTERNS) {
|
|
477
|
+
masked = masked.replace(pattern, '[REDACTED]');
|
|
478
|
+
}
|
|
479
|
+
return masked;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
export function truncateOutput(
|
|
483
|
+
output: string,
|
|
484
|
+
options: { maxLength?: number; maxLines?: number }
|
|
485
|
+
): string {
|
|
486
|
+
const { maxLength = 10000, maxLines = 100 } = options;
|
|
487
|
+
// ... 구현
|
|
488
|
+
}
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
**작업 항목**:
|
|
492
|
+
- [ ] maskSensitiveData 함수
|
|
493
|
+
- [ ] maskSensitiveInput 함수 (JSON 재귀 마스킹)
|
|
494
|
+
- [ ] truncateOutput 함수
|
|
495
|
+
- [ ] 도구별 압축 전략 구현
|
|
496
|
+
|
|
497
|
+
### 2.3 메타데이터 추출기
|
|
498
|
+
|
|
499
|
+
**파일**: `src/core/metadata-extractor.ts` (신규)
|
|
500
|
+
|
|
501
|
+
```typescript
|
|
502
|
+
export function extractMetadata(
|
|
503
|
+
toolName: string,
|
|
504
|
+
input: Record<string, unknown>,
|
|
505
|
+
success: boolean
|
|
506
|
+
): ToolMetadata {
|
|
507
|
+
switch (toolName) {
|
|
508
|
+
case 'Read':
|
|
509
|
+
case 'Write':
|
|
510
|
+
case 'Edit':
|
|
511
|
+
return {
|
|
512
|
+
filePath: input.file_path as string,
|
|
513
|
+
fileType: getFileType(input.file_path as string)
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
case 'Bash':
|
|
517
|
+
return {
|
|
518
|
+
command: input.command as string
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
case 'Grep':
|
|
522
|
+
return {
|
|
523
|
+
pattern: input.pattern as string
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
// ... 기타 도구
|
|
527
|
+
|
|
528
|
+
default:
|
|
529
|
+
return {};
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
**작업 항목**:
|
|
535
|
+
- [ ] extractMetadata 함수
|
|
536
|
+
- [ ] 도구별 메타데이터 추출 로직
|
|
537
|
+
- [ ] getFileType 유틸리티
|
|
538
|
+
|
|
539
|
+
## Phase 3: 서비스 연동 (P0)
|
|
540
|
+
|
|
541
|
+
### 3.1 MemoryService 확장
|
|
542
|
+
|
|
543
|
+
**파일**: `src/services/memory-service.ts` 수정
|
|
544
|
+
|
|
545
|
+
```typescript
|
|
546
|
+
export class MemoryService {
|
|
547
|
+
// 기존 메서드들...
|
|
548
|
+
|
|
549
|
+
async storeToolObservation(observation: ToolObservationPayload): Promise<string> {
|
|
550
|
+
const eventId = await this.eventStore.append({
|
|
551
|
+
eventType: 'tool_observation',
|
|
552
|
+
sessionId: this.currentSessionId,
|
|
553
|
+
payload: observation
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
// 임베딩을 위한 outbox 추가
|
|
557
|
+
await this.eventStore.addToOutbox(eventId);
|
|
558
|
+
|
|
559
|
+
return eventId;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
```
|
|
563
|
+
|
|
564
|
+
**작업 항목**:
|
|
565
|
+
- [ ] storeToolObservation 메서드 추가
|
|
566
|
+
- [ ] Outbox 연동
|
|
567
|
+
|
|
568
|
+
### 3.2 임베딩 콘텐츠 생성
|
|
569
|
+
|
|
570
|
+
**파일**: `src/core/embedder.ts` 수정
|
|
571
|
+
|
|
572
|
+
```typescript
|
|
573
|
+
export function createEmbeddingContent(event: Event): string {
|
|
574
|
+
if (event.eventType === 'tool_observation') {
|
|
575
|
+
return createToolObservationEmbedding(event.payload);
|
|
576
|
+
}
|
|
577
|
+
// 기존 로직...
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function createToolObservationEmbedding(payload: ToolObservationPayload): string {
|
|
581
|
+
const parts: string[] = [];
|
|
582
|
+
|
|
583
|
+
parts.push(`Tool: ${payload.toolName}`);
|
|
584
|
+
|
|
585
|
+
if (payload.metadata?.filePath) {
|
|
586
|
+
parts.push(`File: ${payload.metadata.filePath}`);
|
|
587
|
+
}
|
|
588
|
+
if (payload.metadata?.command) {
|
|
589
|
+
parts.push(`Command: ${payload.metadata.command}`);
|
|
590
|
+
}
|
|
591
|
+
if (payload.metadata?.pattern) {
|
|
592
|
+
parts.push(`Pattern: ${payload.metadata.pattern}`);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
parts.push(`Result: ${payload.success ? 'Success' : 'Failed'}`);
|
|
596
|
+
|
|
597
|
+
return parts.join('\n');
|
|
598
|
+
}
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
**작업 항목**:
|
|
602
|
+
- [ ] tool_observation 이벤트용 임베딩 콘텐츠 생성
|
|
603
|
+
- [ ] VectorWorker에서 tool_observation 처리
|
|
604
|
+
|
|
605
|
+
## Phase 4: 훅 등록 (P0)
|
|
606
|
+
|
|
607
|
+
### 4.1 hooks.json 수정
|
|
608
|
+
|
|
609
|
+
**파일**: `.claude-plugin/hooks.json` 수정
|
|
610
|
+
|
|
611
|
+
```json
|
|
612
|
+
{
|
|
613
|
+
"hooks": [
|
|
614
|
+
{
|
|
615
|
+
"event": "session-start",
|
|
616
|
+
"script": "node dist/hooks/session-start.js"
|
|
617
|
+
},
|
|
618
|
+
{
|
|
619
|
+
"event": "user-prompt-submit",
|
|
620
|
+
"script": "node dist/hooks/user-prompt-submit.js"
|
|
621
|
+
},
|
|
622
|
+
{
|
|
623
|
+
"event": "post-tool-use",
|
|
624
|
+
"script": "node dist/hooks/post-tool-use.js"
|
|
625
|
+
},
|
|
626
|
+
{
|
|
627
|
+
"event": "stop",
|
|
628
|
+
"script": "node dist/hooks/stop.js"
|
|
629
|
+
},
|
|
630
|
+
{
|
|
631
|
+
"event": "session-end",
|
|
632
|
+
"script": "node dist/hooks/session-end.js"
|
|
633
|
+
}
|
|
634
|
+
]
|
|
635
|
+
}
|
|
636
|
+
```
|
|
637
|
+
|
|
638
|
+
**작업 항목**:
|
|
639
|
+
- [ ] post-tool-use 훅 등록
|
|
640
|
+
- [ ] 스크립트 경로 확인
|
|
641
|
+
|
|
642
|
+
### 4.2 빌드 스크립트 수정
|
|
643
|
+
|
|
644
|
+
**파일**: `package.json` 또는 빌드 설정
|
|
645
|
+
|
|
646
|
+
```json
|
|
647
|
+
{
|
|
648
|
+
"scripts": {
|
|
649
|
+
"build:hooks": "esbuild src/hooks/*.ts --bundle --platform=node --outdir=dist/hooks"
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
```
|
|
653
|
+
|
|
654
|
+
**작업 항목**:
|
|
655
|
+
- [ ] post-tool-use.ts 빌드 포함
|
|
656
|
+
- [ ] 번들 테스트
|
|
657
|
+
|
|
658
|
+
## Phase 5: 검색 연동 (P1)
|
|
659
|
+
|
|
660
|
+
### 5.1 Retriever 확장
|
|
661
|
+
|
|
662
|
+
**파일**: `src/core/retriever.ts` 수정
|
|
663
|
+
|
|
664
|
+
```typescript
|
|
665
|
+
export class Retriever {
|
|
666
|
+
async searchToolHistory(query: string, options?: SearchOptions): Promise<ToolObservation[]> {
|
|
667
|
+
const vectorResults = await this.vectorStore.search(query, {
|
|
668
|
+
filter: { eventType: 'tool_observation' },
|
|
669
|
+
topK: options?.topK ?? 5
|
|
670
|
+
});
|
|
671
|
+
|
|
672
|
+
return vectorResults.map(r => r.payload as ToolObservation);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
async getRecentToolsForFile(filePath: string): Promise<ToolObservation[]> {
|
|
676
|
+
// 특정 파일 관련 최근 도구 사용 조회
|
|
677
|
+
return this.eventStore.query({
|
|
678
|
+
eventType: 'tool_observation',
|
|
679
|
+
filter: { 'payload.metadata.filePath': filePath },
|
|
680
|
+
orderBy: 'timestamp DESC',
|
|
681
|
+
limit: 10
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
```
|
|
686
|
+
|
|
687
|
+
**작업 항목**:
|
|
688
|
+
- [ ] searchToolHistory 메서드
|
|
689
|
+
- [ ] getRecentToolsForFile 메서드
|
|
690
|
+
- [ ] 필터링 옵션
|
|
691
|
+
|
|
692
|
+
### 5.2 user-prompt-submit 확장
|
|
693
|
+
|
|
694
|
+
**파일**: `src/hooks/user-prompt-submit.ts` 수정
|
|
695
|
+
|
|
696
|
+
```typescript
|
|
697
|
+
async function handleUserPromptSubmit(input: UserPromptInput): Promise<HookOutput> {
|
|
698
|
+
// 기존 메모리 검색
|
|
699
|
+
const memories = await retriever.search(input.prompt);
|
|
700
|
+
|
|
701
|
+
// 관련 도구 사용 이력 추가
|
|
702
|
+
const toolHistory = await retriever.searchToolHistory(input.prompt, { topK: 3 });
|
|
703
|
+
|
|
704
|
+
// 컨텍스트 조합
|
|
705
|
+
return {
|
|
706
|
+
context: formatContext(memories, toolHistory)
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
```
|
|
710
|
+
|
|
711
|
+
**작업 항목**:
|
|
712
|
+
- [ ] 도구 이력을 컨텍스트에 포함
|
|
713
|
+
- [ ] 포맷팅 함수 확장
|
|
714
|
+
|
|
715
|
+
## 파일 목록
|
|
716
|
+
|
|
717
|
+
### 신규 파일
|
|
718
|
+
```
|
|
719
|
+
src/hooks/post-tool-use.ts # 메인 훅 구현
|
|
720
|
+
src/core/privacy.ts # 프라이버시 유틸리티
|
|
721
|
+
src/core/metadata-extractor.ts # 메타데이터 추출
|
|
722
|
+
```
|
|
723
|
+
|
|
724
|
+
### 수정 파일
|
|
725
|
+
```
|
|
726
|
+
src/core/types.ts # ToolObservationPayload 추가
|
|
727
|
+
src/services/memory-service.ts # storeToolObservation 메서드
|
|
728
|
+
src/core/embedder.ts # 임베딩 콘텐츠 생성
|
|
729
|
+
src/core/retriever.ts # 도구 이력 검색
|
|
730
|
+
src/hooks/user-prompt-submit.ts # 컨텍스트 포함
|
|
731
|
+
.claude-plugin/hooks.json # 훅 등록
|
|
732
|
+
```
|
|
733
|
+
|
|
734
|
+
## 테스트
|
|
735
|
+
|
|
736
|
+
### 필수 테스트 케이스
|
|
737
|
+
|
|
738
|
+
1. **훅 호출 테스트**
|
|
739
|
+
```typescript
|
|
740
|
+
test('should store tool observation after Read', async () => {
|
|
741
|
+
await handlePostToolUse({
|
|
742
|
+
tool_name: 'Read',
|
|
743
|
+
tool_input: { file_path: '/test.ts' },
|
|
744
|
+
tool_output: 'file content...',
|
|
745
|
+
session_id: 'session_1',
|
|
746
|
+
started_at: '2026-02-01T10:00:00Z',
|
|
747
|
+
ended_at: '2026-02-01T10:00:01Z'
|
|
748
|
+
});
|
|
749
|
+
|
|
750
|
+
const events = await eventStore.query({ eventType: 'tool_observation' });
|
|
751
|
+
expect(events.length).toBe(1);
|
|
752
|
+
});
|
|
753
|
+
```
|
|
754
|
+
|
|
755
|
+
2. **민감 정보 마스킹**
|
|
756
|
+
```typescript
|
|
757
|
+
test('should mask sensitive data', () => {
|
|
758
|
+
const input = 'password=secret123';
|
|
759
|
+
const masked = maskSensitiveData(input);
|
|
760
|
+
expect(masked).toBe('[REDACTED]');
|
|
761
|
+
});
|
|
762
|
+
```
|
|
763
|
+
|
|
764
|
+
3. **제외 도구 스킵**
|
|
765
|
+
```typescript
|
|
766
|
+
test('should skip excluded tools', async () => {
|
|
767
|
+
await handlePostToolUse({
|
|
768
|
+
tool_name: 'TodoWrite',
|
|
769
|
+
// ...
|
|
770
|
+
});
|
|
771
|
+
|
|
772
|
+
const events = await eventStore.query({ eventType: 'tool_observation' });
|
|
773
|
+
expect(events.length).toBe(0);
|
|
774
|
+
});
|
|
775
|
+
```
|
|
776
|
+
|
|
777
|
+
4. **출력 압축**
|
|
778
|
+
```typescript
|
|
779
|
+
test('should truncate long output', () => {
|
|
780
|
+
const longOutput = 'x'.repeat(20000);
|
|
781
|
+
const truncated = truncateOutput(longOutput, { maxLength: 10000 });
|
|
782
|
+
expect(truncated.length).toBeLessThanOrEqual(10100); // marker 포함
|
|
783
|
+
});
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
## 마일스톤
|
|
787
|
+
|
|
788
|
+
| 단계 | 완료 기준 |
|
|
789
|
+
|------|----------|
|
|
790
|
+
| M1 | 타입 정의 완료 |
|
|
791
|
+
| M2 | 훅 기본 구현 (저장만) |
|
|
792
|
+
| M3 | 프라이버시 필터링 |
|
|
793
|
+
| M4 | 출력 압축 |
|
|
794
|
+
| M5 | 임베딩 연동 |
|
|
795
|
+
| M6 | 검색 연동 |
|
|
796
|
+
| M7 | 테스트 통과 |
|
|
797
|
+
|
|
798
|
+
## 2026-02-25T12:31:26.368Z | 3d75016f-3046-478d-b3b2-24f067ad5f4d
|
|
799
|
+
- type: session_summary
|
|
800
|
+
- session: import:organized
|
|
801
|
+
# PostToolUse Hook Specification
|
|
802
|
+
|
|
803
|
+
> **Version**: 1.0.0
|
|
804
|
+
> **Status**: Draft
|
|
805
|
+
> **Created**: 2026-02-01
|
|
806
|
+
> **Reference**: claude-mem (thedotmack/claude-mem)
|
|
807
|
+
|
|
808
|
+
## 1. 개요
|
|
809
|
+
|
|
810
|
+
### 1.1 문제 정의
|
|
811
|
+
|
|
812
|
+
현재 시스템에서 도구 사용 결과가 메모리에 저장되지 않음:
|
|
813
|
+
|
|
814
|
+
1. **도구 실행 컨텍스트 손실**: 파일 읽기/쓰기 결과가 별도로 기록되지 않음
|
|
815
|
+
2. **작업 패턴 학습 불가**: 어떤 도구를 어떤 상황에서 사용했는지 추적 불가
|
|
816
|
+
3. **세션 재구성 어려움**: 과거 세션의 실제 작업 내용 파악 어려움
|
|
817
|
+
|
|
818
|
+
### 1.2 해결 방향
|
|
819
|
+
|
|
820
|
+
**PostToolUse 훅 추가**:
|
|
821
|
+
- 도구 실행 직후 호출되는 훅
|
|
822
|
+
- 도구 이름, 입력 파라미터, 출력 결과를 캡처
|
|
823
|
+
- EventStore에 `tool_observation` 이벤트로 저장
|
|
824
|
+
|
|
825
|
+
## 2. 핵심 개념
|
|
826
|
+
|
|
827
|
+
### 2.1 훅 라이프사이클
|
|
828
|
+
|
|
829
|
+
```
|
|
830
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
831
|
+
│ Claude Code Session │
|
|
832
|
+
├─────────────────────────────────────────────────────────────┤
|
|
833
|
+
│ │
|
|
834
|
+
│ session-start ────────────────────────────────────────────▶│
|
|
835
|
+
│ │ │
|
|
836
|
+
│ ▼ │
|
|
837
|
+
│ user-prompt-submit ◀──────────────────────────────────────┐│
|
|
838
|
+
│ │ ││
|
|
839
|
+
│ ▼ ││
|
|
840
|
+
│ [Agent Processing] ││
|
|
841
|
+
│ │ ││
|
|
842
|
+
│ ├── Tool Execution ─────┐ ││
|
|
843
|
+
│ │ ▼ ││
|
|
844
|
+
│ │ post-tool-use (NEW) ││
|
|
845
|
+
│ │ │ ││
|
|
846
|
+
│ │◀──────────────────────┘ ││
|
|
847
|
+
│ │ ││
|
|
848
|
+
│ ▼ ││
|
|
849
|
+
│ stop ───────────────────────────────────────────────────┘│
|
|
850
|
+
│ │ │
|
|
851
|
+
│ ▼ │
|
|
852
|
+
│ session-end │
|
|
853
|
+
│ │
|
|
854
|
+
└─────────────────────────────────────────────────────────────┘
|
|
855
|
+
```
|
|
856
|
+
|
|
857
|
+
### 2.2 캡처할 데이터
|
|
858
|
+
|
|
859
|
+
| 필드 | 타입 | 설명 |
|
|
860
|
+
|------|------|------|
|
|
861
|
+
| tool_name | string | 실행된 도구 이름 (Read, Write, Bash 등) |
|
|
862
|
+
| tool_input | object | 도구에 전달된 파라미터 |
|
|
863
|
+
| tool_output | string | 도구 실행 결과 (truncated) |
|
|
864
|
+
| duration_ms | number | 실행 시간 |
|
|
865
|
+
| success | boolean | 성공/실패 여부 |
|
|
866
|
+
| error_message | string? | 실패 시 에러 메시지 |
|
|
867
|
+
|
|
868
|
+
### 2.3 지원 도구 목록
|
|
869
|
+
|
|
870
|
+
```typescript
|
|
871
|
+
type SupportedTool =
|
|
872
|
+
| 'Read' // 파일 읽기
|
|
873
|
+
| 'Write' // 파일 쓰기
|
|
874
|
+
| 'Edit' // 파일 편집
|
|
875
|
+
| 'Bash' // 명령 실행
|
|
876
|
+
| 'Glob' // 파일 검색
|
|
877
|
+
| 'Grep' // 내용 검색
|
|
878
|
+
| 'WebFetch' // 웹 요청
|
|
879
|
+
| 'WebSearch' // 웹 검색
|
|
880
|
+
| 'Task' // 서브에이전트
|
|
881
|
+
| 'NotebookEdit'; // 노트북 편집
|
|
882
|
+
```
|
|
883
|
+
|
|
884
|
+
## 3. 이벤트 스키마
|
|
885
|
+
|
|
886
|
+
### 3.1 ToolObservation 이벤트
|
|
887
|
+
|
|
888
|
+
```typescript
|
|
889
|
+
const ToolObservationEventSchema = z.object({
|
|
890
|
+
eventId: z.string().uuid(),
|
|
891
|
+
eventType: z.literal('tool_observation'),
|
|
892
|
+
sessionId: z.string(),
|
|
893
|
+
timestamp: z.date(),
|
|
894
|
+
payload: z.object({
|
|
895
|
+
toolName: z.string(),
|
|
896
|
+
toolInput: z.record(z.unknown()),
|
|
897
|
+
toolOutput: z.string().max(10000), // 10KB 제한
|
|
898
|
+
durationMs: z.number(),
|
|
899
|
+
success: z.boolean(),
|
|
900
|
+
errorMessage: z.string().optional(),
|
|
901
|
+
|
|
902
|
+
// 컨텍스트
|
|
903
|
+
promptIndex: z.number(), // 몇 번째 프롬프트에서 실행됐는지
|
|
904
|
+
toolIndex: z.number(), // 해당 프롬프트 내 몇 번째 도구인지
|
|
905
|
+
|
|
906
|
+
// 메타데이터 (도구별 특화)
|
|
907
|
+
metadata: z.object({
|
|
908
|
+
// Read/Write/Edit
|
|
909
|
+
filePath: z.string().optional(),
|
|
910
|
+
fileType: z.string().optional(),
|
|
911
|
+
lineCount: z.number().optional(),
|
|
912
|
+
|
|
913
|
+
// Bash
|
|
914
|
+
command: z.string().optional(),
|
|
915
|
+
exitCode: z.number().optional(),
|
|
916
|
+
|
|
917
|
+
// Grep/Glob
|
|
918
|
+
pattern: z.string().optional(),
|
|
919
|
+
matchCount: z.number().optional(),
|
|
920
|
+
|
|
921
|
+
// WebFetch
|
|
922
|
+
url: z.string().optional(),
|
|
923
|
+
statusCode: z.number().optional()
|
|
924
|
+
}).optional()
|
|
925
|
+
})
|
|
926
|
+
});
|
|
927
|
+
```
|
|
928
|
+
|
|
929
|
+
### 3.2 도구별 메타데이터 예시
|
|
930
|
+
|
|
931
|
+
```typescript
|
|
932
|
+
// Read 도구
|
|
933
|
+
{
|
|
934
|
+
toolName: 'Read',
|
|
935
|
+
toolInput: { file_path: '/src/core/types.ts' },
|
|
936
|
+
toolOutput: '// Type definitions...', // truncated
|
|
937
|
+
metadata: {
|
|
938
|
+
filePath: '/src/core/types.ts',
|
|
939
|
+
fileType: 'typescript',
|
|
940
|
+
lineCount: 547
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
// Bash 도구
|
|
945
|
+
{
|
|
946
|
+
toolName: 'Bash',
|
|
947
|
+
toolInput: { command: 'npm test' },
|
|
948
|
+
toolOutput: 'All 42 tests passed',
|
|
949
|
+
metadata: {
|
|
950
|
+
command: 'npm test',
|
|
951
|
+
exitCode: 0
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
// Grep 도구
|
|
956
|
+
{
|
|
957
|
+
toolName: 'Grep',
|
|
958
|
+
toolInput: { pattern: 'async function', path: '/src' },
|
|
959
|
+
toolOutput: 'Found 15 matches in 8 files',
|
|
960
|
+
metadata: {
|
|
961
|
+
pattern: 'async function',
|
|
962
|
+
matchCount: 15
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
```
|
|
966
|
+
|
|
967
|
+
## 4. 훅 인터페이스
|
|
968
|
+
|
|
969
|
+
### 4.1 훅 입력
|
|
970
|
+
|
|
971
|
+
```typescript
|
|
972
|
+
interface PostToolUseHookInput {
|
|
973
|
+
// Claude Code에서 전달하는 데이터
|
|
974
|
+
tool_name: string;
|
|
975
|
+
tool_input: Record<string, unknown>;
|
|
976
|
+
tool_output: string;
|
|
977
|
+
tool_error?: string;
|
|
978
|
+
|
|
979
|
+
// 세션 컨텍스트
|
|
980
|
+
session_id: string;
|
|
981
|
+
conversation_id: string;
|
|
982
|
+
|
|
983
|
+
// 타이밍 정보
|
|
984
|
+
started_at: string;
|
|
985
|
+
ended_at: string;
|
|
986
|
+
}
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
### 4.2 훅 출력
|
|
990
|
+
|
|
991
|
+
```typescript
|
|
992
|
+
interface PostToolUseHookOutput {
|
|
993
|
+
// 저장 결과
|
|
994
|
+
stored: boolean;
|
|
995
|
+
event_id?: string;
|
|
996
|
+
|
|
997
|
+
// 선택적 피드백 (Claude에게 전달)
|
|
998
|
+
feedback?: string;
|
|
999
|
+
|
|
1000
|
+
// 에러
|
|
1001
|
+
error?: string;
|
|
1002
|
+
}
|
|
1003
|
+
```
|
|
1004
|
+
|
|
1005
|
+
## 5. 프라이버시 필터링
|
|
1006
|
+
|
|
1007
|
+
### 5.1 민감 정보 마스킹
|
|
1008
|
+
|
|
1009
|
+
```typescript
|
|
1010
|
+
const SENSITIVE_PATTERNS = [
|
|
1011
|
+
/password\s*[:=]\s*['"]?[^\s'"]+/gi,
|
|
1012
|
+
/api[_-]?key\s*[:=]\s*['"]?[^\s'"]+/gi,
|
|
1013
|
+
/secret\s*[:=]\s*['"]?[^\s'"]+/gi,
|
|
1014
|
+
/token\s*[:=]\s*['"]?[^\s'"]+/gi,
|
|
1015
|
+
/bearer\s+[a-zA-Z0-9\-_.]+/gi,
|
|
1016
|
+
/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi
|
|
1017
|
+
];
|
|
1018
|
+
|
|
1019
|
+
function maskSensitiveData(content: string): string {
|
|
1020
|
+
let masked = content;
|
|
1021
|
+
for (const pattern of SENSITIVE_PATTERNS) {
|
|
1022
|
+
masked = masked.replace(pattern, '[REDACTED]');
|
|
1023
|
+
}
|
|
1024
|
+
return masked;
|
|
1025
|
+
}
|
|
1026
|
+
```
|
|
1027
|
+
|
|
1028
|
+
### 5.2 제외할 도구
|
|
1029
|
+
|
|
1030
|
+
```typescript
|
|
1031
|
+
const EXCLUDED_TOOLS = [
|
|
1032
|
+
'TodoWrite', // 내부 상태 관리
|
|
1033
|
+
'TodoRead',
|
|
1034
|
+
];
|
|
1035
|
+
|
|
1036
|
+
function shouldStore(toolName: string): boolean {
|
|
1037
|
+
return !EXCLUDED_TOOLS.includes(toolName);
|
|
1038
|
+
}
|
|
1039
|
+
```
|
|
1040
|
+
|
|
1041
|
+
## 6. 출력 압축
|
|
1042
|
+
|
|
1043
|
+
### 6.1 크기 제한
|
|
1044
|
+
|
|
1045
|
+
```typescript
|
|
1046
|
+
const OUTPUT_LIMITS = {
|
|
1047
|
+
maxLength: 10000, // 10KB
|
|
1048
|
+
maxLines: 100, // 100줄
|
|
1049
|
+
truncationMarker: '\n...[TRUNCATED]...\n'
|
|
1050
|
+
};
|
|
1051
|
+
|
|
1052
|
+
function truncateOutput(output: string): string {
|
|
1053
|
+
const lines = output.split('\n');
|
|
1054
|
+
|
|
1055
|
+
if (lines.length > OUTPUT_LIMITS.maxLines) {
|
|
1056
|
+
const head = lines.slice(0, 50);
|
|
1057
|
+
const tail = lines.slice(-50);
|
|
1058
|
+
return head.join('\n') + OUTPUT_LIMITS.truncationMarker + tail.join('\n');
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
if (output.length > OUTPUT_LIMITS.maxLength) {
|
|
1062
|
+
return output.slice(0, OUTPUT_LIMITS.maxLength / 2) +
|
|
1063
|
+
OUTPUT_LIMITS.truncationMarker +
|
|
1064
|
+
output.slice(-OUTPUT_LIMITS.maxLength / 2);
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
return output;
|
|
1068
|
+
}
|
|
1069
|
+
```
|
|
1070
|
+
|
|
1071
|
+
### 6.2 도구별 압축 전략
|
|
1072
|
+
|
|
1073
|
+
| 도구 | 압축 전략 |
|
|
1074
|
+
|------|----------|
|
|
1075
|
+
| Read | 첫 50줄 + 마지막 50줄, 파일 타입 보존 |
|
|
1076
|
+
| Bash | 전체 출력, exitCode 보존 |
|
|
1077
|
+
| Grep | 매칭된 파일 목록만, 전체 내용 제외 |
|
|
1078
|
+
| Glob | 파일 경로 목록만 |
|
|
1079
|
+
| WebFetch | 첫 500자 요약 |
|
|
1080
|
+
|
|
1081
|
+
## 7. 벡터 임베딩 연동
|
|
1082
|
+
|
|
1083
|
+
### 7.1 임베딩 대상
|
|
1084
|
+
|
|
1085
|
+
```typescript
|
|
1086
|
+
function createEmbeddingContent(observation: ToolObservation): string {
|
|
1087
|
+
const parts: string[] = [];
|
|
1088
|
+
|
|
1089
|
+
// 도구 이름
|
|
1090
|
+
parts.push(`Tool: ${observation.toolName}`);
|
|
1091
|
+
|
|
1092
|
+
// 주요 입력
|
|
1093
|
+
if (observation.metadata?.filePath) {
|
|
1094
|
+
parts.push(`File: ${observation.metadata.filePath}`);
|
|
1095
|
+
}
|
|
1096
|
+
if (observation.metadata?.command) {
|
|
1097
|
+
parts.push(`Command: ${observation.metadata.command}`);
|
|
1098
|
+
}
|
|
1099
|
+
if (observation.metadata?.pattern) {
|
|
1100
|
+
parts.push(`Pattern: ${observation.metadata.pattern}`);
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
// 결과 요약
|
|
1104
|
+
parts.push(`Result: ${observation.success ? 'Success' : 'Failed'}`);
|
|
1105
|
+
|
|
1106
|
+
return parts.join('\n');
|
|
1107
|
+
}
|
|
1108
|
+
```
|
|
1109
|
+
|
|
1110
|
+
### 7.2 Outbox 연동
|
|
1111
|
+
|
|
1112
|
+
```typescript
|
|
1113
|
+
// tool_observation도 Outbox에 추가하여 벡터화
|
|
1114
|
+
await eventStore.append({
|
|
1115
|
+
eventType: 'tool_observation',
|
|
1116
|
+
payload: observation
|
|
1117
|
+
});
|
|
1118
|
+
|
|
1119
|
+
// VectorWorker가 배치 처리
|
|
1120
|
+
// embedding content: "Tool: Read\nFile: /src/types.ts\nResult: Success"
|
|
1121
|
+
```
|
|
1122
|
+
|
|
1123
|
+
## 8. 검색 활용
|
|
1124
|
+
|
|
1125
|
+
### 8.1 도구 사용 이력 검색
|
|
1126
|
+
|
|
1127
|
+
```sql
|
|
1128
|
+
-- 특정 파일 관련 도구 사용 이력
|
|
1129
|
+
SELECT * FROM events
|
|
1130
|
+
WHERE event_type = 'tool_observation'
|
|
1131
|
+
AND JSON_EXTRACT(payload_json, '$.metadata.filePath') LIKE '%types.ts%'
|
|
1132
|
+
ORDER BY timestamp DESC
|
|
1133
|
+
LIMIT 10;
|
|
1134
|
+
|
|
1135
|
+
-- 실패한 도구 실행 조회
|
|
1136
|
+
SELECT * FROM events
|
|
1137
|
+
WHERE event_type = 'tool_observation'
|
|
1138
|
+
AND JSON_EXTRACT(payload_json, '$.success') = false
|
|
1139
|
+
ORDER BY timestamp DESC;
|
|
1140
|
+
```
|
|
1141
|
+
|
|
1142
|
+
### 8.2 컨텍스트 주입 활용
|
|
1143
|
+
|
|
1144
|
+
```typescript
|
|
1145
|
+
// user-prompt-submit에서 활용
|
|
1146
|
+
async function getRelevantToolHistory(query: string): Promise<ToolObservation[]> {
|
|
1147
|
+
// 벡터 검색으로 관련 도구 사용 이력 조회
|
|
1148
|
+
const results = await vectorStore.search(query, {
|
|
1149
|
+
filter: { eventType: 'tool_observation' },
|
|
1150
|
+
topK: 5
|
|
1151
|
+
});
|
|
1152
|
+
|
|
1153
|
+
return results.map(r => r.payload as ToolObservation);
|
|
1154
|
+
}
|
|
1155
|
+
```
|
|
1156
|
+
|
|
1157
|
+
## 9. 성공 기준
|
|
1158
|
+
|
|
1159
|
+
- [ ] PostToolUse 훅이 모든 도구 실행 후 호출됨
|
|
1160
|
+
- [ ] tool_observation 이벤트가 EventStore에 저장됨
|
|
1161
|
+
- [ ] 민감 정보가 마스킹됨
|
|
1162
|
+
- [ ] 출력이 크기 제한 내로 압축됨
|
|
1163
|
+
- [ ] 벡터 임베딩이 생성됨
|
|
1164
|
+
- [ ] 도구 사용 이력 검색이 가능함
|