claude-brain 0.5.1 → 0.9.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 (43) hide show
  1. package/VERSION +1 -1
  2. package/assets/CLAUDE-unified.md +11 -0
  3. package/package.json +5 -1
  4. package/packs/backend/node.json +173 -0
  5. package/packs/core/javascript.json +176 -0
  6. package/packs/core/typescript.json +222 -0
  7. package/packs/frontend/react.json +254 -0
  8. package/packs/meta/testing.json +172 -0
  9. package/src/cli/bin.ts +14 -0
  10. package/src/cli/commands/hooks.ts +214 -0
  11. package/src/cli/commands/pack.ts +197 -0
  12. package/src/cli/commands/serve.ts +34 -0
  13. package/src/config/defaults.ts +1 -1
  14. package/src/config/schema.ts +85 -2
  15. package/src/hooks/brain-hook.ts +110 -0
  16. package/src/hooks/capture.ts +161 -0
  17. package/src/hooks/deduplicator.ts +72 -0
  18. package/src/hooks/index.ts +19 -0
  19. package/src/hooks/installer.ts +181 -0
  20. package/src/hooks/passive-classifier.ts +366 -0
  21. package/src/hooks/queue.ts +122 -0
  22. package/src/hooks/session-tracker.ts +199 -0
  23. package/src/hooks/types.ts +47 -0
  24. package/src/memory/chroma/store.ts +2 -1
  25. package/src/memory/index.ts +1 -0
  26. package/src/memory/store.ts +1 -0
  27. package/src/packs/index.ts +9 -0
  28. package/src/packs/loader.ts +134 -0
  29. package/src/packs/manager.ts +204 -0
  30. package/src/packs/ranker.ts +78 -0
  31. package/src/packs/types.ts +81 -0
  32. package/src/routing/entity-extractor.ts +410 -0
  33. package/src/routing/intent-classifier.ts +229 -0
  34. package/src/routing/response-filter.ts +221 -0
  35. package/src/routing/router.ts +671 -0
  36. package/src/server/handlers/call-tool.ts +7 -0
  37. package/src/server/handlers/list-tools.ts +22 -5
  38. package/src/server/handlers/tools/brain.ts +85 -0
  39. package/src/server/handlers/tools/init-project.ts +47 -0
  40. package/src/server/handlers/tools/schemas.ts +12 -0
  41. package/src/server/http-api.ts +188 -0
  42. package/src/tools/registry.ts +9 -0
  43. package/src/tools/schemas.ts +33 -1
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Phase 17: Smart Deduplicator
3
+ * Three-tier dedup before storage:
4
+ * >0.95 similarity → skip (exact duplicate)
5
+ * 0.85–0.95 similarity → merge (update existing)
6
+ * <0.85 similarity → store_new
7
+ */
8
+
9
+ import type { MemoryManager } from '@/memory'
10
+ import type { CapturedKnowledge, StoreAction } from './types'
11
+ import type { HooksConfig } from '@/config/schema'
12
+
13
+ export class SmartDeduplicator {
14
+ private skipThreshold: number
15
+ private mergeThreshold: number
16
+
17
+ constructor(config?: HooksConfig['deduplication']) {
18
+ this.skipThreshold = config?.skipThreshold ?? 0.95
19
+ this.mergeThreshold = config?.mergeThreshold ?? 0.85
20
+ }
21
+
22
+ /**
23
+ * Check captured knowledge against existing memory
24
+ * and decide: store_new, merge, or skip
25
+ */
26
+ async beforeStore(
27
+ knowledge: CapturedKnowledge,
28
+ memoryManager: MemoryManager
29
+ ): Promise<StoreAction> {
30
+ try {
31
+ const results = await memoryManager.searchRaw(knowledge.content, {
32
+ project: knowledge.project,
33
+ limit: 3,
34
+ minSimilarity: this.mergeThreshold,
35
+ })
36
+
37
+ if (!results || results.length === 0) {
38
+ return { action: 'store_new' }
39
+ }
40
+
41
+ const topResult = results[0]
42
+ const similarity = topResult.similarity ?? 0
43
+
44
+ if (similarity >= this.skipThreshold) {
45
+ return {
46
+ action: 'skip',
47
+ reason: `Duplicate (similarity: ${similarity.toFixed(3)})`,
48
+ }
49
+ }
50
+
51
+ if (similarity >= this.mergeThreshold) {
52
+ const existingId = topResult.memory?.id || topResult.id
53
+ const existingContent = topResult.memory?.content ||
54
+ topResult.decision?.decision ||
55
+ ''
56
+ const datestamp = new Date().toISOString().split('T')[0]
57
+ const mergedContent = `${existingContent}\n[Updated ${datestamp}]: ${knowledge.content}`
58
+
59
+ return {
60
+ action: 'merge',
61
+ existingId,
62
+ mergedContent,
63
+ }
64
+ }
65
+
66
+ return { action: 'store_new' }
67
+ } catch {
68
+ // If search fails, store as new to avoid data loss
69
+ return { action: 'store_new' }
70
+ }
71
+ }
72
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Phase 17: Passive Learning via Hooks
3
+ * Module re-exports
4
+ */
5
+
6
+ export type {
7
+ HookInput,
8
+ CapturedKnowledge,
9
+ KnowledgeType,
10
+ StoreAction,
11
+ HookStats,
12
+ } from './types'
13
+
14
+ export { PassiveClassifier } from './passive-classifier'
15
+ export { BrainCapture } from './capture'
16
+ export { SmartDeduplicator } from './deduplicator'
17
+ export { HookSessionTracker } from './session-tracker'
18
+ export { appendToQueue, readQueue, clearQueue, drainQueue, getQueuePath } from './queue'
19
+ export { installHooks, uninstallHooks, isHooksInstalled, getHookScriptPath } from './installer'
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Phase 17: Hook Installer
3
+ * Manages installation/removal of Claude Code hooks in ~/.claude/settings.json.
4
+ */
5
+
6
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from 'node:fs'
7
+ import { join, dirname } from 'node:path'
8
+ import { homedir } from 'node:os'
9
+ import { getClaudeBrainHome } from '@/config/home'
10
+
11
+ const CLAUDE_SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')
12
+ const HOOK_MARKER = 'claude-brain-hook'
13
+
14
+ /** Get the path where the hook script should be installed */
15
+ export function getHookScriptPath(): string {
16
+ return join(getClaudeBrainHome(), 'hooks', 'brain-hook.ts')
17
+ }
18
+
19
+ /** Read Claude Code settings.json, creating if needed */
20
+ function readSettings(): Record<string, any> {
21
+ if (!existsSync(CLAUDE_SETTINGS_PATH)) return {}
22
+ try {
23
+ return JSON.parse(readFileSync(CLAUDE_SETTINGS_PATH, 'utf-8'))
24
+ } catch {
25
+ return {}
26
+ }
27
+ }
28
+
29
+ /** Write settings.json atomically (write temp → rename) */
30
+ function writeSettings(settings: Record<string, any>): void {
31
+ const dir = dirname(CLAUDE_SETTINGS_PATH)
32
+ if (!existsSync(dir)) {
33
+ mkdirSync(dir, { recursive: true })
34
+ }
35
+
36
+ const tmpPath = CLAUDE_SETTINGS_PATH + '.tmp'
37
+ writeFileSync(tmpPath, JSON.stringify(settings, null, 2) + '\n', 'utf-8')
38
+ renameSync(tmpPath, CLAUDE_SETTINGS_PATH)
39
+ }
40
+
41
+ /** Build the hook command string */
42
+ function buildHookCommand(event: string): string {
43
+ const scriptPath = getHookScriptPath()
44
+ return `bun "${scriptPath}" --event ${event} # ${HOOK_MARKER}`
45
+ }
46
+
47
+ /**
48
+ * Install Claude Brain hooks into Claude Code settings.
49
+ * Adds PostToolUse and Stop hook entries.
50
+ */
51
+ export function installHooks(): { installed: boolean; message: string } {
52
+ if (isHooksInstalled()) {
53
+ return { installed: true, message: 'Hooks already installed' }
54
+ }
55
+
56
+ const settings = readSettings()
57
+
58
+ // Ensure hooks object exists
59
+ if (!settings.hooks) settings.hooks = {}
60
+
61
+ // PostToolUse hook — runs on every tool completion
62
+ if (!settings.hooks.PostToolUse) settings.hooks.PostToolUse = []
63
+ settings.hooks.PostToolUse.push({
64
+ matcher: '',
65
+ hooks: [{
66
+ type: 'command',
67
+ command: buildHookCommand('PostToolUse'),
68
+ }],
69
+ })
70
+
71
+ // Stop hook — triggers session-end summary
72
+ if (!settings.hooks.Stop) settings.hooks.Stop = []
73
+ settings.hooks.Stop.push({
74
+ matcher: '',
75
+ hooks: [{
76
+ type: 'command',
77
+ command: buildHookCommand('Stop'),
78
+ }],
79
+ })
80
+
81
+ writeSettings(settings)
82
+
83
+ // Copy hook script to install location
84
+ copyHookScript()
85
+
86
+ return { installed: true, message: 'Hooks installed successfully' }
87
+ }
88
+
89
+ /**
90
+ * Remove Claude Brain hooks from Claude Code settings.
91
+ */
92
+ export function uninstallHooks(): { uninstalled: boolean; message: string } {
93
+ if (!isHooksInstalled()) {
94
+ return { uninstalled: true, message: 'Hooks not installed' }
95
+ }
96
+
97
+ const settings = readSettings()
98
+
99
+ if (settings.hooks) {
100
+ // Remove our entries from PostToolUse
101
+ if (Array.isArray(settings.hooks.PostToolUse)) {
102
+ settings.hooks.PostToolUse = settings.hooks.PostToolUse.filter(
103
+ (entry: any) => !isOurHookEntry(entry)
104
+ )
105
+ if (settings.hooks.PostToolUse.length === 0) {
106
+ delete settings.hooks.PostToolUse
107
+ }
108
+ }
109
+
110
+ // Remove our entries from Stop
111
+ if (Array.isArray(settings.hooks.Stop)) {
112
+ settings.hooks.Stop = settings.hooks.Stop.filter(
113
+ (entry: any) => !isOurHookEntry(entry)
114
+ )
115
+ if (settings.hooks.Stop.length === 0) {
116
+ delete settings.hooks.Stop
117
+ }
118
+ }
119
+
120
+ // Clean up empty hooks object
121
+ if (Object.keys(settings.hooks).length === 0) {
122
+ delete settings.hooks
123
+ }
124
+ }
125
+
126
+ writeSettings(settings)
127
+
128
+ return { uninstalled: true, message: 'Hooks uninstalled successfully' }
129
+ }
130
+
131
+ /**
132
+ * Check if hooks are already installed.
133
+ */
134
+ export function isHooksInstalled(): boolean {
135
+ const settings = readSettings()
136
+ if (!settings.hooks) return false
137
+
138
+ const hasPostToolUse = Array.isArray(settings.hooks.PostToolUse) &&
139
+ settings.hooks.PostToolUse.some((entry: any) => isOurHookEntry(entry))
140
+
141
+ const hasStop = Array.isArray(settings.hooks.Stop) &&
142
+ settings.hooks.Stop.some((entry: any) => isOurHookEntry(entry))
143
+
144
+ return hasPostToolUse || hasStop
145
+ }
146
+
147
+ /** Check if a hook entry belongs to us (by marker in command) */
148
+ function isOurHookEntry(entry: any): boolean {
149
+ if (!entry || !Array.isArray(entry.hooks)) return false
150
+ return entry.hooks.some(
151
+ (h: any) => typeof h.command === 'string' && h.command.includes(HOOK_MARKER)
152
+ )
153
+ }
154
+
155
+ /** Copy the hook script to the install location */
156
+ function copyHookScript(): void {
157
+ const destPath = getHookScriptPath()
158
+ const destDir = dirname(destPath)
159
+
160
+ if (!existsSync(destDir)) {
161
+ mkdirSync(destDir, { recursive: true })
162
+ }
163
+
164
+ // Find source script relative to this file
165
+ // In development: src/hooks/brain-hook.ts
166
+ // In production: dist/hooks/brain-hook.js
167
+ const srcPath = join(dirname(new URL(import.meta.url).pathname), 'brain-hook.ts')
168
+
169
+ if (existsSync(srcPath)) {
170
+ const content = readFileSync(srcPath, 'utf-8')
171
+ writeFileSync(destPath, content, 'utf-8')
172
+ } else {
173
+ // Try .js extension for compiled version
174
+ const jsSrcPath = srcPath.replace('.ts', '.js')
175
+ if (existsSync(jsSrcPath)) {
176
+ const content = readFileSync(jsSrcPath, 'utf-8')
177
+ writeFileSync(destPath, content, 'utf-8')
178
+ }
179
+ // If neither exists, the hook script will need to be installed separately
180
+ }
181
+ }
@@ -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
+ }