@timmeck/brain 1.8.5 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/.dockerignore +11 -0
  2. package/Dockerfile +21 -0
  3. package/README.md +19 -0
  4. package/assets/brain-avatar-256.png +0 -0
  5. package/assets/brain-avatar-512.png +0 -0
  6. package/assets/brain-avatar.png +0 -0
  7. package/brain.log +1164 -0
  8. package/{src/cli/commands/dashboard.ts → dashboard.html} +688 -807
  9. package/dist/api/server.d.ts +4 -18
  10. package/dist/api/server.js +4 -173
  11. package/dist/api/server.js.map +1 -1
  12. package/dist/brain.d.ts +6 -0
  13. package/dist/brain.js +56 -4
  14. package/dist/brain.js.map +1 -1
  15. package/dist/cli/colors.d.ts +4 -25
  16. package/dist/cli/colors.js +3 -89
  17. package/dist/cli/colors.js.map +1 -1
  18. package/dist/cli/commands/peers.d.ts +2 -0
  19. package/dist/cli/commands/peers.js +38 -0
  20. package/dist/cli/commands/peers.js.map +1 -0
  21. package/dist/cli/commands/start.js +54 -17
  22. package/dist/cli/commands/start.js.map +1 -1
  23. package/dist/db/connection.d.ts +1 -2
  24. package/dist/db/connection.js +1 -18
  25. package/dist/db/connection.js.map +1 -1
  26. package/dist/index.js +3 -1
  27. package/dist/index.js.map +1 -1
  28. package/dist/ipc/__tests__/protocol.test.d.ts +1 -0
  29. package/dist/ipc/__tests__/protocol.test.js +117 -0
  30. package/dist/ipc/__tests__/protocol.test.js.map +1 -0
  31. package/dist/ipc/client.d.ts +1 -16
  32. package/dist/ipc/client.js +1 -100
  33. package/dist/ipc/client.js.map +1 -1
  34. package/dist/ipc/protocol.d.ts +1 -8
  35. package/dist/ipc/protocol.js +1 -28
  36. package/dist/ipc/protocol.js.map +1 -1
  37. package/dist/ipc/router.js +8 -0
  38. package/dist/ipc/router.js.map +1 -1
  39. package/dist/ipc/server.d.ts +1 -22
  40. package/dist/ipc/server.js +1 -163
  41. package/dist/ipc/server.js.map +1 -1
  42. package/dist/mcp/http-server.d.ts +1 -7
  43. package/dist/mcp/http-server.js +6 -117
  44. package/dist/mcp/http-server.js.map +1 -1
  45. package/dist/mcp/server.js +5 -61
  46. package/dist/mcp/server.js.map +1 -1
  47. package/dist/signals/__tests__/fingerprint.test.d.ts +1 -0
  48. package/dist/signals/__tests__/fingerprint.test.js +118 -0
  49. package/dist/signals/__tests__/fingerprint.test.js.map +1 -0
  50. package/dist/types/ipc.types.d.ts +1 -11
  51. package/dist/utils/__tests__/hash.test.d.ts +1 -0
  52. package/dist/utils/__tests__/hash.test.js +32 -0
  53. package/dist/utils/__tests__/hash.test.js.map +1 -0
  54. package/dist/utils/__tests__/paths.test.d.ts +1 -0
  55. package/dist/utils/__tests__/paths.test.js +75 -0
  56. package/dist/utils/__tests__/paths.test.js.map +1 -0
  57. package/dist/utils/events.d.ts +4 -8
  58. package/dist/utils/events.js +2 -14
  59. package/dist/utils/events.js.map +1 -1
  60. package/dist/utils/hash.d.ts +1 -1
  61. package/dist/utils/hash.js +1 -4
  62. package/dist/utils/hash.js.map +1 -1
  63. package/dist/utils/logger.d.ts +3 -2
  64. package/dist/utils/logger.js +8 -35
  65. package/dist/utils/logger.js.map +1 -1
  66. package/dist/utils/paths.d.ts +2 -1
  67. package/dist/utils/paths.js +4 -13
  68. package/dist/utils/paths.js.map +1 -1
  69. package/gen_avatar.py +142 -0
  70. package/package.json +2 -1
  71. package/BRAIN_PLAN.md +0 -3324
  72. package/src/api/server.ts +0 -395
  73. package/src/brain.ts +0 -266
  74. package/src/cli/colors.ts +0 -116
  75. package/src/cli/commands/config.ts +0 -169
  76. package/src/cli/commands/doctor.ts +0 -124
  77. package/src/cli/commands/explain.ts +0 -83
  78. package/src/cli/commands/export.ts +0 -31
  79. package/src/cli/commands/import.ts +0 -199
  80. package/src/cli/commands/insights.ts +0 -65
  81. package/src/cli/commands/learn.ts +0 -24
  82. package/src/cli/commands/modules.ts +0 -53
  83. package/src/cli/commands/network.ts +0 -67
  84. package/src/cli/commands/projects.ts +0 -42
  85. package/src/cli/commands/query.ts +0 -120
  86. package/src/cli/commands/start.ts +0 -62
  87. package/src/cli/commands/status.ts +0 -75
  88. package/src/cli/commands/stop.ts +0 -34
  89. package/src/cli/ipc-helper.ts +0 -22
  90. package/src/cli/update-check.ts +0 -63
  91. package/src/code/analyzer.ts +0 -117
  92. package/src/code/fingerprint.ts +0 -87
  93. package/src/code/matcher.ts +0 -129
  94. package/src/code/parsers/generic.ts +0 -29
  95. package/src/code/parsers/python.ts +0 -54
  96. package/src/code/parsers/typescript.ts +0 -65
  97. package/src/code/registry.ts +0 -60
  98. package/src/code/scorer.ts +0 -120
  99. package/src/config.ts +0 -135
  100. package/src/dashboard/server.ts +0 -142
  101. package/src/db/connection.ts +0 -22
  102. package/src/db/migrations/001_core_schema.ts +0 -120
  103. package/src/db/migrations/002_learning_schema.ts +0 -38
  104. package/src/db/migrations/003_code_schema.ts +0 -53
  105. package/src/db/migrations/004_synapses_schema.ts +0 -57
  106. package/src/db/migrations/005_fts_indexes.ts +0 -78
  107. package/src/db/migrations/006_synapses_phase3.ts +0 -17
  108. package/src/db/migrations/007_feedback.ts +0 -13
  109. package/src/db/migrations/008_git_integration.ts +0 -38
  110. package/src/db/migrations/009_embeddings.ts +0 -8
  111. package/src/db/migrations/index.ts +0 -70
  112. package/src/db/repositories/antipattern.repository.ts +0 -66
  113. package/src/db/repositories/code-module.repository.ts +0 -142
  114. package/src/db/repositories/error.repository.ts +0 -189
  115. package/src/db/repositories/insight.repository.ts +0 -99
  116. package/src/db/repositories/notification.repository.ts +0 -66
  117. package/src/db/repositories/project.repository.ts +0 -93
  118. package/src/db/repositories/rule.repository.ts +0 -108
  119. package/src/db/repositories/solution.repository.ts +0 -154
  120. package/src/db/repositories/synapse.repository.ts +0 -163
  121. package/src/db/repositories/terminal.repository.ts +0 -101
  122. package/src/embeddings/engine.ts +0 -238
  123. package/src/hooks/post-tool-use.ts +0 -92
  124. package/src/hooks/post-write.ts +0 -129
  125. package/src/index.ts +0 -63
  126. package/src/ipc/client.ts +0 -118
  127. package/src/ipc/protocol.ts +0 -35
  128. package/src/ipc/router.ts +0 -133
  129. package/src/ipc/server.ts +0 -176
  130. package/src/learning/confidence-scorer.ts +0 -80
  131. package/src/learning/decay.ts +0 -46
  132. package/src/learning/learning-engine.ts +0 -170
  133. package/src/learning/pattern-extractor.ts +0 -90
  134. package/src/learning/rule-generator.ts +0 -74
  135. package/src/main.rs:10:5 +0 -0
  136. package/src/matching/error-matcher.ts +0 -166
  137. package/src/matching/fingerprint.ts +0 -34
  138. package/src/matching/similarity.ts +0 -61
  139. package/src/matching/tfidf.ts +0 -74
  140. package/src/matching/tokenizer.ts +0 -41
  141. package/src/mcp/auto-detect.ts +0 -93
  142. package/src/mcp/http-server.ts +0 -140
  143. package/src/mcp/server.ts +0 -73
  144. package/src/mcp/tools.ts +0 -328
  145. package/src/parsing/error-parser.ts +0 -28
  146. package/src/parsing/parsers/compiler.ts +0 -93
  147. package/src/parsing/parsers/generic.ts +0 -28
  148. package/src/parsing/parsers/go.ts +0 -97
  149. package/src/parsing/parsers/node.ts +0 -69
  150. package/src/parsing/parsers/python.ts +0 -62
  151. package/src/parsing/parsers/rust.ts +0 -50
  152. package/src/parsing/parsers/shell.ts +0 -42
  153. package/src/parsing/types.ts +0 -47
  154. package/src/research/gap-analyzer.ts +0 -135
  155. package/src/research/insight-generator.ts +0 -123
  156. package/src/research/research-engine.ts +0 -116
  157. package/src/research/synergy-detector.ts +0 -126
  158. package/src/research/template-extractor.ts +0 -130
  159. package/src/research/trend-analyzer.ts +0 -127
  160. package/src/services/analytics.service.ts +0 -226
  161. package/src/services/code.service.ts +0 -271
  162. package/src/services/error.service.ts +0 -266
  163. package/src/services/git.service.ts +0 -132
  164. package/src/services/notification.service.ts +0 -41
  165. package/src/services/prevention.service.ts +0 -159
  166. package/src/services/research.service.ts +0 -98
  167. package/src/services/solution.service.ts +0 -174
  168. package/src/services/synapse.service.ts +0 -59
  169. package/src/services/terminal.service.ts +0 -81
  170. package/src/synapses/activation.ts +0 -80
  171. package/src/synapses/decay.ts +0 -38
  172. package/src/synapses/hebbian.ts +0 -69
  173. package/src/synapses/pathfinder.ts +0 -81
  174. package/src/synapses/synapse-manager.ts +0 -113
  175. package/src/types/code.types.ts +0 -52
  176. package/src/types/config.types.ts +0 -103
  177. package/src/types/error.types.ts +0 -67
  178. package/src/types/ipc.types.ts +0 -8
  179. package/src/types/mcp.types.ts +0 -53
  180. package/src/types/research.types.ts +0 -28
  181. package/src/types/solution.types.ts +0 -30
  182. package/src/types/synapse.types.ts +0 -50
  183. package/src/utils/events.ts +0 -45
  184. package/src/utils/hash.ts +0 -5
  185. package/src/utils/logger.ts +0 -48
  186. package/src/utils/paths.ts +0 -19
  187. package/tests/e2e/test_code_intelligence.py +0 -1015
  188. package/tests/e2e/test_error_memory.py +0 -451
  189. package/tests/e2e/test_full_integration.py +0 -534
  190. package/tests/fixtures/code-modules/modules.ts +0 -83
  191. package/tests/fixtures/errors/go.ts +0 -9
  192. package/tests/fixtures/errors/node.ts +0 -24
  193. package/tests/fixtures/errors/python.ts +0 -21
  194. package/tests/fixtures/errors/rust.ts +0 -25
  195. package/tests/fixtures/errors/shell.ts +0 -15
  196. package/tests/fixtures/solutions/solutions.ts +0 -27
  197. package/tests/helpers/setup-db.ts +0 -52
  198. package/tests/integration/code-flow.test.ts +0 -86
  199. package/tests/integration/error-flow.test.ts +0 -83
  200. package/tests/integration/ipc-flow.test.ts +0 -166
  201. package/tests/integration/learning-cycle.test.ts +0 -82
  202. package/tests/integration/synapse-flow.test.ts +0 -117
  203. package/tests/unit/code/analyzer.test.ts +0 -58
  204. package/tests/unit/code/fingerprint.test.ts +0 -51
  205. package/tests/unit/code/scorer.test.ts +0 -55
  206. package/tests/unit/learning/confidence-scorer.test.ts +0 -60
  207. package/tests/unit/learning/decay.test.ts +0 -45
  208. package/tests/unit/learning/pattern-extractor.test.ts +0 -50
  209. package/tests/unit/matching/error-matcher.test.ts +0 -69
  210. package/tests/unit/matching/fingerprint.test.ts +0 -47
  211. package/tests/unit/matching/similarity.test.ts +0 -65
  212. package/tests/unit/matching/tfidf.test.ts +0 -71
  213. package/tests/unit/matching/tokenizer.test.ts +0 -83
  214. package/tests/unit/parsing/parsers.test.ts +0 -113
  215. package/tests/unit/research/gap-analyzer.test.ts +0 -45
  216. package/tests/unit/research/trend-analyzer.test.ts +0 -45
  217. package/tests/unit/synapses/activation.test.ts +0 -80
  218. package/tests/unit/synapses/decay.test.ts +0 -27
  219. package/tests/unit/synapses/hebbian.test.ts +0 -96
  220. package/tests/unit/synapses/pathfinder.test.ts +0 -72
  221. package/tsconfig.json +0 -18
@@ -1,60 +0,0 @@
1
- import type { ExportInfo } from '../types/code.types.js';
2
- import { analyzeCode, measureCohesion } from './analyzer.js';
3
-
4
- export type ModuleType = 'file' | 'class' | 'function';
5
-
6
- export function detectGranularity(
7
- source: string,
8
- language: string,
9
- ): ModuleType {
10
- const { exports } = analyzeCode(source, language);
11
-
12
- const hasDefault = exports.some(e => e.name === 'default');
13
- if (hasDefault && exports.length <= 3) return 'file';
14
-
15
- const classes = exports.filter(e => e.type === 'class');
16
- if (classes.length === 1 && exports.length <= 3) return 'class';
17
-
18
- if (exports.length > 3) {
19
- const cohesion = measureCohesion(exports);
20
- if (cohesion < 0.5) return 'function';
21
- }
22
-
23
- return 'file';
24
- }
25
-
26
- export interface ModuleRegistration {
27
- name: string;
28
- filePath: string;
29
- language: string;
30
- source: string;
31
- description?: string;
32
- projectId: number;
33
- }
34
-
35
- export interface RegisteredModule {
36
- name: string;
37
- moduleType: ModuleType;
38
- exports: ExportInfo[];
39
- externalDeps: string[];
40
- internalDeps: string[];
41
- isPure: boolean;
42
- hasTypeAnnotations: boolean;
43
- linesOfCode: number;
44
- }
45
-
46
- export function prepareModule(reg: ModuleRegistration): RegisteredModule {
47
- const analysis = analyzeCode(reg.source, reg.language);
48
- const moduleType = detectGranularity(reg.source, reg.language);
49
-
50
- return {
51
- name: reg.name,
52
- moduleType,
53
- exports: analysis.exports,
54
- externalDeps: analysis.externalDeps,
55
- internalDeps: analysis.internalDeps,
56
- isPure: analysis.isPure,
57
- hasTypeAnnotations: analysis.hasTypeAnnotations,
58
- linesOfCode: analysis.linesOfCode,
59
- };
60
- }
@@ -1,120 +0,0 @@
1
- import type { ExportInfo } from '../types/code.types.js';
2
-
3
- export interface CodeUnitForScoring {
4
- source: string;
5
- filePath: string;
6
- exports: ExportInfo[];
7
- internalDeps: string[];
8
- hasTypeAnnotations: boolean;
9
- complexity?: number;
10
- }
11
-
12
- interface ReusabilitySignal {
13
- name: string;
14
- weight: number;
15
- check: (code: CodeUnitForScoring) => number;
16
- }
17
-
18
- const REUSABILITY_SIGNALS: ReusabilitySignal[] = [
19
- {
20
- name: 'single_responsibility',
21
- weight: 0.20,
22
- check: (code) => {
23
- const count = code.exports.length;
24
- if (count === 0) return 0;
25
- if (count <= 3) return 1.0;
26
- if (count <= 6) return 0.6;
27
- return 0.3;
28
- },
29
- },
30
- {
31
- name: 'pure_function',
32
- weight: 0.20,
33
- check: (code) => {
34
- const sideEffects = [
35
- 'fs.', 'process.', 'console.', 'fetch(',
36
- 'XMLHttpRequest', 'document.', 'window.',
37
- 'global.', 'require(',
38
- ];
39
- const found = sideEffects.filter(se => code.source.includes(se));
40
- return found.length === 0 ? 1.0 : Math.max(0, 1 - found.length * 0.3);
41
- },
42
- },
43
- {
44
- name: 'clear_interface',
45
- weight: 0.20,
46
- check: (code) => {
47
- let score = 0.5;
48
- if (code.hasTypeAnnotations) score += 0.3;
49
- if (!code.source.includes(': any')) score += 0.2;
50
- return Math.min(1.0, score);
51
- },
52
- },
53
- {
54
- name: 'cohesion',
55
- weight: 0.15,
56
- check: (code) => {
57
- const internalImports = code.internalDeps.length;
58
- const exportCount = code.exports.length;
59
- if (exportCount === 0) return 0;
60
- const ratio = internalImports / exportCount;
61
- if (ratio === 0) return 1.0;
62
- if (ratio < 0.5) return 0.8;
63
- if (ratio < 1.0) return 0.5;
64
- return 0.2;
65
- },
66
- },
67
- {
68
- name: 'generic_utility',
69
- weight: 0.10,
70
- check: (code) => {
71
- const utilPaths = ['utils/', 'helpers/', 'lib/', 'shared/', 'common/'];
72
- const isUtilPath = utilPaths.some(p => code.filePath.includes(p));
73
- const hasGenerics = /<[A-Z]\w*>/.test(code.source);
74
- let score = 0;
75
- if (isUtilPath) score += 0.6;
76
- if (hasGenerics) score += 0.4;
77
- return Math.min(1.0, score || 0.2);
78
- },
79
- },
80
- {
81
- name: 'documentation',
82
- weight: 0.10,
83
- check: (code) => {
84
- const hasJsdoc = /\/\*\*[\s\S]*?\*\//.test(code.source);
85
- const hasDocstring = /"""[\s\S]*?"""/.test(code.source) || /'''[\s\S]*?'''/.test(code.source);
86
- const hasInlineComments = (code.source.match(/\/\/ /g) ?? []).length >= 2;
87
- if (hasJsdoc || hasDocstring) return 1.0;
88
- if (hasInlineComments) return 0.5;
89
- return 0.1;
90
- },
91
- },
92
- {
93
- name: 'low_complexity',
94
- weight: 0.10,
95
- check: (code) => {
96
- const cc = code.complexity ?? 1;
97
- if (cc <= 5) return 1.0;
98
- if (cc <= 10) return 0.7;
99
- if (cc <= 20) return 0.4;
100
- return 0.1;
101
- },
102
- },
103
- ];
104
-
105
- export const MODULE_THRESHOLD = 0.60;
106
-
107
- export function computeReusabilityScore(code: CodeUnitForScoring): number {
108
- let totalScore = 0;
109
- for (const signal of REUSABILITY_SIGNALS) {
110
- totalScore += signal.check(code) * signal.weight;
111
- }
112
- return Math.min(1.0, totalScore);
113
- }
114
-
115
- export function getSignalBreakdown(code: CodeUnitForScoring): Array<{ name: string; score: number; weighted: number }> {
116
- return REUSABILITY_SIGNALS.map(signal => {
117
- const score = signal.check(code);
118
- return { name: signal.name, score, weighted: score * signal.weight };
119
- });
120
- }
package/src/config.ts DELETED
@@ -1,135 +0,0 @@
1
- import path from 'node:path';
2
- import fs from 'node:fs';
3
- import type { BrainConfig } from './types/config.types.js';
4
- import { getDataDir, getPipeName } from './utils/paths.js';
5
-
6
- const defaults: BrainConfig = {
7
- dataDir: getDataDir(),
8
- dbPath: path.join(getDataDir(), 'brain.db'),
9
- ipc: {
10
- pipeName: getPipeName(),
11
- timeout: 5000,
12
- },
13
- api: {
14
- port: 7777,
15
- enabled: true,
16
- },
17
- mcpHttp: {
18
- port: 7778,
19
- enabled: true,
20
- },
21
- embeddings: {
22
- enabled: true,
23
- modelName: 'Xenova/all-MiniLM-L6-v2',
24
- cacheDir: path.join(getDataDir(), 'models'),
25
- sweepIntervalMs: 300_000, // 5 minutes
26
- batchSize: 50,
27
- },
28
- learning: {
29
- intervalMs: 900_000,
30
- minOccurrences: 3,
31
- minSuccessRate: 0.70,
32
- minConfidence: 0.60,
33
- pruneThreshold: 0.20,
34
- maxRejectionRate: 0.50,
35
- decayHalfLifeDays: 30,
36
- },
37
- terminal: {
38
- staleTimeout: 300000, // 5 min
39
- maxConnected: 50,
40
- },
41
- matching: {
42
- fingerprintFields: ['type', 'message', 'file_path'],
43
- similarityThreshold: 0.8,
44
- maxResults: 10,
45
- crossProjectMatching: true,
46
- crossProjectWeight: 0.7,
47
- },
48
- code: {
49
- supportedLanguages: ['typescript', 'javascript', 'python', 'rust', 'go'],
50
- maxModuleSize: 50000,
51
- similarityThreshold: 0.75,
52
- },
53
- synapses: {
54
- initialWeight: 0.1,
55
- learningRate: 0.15,
56
- decayHalfLifeDays: 45,
57
- pruneThreshold: 0.05,
58
- decayAfterDays: 14,
59
- maxDepth: 3,
60
- minActivationWeight: 0.2,
61
- },
62
- research: {
63
- intervalMs: 3_600_000,
64
- initialDelayMs: 300_000,
65
- minDataPoints: 10,
66
- trendWindowDays: 7,
67
- gapMinOccurrences: 5,
68
- synergyMinWeight: 0.5,
69
- templateMinAdaptations: 3,
70
- insightExpiryDays: 30,
71
- },
72
- log: {
73
- level: 'info',
74
- file: path.join(getDataDir(), 'brain.log'),
75
- maxSize: 10 * 1024 * 1024,
76
- maxFiles: 3,
77
- },
78
- retention: {
79
- errorDays: 90,
80
- solutionDays: 365,
81
- insightDays: 30,
82
- },
83
- };
84
-
85
- function applyEnvOverrides(config: BrainConfig): void {
86
- if (process.env['BRAIN_DATA_DIR']) {
87
- config.dataDir = process.env['BRAIN_DATA_DIR'];
88
- config.dbPath = path.join(config.dataDir, 'brain.db');
89
- config.log.file = path.join(config.dataDir, 'brain.log');
90
- }
91
- if (process.env['BRAIN_DB_PATH']) config.dbPath = process.env['BRAIN_DB_PATH'];
92
- if (process.env['BRAIN_LOG_LEVEL']) config.log.level = process.env['BRAIN_LOG_LEVEL'];
93
- if (process.env['BRAIN_PIPE_NAME']) config.ipc.pipeName = process.env['BRAIN_PIPE_NAME'];
94
- if (process.env['BRAIN_API_PORT']) config.api.port = Number(process.env['BRAIN_API_PORT']);
95
- if (process.env['BRAIN_API_ENABLED']) config.api.enabled = process.env['BRAIN_API_ENABLED'] !== 'false';
96
- if (process.env['BRAIN_API_KEY']) config.api.apiKey = process.env['BRAIN_API_KEY'];
97
- if (process.env['BRAIN_MCP_HTTP_PORT']) config.mcpHttp.port = Number(process.env['BRAIN_MCP_HTTP_PORT']);
98
- if (process.env['BRAIN_MCP_HTTP_ENABLED']) config.mcpHttp.enabled = process.env['BRAIN_MCP_HTTP_ENABLED'] !== 'false';
99
- if (process.env['BRAIN_EMBEDDINGS_ENABLED']) config.embeddings.enabled = process.env['BRAIN_EMBEDDINGS_ENABLED'] !== 'false';
100
- if (process.env['BRAIN_EMBEDDINGS_MODEL']) config.embeddings.modelName = process.env['BRAIN_EMBEDDINGS_MODEL'];
101
- }
102
-
103
- function deepMerge(target: Record<string, unknown>, source: Record<string, unknown>): void {
104
- for (const key of Object.keys(source)) {
105
- const val = source[key];
106
- if (val && typeof val === 'object' && !Array.isArray(val) && target[key] && typeof target[key] === 'object') {
107
- deepMerge(target[key] as Record<string, unknown>, val as Record<string, unknown>);
108
- } else if (val !== undefined) {
109
- target[key] = val;
110
- }
111
- }
112
- }
113
-
114
- export function loadConfig(configPath?: string): BrainConfig {
115
- const config = structuredClone(defaults);
116
-
117
- if (configPath) {
118
- const filePath = path.resolve(configPath);
119
- if (fs.existsSync(filePath)) {
120
- const raw = fs.readFileSync(filePath, 'utf-8');
121
- const fileConfig = JSON.parse(raw) as Partial<BrainConfig>;
122
- deepMerge(config as unknown as Record<string, unknown>, fileConfig as unknown as Record<string, unknown>);
123
- }
124
- } else {
125
- const defaultConfigPath = path.join(getDataDir(), 'config.json');
126
- if (fs.existsSync(defaultConfigPath)) {
127
- const raw = fs.readFileSync(defaultConfigPath, 'utf-8');
128
- const fileConfig = JSON.parse(raw) as Partial<BrainConfig>;
129
- deepMerge(config as unknown as Record<string, unknown>, fileConfig as unknown as Record<string, unknown>);
130
- }
131
- }
132
-
133
- applyEnvOverrides(config);
134
- return config;
135
- }
@@ -1,142 +0,0 @@
1
- import http from 'node:http';
2
- import { getEventBus } from '../utils/events.js';
3
- import { getLogger } from '../utils/logger.js';
4
-
5
- export interface DashboardServerOptions {
6
- port: number;
7
- getDashboardHtml: () => string;
8
- getStats: () => unknown;
9
- }
10
-
11
- export class DashboardServer {
12
- private server: http.Server | null = null;
13
- private clients: Set<http.ServerResponse> = new Set();
14
- private logger = getLogger();
15
-
16
- constructor(private options: DashboardServerOptions) {}
17
-
18
- start(): void {
19
- const { port, getDashboardHtml, getStats } = this.options;
20
- const bus = getEventBus();
21
-
22
- this.server = http.createServer((req, res) => {
23
- const url = new URL(req.url ?? '/', `http://localhost:${port}`);
24
-
25
- // CORS
26
- res.setHeader('Access-Control-Allow-Origin', '*');
27
- res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
28
-
29
- if (req.method === 'OPTIONS') {
30
- res.writeHead(204);
31
- res.end();
32
- return;
33
- }
34
-
35
- if (url.pathname === '/events') {
36
- // SSE endpoint
37
- res.writeHead(200, {
38
- 'Content-Type': 'text/event-stream',
39
- 'Cache-Control': 'no-cache',
40
- 'Connection': 'keep-alive',
41
- });
42
- res.write('data: {"type":"connected"}\n\n');
43
-
44
- this.clients.add(res);
45
- req.on('close', () => this.clients.delete(res));
46
- return;
47
- }
48
-
49
- if (url.pathname === '/api/stats') {
50
- const stats = getStats();
51
- res.writeHead(200, { 'Content-Type': 'application/json' });
52
- res.end(JSON.stringify(stats));
53
- return;
54
- }
55
-
56
- if (url.pathname === '/' || url.pathname === '/dashboard') {
57
- const html = getDashboardHtml();
58
- // Inject SSE script into the dashboard
59
- const sseScript = `
60
- <script>
61
- (function(){
62
- const evtSource = new EventSource('/events');
63
- evtSource.onmessage = function(e) {
64
- try {
65
- const data = JSON.parse(e.data);
66
- if (data.type === 'stats_update') {
67
- // Update stat cards
68
- document.querySelectorAll('.stat-number').forEach(el => {
69
- const key = el.parentElement?.querySelector('.stat-label')?.textContent?.toLowerCase();
70
- if (key && data.stats[key] !== undefined) {
71
- el.textContent = Number(data.stats[key]).toLocaleString();
72
- }
73
- });
74
- }
75
- if (data.type === 'event') {
76
- // Flash the activity dot
77
- const dot = document.querySelector('.activity-dot');
78
- if (dot) { dot.style.background = '#ff5577'; setTimeout(() => dot.style.background = '', 500); }
79
- }
80
- } catch {}
81
- };
82
- evtSource.onerror = function() { setTimeout(() => location.reload(), 5000); };
83
- })();
84
- </script>`;
85
- const liveHtml = html.replace('</body>', sseScript + '</body>');
86
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
87
- res.end(liveHtml);
88
- return;
89
- }
90
-
91
- res.writeHead(404, { 'Content-Type': 'text/plain' });
92
- res.end('Not Found');
93
- });
94
-
95
- // Forward Brain events to SSE clients
96
- const eventNames = [
97
- 'error:reported', 'error:resolved', 'solution:applied',
98
- 'solution:created', 'module:registered', 'module:updated',
99
- 'synapse:created', 'synapse:strengthened',
100
- 'insight:created', 'rule:learned',
101
- ] as const;
102
-
103
- for (const eventName of eventNames) {
104
- bus.on(eventName, (data: unknown) => {
105
- this.broadcast({ type: 'event', event: eventName, data });
106
- });
107
- }
108
-
109
- // Periodic stats broadcast (every 30s)
110
- setInterval(() => {
111
- if (this.clients.size > 0) {
112
- const stats = getStats();
113
- this.broadcast({ type: 'stats_update', stats });
114
- }
115
- }, 30_000);
116
-
117
- this.server.listen(port, () => {
118
- this.logger.info(`Dashboard server started on http://localhost:${port}`);
119
- });
120
- }
121
-
122
- stop(): void {
123
- for (const client of this.clients) {
124
- client.end();
125
- }
126
- this.clients.clear();
127
- this.server?.close();
128
- this.server = null;
129
- this.logger.info('Dashboard server stopped');
130
- }
131
-
132
- private broadcast(data: unknown): void {
133
- const msg = `data: ${JSON.stringify(data)}\n\n`;
134
- for (const client of this.clients) {
135
- try {
136
- client.write(msg);
137
- } catch {
138
- this.clients.delete(client);
139
- }
140
- }
141
- }
142
- }
@@ -1,22 +0,0 @@
1
- import Database from 'better-sqlite3';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { getLogger } from '../utils/logger.js';
5
-
6
- export function createConnection(dbPath: string): Database.Database {
7
- const logger = getLogger();
8
- const dir = path.dirname(dbPath);
9
- if (!fs.existsSync(dir)) {
10
- fs.mkdirSync(dir, { recursive: true });
11
- }
12
-
13
- logger.info(`Opening database at ${dbPath}`);
14
- const db = new Database(dbPath);
15
-
16
- db.pragma('journal_mode = WAL');
17
- db.pragma('synchronous = NORMAL');
18
- db.pragma('cache_size = 10000');
19
- db.pragma('foreign_keys = ON');
20
-
21
- return db;
22
- }
@@ -1,120 +0,0 @@
1
- import type Database from 'better-sqlite3';
2
-
3
- export function up(db: Database.Database): void {
4
- db.exec(`
5
- CREATE TABLE IF NOT EXISTS projects (
6
- id INTEGER PRIMARY KEY AUTOINCREMENT,
7
- name TEXT NOT NULL UNIQUE,
8
- path TEXT,
9
- language TEXT,
10
- framework TEXT,
11
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
12
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
13
- );
14
-
15
- CREATE TABLE IF NOT EXISTS terminals (
16
- id INTEGER PRIMARY KEY AUTOINCREMENT,
17
- uuid TEXT NOT NULL UNIQUE,
18
- project_id INTEGER,
19
- pid INTEGER,
20
- shell TEXT,
21
- cwd TEXT,
22
- connected_at TEXT NOT NULL DEFAULT (datetime('now')),
23
- last_seen TEXT NOT NULL DEFAULT (datetime('now')),
24
- disconnected_at TEXT,
25
- FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE SET NULL
26
- );
27
-
28
- CREATE TABLE IF NOT EXISTS errors (
29
- id INTEGER PRIMARY KEY AUTOINCREMENT,
30
- project_id INTEGER NOT NULL,
31
- terminal_id INTEGER,
32
- fingerprint TEXT NOT NULL,
33
- type TEXT NOT NULL,
34
- message TEXT NOT NULL,
35
- raw_output TEXT NOT NULL,
36
- context TEXT,
37
- file_path TEXT,
38
- line_number INTEGER,
39
- column_number INTEGER,
40
- occurrence_count INTEGER NOT NULL DEFAULT 1,
41
- first_seen TEXT NOT NULL DEFAULT (datetime('now')),
42
- last_seen TEXT NOT NULL DEFAULT (datetime('now')),
43
- resolved INTEGER NOT NULL DEFAULT 0,
44
- resolved_at TEXT,
45
- FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
46
- FOREIGN KEY (terminal_id) REFERENCES terminals(id) ON DELETE SET NULL
47
- );
48
-
49
- CREATE TABLE IF NOT EXISTS stack_frames (
50
- id INTEGER PRIMARY KEY AUTOINCREMENT,
51
- error_id INTEGER NOT NULL,
52
- frame_index INTEGER NOT NULL,
53
- file TEXT NOT NULL,
54
- line INTEGER NOT NULL,
55
- "column" INTEGER,
56
- function_name TEXT,
57
- source TEXT,
58
- FOREIGN KEY (error_id) REFERENCES errors(id) ON DELETE CASCADE
59
- );
60
-
61
- CREATE TABLE IF NOT EXISTS solutions (
62
- id INTEGER PRIMARY KEY AUTOINCREMENT,
63
- description TEXT NOT NULL,
64
- commands TEXT,
65
- code_change TEXT,
66
- source TEXT NOT NULL DEFAULT 'manual',
67
- confidence REAL NOT NULL DEFAULT 0.5,
68
- success_count INTEGER NOT NULL DEFAULT 0,
69
- fail_count INTEGER NOT NULL DEFAULT 0,
70
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
71
- updated_at TEXT NOT NULL DEFAULT (datetime('now'))
72
- );
73
-
74
- CREATE TABLE IF NOT EXISTS error_solutions (
75
- id INTEGER PRIMARY KEY AUTOINCREMENT,
76
- error_id INTEGER NOT NULL,
77
- solution_id INTEGER NOT NULL,
78
- applied_at TEXT,
79
- success INTEGER,
80
- FOREIGN KEY (error_id) REFERENCES errors(id) ON DELETE CASCADE,
81
- FOREIGN KEY (solution_id) REFERENCES solutions(id) ON DELETE CASCADE,
82
- UNIQUE(error_id, solution_id)
83
- );
84
-
85
- CREATE TABLE IF NOT EXISTS solution_attempts (
86
- id INTEGER PRIMARY KEY AUTOINCREMENT,
87
- error_solution_id INTEGER NOT NULL,
88
- terminal_id INTEGER,
89
- attempted_at TEXT NOT NULL DEFAULT (datetime('now')),
90
- success INTEGER NOT NULL DEFAULT 0,
91
- output TEXT,
92
- duration_ms INTEGER,
93
- FOREIGN KEY (error_solution_id) REFERENCES error_solutions(id) ON DELETE CASCADE,
94
- FOREIGN KEY (terminal_id) REFERENCES terminals(id) ON DELETE SET NULL
95
- );
96
-
97
- CREATE TABLE IF NOT EXISTS error_chains (
98
- id INTEGER PRIMARY KEY AUTOINCREMENT,
99
- parent_error_id INTEGER NOT NULL,
100
- child_error_id INTEGER NOT NULL,
101
- relationship TEXT NOT NULL DEFAULT 'causes',
102
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
103
- FOREIGN KEY (parent_error_id) REFERENCES errors(id) ON DELETE CASCADE,
104
- FOREIGN KEY (child_error_id) REFERENCES errors(id) ON DELETE CASCADE,
105
- UNIQUE(parent_error_id, child_error_id)
106
- );
107
-
108
- CREATE INDEX IF NOT EXISTS idx_errors_fingerprint ON errors(fingerprint);
109
- CREATE INDEX IF NOT EXISTS idx_errors_project ON errors(project_id);
110
- CREATE INDEX IF NOT EXISTS idx_errors_type ON errors(type);
111
- CREATE INDEX IF NOT EXISTS idx_errors_resolved ON errors(resolved);
112
- CREATE INDEX IF NOT EXISTS idx_errors_last_seen ON errors(last_seen);
113
- CREATE INDEX IF NOT EXISTS idx_stack_frames_error ON stack_frames(error_id);
114
- CREATE INDEX IF NOT EXISTS idx_error_solutions_error ON error_solutions(error_id);
115
- CREATE INDEX IF NOT EXISTS idx_error_solutions_solution ON error_solutions(solution_id);
116
- CREATE INDEX IF NOT EXISTS idx_solution_attempts_es ON solution_attempts(error_solution_id);
117
- CREATE INDEX IF NOT EXISTS idx_terminals_uuid ON terminals(uuid);
118
- CREATE INDEX IF NOT EXISTS idx_terminals_project ON terminals(project_id);
119
- `);
120
- }
@@ -1,38 +0,0 @@
1
- import type Database from 'better-sqlite3';
2
-
3
- export function up(db: Database.Database): void {
4
- db.exec(`
5
- CREATE TABLE IF NOT EXISTS rules (
6
- id INTEGER PRIMARY KEY AUTOINCREMENT,
7
- pattern TEXT NOT NULL,
8
- action TEXT NOT NULL,
9
- description TEXT,
10
- confidence REAL NOT NULL DEFAULT 0.5,
11
- occurrences INTEGER NOT NULL DEFAULT 0,
12
- active INTEGER NOT NULL DEFAULT 1,
13
- project_id INTEGER,
14
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
15
- updated_at TEXT NOT NULL DEFAULT (datetime('now')),
16
- FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE SET NULL
17
- );
18
-
19
- CREATE TABLE IF NOT EXISTS antipatterns (
20
- id INTEGER PRIMARY KEY AUTOINCREMENT,
21
- pattern TEXT NOT NULL,
22
- description TEXT NOT NULL,
23
- severity TEXT NOT NULL DEFAULT 'warning',
24
- suggestion TEXT,
25
- occurrences INTEGER NOT NULL DEFAULT 0,
26
- project_id INTEGER,
27
- global INTEGER NOT NULL DEFAULT 0,
28
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
29
- FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE SET NULL
30
- );
31
-
32
- CREATE INDEX IF NOT EXISTS idx_rules_pattern ON rules(pattern);
33
- CREATE INDEX IF NOT EXISTS idx_rules_active ON rules(active);
34
- CREATE INDEX IF NOT EXISTS idx_rules_project ON rules(project_id);
35
- CREATE INDEX IF NOT EXISTS idx_antipatterns_project ON antipatterns(project_id);
36
- CREATE INDEX IF NOT EXISTS idx_antipatterns_global ON antipatterns(global);
37
- `);
38
- }
@@ -1,53 +0,0 @@
1
- import type Database from 'better-sqlite3';
2
-
3
- export function up(db: Database.Database): void {
4
- db.exec(`
5
- CREATE TABLE IF NOT EXISTS code_modules (
6
- id INTEGER PRIMARY KEY AUTOINCREMENT,
7
- project_id INTEGER NOT NULL,
8
- name TEXT NOT NULL,
9
- file_path TEXT NOT NULL,
10
- language TEXT NOT NULL,
11
- fingerprint TEXT NOT NULL,
12
- description TEXT,
13
- source_hash TEXT NOT NULL,
14
- lines_of_code INTEGER NOT NULL DEFAULT 0,
15
- complexity INTEGER,
16
- reusability_score REAL NOT NULL DEFAULT 0.0,
17
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
18
- updated_at TEXT NOT NULL DEFAULT (datetime('now')),
19
- FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
20
- );
21
-
22
- CREATE TABLE IF NOT EXISTS module_usages (
23
- id INTEGER PRIMARY KEY AUTOINCREMENT,
24
- module_id INTEGER NOT NULL,
25
- used_in_project_id INTEGER NOT NULL,
26
- used_in_file TEXT NOT NULL,
27
- usage_type TEXT NOT NULL DEFAULT 'import',
28
- first_used TEXT NOT NULL DEFAULT (datetime('now')),
29
- last_used TEXT NOT NULL DEFAULT (datetime('now')),
30
- FOREIGN KEY (module_id) REFERENCES code_modules(id) ON DELETE CASCADE,
31
- FOREIGN KEY (used_in_project_id) REFERENCES projects(id) ON DELETE CASCADE
32
- );
33
-
34
- CREATE TABLE IF NOT EXISTS module_similarities (
35
- id INTEGER PRIMARY KEY AUTOINCREMENT,
36
- module_a_id INTEGER NOT NULL,
37
- module_b_id INTEGER NOT NULL,
38
- similarity_score REAL NOT NULL,
39
- computed_at TEXT NOT NULL DEFAULT (datetime('now')),
40
- FOREIGN KEY (module_a_id) REFERENCES code_modules(id) ON DELETE CASCADE,
41
- FOREIGN KEY (module_b_id) REFERENCES code_modules(id) ON DELETE CASCADE,
42
- UNIQUE(module_a_id, module_b_id)
43
- );
44
-
45
- CREATE INDEX IF NOT EXISTS idx_code_modules_project ON code_modules(project_id);
46
- CREATE INDEX IF NOT EXISTS idx_code_modules_fingerprint ON code_modules(fingerprint);
47
- CREATE INDEX IF NOT EXISTS idx_code_modules_language ON code_modules(language);
48
- CREATE INDEX IF NOT EXISTS idx_module_usages_module ON module_usages(module_id);
49
- CREATE INDEX IF NOT EXISTS idx_module_usages_project ON module_usages(used_in_project_id);
50
- CREATE INDEX IF NOT EXISTS idx_module_similarities_a ON module_similarities(module_a_id);
51
- CREATE INDEX IF NOT EXISTS idx_module_similarities_b ON module_similarities(module_b_id);
52
- `);
53
- }