claude-brain 0.17.13 → 0.22.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 (46) hide show
  1. package/VERSION +1 -1
  2. package/package.json +3 -1
  3. package/scripts/postinstall.mjs +80 -104
  4. package/src/cli/auto-setup.ts +1 -9
  5. package/src/cli/bin.ts +23 -2
  6. package/src/cli/commands/export.ts +130 -0
  7. package/src/cli/commands/reindex.ts +107 -0
  8. package/src/cli/commands/serve.ts +54 -0
  9. package/src/cli/commands/status.ts +158 -0
  10. package/src/code-intelligence/indexer.ts +315 -0
  11. package/src/code-intelligence/linker.ts +178 -0
  12. package/src/code-intelligence/parser.ts +484 -0
  13. package/src/code-intelligence/query.ts +291 -0
  14. package/src/code-intelligence/schema.ts +83 -0
  15. package/src/code-intelligence/types.ts +95 -0
  16. package/src/config/defaults.ts +3 -3
  17. package/src/config/loader.ts +6 -0
  18. package/src/config/schema.ts +28 -2
  19. package/src/health/index.ts +5 -2
  20. package/src/hooks/brain-hook.ts +4 -1
  21. package/src/hooks/context-hook.ts +69 -10
  22. package/src/hooks/installer.ts +4 -7
  23. package/src/intelligence/cross-project/index.ts +1 -7
  24. package/src/intelligence/prediction/index.ts +1 -7
  25. package/src/intelligence/reasoning/index.ts +1 -7
  26. package/src/memory/compression.ts +105 -0
  27. package/src/memory/fts5-search.ts +456 -0
  28. package/src/memory/index.ts +342 -38
  29. package/src/memory/migrations/add-fts5.ts +98 -0
  30. package/src/memory/pruning.ts +60 -0
  31. package/src/routing/intent-classifier.ts +58 -1
  32. package/src/routing/response-filter.ts +128 -0
  33. package/src/routing/router.ts +457 -54
  34. package/src/server/http-api.ts +319 -1
  35. package/src/server/providers/resources.ts +1 -42
  36. package/src/server/services.ts +113 -12
  37. package/src/server/web-viewer.ts +1115 -0
  38. package/src/setup/index.ts +12 -22
  39. package/src/tools/schemas.ts +1 -1
  40. package/src/intelligence/cross-project/affinity.ts +0 -159
  41. package/src/intelligence/cross-project/transfer.ts +0 -201
  42. package/src/intelligence/prediction/context-anticipator.ts +0 -198
  43. package/src/intelligence/prediction/decision-predictor.ts +0 -184
  44. package/src/intelligence/reasoning/counterfactual.ts +0 -248
  45. package/src/intelligence/reasoning/synthesizer.ts +0 -167
  46. package/src/setup/wizard.ts +0 -459
@@ -0,0 +1,484 @@
1
+ import Parser from 'web-tree-sitter'
2
+ import { join, extname } from 'node:path'
3
+ import type { Language, CodeSymbol, ParsedFile, ImportInfo } from './types'
4
+
5
+ /** Map file extensions to Language */
6
+ const EXTENSION_MAP: Record<string, Language> = {
7
+ '.ts': 'typescript',
8
+ '.tsx': 'tsx',
9
+ '.js': 'javascript',
10
+ '.jsx': 'jsx',
11
+ '.mjs': 'javascript',
12
+ '.cjs': 'javascript',
13
+ '.py': 'python',
14
+ '.go': 'go',
15
+ '.rs': 'rust',
16
+ '.vue': 'vue',
17
+ '.html': 'html',
18
+ '.css': 'css',
19
+ '.json': 'json',
20
+ '.yaml': 'yaml',
21
+ '.yml': 'yaml',
22
+ }
23
+
24
+ /** Languages that share the TypeScript grammar */
25
+ const TS_FAMILY = new Set<Language>(['typescript', 'javascript'])
26
+
27
+ /** Languages that use the TSX grammar */
28
+ const TSX_FAMILY = new Set<Language>(['tsx', 'jsx'])
29
+
30
+ /** Map Language to WASM grammar file name */
31
+ function grammarNameForLanguage(lang: Language): string | null {
32
+ if (TS_FAMILY.has(lang)) return 'typescript'
33
+ if (TSX_FAMILY.has(lang)) return 'tsx'
34
+ return null
35
+ }
36
+
37
+ /**
38
+ * Tree-sitter based code parser.
39
+ * Currently supports TypeScript, JavaScript, TSX, and JSX.
40
+ * Call `initialize()` once before using `parseFile()`.
41
+ */
42
+ export class CodeParser {
43
+ private parser: Parser | null = null
44
+ private languages = new Map<string, Parser.Language>()
45
+ private initialized = false
46
+
47
+ /**
48
+ * Initialize the parser and load WASM grammars.
49
+ * Must be called once before parseFile().
50
+ */
51
+ async initialize(): Promise<void> {
52
+ if (this.initialized) return
53
+
54
+ await Parser.init()
55
+ this.parser = new Parser()
56
+
57
+ const grammarsToLoad = ['typescript', 'tsx']
58
+ for (const name of grammarsToLoad) {
59
+ const wasmPath = this.resolveWasmPath(name)
60
+ try {
61
+ const lang = await Parser.Language.load(wasmPath)
62
+ this.languages.set(name, lang)
63
+ } catch (err) {
64
+ throw new Error(
65
+ `Failed to load tree-sitter WASM grammar "${name}" from ${wasmPath}: ${err instanceof Error ? err.message : String(err)}`
66
+ )
67
+ }
68
+ }
69
+
70
+ this.initialized = true
71
+ }
72
+
73
+ /**
74
+ * Detect language from a file path's extension.
75
+ * Returns null for unsupported file types.
76
+ */
77
+ detectLanguage(filePath: string): Language | null {
78
+ const ext = extname(filePath).toLowerCase()
79
+ return EXTENSION_MAP[ext] ?? null
80
+ }
81
+
82
+ /**
83
+ * Parse a file and extract its symbols and imports.
84
+ * Returns an empty symbol list for unsupported languages.
85
+ */
86
+ async parseFile(filePath: string, content: string): Promise<ParsedFile> {
87
+ const language = this.detectLanguage(filePath)
88
+ if (!language) {
89
+ return {
90
+ filePath,
91
+ language: 'typescript',
92
+ symbols: [],
93
+ imports: [],
94
+ lineCount: content.split('\n').length,
95
+ }
96
+ }
97
+
98
+ const grammarName = grammarNameForLanguage(language)
99
+ if (!grammarName) {
100
+ return {
101
+ filePath,
102
+ language,
103
+ symbols: [],
104
+ imports: [],
105
+ lineCount: content.split('\n').length,
106
+ }
107
+ }
108
+
109
+ if (!this.initialized || !this.parser) {
110
+ throw new Error('CodeParser not initialized. Call initialize() first.')
111
+ }
112
+
113
+ const treeSitterLang = this.languages.get(grammarName)
114
+ if (!treeSitterLang) {
115
+ throw new Error(`Grammar "${grammarName}" not loaded.`)
116
+ }
117
+
118
+ this.parser.setLanguage(treeSitterLang)
119
+
120
+ let tree: Parser.Tree | undefined
121
+ try {
122
+ tree = this.parser.parse(content)
123
+
124
+ const symbols = this.extractSymbols(tree, filePath)
125
+ const imports = this.extractImports(tree)
126
+
127
+ return {
128
+ filePath,
129
+ language,
130
+ symbols,
131
+ imports,
132
+ lineCount: content.split('\n').length,
133
+ }
134
+ } finally {
135
+ tree?.delete()
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Extract symbols (functions, classes, interfaces, etc.) from a parsed tree.
141
+ */
142
+ private extractSymbols(tree: Parser.Tree, filePath: string): CodeSymbol[] {
143
+ const symbols: CodeSymbol[] = []
144
+ this.walkForSymbols(tree.rootNode, filePath, null, false, symbols)
145
+ return symbols
146
+ }
147
+
148
+ /**
149
+ * Recursively walk the AST to find symbol declarations.
150
+ */
151
+ private walkForSymbols(
152
+ node: Parser.SyntaxNode,
153
+ filePath: string,
154
+ parentSymbol: string | null,
155
+ isExported: boolean,
156
+ symbols: CodeSymbol[]
157
+ ): void {
158
+ const type = node.type
159
+
160
+ if (type === 'export_statement') {
161
+ for (const child of node.namedChildren) {
162
+ this.walkForSymbols(child, filePath, parentSymbol, true, symbols)
163
+ }
164
+ return
165
+ }
166
+
167
+ const symbol = this.nodeToSymbol(node, filePath, parentSymbol, isExported)
168
+ if (symbol) {
169
+ symbols.push(symbol)
170
+
171
+ // For classes/interfaces, walk children to find methods
172
+ if (symbol.type === 'class' || symbol.type === 'interface') {
173
+ const body = node.childForFieldName('body')
174
+ if (body) {
175
+ for (const child of body.namedChildren) {
176
+ this.walkForSymbols(child, filePath, symbol.name, isExported, symbols)
177
+ }
178
+ }
179
+ return
180
+ }
181
+ }
182
+
183
+ // Continue walking for top-level containers
184
+ if (this.isContainerNode(type)) {
185
+ for (const child of node.namedChildren) {
186
+ this.walkForSymbols(child, filePath, parentSymbol, false, symbols)
187
+ }
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Convert a tree-sitter node to a CodeSymbol if it represents a declaration.
193
+ */
194
+ private nodeToSymbol(
195
+ node: Parser.SyntaxNode,
196
+ filePath: string,
197
+ parentSymbol: string | null,
198
+ isExported: boolean
199
+ ): CodeSymbol | null {
200
+ const type = node.type
201
+
202
+ switch (type) {
203
+ case 'function_declaration':
204
+ case 'function_signature': {
205
+ const name = node.childForFieldName('name')
206
+ if (!name) return null
207
+ return {
208
+ name: name.text,
209
+ type: 'function',
210
+ filePath,
211
+ lineStart: node.startPosition.row + 1,
212
+ lineEnd: node.endPosition.row + 1,
213
+ parentSymbol: parentSymbol ?? undefined,
214
+ signature: this.extractSignature(node),
215
+ exported: isExported,
216
+ }
217
+ }
218
+
219
+ case 'class_declaration': {
220
+ const name = node.childForFieldName('name')
221
+ if (!name) return null
222
+ return {
223
+ name: name.text,
224
+ type: 'class',
225
+ filePath,
226
+ lineStart: node.startPosition.row + 1,
227
+ lineEnd: node.endPosition.row + 1,
228
+ parentSymbol: parentSymbol ?? undefined,
229
+ exported: isExported,
230
+ }
231
+ }
232
+
233
+ case 'interface_declaration': {
234
+ const name = node.childForFieldName('name')
235
+ if (!name) return null
236
+ return {
237
+ name: name.text,
238
+ type: 'interface',
239
+ filePath,
240
+ lineStart: node.startPosition.row + 1,
241
+ lineEnd: node.endPosition.row + 1,
242
+ parentSymbol: parentSymbol ?? undefined,
243
+ exported: isExported,
244
+ }
245
+ }
246
+
247
+ case 'type_alias_declaration': {
248
+ const name = node.childForFieldName('name')
249
+ if (!name) return null
250
+ return {
251
+ name: name.text,
252
+ type: 'type',
253
+ filePath,
254
+ lineStart: node.startPosition.row + 1,
255
+ lineEnd: node.endPosition.row + 1,
256
+ parentSymbol: parentSymbol ?? undefined,
257
+ exported: isExported,
258
+ }
259
+ }
260
+
261
+ case 'enum_declaration': {
262
+ const name = node.childForFieldName('name')
263
+ if (!name) return null
264
+ return {
265
+ name: name.text,
266
+ type: 'enum',
267
+ filePath,
268
+ lineStart: node.startPosition.row + 1,
269
+ lineEnd: node.endPosition.row + 1,
270
+ parentSymbol: parentSymbol ?? undefined,
271
+ exported: isExported,
272
+ }
273
+ }
274
+
275
+ case 'method_definition':
276
+ case 'method_signature': {
277
+ const name = node.childForFieldName('name')
278
+ if (!name) return null
279
+ return {
280
+ name: name.text,
281
+ type: 'method',
282
+ filePath,
283
+ lineStart: node.startPosition.row + 1,
284
+ lineEnd: node.endPosition.row + 1,
285
+ parentSymbol: parentSymbol ?? undefined,
286
+ signature: this.extractSignature(node),
287
+ exported: isExported,
288
+ }
289
+ }
290
+
291
+ case 'public_field_definition':
292
+ case 'property_signature': {
293
+ const name = node.childForFieldName('name')
294
+ if (!name) return null
295
+ return {
296
+ name: name.text,
297
+ type: 'variable',
298
+ filePath,
299
+ lineStart: node.startPosition.row + 1,
300
+ lineEnd: node.endPosition.row + 1,
301
+ parentSymbol: parentSymbol ?? undefined,
302
+ exported: isExported,
303
+ }
304
+ }
305
+
306
+ case 'lexical_declaration':
307
+ case 'variable_declaration': {
308
+ return this.extractFromLexicalDeclaration(node, filePath, parentSymbol, isExported)
309
+ }
310
+
311
+ default:
312
+ return null
313
+ }
314
+ }
315
+
316
+ /**
317
+ * Extract a symbol from a lexical_declaration (const/let) or variable_declaration (var).
318
+ * Handles arrow functions assigned to variables.
319
+ */
320
+ private extractFromLexicalDeclaration(
321
+ node: Parser.SyntaxNode,
322
+ filePath: string,
323
+ parentSymbol: string | null,
324
+ isExported: boolean
325
+ ): CodeSymbol | null {
326
+ const declarator = node.namedChildren.find(
327
+ (c) => c.type === 'variable_declarator'
328
+ )
329
+ if (!declarator) return null
330
+
331
+ const name = declarator.childForFieldName('name')
332
+ if (!name) return null
333
+
334
+ const value = declarator.childForFieldName('value')
335
+ const isConst = node.text.trimStart().startsWith('const')
336
+
337
+ if (value && (value.type === 'arrow_function' || value.type === 'function_expression' || value.type === 'function')) {
338
+ return {
339
+ name: name.text,
340
+ type: 'function',
341
+ filePath,
342
+ lineStart: node.startPosition.row + 1,
343
+ lineEnd: node.endPosition.row + 1,
344
+ parentSymbol: parentSymbol ?? undefined,
345
+ signature: this.extractSignature(value),
346
+ exported: isExported,
347
+ }
348
+ }
349
+
350
+ return {
351
+ name: name.text,
352
+ type: isConst ? 'constant' : 'variable',
353
+ filePath,
354
+ lineStart: node.startPosition.row + 1,
355
+ lineEnd: node.endPosition.row + 1,
356
+ parentSymbol: parentSymbol ?? undefined,
357
+ exported: isExported,
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Extract function signature (parameters + return type).
363
+ */
364
+ private extractSignature(node: Parser.SyntaxNode): string | undefined {
365
+ const params = node.childForFieldName('parameters')
366
+ const returnType = node.childForFieldName('return_type')
367
+
368
+ if (!params) return undefined
369
+
370
+ let sig = params.text
371
+ if (returnType) {
372
+ // returnType.text may include the leading `:`, so avoid doubling it
373
+ const rt = returnType.text.trimStart()
374
+ sig += rt.startsWith(':') ? ' ' + rt : ': ' + rt
375
+ }
376
+ return sig
377
+ }
378
+
379
+ /**
380
+ * Extract import statements from the AST.
381
+ */
382
+ private extractImports(tree: Parser.Tree): ImportInfo[] {
383
+ const imports: ImportInfo[] = []
384
+
385
+ for (const child of tree.rootNode.namedChildren) {
386
+ if (child.type === 'import_statement') {
387
+ const info = this.parseImportStatement(child)
388
+ if (info) imports.push(info)
389
+ }
390
+ }
391
+
392
+ return imports
393
+ }
394
+
395
+ /**
396
+ * Parse a single import_statement node into an ImportInfo.
397
+ */
398
+ private parseImportStatement(node: Parser.SyntaxNode): ImportInfo | null {
399
+ const source = node.childForFieldName('source')
400
+ if (!source) return null
401
+
402
+ const sourcePath = source.text.replace(/^['"]|['"]$/g, '')
403
+ const names: string[] = []
404
+
405
+ for (const child of node.namedChildren) {
406
+ if (child.type === 'import_clause') {
407
+ this.collectImportNames(child, names)
408
+ }
409
+ if (child.type === 'namespace_import') {
410
+ const alias = child.childForFieldName('name') ?? child.namedChildren[0]
411
+ if (alias) names.push(alias.text)
412
+ }
413
+ if (child.type === 'named_imports') {
414
+ for (const spec of child.namedChildren) {
415
+ if (spec.type === 'import_specifier') {
416
+ const specName = spec.childForFieldName('name') ?? spec.namedChildren[0]
417
+ if (specName) names.push(specName.text)
418
+ }
419
+ }
420
+ }
421
+ }
422
+
423
+ return {
424
+ source: sourcePath,
425
+ names,
426
+ importType: 'import',
427
+ line: node.startPosition.row + 1,
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Collect imported names from an import_clause node.
433
+ */
434
+ private collectImportNames(node: Parser.SyntaxNode, names: string[]): void {
435
+ for (const child of node.namedChildren) {
436
+ switch (child.type) {
437
+ case 'identifier':
438
+ names.push(child.text)
439
+ break
440
+ case 'named_imports':
441
+ for (const spec of child.namedChildren) {
442
+ if (spec.type === 'import_specifier') {
443
+ const specName = spec.childForFieldName('name') ?? spec.namedChildren[0]
444
+ if (specName) names.push(specName.text)
445
+ }
446
+ }
447
+ break
448
+ case 'namespace_import': {
449
+ const alias = child.childForFieldName('name') ?? child.namedChildren[0]
450
+ if (alias) names.push(alias.text)
451
+ break
452
+ }
453
+ }
454
+ }
455
+ }
456
+
457
+ /**
458
+ * Check if a node type is a container that may hold declarations.
459
+ */
460
+ private isContainerNode(type: string): boolean {
461
+ return (
462
+ type === 'program' ||
463
+ type === 'statement_block' ||
464
+ type === 'module' ||
465
+ type === 'export_statement'
466
+ )
467
+ }
468
+
469
+ /**
470
+ * Resolve the path to a tree-sitter WASM grammar file.
471
+ */
472
+ private resolveWasmPath(grammarName: string): string {
473
+ try {
474
+ const wasmsDir = require.resolve('tree-sitter-wasms/package.json')
475
+ return join(wasmsDir, '..', 'out', `tree-sitter-${grammarName}.wasm`)
476
+ } catch {
477
+ return join(
478
+ import.meta.dir,
479
+ '../../node_modules/tree-sitter-wasms/out',
480
+ `tree-sitter-${grammarName}.wasm`
481
+ )
482
+ }
483
+ }
484
+ }