claude-brain 0.5.0 → 0.8.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/VERSION +1 -1
- package/assets/CLAUDE-unified.md +11 -0
- package/package.json +2 -1
- package/packs/backend/node.json +173 -0
- package/packs/core/javascript.json +176 -0
- package/packs/core/typescript.json +222 -0
- package/packs/frontend/react.json +254 -0
- package/packs/meta/testing.json +172 -0
- package/src/cli/bin.ts +14 -0
- package/src/cli/commands/chroma.ts +53 -17
- package/src/cli/commands/hooks.ts +214 -0
- package/src/cli/commands/pack.ts +197 -0
- package/src/cli/commands/serve.ts +34 -0
- package/src/config/defaults.ts +1 -1
- package/src/config/schema.ts +85 -2
- package/src/hooks/brain-hook.ts +110 -0
- package/src/hooks/capture.ts +161 -0
- package/src/hooks/deduplicator.ts +72 -0
- package/src/hooks/index.ts +19 -0
- package/src/hooks/installer.ts +181 -0
- package/src/hooks/passive-classifier.ts +366 -0
- package/src/hooks/queue.ts +122 -0
- package/src/hooks/session-tracker.ts +199 -0
- package/src/hooks/types.ts +47 -0
- package/src/memory/chroma/client.ts +1 -1
- package/src/memory/chroma/index.ts +1 -1
- package/src/memory/chroma/store.ts +29 -9
- package/src/memory/index.ts +1 -0
- package/src/memory/store.ts +1 -0
- package/src/packs/index.ts +9 -0
- package/src/packs/loader.ts +134 -0
- package/src/packs/manager.ts +204 -0
- package/src/packs/ranker.ts +78 -0
- package/src/packs/types.ts +81 -0
- package/src/routing/entity-extractor.ts +410 -0
- package/src/routing/intent-classifier.ts +229 -0
- package/src/routing/response-filter.ts +221 -0
- package/src/routing/router.ts +671 -0
- package/src/server/handlers/call-tool.ts +7 -0
- package/src/server/handlers/list-tools.ts +22 -5
- package/src/server/handlers/tools/brain.ts +85 -0
- package/src/server/handlers/tools/init-project.ts +47 -0
- package/src/server/handlers/tools/schemas.ts +12 -0
- package/src/server/http-api.ts +188 -0
- package/src/tools/registry.ts +9 -0
- package/src/tools/schemas.ts +33 -1
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 17: Passive Classifier
|
|
3
|
+
* Extracts knowledge from tool outputs using lightweight pattern matching.
|
|
4
|
+
* No embeddings needed — runs fast enough for hook context (<200ms).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { HookInput, CapturedKnowledge } from './types'
|
|
8
|
+
|
|
9
|
+
/** Phrases that indicate a decision was made */
|
|
10
|
+
const DECISION_PHRASES = [
|
|
11
|
+
'i recommend', 'you should use', 'the best approach', 'i suggest',
|
|
12
|
+
'better to use', 'prefer using', 'go with', 'choose', 'instead of',
|
|
13
|
+
'the right choice', 'decided to', "let's use", 'we will use',
|
|
14
|
+
'the solution is', 'implement using', 'going with', 'switching to',
|
|
15
|
+
'adopting', 'we chose', 'the plan is to'
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
/** Phrases indicating a correction or lesson */
|
|
19
|
+
const CORRECTION_PHRASES = [
|
|
20
|
+
'the bug was', 'the issue was', 'the problem was', 'mistake was',
|
|
21
|
+
'should have', 'should not have', "shouldn't have",
|
|
22
|
+
'lesson learned', "don't use", 'avoid using', 'never use',
|
|
23
|
+
'the fix is', 'the fix was', 'fixed by', 'solved by'
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
/** Package install patterns for bash commands */
|
|
27
|
+
const INSTALL_PATTERNS = [
|
|
28
|
+
/(?:npm|yarn|pnpm|bun)\s+(?:install|add|i)\s+(.+)/i,
|
|
29
|
+
/pip\s+install\s+(.+)/i,
|
|
30
|
+
/cargo\s+add\s+(.+)/i,
|
|
31
|
+
/go\s+get\s+(.+)/i,
|
|
32
|
+
/gem\s+install\s+(.+)/i,
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
/** Git operation patterns */
|
|
36
|
+
const GIT_PATTERNS = [
|
|
37
|
+
/git\s+commit\s+.*-m\s+["'](.+?)["']/i,
|
|
38
|
+
/git\s+merge\s+(\S+)/i,
|
|
39
|
+
/git\s+checkout\s+-b\s+(\S+)/i,
|
|
40
|
+
/git\s+branch\s+(\S+)/i,
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
/** Test/build command patterns */
|
|
44
|
+
const BUILD_PATTERNS = [
|
|
45
|
+
/(?:npm|yarn|pnpm|bun)\s+(?:run\s+)?(?:test|build|lint|typecheck|check)/i,
|
|
46
|
+
/(?:jest|vitest|pytest|cargo\s+test|go\s+test)/i,
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
/** Bash commands to skip (low signal) */
|
|
50
|
+
const SKIP_COMMANDS = new Set([
|
|
51
|
+
'cd', 'ls', 'cat', 'head', 'tail', 'pwd', 'echo', 'clear', 'which', 'whoami',
|
|
52
|
+
'date', 'env', 'printenv', 'export', 'source', 'alias', 'history',
|
|
53
|
+
])
|
|
54
|
+
|
|
55
|
+
/** File extension to technology mapping */
|
|
56
|
+
const EXT_TO_TECH: Record<string, string> = {
|
|
57
|
+
'.ts': 'typescript', '.tsx': 'typescript', '.js': 'javascript', '.jsx': 'javascript',
|
|
58
|
+
'.py': 'python', '.rs': 'rust', '.go': 'go', '.java': 'java',
|
|
59
|
+
'.rb': 'ruby', '.php': 'php', '.swift': 'swift', '.kt': 'kotlin',
|
|
60
|
+
'.vue': 'vue', '.svelte': 'svelte', '.astro': 'astro',
|
|
61
|
+
'.css': 'css', '.scss': 'sass', '.less': 'less',
|
|
62
|
+
'.sql': 'sql', '.graphql': 'graphql', '.gql': 'graphql',
|
|
63
|
+
'.yml': 'yaml', '.yaml': 'yaml', '.toml': 'toml',
|
|
64
|
+
'.dockerfile': 'docker', '.prisma': 'prisma',
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Path segments that indicate file role */
|
|
68
|
+
const PATH_ROLE_MAP: Record<string, string> = {
|
|
69
|
+
'test': 'testing', 'tests': 'testing', '__tests__': 'testing', 'spec': 'testing',
|
|
70
|
+
'src': 'source', 'lib': 'library', 'utils': 'utility', 'helpers': 'utility',
|
|
71
|
+
'components': 'component', 'pages': 'page', 'routes': 'routing',
|
|
72
|
+
'api': 'api', 'server': 'server', 'client': 'client',
|
|
73
|
+
'config': 'configuration', 'scripts': 'scripting',
|
|
74
|
+
'hooks': 'hooks', 'middleware': 'middleware', 'types': 'types',
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class PassiveClassifier {
|
|
78
|
+
/**
|
|
79
|
+
* Classify a hook event and extract knowledge if found.
|
|
80
|
+
* Returns null if no knowledge worth capturing.
|
|
81
|
+
*/
|
|
82
|
+
classify(input: HookInput): CapturedKnowledge | null {
|
|
83
|
+
const toolName = input.tool_name?.toLowerCase()
|
|
84
|
+
if (!toolName) return null
|
|
85
|
+
|
|
86
|
+
switch (toolName) {
|
|
87
|
+
case 'edit':
|
|
88
|
+
case 'write':
|
|
89
|
+
return this.classifyFileEdit(input)
|
|
90
|
+
case 'bash':
|
|
91
|
+
return this.classifyBashCommand(input)
|
|
92
|
+
default:
|
|
93
|
+
// Read, Glob, Grep — skip (read-only, low signal)
|
|
94
|
+
return null
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private classifyFileEdit(input: HookInput): CapturedKnowledge | null {
|
|
99
|
+
const toolInput = input.tool_input
|
|
100
|
+
if (!toolInput) return null
|
|
101
|
+
|
|
102
|
+
const filePath = (toolInput.file_path || toolInput.path || '') as string
|
|
103
|
+
if (!filePath) return null
|
|
104
|
+
|
|
105
|
+
const technologies = this.extractTechFromPath(filePath)
|
|
106
|
+
const role = this.extractRoleFromPath(filePath)
|
|
107
|
+
|
|
108
|
+
// Check if the edit content contains decision language
|
|
109
|
+
const content = toolInput.new_string || toolInput.content || ''
|
|
110
|
+
const responseText = this.extractResponseText(input.tool_response)
|
|
111
|
+
|
|
112
|
+
// Check for new file creation (Write tool)
|
|
113
|
+
if (input.tool_name?.toLowerCase() === 'write') {
|
|
114
|
+
return {
|
|
115
|
+
type: 'pattern',
|
|
116
|
+
confidence: 0.7,
|
|
117
|
+
content: `Created ${role ? role + ' ' : ''}file: ${this.shortenPath(filePath)}${technologies.length ? ` (${technologies.join(', ')})` : ''}`,
|
|
118
|
+
project: this.extractProjectFromCwd(input.cwd),
|
|
119
|
+
technologies,
|
|
120
|
+
metadata: { filePath, role, action: 'create' },
|
|
121
|
+
source: 'hook-passive',
|
|
122
|
+
timestamp: new Date().toISOString(),
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// For edits, only capture if they look significant
|
|
127
|
+
if (typeof content === 'string' && content.length > 50) {
|
|
128
|
+
const decisionInContent = this.detectDecisionLanguage(content)
|
|
129
|
+
if (decisionInContent) {
|
|
130
|
+
return {
|
|
131
|
+
type: 'decision',
|
|
132
|
+
confidence: 0.75,
|
|
133
|
+
content: decisionInContent,
|
|
134
|
+
project: this.extractProjectFromCwd(input.cwd),
|
|
135
|
+
technologies,
|
|
136
|
+
metadata: { filePath, role, action: 'edit' },
|
|
137
|
+
source: 'hook-passive',
|
|
138
|
+
timestamp: new Date().toISOString(),
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Check tool response for decision language
|
|
144
|
+
if (responseText) {
|
|
145
|
+
const decisionInResponse = this.detectDecisionLanguage(responseText)
|
|
146
|
+
if (decisionInResponse) {
|
|
147
|
+
return {
|
|
148
|
+
type: 'decision',
|
|
149
|
+
confidence: 0.7,
|
|
150
|
+
content: decisionInResponse,
|
|
151
|
+
project: this.extractProjectFromCwd(input.cwd),
|
|
152
|
+
technologies,
|
|
153
|
+
metadata: { filePath, role, action: 'edit' },
|
|
154
|
+
source: 'hook-passive',
|
|
155
|
+
timestamp: new Date().toISOString(),
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return null
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private classifyBashCommand(input: HookInput): CapturedKnowledge | null {
|
|
164
|
+
const command = (input.tool_input?.command || '') as string
|
|
165
|
+
if (!command || command.length < 3) return null
|
|
166
|
+
|
|
167
|
+
// Skip low-signal commands
|
|
168
|
+
const firstWord = command.trim().split(/\s+/)[0]?.toLowerCase()
|
|
169
|
+
if (firstWord && SKIP_COMMANDS.has(firstWord)) return null
|
|
170
|
+
|
|
171
|
+
// Package installs
|
|
172
|
+
for (const pattern of INSTALL_PATTERNS) {
|
|
173
|
+
const match = command.match(pattern)
|
|
174
|
+
if (match) {
|
|
175
|
+
const packages = match[1]?.trim()
|
|
176
|
+
if (packages) {
|
|
177
|
+
return {
|
|
178
|
+
type: 'decision',
|
|
179
|
+
confidence: 0.85,
|
|
180
|
+
content: `Installed package(s): ${packages}`,
|
|
181
|
+
project: this.extractProjectFromCwd(input.cwd),
|
|
182
|
+
technologies: this.extractTechFromPackages(packages),
|
|
183
|
+
metadata: { command, action: 'install' },
|
|
184
|
+
source: 'hook-passive',
|
|
185
|
+
timestamp: new Date().toISOString(),
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Git operations
|
|
192
|
+
for (const pattern of GIT_PATTERNS) {
|
|
193
|
+
const match = command.match(pattern)
|
|
194
|
+
if (match) {
|
|
195
|
+
return {
|
|
196
|
+
type: 'progress',
|
|
197
|
+
confidence: 0.8,
|
|
198
|
+
content: `Git: ${command.trim().slice(0, 200)}`,
|
|
199
|
+
project: this.extractProjectFromCwd(input.cwd),
|
|
200
|
+
technologies: ['git'],
|
|
201
|
+
metadata: { command, action: 'git' },
|
|
202
|
+
source: 'hook-passive',
|
|
203
|
+
timestamp: new Date().toISOString(),
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Test/build runs
|
|
209
|
+
for (const pattern of BUILD_PATTERNS) {
|
|
210
|
+
if (pattern.test(command)) {
|
|
211
|
+
const responseText = this.extractResponseText(input.tool_response)
|
|
212
|
+
const failed = responseText?.toLowerCase().includes('fail') ||
|
|
213
|
+
responseText?.toLowerCase().includes('error')
|
|
214
|
+
|
|
215
|
+
if (failed) {
|
|
216
|
+
return {
|
|
217
|
+
type: 'correction',
|
|
218
|
+
confidence: 0.75,
|
|
219
|
+
content: `Build/test failure: ${command.trim().slice(0, 100)}`,
|
|
220
|
+
project: this.extractProjectFromCwd(input.cwd),
|
|
221
|
+
technologies: [],
|
|
222
|
+
metadata: { command, action: 'build', failed: true },
|
|
223
|
+
source: 'hook-passive',
|
|
224
|
+
timestamp: new Date().toISOString(),
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
type: 'progress',
|
|
230
|
+
confidence: 0.7,
|
|
231
|
+
content: `Ran: ${command.trim().slice(0, 200)}`,
|
|
232
|
+
project: this.extractProjectFromCwd(input.cwd),
|
|
233
|
+
technologies: [],
|
|
234
|
+
metadata: { command, action: 'build', failed: false },
|
|
235
|
+
source: 'hook-passive',
|
|
236
|
+
timestamp: new Date().toISOString(),
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Check response text for decision/correction language
|
|
242
|
+
const responseText = this.extractResponseText(input.tool_response)
|
|
243
|
+
if (responseText) {
|
|
244
|
+
const correction = this.detectCorrectionLanguage(responseText)
|
|
245
|
+
if (correction) {
|
|
246
|
+
return {
|
|
247
|
+
type: 'correction',
|
|
248
|
+
confidence: 0.7,
|
|
249
|
+
content: correction,
|
|
250
|
+
project: this.extractProjectFromCwd(input.cwd),
|
|
251
|
+
technologies: [],
|
|
252
|
+
metadata: { command, action: 'bash' },
|
|
253
|
+
source: 'hook-passive',
|
|
254
|
+
timestamp: new Date().toISOString(),
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
return null
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Extract technology names from file path based on extension */
|
|
263
|
+
private extractTechFromPath(filePath: string): string[] {
|
|
264
|
+
const techs: string[] = []
|
|
265
|
+
const ext = filePath.match(/\.[a-z]+$/i)?.[0]?.toLowerCase()
|
|
266
|
+
if (ext && EXT_TO_TECH[ext]) {
|
|
267
|
+
techs.push(EXT_TO_TECH[ext])
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Check for Dockerfile without extension
|
|
271
|
+
const basename = filePath.split('/').pop()?.toLowerCase() || ''
|
|
272
|
+
if (basename === 'dockerfile' || basename.startsWith('dockerfile.')) {
|
|
273
|
+
techs.push('docker')
|
|
274
|
+
}
|
|
275
|
+
if (basename === 'docker-compose.yml' || basename === 'docker-compose.yaml') {
|
|
276
|
+
techs.push('docker')
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
return techs
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Extract file role from path segments */
|
|
283
|
+
private extractRoleFromPath(filePath: string): string | undefined {
|
|
284
|
+
const segments = filePath.toLowerCase().split('/')
|
|
285
|
+
for (const segment of segments) {
|
|
286
|
+
if (PATH_ROLE_MAP[segment]) return PATH_ROLE_MAP[segment]
|
|
287
|
+
}
|
|
288
|
+
return undefined
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Extract technology names from package install strings */
|
|
292
|
+
private extractTechFromPackages(packages: string): string[] {
|
|
293
|
+
return packages
|
|
294
|
+
.split(/\s+/)
|
|
295
|
+
.filter(p => !p.startsWith('-') && p.length > 1)
|
|
296
|
+
.map(p => p.replace(/@[^/]+$/, '')) // strip version
|
|
297
|
+
.slice(0, 10) // limit
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Detect decision language in text, return the relevant sentence */
|
|
301
|
+
private detectDecisionLanguage(text: string): string | null {
|
|
302
|
+
const lower = text.toLowerCase()
|
|
303
|
+
for (const phrase of DECISION_PHRASES) {
|
|
304
|
+
const idx = lower.indexOf(phrase)
|
|
305
|
+
if (idx !== -1) {
|
|
306
|
+
// Extract surrounding context (up to 300 chars)
|
|
307
|
+
const start = Math.max(0, text.lastIndexOf('\n', idx) + 1)
|
|
308
|
+
const end = Math.min(text.length, text.indexOf('\n', idx + phrase.length))
|
|
309
|
+
const sentence = text.slice(start, end === -1 ? Math.min(idx + 300, text.length) : end).trim()
|
|
310
|
+
if (sentence.length > 10) return sentence
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return null
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Detect correction/lesson language in text */
|
|
317
|
+
private detectCorrectionLanguage(text: string): string | null {
|
|
318
|
+
const lower = text.toLowerCase()
|
|
319
|
+
for (const phrase of CORRECTION_PHRASES) {
|
|
320
|
+
const idx = lower.indexOf(phrase)
|
|
321
|
+
if (idx !== -1) {
|
|
322
|
+
const start = Math.max(0, text.lastIndexOf('\n', idx) + 1)
|
|
323
|
+
const end = Math.min(text.length, text.indexOf('\n', idx + phrase.length))
|
|
324
|
+
const sentence = text.slice(start, end === -1 ? Math.min(idx + 300, text.length) : end).trim()
|
|
325
|
+
if (sentence.length > 10) return sentence
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return null
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Extract project name from cwd (last directory segment) */
|
|
332
|
+
private extractProjectFromCwd(cwd: string): string | undefined {
|
|
333
|
+
if (!cwd) return undefined
|
|
334
|
+
const parts = cwd.split('/').filter(Boolean)
|
|
335
|
+
const last = parts.pop()
|
|
336
|
+
if (last && last.length > 1 && last.length < 50) {
|
|
337
|
+
return last.replace(/\s+/g, '-').toLowerCase()
|
|
338
|
+
}
|
|
339
|
+
return undefined
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Shorten a file path for display */
|
|
343
|
+
private shortenPath(filePath: string): string {
|
|
344
|
+
const parts = filePath.split('/')
|
|
345
|
+
if (parts.length <= 3) return filePath
|
|
346
|
+
return `.../${parts.slice(-3).join('/')}`
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Extract text content from tool_response */
|
|
350
|
+
private extractResponseText(response: HookInput['tool_response']): string | null {
|
|
351
|
+
if (!response) return null
|
|
352
|
+
|
|
353
|
+
if (typeof response.content === 'string') {
|
|
354
|
+
return response.content.slice(0, 2000)
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
if (Array.isArray(response.content)) {
|
|
358
|
+
const texts = response.content
|
|
359
|
+
.filter(block => block.type === 'text' && block.text)
|
|
360
|
+
.map(block => block.text!)
|
|
361
|
+
return texts.join('\n').slice(0, 2000) || null
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return null
|
|
365
|
+
}
|
|
366
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 17: File Queue
|
|
3
|
+
* JSONL-based offline fallback when HTTP API server is unreachable.
|
|
4
|
+
* Queue file: ~/.claude-brain/data/hook-queue.jsonl
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { appendFileSync, readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs'
|
|
8
|
+
import { dirname, join } from 'node:path'
|
|
9
|
+
import { getHomePaths } from '@/config/home'
|
|
10
|
+
import type { CapturedKnowledge } from './types'
|
|
11
|
+
|
|
12
|
+
/** Get the queue file path */
|
|
13
|
+
export function getQueuePath(): string {
|
|
14
|
+
return join(getHomePaths().data, 'hook-queue.jsonl')
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Append captured knowledge to the offline queue.
|
|
19
|
+
* Creates the file and parent directory if needed.
|
|
20
|
+
*/
|
|
21
|
+
export function appendToQueue(items: CapturedKnowledge[]): void {
|
|
22
|
+
if (items.length === 0) return
|
|
23
|
+
|
|
24
|
+
const queuePath = getQueuePath()
|
|
25
|
+
const dir = dirname(queuePath)
|
|
26
|
+
|
|
27
|
+
if (!existsSync(dir)) {
|
|
28
|
+
mkdirSync(dir, { recursive: true })
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const lines = items.map(item => JSON.stringify(item)).join('\n') + '\n'
|
|
32
|
+
appendFileSync(queuePath, lines, 'utf-8')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Read all items from the queue file.
|
|
37
|
+
* Returns empty array if file doesn't exist.
|
|
38
|
+
*/
|
|
39
|
+
export function readQueue(): CapturedKnowledge[] {
|
|
40
|
+
const queuePath = getQueuePath()
|
|
41
|
+
|
|
42
|
+
if (!existsSync(queuePath)) return []
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
const content = readFileSync(queuePath, 'utf-8').trim()
|
|
46
|
+
if (!content) return []
|
|
47
|
+
|
|
48
|
+
return content
|
|
49
|
+
.split('\n')
|
|
50
|
+
.filter(line => line.trim())
|
|
51
|
+
.map(line => {
|
|
52
|
+
try {
|
|
53
|
+
return JSON.parse(line) as CapturedKnowledge
|
|
54
|
+
} catch {
|
|
55
|
+
return null
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
.filter((item): item is CapturedKnowledge => item !== null)
|
|
59
|
+
} catch {
|
|
60
|
+
return []
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Clear the queue file after successful processing.
|
|
66
|
+
*/
|
|
67
|
+
export function clearQueue(): void {
|
|
68
|
+
const queuePath = getQueuePath()
|
|
69
|
+
if (existsSync(queuePath)) {
|
|
70
|
+
writeFileSync(queuePath, '', 'utf-8')
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Drain the queue by POSTing items to the ingest endpoint in batches.
|
|
76
|
+
* Called on server startup.
|
|
77
|
+
*
|
|
78
|
+
* @param port The HTTP API port
|
|
79
|
+
* @param batchSize Number of items per POST
|
|
80
|
+
* @returns Number of items drained
|
|
81
|
+
*/
|
|
82
|
+
export async function drainQueue(port: number = 3000, batchSize: number = 10): Promise<number> {
|
|
83
|
+
const items = readQueue()
|
|
84
|
+
if (items.length === 0) return 0
|
|
85
|
+
|
|
86
|
+
let drained = 0
|
|
87
|
+
const url = `http://localhost:${port}/api/hooks/ingest`
|
|
88
|
+
|
|
89
|
+
for (let i = 0; i < items.length; i += batchSize) {
|
|
90
|
+
const batch = items.slice(i, i + batchSize)
|
|
91
|
+
try {
|
|
92
|
+
const res = await fetch(url, {
|
|
93
|
+
method: 'POST',
|
|
94
|
+
headers: { 'Content-Type': 'application/json' },
|
|
95
|
+
body: JSON.stringify({ knowledge: batch }),
|
|
96
|
+
signal: AbortSignal.timeout(5000),
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
if (res.ok) {
|
|
100
|
+
drained += batch.length
|
|
101
|
+
} else {
|
|
102
|
+
// Stop draining on first failure
|
|
103
|
+
break
|
|
104
|
+
}
|
|
105
|
+
} catch {
|
|
106
|
+
// Server not ready yet, stop
|
|
107
|
+
break
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (drained === items.length) {
|
|
112
|
+
clearQueue()
|
|
113
|
+
} else if (drained > 0) {
|
|
114
|
+
// Partially drained — rewrite queue with remaining items
|
|
115
|
+
const remaining = items.slice(drained)
|
|
116
|
+
const queuePath = getQueuePath()
|
|
117
|
+
const lines = remaining.map(item => JSON.stringify(item)).join('\n') + '\n'
|
|
118
|
+
writeFileSync(queuePath, lines, 'utf-8')
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return drained
|
|
122
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Phase 17: Session Tracker
|
|
3
|
+
* Server-side session tracking that maintains state across hook invocations.
|
|
4
|
+
* Buffers CapturedKnowledge items and generates session summaries on idle/stop.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { Logger } from 'pino'
|
|
8
|
+
import type { EpisodeManager } from '@/memory/episodic/manager'
|
|
9
|
+
import { ExtractiveSummarizer } from '@/memory/episodic/summarizer'
|
|
10
|
+
import type { CapturedKnowledge } from './types'
|
|
11
|
+
import type { HooksConfig } from '@/config/schema'
|
|
12
|
+
|
|
13
|
+
interface SessionState {
|
|
14
|
+
sessionId: string
|
|
15
|
+
project?: string
|
|
16
|
+
items: CapturedKnowledge[]
|
|
17
|
+
startedAt: string
|
|
18
|
+
lastActivityAt: string
|
|
19
|
+
episodeId?: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class HookSessionTracker {
|
|
23
|
+
private logger: Logger
|
|
24
|
+
private episodeManager: EpisodeManager | null
|
|
25
|
+
private summarizer: ExtractiveSummarizer
|
|
26
|
+
private sessions: Map<string, SessionState> = new Map()
|
|
27
|
+
private idleTimers: Map<string, ReturnType<typeof setTimeout>> = new Map()
|
|
28
|
+
private idleTimeoutMs: number
|
|
29
|
+
private minEventsForSummary: number
|
|
30
|
+
|
|
31
|
+
constructor(
|
|
32
|
+
logger: Logger,
|
|
33
|
+
episodeManager: EpisodeManager | null,
|
|
34
|
+
config?: HooksConfig['sessions']
|
|
35
|
+
) {
|
|
36
|
+
this.logger = logger.child({ component: 'hook-session-tracker' })
|
|
37
|
+
this.episodeManager = episodeManager
|
|
38
|
+
this.summarizer = new ExtractiveSummarizer()
|
|
39
|
+
this.idleTimeoutMs = (config?.idleTimeoutMinutes ?? 30) * 60 * 1000
|
|
40
|
+
this.minEventsForSummary = config?.minEventsForSummary ?? 3
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Track a captured knowledge item within a session.
|
|
45
|
+
*/
|
|
46
|
+
async track(sessionId: string, knowledge: CapturedKnowledge): Promise<void> {
|
|
47
|
+
let session = this.sessions.get(sessionId)
|
|
48
|
+
|
|
49
|
+
if (!session) {
|
|
50
|
+
session = {
|
|
51
|
+
sessionId,
|
|
52
|
+
project: knowledge.project,
|
|
53
|
+
items: [],
|
|
54
|
+
startedAt: new Date().toISOString(),
|
|
55
|
+
lastActivityAt: new Date().toISOString(),
|
|
56
|
+
}
|
|
57
|
+
this.sessions.set(sessionId, session)
|
|
58
|
+
|
|
59
|
+
// Start episode if manager available
|
|
60
|
+
if (this.episodeManager) {
|
|
61
|
+
try {
|
|
62
|
+
const episode = await this.episodeManager.startEpisode(knowledge.project)
|
|
63
|
+
session.episodeId = episode.id
|
|
64
|
+
} catch (err) {
|
|
65
|
+
this.logger.warn({ err }, 'Failed to start episode for session')
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
session.items.push(knowledge)
|
|
71
|
+
session.lastActivityAt = new Date().toISOString()
|
|
72
|
+
|
|
73
|
+
// Reset idle timer
|
|
74
|
+
this.resetIdleTimer(sessionId)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* End a session immediately (triggered by Stop hook event).
|
|
79
|
+
*/
|
|
80
|
+
async endSession(sessionId: string): Promise<void> {
|
|
81
|
+
const session = this.sessions.get(sessionId)
|
|
82
|
+
if (!session) return
|
|
83
|
+
|
|
84
|
+
this.clearIdleTimer(sessionId)
|
|
85
|
+
await this.summarizeAndPersist(session)
|
|
86
|
+
this.sessions.delete(sessionId)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* End all active sessions (for server shutdown).
|
|
91
|
+
*/
|
|
92
|
+
async endAllSessions(): Promise<void> {
|
|
93
|
+
const sessionIds = Array.from(this.sessions.keys())
|
|
94
|
+
for (const id of sessionIds) {
|
|
95
|
+
await this.endSession(id)
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Get stats about tracked sessions.
|
|
101
|
+
*/
|
|
102
|
+
getStats(): { activeSessions: number; totalItems: number } {
|
|
103
|
+
let totalItems = 0
|
|
104
|
+
for (const session of this.sessions.values()) {
|
|
105
|
+
totalItems += session.items.length
|
|
106
|
+
}
|
|
107
|
+
return { activeSessions: this.sessions.size, totalItems }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
private resetIdleTimer(sessionId: string): void {
|
|
111
|
+
this.clearIdleTimer(sessionId)
|
|
112
|
+
const timer = setTimeout(() => {
|
|
113
|
+
this.onIdle(sessionId)
|
|
114
|
+
}, this.idleTimeoutMs)
|
|
115
|
+
this.idleTimers.set(sessionId, timer)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
private clearIdleTimer(sessionId: string): void {
|
|
119
|
+
const existing = this.idleTimers.get(sessionId)
|
|
120
|
+
if (existing) {
|
|
121
|
+
clearTimeout(existing)
|
|
122
|
+
this.idleTimers.delete(sessionId)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
private async onIdle(sessionId: string): Promise<void> {
|
|
127
|
+
this.logger.debug({ sessionId }, 'Session idle timeout, summarizing')
|
|
128
|
+
await this.endSession(sessionId)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private async summarizeAndPersist(session: SessionState): Promise<void> {
|
|
132
|
+
if (session.items.length < this.minEventsForSummary) {
|
|
133
|
+
this.logger.debug(
|
|
134
|
+
{ sessionId: session.sessionId, items: session.items.length },
|
|
135
|
+
'Too few items for summary, skipping'
|
|
136
|
+
)
|
|
137
|
+
// Still end the episode if started
|
|
138
|
+
if (session.episodeId && this.episodeManager) {
|
|
139
|
+
try {
|
|
140
|
+
await this.episodeManager.endEpisode(session.episodeId)
|
|
141
|
+
} catch {}
|
|
142
|
+
}
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
this.logger.info(
|
|
147
|
+
{ sessionId: session.sessionId, items: session.items.length, project: session.project },
|
|
148
|
+
'Summarizing session'
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
// Build a synthetic episode for the summarizer
|
|
152
|
+
const messages = session.items.map((item) => ({
|
|
153
|
+
role: 'assistant' as const,
|
|
154
|
+
content: `[${item.type}] ${item.content}`,
|
|
155
|
+
timestamp: item.timestamp,
|
|
156
|
+
token_estimate: Math.ceil(item.content.length / 4),
|
|
157
|
+
}))
|
|
158
|
+
|
|
159
|
+
const syntheticEpisode = {
|
|
160
|
+
id: session.sessionId,
|
|
161
|
+
project: session.project,
|
|
162
|
+
status: 'completed' as const,
|
|
163
|
+
started_at: session.startedAt,
|
|
164
|
+
ended_at: new Date().toISOString(),
|
|
165
|
+
messages,
|
|
166
|
+
related_decisions: session.items
|
|
167
|
+
.filter(i => i.type === 'decision')
|
|
168
|
+
.map((_, idx) => `hook-decision-${idx}`),
|
|
169
|
+
related_patterns: session.items
|
|
170
|
+
.filter(i => i.type === 'pattern')
|
|
171
|
+
.map((_, idx) => `hook-pattern-${idx}`),
|
|
172
|
+
related_corrections: session.items
|
|
173
|
+
.filter(i => i.type === 'correction')
|
|
174
|
+
.map((_, idx) => `hook-correction-${idx}`),
|
|
175
|
+
token_count: messages.reduce((sum, m) => sum + (m.token_estimate || 0), 0),
|
|
176
|
+
message_count: messages.length,
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const summary = this.summarizer.summarize(syntheticEpisode)
|
|
180
|
+
|
|
181
|
+
// End the episode with summary attached
|
|
182
|
+
if (session.episodeId && this.episodeManager) {
|
|
183
|
+
try {
|
|
184
|
+
// Add messages to episode before ending
|
|
185
|
+
for (const msg of messages) {
|
|
186
|
+
await this.episodeManager.addMessage(session.episodeId, msg)
|
|
187
|
+
}
|
|
188
|
+
await this.episodeManager.endEpisode(session.episodeId)
|
|
189
|
+
} catch (err) {
|
|
190
|
+
this.logger.warn({ err, sessionId: session.sessionId }, 'Failed to end episode')
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
this.logger.info(
|
|
195
|
+
{ sessionId: session.sessionId, summary: summary.brief },
|
|
196
|
+
'Session summarized'
|
|
197
|
+
)
|
|
198
|
+
}
|
|
199
|
+
}
|