@timmeck/brain 1.9.0 → 2.1.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 (253) hide show
  1. package/README.md +33 -0
  2. package/brain.log +3876 -0
  3. package/{src/cli/commands/dashboard.ts → dashboard.html} +694 -807
  4. package/dist/api/server.d.ts +4 -18
  5. package/dist/api/server.js +4 -173
  6. package/dist/api/server.js.map +1 -1
  7. package/dist/brain.d.ts +2 -0
  8. package/dist/brain.js +15 -4
  9. package/dist/brain.js.map +1 -1
  10. package/dist/cli/colors.d.ts +4 -25
  11. package/dist/cli/colors.js +3 -89
  12. package/dist/cli/colors.js.map +1 -1
  13. package/dist/cli/commands/dashboard.js +21 -2
  14. package/dist/cli/commands/dashboard.js.map +1 -1
  15. package/dist/cli/commands/peers.d.ts +2 -0
  16. package/dist/cli/commands/peers.js +38 -0
  17. package/dist/cli/commands/peers.js.map +1 -0
  18. package/dist/cli/commands/status.js +0 -1
  19. package/dist/cli/commands/status.js.map +1 -1
  20. package/dist/config.js +2 -29
  21. package/dist/config.js.map +1 -1
  22. package/dist/db/connection.d.ts +1 -2
  23. package/dist/db/connection.js +1 -18
  24. package/dist/db/connection.js.map +1 -1
  25. package/dist/index.js +3 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/ipc/__tests__/protocol.test.d.ts +1 -0
  28. package/dist/ipc/__tests__/protocol.test.js +117 -0
  29. package/dist/ipc/__tests__/protocol.test.js.map +1 -0
  30. package/dist/ipc/client.d.ts +1 -16
  31. package/dist/ipc/client.js +1 -100
  32. package/dist/ipc/client.js.map +1 -1
  33. package/dist/ipc/protocol.d.ts +1 -8
  34. package/dist/ipc/protocol.js +1 -28
  35. package/dist/ipc/protocol.js.map +1 -1
  36. package/dist/ipc/router.d.ts +2 -0
  37. package/dist/ipc/router.js +30 -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/learning/confidence-scorer.d.ts +2 -5
  43. package/dist/learning/confidence-scorer.js +4 -19
  44. package/dist/learning/confidence-scorer.js.map +1 -1
  45. package/dist/learning/decay.js +2 -3
  46. package/dist/learning/decay.js.map +1 -1
  47. package/dist/learning/learning-engine.d.ts +2 -5
  48. package/dist/learning/learning-engine.js +3 -15
  49. package/dist/learning/learning-engine.js.map +1 -1
  50. package/dist/mcp/http-server.d.ts +1 -7
  51. package/dist/mcp/http-server.js +6 -117
  52. package/dist/mcp/http-server.js.map +1 -1
  53. package/dist/mcp/server.js +5 -61
  54. package/dist/mcp/server.js.map +1 -1
  55. package/dist/mcp/tools.js +36 -0
  56. package/dist/mcp/tools.js.map +1 -1
  57. package/dist/parsing/parsers/compiler.js +1 -1
  58. package/dist/parsing/parsers/compiler.js.map +1 -1
  59. package/dist/research/research-engine.d.ts +2 -6
  60. package/dist/research/research-engine.js +3 -23
  61. package/dist/research/research-engine.js.map +1 -1
  62. package/dist/services/synapse.service.d.ts +3 -3
  63. package/dist/signals/__tests__/fingerprint.test.d.ts +1 -0
  64. package/dist/signals/__tests__/fingerprint.test.js +118 -0
  65. package/dist/signals/__tests__/fingerprint.test.js.map +1 -0
  66. package/dist/synapses/activation.d.ts +3 -13
  67. package/dist/synapses/activation.js +2 -49
  68. package/dist/synapses/activation.js.map +1 -1
  69. package/dist/synapses/decay.d.ts +2 -11
  70. package/dist/synapses/decay.js +2 -26
  71. package/dist/synapses/decay.js.map +1 -1
  72. package/dist/synapses/hebbian.d.ts +2 -13
  73. package/dist/synapses/hebbian.js +2 -35
  74. package/dist/synapses/hebbian.js.map +1 -1
  75. package/dist/synapses/pathfinder.d.ts +2 -14
  76. package/dist/synapses/pathfinder.js +2 -49
  77. package/dist/synapses/pathfinder.js.map +1 -1
  78. package/dist/synapses/synapse-manager.d.ts +7 -23
  79. package/dist/synapses/synapse-manager.js +6 -63
  80. package/dist/synapses/synapse-manager.js.map +1 -1
  81. package/dist/types/ipc.types.d.ts +1 -11
  82. package/dist/utils/__tests__/hash.test.d.ts +1 -0
  83. package/dist/utils/__tests__/hash.test.js +32 -0
  84. package/dist/utils/__tests__/hash.test.js.map +1 -0
  85. package/dist/utils/__tests__/paths.test.d.ts +1 -0
  86. package/dist/utils/__tests__/paths.test.js +75 -0
  87. package/dist/utils/__tests__/paths.test.js.map +1 -0
  88. package/dist/utils/events.d.ts +4 -8
  89. package/dist/utils/events.js +2 -14
  90. package/dist/utils/events.js.map +1 -1
  91. package/dist/utils/hash.d.ts +1 -1
  92. package/dist/utils/hash.js +1 -4
  93. package/dist/utils/hash.js.map +1 -1
  94. package/dist/utils/logger.d.ts +3 -2
  95. package/dist/utils/logger.js +8 -35
  96. package/dist/utils/logger.js.map +1 -1
  97. package/dist/utils/paths.d.ts +2 -1
  98. package/dist/utils/paths.js +4 -13
  99. package/dist/utils/paths.js.map +1 -1
  100. package/eslint.config.js +14 -0
  101. package/package.json +56 -49
  102. package/BRAIN_PLAN.md +0 -3324
  103. package/reddit_post.md +0 -45
  104. package/src/api/server.ts +0 -395
  105. package/src/brain.ts +0 -313
  106. package/src/cli/colors.ts +0 -116
  107. package/src/cli/commands/config.ts +0 -169
  108. package/src/cli/commands/doctor.ts +0 -124
  109. package/src/cli/commands/explain.ts +0 -83
  110. package/src/cli/commands/export.ts +0 -31
  111. package/src/cli/commands/import.ts +0 -199
  112. package/src/cli/commands/insights.ts +0 -65
  113. package/src/cli/commands/learn.ts +0 -24
  114. package/src/cli/commands/modules.ts +0 -53
  115. package/src/cli/commands/network.ts +0 -67
  116. package/src/cli/commands/projects.ts +0 -42
  117. package/src/cli/commands/query.ts +0 -120
  118. package/src/cli/commands/start.ts +0 -105
  119. package/src/cli/commands/status.ts +0 -75
  120. package/src/cli/commands/stop.ts +0 -34
  121. package/src/cli/ipc-helper.ts +0 -22
  122. package/src/cli/update-check.ts +0 -63
  123. package/src/code/analyzer.ts +0 -117
  124. package/src/code/fingerprint.ts +0 -87
  125. package/src/code/matcher.ts +0 -129
  126. package/src/code/parsers/generic.ts +0 -29
  127. package/src/code/parsers/python.ts +0 -54
  128. package/src/code/parsers/typescript.ts +0 -65
  129. package/src/code/registry.ts +0 -60
  130. package/src/code/scorer.ts +0 -120
  131. package/src/config.ts +0 -135
  132. package/src/dashboard/server.ts +0 -142
  133. package/src/db/connection.ts +0 -22
  134. package/src/db/migrations/001_core_schema.ts +0 -120
  135. package/src/db/migrations/002_learning_schema.ts +0 -38
  136. package/src/db/migrations/003_code_schema.ts +0 -53
  137. package/src/db/migrations/004_synapses_schema.ts +0 -57
  138. package/src/db/migrations/005_fts_indexes.ts +0 -78
  139. package/src/db/migrations/006_synapses_phase3.ts +0 -17
  140. package/src/db/migrations/007_feedback.ts +0 -13
  141. package/src/db/migrations/008_git_integration.ts +0 -38
  142. package/src/db/migrations/009_embeddings.ts +0 -8
  143. package/src/db/migrations/index.ts +0 -70
  144. package/src/db/repositories/antipattern.repository.ts +0 -66
  145. package/src/db/repositories/code-module.repository.ts +0 -142
  146. package/src/db/repositories/error.repository.ts +0 -189
  147. package/src/db/repositories/insight.repository.ts +0 -99
  148. package/src/db/repositories/notification.repository.ts +0 -66
  149. package/src/db/repositories/project.repository.ts +0 -93
  150. package/src/db/repositories/rule.repository.ts +0 -108
  151. package/src/db/repositories/solution.repository.ts +0 -154
  152. package/src/db/repositories/synapse.repository.ts +0 -163
  153. package/src/db/repositories/terminal.repository.ts +0 -101
  154. package/src/embeddings/engine.ts +0 -238
  155. package/src/hooks/post-tool-use.ts +0 -92
  156. package/src/hooks/post-write.ts +0 -129
  157. package/src/index.ts +0 -63
  158. package/src/ipc/client.ts +0 -118
  159. package/src/ipc/protocol.ts +0 -35
  160. package/src/ipc/router.ts +0 -133
  161. package/src/ipc/server.ts +0 -176
  162. package/src/learning/confidence-scorer.ts +0 -80
  163. package/src/learning/decay.ts +0 -46
  164. package/src/learning/learning-engine.ts +0 -170
  165. package/src/learning/pattern-extractor.ts +0 -90
  166. package/src/learning/rule-generator.ts +0 -74
  167. package/src/main.rs:10:5 +0 -0
  168. package/src/matching/error-matcher.ts +0 -166
  169. package/src/matching/fingerprint.ts +0 -34
  170. package/src/matching/similarity.ts +0 -61
  171. package/src/matching/tfidf.ts +0 -74
  172. package/src/matching/tokenizer.ts +0 -41
  173. package/src/mcp/auto-detect.ts +0 -93
  174. package/src/mcp/http-server.ts +0 -140
  175. package/src/mcp/server.ts +0 -73
  176. package/src/mcp/tools.ts +0 -328
  177. package/src/parsing/error-parser.ts +0 -28
  178. package/src/parsing/parsers/compiler.ts +0 -93
  179. package/src/parsing/parsers/generic.ts +0 -28
  180. package/src/parsing/parsers/go.ts +0 -97
  181. package/src/parsing/parsers/node.ts +0 -69
  182. package/src/parsing/parsers/python.ts +0 -62
  183. package/src/parsing/parsers/rust.ts +0 -50
  184. package/src/parsing/parsers/shell.ts +0 -42
  185. package/src/parsing/types.ts +0 -47
  186. package/src/research/gap-analyzer.ts +0 -135
  187. package/src/research/insight-generator.ts +0 -123
  188. package/src/research/research-engine.ts +0 -116
  189. package/src/research/synergy-detector.ts +0 -126
  190. package/src/research/template-extractor.ts +0 -130
  191. package/src/research/trend-analyzer.ts +0 -127
  192. package/src/services/analytics.service.ts +0 -226
  193. package/src/services/code.service.ts +0 -271
  194. package/src/services/error.service.ts +0 -266
  195. package/src/services/git.service.ts +0 -132
  196. package/src/services/notification.service.ts +0 -41
  197. package/src/services/prevention.service.ts +0 -159
  198. package/src/services/research.service.ts +0 -98
  199. package/src/services/solution.service.ts +0 -174
  200. package/src/services/synapse.service.ts +0 -59
  201. package/src/services/terminal.service.ts +0 -81
  202. package/src/synapses/activation.ts +0 -80
  203. package/src/synapses/decay.ts +0 -38
  204. package/src/synapses/hebbian.ts +0 -69
  205. package/src/synapses/pathfinder.ts +0 -81
  206. package/src/synapses/synapse-manager.ts +0 -113
  207. package/src/types/code.types.ts +0 -52
  208. package/src/types/config.types.ts +0 -103
  209. package/src/types/error.types.ts +0 -67
  210. package/src/types/ipc.types.ts +0 -8
  211. package/src/types/mcp.types.ts +0 -53
  212. package/src/types/research.types.ts +0 -28
  213. package/src/types/solution.types.ts +0 -30
  214. package/src/types/synapse.types.ts +0 -50
  215. package/src/utils/events.ts +0 -45
  216. package/src/utils/hash.ts +0 -5
  217. package/src/utils/logger.ts +0 -48
  218. package/src/utils/paths.ts +0 -19
  219. package/tests/e2e/test_code_intelligence.py +0 -1015
  220. package/tests/e2e/test_error_memory.py +0 -451
  221. package/tests/e2e/test_full_integration.py +0 -534
  222. package/tests/fixtures/code-modules/modules.ts +0 -83
  223. package/tests/fixtures/errors/go.ts +0 -9
  224. package/tests/fixtures/errors/node.ts +0 -24
  225. package/tests/fixtures/errors/python.ts +0 -21
  226. package/tests/fixtures/errors/rust.ts +0 -25
  227. package/tests/fixtures/errors/shell.ts +0 -15
  228. package/tests/fixtures/solutions/solutions.ts +0 -27
  229. package/tests/helpers/setup-db.ts +0 -52
  230. package/tests/integration/code-flow.test.ts +0 -86
  231. package/tests/integration/error-flow.test.ts +0 -83
  232. package/tests/integration/ipc-flow.test.ts +0 -166
  233. package/tests/integration/learning-cycle.test.ts +0 -82
  234. package/tests/integration/synapse-flow.test.ts +0 -117
  235. package/tests/unit/code/analyzer.test.ts +0 -58
  236. package/tests/unit/code/fingerprint.test.ts +0 -51
  237. package/tests/unit/code/scorer.test.ts +0 -55
  238. package/tests/unit/learning/confidence-scorer.test.ts +0 -60
  239. package/tests/unit/learning/decay.test.ts +0 -45
  240. package/tests/unit/learning/pattern-extractor.test.ts +0 -50
  241. package/tests/unit/matching/error-matcher.test.ts +0 -69
  242. package/tests/unit/matching/fingerprint.test.ts +0 -47
  243. package/tests/unit/matching/similarity.test.ts +0 -65
  244. package/tests/unit/matching/tfidf.test.ts +0 -71
  245. package/tests/unit/matching/tokenizer.test.ts +0 -83
  246. package/tests/unit/parsing/parsers.test.ts +0 -113
  247. package/tests/unit/research/gap-analyzer.test.ts +0 -45
  248. package/tests/unit/research/trend-analyzer.test.ts +0 -45
  249. package/tests/unit/synapses/activation.test.ts +0 -80
  250. package/tests/unit/synapses/decay.test.ts +0 -27
  251. package/tests/unit/synapses/hebbian.test.ts +0 -96
  252. package/tests/unit/synapses/pathfinder.test.ts +0 -72
  253. package/tsconfig.json +0 -18
@@ -1,126 +0,0 @@
1
- import type { ResearchConfig } from '../types/config.types.js';
2
- import type { SynapseRepository } from '../db/repositories/synapse.repository.js';
3
- import type { CodeModuleRepository } from '../db/repositories/code-module.repository.js';
4
- import type { SolutionRepository } from '../db/repositories/solution.repository.js';
5
- import type { ErrorRepository } from '../db/repositories/error.repository.js';
6
- import type { ProjectRepository } from '../db/repositories/project.repository.js';
7
- import type { InsightRepository } from '../db/repositories/insight.repository.js';
8
- import { getLogger } from '../utils/logger.js';
9
-
10
- /**
11
- * Detects synergies: module pairs, transferable solutions, workflow patterns.
12
- */
13
- export class SynergyDetector {
14
- private logger = getLogger();
15
-
16
- constructor(
17
- private synapseRepo: SynapseRepository,
18
- private codeModuleRepo: CodeModuleRepository,
19
- private solutionRepo: SolutionRepository,
20
- private errorRepo: ErrorRepository,
21
- private projectRepo: ProjectRepository,
22
- private insightRepo: InsightRepository,
23
- private config: ResearchConfig,
24
- ) {}
25
-
26
- detect(): number {
27
- let insightsCreated = 0;
28
-
29
- insightsCreated += this.findModuleSynergies();
30
- insightsCreated += this.findTransferableSolutions();
31
-
32
- this.logger.info(`Synergy detection complete: ${insightsCreated} insights`);
33
- return insightsCreated;
34
- }
35
-
36
- private findModuleSynergies(): number {
37
- const strongSynapses = this.synapseRepo.findByWeight(this.config.synergyMinWeight);
38
- const modulePairs = strongSynapses.filter(s =>
39
- s.source_type === 'code_module' &&
40
- s.target_type === 'code_module' &&
41
- s.synapse_type === 'co_occurs',
42
- );
43
-
44
- let count = 0;
45
- const expiresAt = new Date(Date.now() + this.config.insightExpiryDays * 86400000).toISOString();
46
-
47
- for (const synapse of modulePairs) {
48
- const sourceModule = this.codeModuleRepo.getById(synapse.source_id);
49
- const targetModule = this.codeModuleRepo.getById(synapse.target_id);
50
- if (!sourceModule || !targetModule) continue;
51
-
52
- this.insightRepo.create({
53
- type: 'correlation',
54
- title: `Strong module pair: ${sourceModule.name} + ${targetModule.name}`,
55
- description: `These modules co-occur with weight ${synapse.weight.toFixed(2)}. Consider combining into a shared package.`,
56
- evidence: JSON.stringify({
57
- sourceId: sourceModule.id,
58
- targetId: targetModule.id,
59
- sourceName: sourceModule.name,
60
- targetName: targetModule.name,
61
- weight: synapse.weight,
62
- }),
63
- priority: Math.min(70, Math.round(synapse.weight * 70)),
64
- project_id: sourceModule.project_id,
65
- active: 1,
66
- expires_at: expiresAt,
67
- });
68
- count++;
69
- }
70
-
71
- return count;
72
- }
73
-
74
- private findTransferableSolutions(): number {
75
- const projects = this.projectRepo.getAll();
76
- if (projects.length < 2) return 0;
77
-
78
- let count = 0;
79
- const expiresAt = new Date(Date.now() + this.config.insightExpiryDays * 86400000).toISOString();
80
-
81
- for (let i = 0; i < projects.length; i++) {
82
- for (let j = i + 1; j < projects.length; j++) {
83
- const projectA = projects[i]!;
84
- const projectB = projects[j]!;
85
-
86
- const errorsA = this.errorRepo.findByProject(projectA.id);
87
- const errorsB = this.errorRepo.findUnresolved(projectB.id);
88
-
89
- const transferable: number[] = [];
90
-
91
- for (const errorB of errorsB) {
92
- const matchingA = errorsA.filter(a => a.type === errorB.type && a.resolved);
93
- for (const matchA of matchingA) {
94
- const solutions = this.solutionRepo.findForError(matchA.id);
95
- for (const sol of solutions) {
96
- const rate = this.solutionRepo.successRate(sol.id);
97
- if (rate >= 0.5 && !transferable.includes(sol.id)) {
98
- transferable.push(sol.id);
99
- }
100
- }
101
- }
102
- }
103
-
104
- if (transferable.length >= 2) {
105
- this.insightRepo.create({
106
- type: 'suggestion',
107
- title: `${projectA.name} has solutions for ${projectB.name}`,
108
- description: `${transferable.length} successful solutions from ${projectA.name} could help resolve errors in ${projectB.name}.`,
109
- evidence: JSON.stringify({
110
- sourceProject: projectA.id,
111
- targetProject: projectB.id,
112
- solutionIds: transferable,
113
- }),
114
- priority: 50,
115
- project_id: projectB.id,
116
- active: 1,
117
- expires_at: expiresAt,
118
- });
119
- count++;
120
- }
121
- }
122
- }
123
-
124
- return count;
125
- }
126
- }
@@ -1,130 +0,0 @@
1
- import type { ResearchConfig } from '../types/config.types.js';
2
- import type { CodeModuleRepository } from '../db/repositories/code-module.repository.js';
3
- import type { ProjectRepository } from '../db/repositories/project.repository.js';
4
- import type { InsightRepository } from '../db/repositories/insight.repository.js';
5
- import { getLogger } from '../utils/logger.js';
6
-
7
- /**
8
- * Identifies code modules adapted across projects that can be generalized into templates.
9
- */
10
- export class TemplateExtractor {
11
- private logger = getLogger();
12
-
13
- constructor(
14
- private codeModuleRepo: CodeModuleRepository,
15
- private projectRepo: ProjectRepository,
16
- private insightRepo: InsightRepository,
17
- private config: ResearchConfig,
18
- ) {}
19
-
20
- extract(): number {
21
- let insightsCreated = 0;
22
-
23
- insightsCreated += this.findReusableModules();
24
- insightsCreated += this.findTemplatingCandidates();
25
-
26
- this.logger.info(`Template extraction complete: ${insightsCreated} insights`);
27
- return insightsCreated;
28
- }
29
-
30
- private findReusableModules(): number {
31
- const projects = this.projectRepo.getAll();
32
- if (projects.length < 2) return 0;
33
-
34
- // Collect all modules grouped by fingerprint
35
- const byFingerprint = new Map<string, Array<{ projectId: number; projectName: string; moduleId: number; moduleName: string }>>();
36
-
37
- for (const project of projects) {
38
- const modules = this.codeModuleRepo.findByProject(project.id);
39
- for (const mod of modules) {
40
- const existing = byFingerprint.get(mod.fingerprint) ?? [];
41
- existing.push({
42
- projectId: project.id,
43
- projectName: project.name,
44
- moduleId: mod.id,
45
- moduleName: mod.name,
46
- });
47
- byFingerprint.set(mod.fingerprint, existing);
48
- }
49
- }
50
-
51
- let count = 0;
52
- const expiresAt = new Date(Date.now() + this.config.insightExpiryDays * 86400000).toISOString();
53
-
54
- for (const [fingerprint, usages] of byFingerprint) {
55
- const uniqueProjects = new Set(usages.map(u => u.projectId));
56
- if (uniqueProjects.size >= this.config.templateMinAdaptations) {
57
- const moduleName = usages[0]!.moduleName;
58
- this.insightRepo.create({
59
- type: 'pattern',
60
- title: `Shared module candidate: ${moduleName}`,
61
- description: `Module "${moduleName}" appears identically in ${uniqueProjects.size} projects. Extract as a shared library.`,
62
- evidence: JSON.stringify({
63
- fingerprint,
64
- projectCount: uniqueProjects.size,
65
- usages: usages.map(u => ({ project: u.projectName, moduleId: u.moduleId })),
66
- }),
67
- priority: Math.min(80, 30 + uniqueProjects.size * 15),
68
- project_id: null,
69
- active: 1,
70
- expires_at: expiresAt,
71
- });
72
- count++;
73
- }
74
- }
75
-
76
- return count;
77
- }
78
-
79
- private findTemplatingCandidates(): number {
80
- const projects = this.projectRepo.getAll();
81
- if (projects.length < 2) return 0;
82
-
83
- // Group modules by name across projects (same name, different fingerprint = adaptation)
84
- const byName = new Map<string, Array<{ projectId: number; projectName: string; moduleId: number; reusability: number }>>();
85
-
86
- for (const project of projects) {
87
- const modules = this.codeModuleRepo.findByProject(project.id);
88
- for (const mod of modules) {
89
- const existing = byName.get(mod.name) ?? [];
90
- existing.push({
91
- projectId: project.id,
92
- projectName: project.name,
93
- moduleId: mod.id,
94
- reusability: mod.reusability_score,
95
- });
96
- byName.set(mod.name, existing);
97
- }
98
- }
99
-
100
- let count = 0;
101
- const expiresAt = new Date(Date.now() + this.config.insightExpiryDays * 86400000).toISOString();
102
-
103
- for (const [name, usages] of byName) {
104
- const uniqueProjects = new Set(usages.map(u => u.projectId));
105
- if (uniqueProjects.size >= this.config.templateMinAdaptations) {
106
- const avgReusability = usages.reduce((sum, u) => sum + u.reusability, 0) / usages.length;
107
- if (avgReusability >= 0.5) {
108
- this.insightRepo.create({
109
- type: 'suggestion',
110
- title: `Template candidate: ${name}`,
111
- description: `"${name}" exists in ${uniqueProjects.size} projects as adaptations (avg reusability ${Math.round(avgReusability * 100)}%). Generalize into parameterized template.`,
112
- evidence: JSON.stringify({
113
- name,
114
- projectCount: uniqueProjects.size,
115
- avgReusability,
116
- usages: usages.map(u => ({ project: u.projectName, moduleId: u.moduleId })),
117
- }),
118
- priority: Math.min(75, 25 + uniqueProjects.size * 10 + Math.round(avgReusability * 20)),
119
- project_id: null,
120
- active: 1,
121
- expires_at: expiresAt,
122
- });
123
- count++;
124
- }
125
- }
126
- }
127
-
128
- return count;
129
- }
130
- }
@@ -1,127 +0,0 @@
1
- import type { ResearchConfig } from '../types/config.types.js';
2
- import type { ErrorRepository } from '../db/repositories/error.repository.js';
3
- import type { SolutionRepository } from '../db/repositories/solution.repository.js';
4
- import type { ProjectRepository } from '../db/repositories/project.repository.js';
5
- import type { InsightRepository } from '../db/repositories/insight.repository.js';
6
- import { getLogger } from '../utils/logger.js';
7
-
8
- /**
9
- * Analyzes error frequency and solution success rate trends over time windows.
10
- */
11
- export class TrendAnalyzer {
12
- private logger = getLogger();
13
-
14
- constructor(
15
- private errorRepo: ErrorRepository,
16
- private solutionRepo: SolutionRepository,
17
- private projectRepo: ProjectRepository,
18
- private insightRepo: InsightRepository,
19
- private config: ResearchConfig,
20
- ) {}
21
-
22
- analyze(): number {
23
- const projects = this.projectRepo.getAll();
24
- let insightsCreated = 0;
25
-
26
- for (const project of projects) {
27
- insightsCreated += this.analyzeErrorTrend(project.id, project.name);
28
- insightsCreated += this.analyzeSolutionTrend(project.id, project.name);
29
- }
30
-
31
- this.logger.info(`Trend analysis complete: ${insightsCreated} insights`);
32
- return insightsCreated;
33
- }
34
-
35
- private analyzeErrorTrend(projectId: number, projectName: string): number {
36
- const windowDays = this.config.trendWindowDays;
37
- const now = Date.now();
38
- const recentSince = new Date(now - windowDays * 86400000).toISOString();
39
- const previousSince = new Date(now - windowDays * 2 * 86400000).toISOString();
40
-
41
- const recentErrors = this.errorRepo.countSince(recentSince, projectId);
42
- const allSinceDouble = this.errorRepo.countSince(previousSince, projectId);
43
- const previousErrors = allSinceDouble - recentErrors;
44
-
45
- if (previousErrors <= 0) return 0;
46
-
47
- const changeRate = (recentErrors - previousErrors) / previousErrors;
48
- const expiresAt = new Date(Date.now() + this.config.insightExpiryDays * 86400000).toISOString();
49
-
50
- if (changeRate > 0.5) {
51
- this.insightRepo.create({
52
- type: 'warning',
53
- title: `Error rate rising in ${projectName}`,
54
- description: `${Math.round(changeRate * 100)}% more errors in the last ${windowDays} days vs previous window. Check recent changes: new dependencies, refactoring, or API changes.`,
55
- evidence: JSON.stringify({ recentErrors, previousErrors, changeRate, windowDays }),
56
- priority: Math.min(90, 50 + Math.round(changeRate * 30)),
57
- project_id: projectId,
58
- active: 1,
59
- expires_at: expiresAt,
60
- });
61
- return 1;
62
- }
63
-
64
- if (changeRate < -0.3) {
65
- this.insightRepo.create({
66
- type: 'pattern',
67
- title: `Error rate declining in ${projectName}`,
68
- description: `${Math.round(-changeRate * 100)}% fewer errors in the last ${windowDays} days. Whatever you're doing is working.`,
69
- evidence: JSON.stringify({ recentErrors, previousErrors, changeRate, windowDays }),
70
- priority: 20,
71
- project_id: projectId,
72
- active: 1,
73
- expires_at: expiresAt,
74
- });
75
- return 1;
76
- }
77
-
78
- return 0;
79
- }
80
-
81
- private analyzeSolutionTrend(projectId: number, projectName: string): number {
82
- const errors = this.errorRepo.findByProject(projectId);
83
- if (errors.length < this.config.minDataPoints) return 0;
84
-
85
- let totalRate = 0;
86
- let recentRate = 0;
87
- let totalCount = 0;
88
- let recentCount = 0;
89
- const recentCutoff = new Date(Date.now() - this.config.trendWindowDays * 86400000).toISOString();
90
-
91
- for (const error of errors) {
92
- const solutions = this.solutionRepo.findForError(error.id);
93
- for (const sol of solutions) {
94
- const rate = this.solutionRepo.successRate(sol.id);
95
- totalRate += rate;
96
- totalCount++;
97
-
98
- if (sol.updated_at >= recentCutoff) {
99
- recentRate += rate;
100
- recentCount++;
101
- }
102
- }
103
- }
104
-
105
- if (totalCount === 0 || recentCount === 0) return 0;
106
-
107
- const avgTotal = totalRate / totalCount;
108
- const avgRecent = recentRate / recentCount;
109
-
110
- if (avgRecent < avgTotal - 0.15 && totalCount >= this.config.minDataPoints) {
111
- const expiresAt = new Date(Date.now() + this.config.insightExpiryDays * 86400000).toISOString();
112
- this.insightRepo.create({
113
- type: 'warning',
114
- title: `Solution quality declining in ${projectName}`,
115
- description: `Recent success rate ${Math.round(avgRecent * 100)}% vs overall ${Math.round(avgTotal * 100)}%. Solutions are becoming less effective.`,
116
- evidence: JSON.stringify({ avgRecent, avgTotal, recentCount, totalCount }),
117
- priority: 60,
118
- project_id: projectId,
119
- active: 1,
120
- expires_at: expiresAt,
121
- });
122
- return 1;
123
- }
124
-
125
- return 0;
126
- }
127
- }
@@ -1,226 +0,0 @@
1
- import type { ErrorRecord } from '../types/error.types.js';
2
- import type { ErrorRepository } from '../db/repositories/error.repository.js';
3
- import type { SolutionRepository } from '../db/repositories/solution.repository.js';
4
- import type { CodeModuleRepository } from '../db/repositories/code-module.repository.js';
5
- import type { RuleRepository } from '../db/repositories/rule.repository.js';
6
- import type { AntipatternRepository } from '../db/repositories/antipattern.repository.js';
7
- import type { InsightRepository } from '../db/repositories/insight.repository.js';
8
- import type { SynapseManager } from '../synapses/synapse-manager.js';
9
- import type { NetworkStats } from '../types/synapse.types.js';
10
-
11
- export interface ProjectSummary {
12
- errors: { total: number; unresolved: number; last7d: number };
13
- solutions: { total: number };
14
- rules: { active: number };
15
- antipatterns: { total: number };
16
- modules: { total: number };
17
- insights: { active: number };
18
- healthScore?: number;
19
- }
20
-
21
- export interface NetworkOverview {
22
- stats: NetworkStats;
23
- strongestSynapses: Array<{
24
- id: number;
25
- source: string;
26
- target: string;
27
- type: string;
28
- weight: number;
29
- }>;
30
- }
31
-
32
- export class AnalyticsService {
33
- constructor(
34
- private errorRepo: ErrorRepository,
35
- private solutionRepo: SolutionRepository,
36
- private codeModuleRepo: CodeModuleRepository,
37
- private ruleRepo: RuleRepository,
38
- private antipatternRepo: AntipatternRepository,
39
- private insightRepo: InsightRepository,
40
- private synapseManager: SynapseManager,
41
- ) {}
42
-
43
- getSummary(projectId?: number): ProjectSummary {
44
- const sevenDaysAgo = new Date(Date.now() - 7 * 86400000).toISOString();
45
-
46
- const unresolvedErrors = this.errorRepo.findUnresolved(projectId);
47
- const allErrors = projectId ? this.errorRepo.findByProject(projectId) : [];
48
- const last7dCount = this.errorRepo.countSince(sevenDaysAgo, projectId);
49
-
50
- const rules = this.ruleRepo.findActive(projectId);
51
- const antipatterns = projectId
52
- ? this.antipatternRepo.findByProject(projectId)
53
- : this.antipatternRepo.findGlobal();
54
-
55
- const moduleCount = projectId
56
- ? this.codeModuleRepo.findByProject(projectId).length
57
- : this.codeModuleRepo.countAll();
58
- const insights = this.insightRepo.findActive(projectId);
59
-
60
- return {
61
- errors: {
62
- total: allErrors.length,
63
- unresolved: unresolvedErrors.length,
64
- last7d: last7dCount,
65
- },
66
- solutions: { total: 0 }, // solutions are global, not per-project
67
- rules: { active: rules.length },
68
- antipatterns: { total: antipatterns.length },
69
- modules: { total: moduleCount },
70
- insights: { active: insights.length },
71
- };
72
- }
73
-
74
- computeHealthScore(projectId?: number): number {
75
- const summary = this.getSummary(projectId);
76
- const networkStats = this.synapseManager.getNetworkStats();
77
-
78
- let score = 0;
79
- let maxScore = 0;
80
-
81
- // Data Volume (30 points)
82
- maxScore += 30;
83
- const dataVolume = summary.errors.total + (summary.modules.total * 2) + summary.solutions.total;
84
- score += Math.min(30, dataVolume * 0.3);
85
-
86
- // Synapse Density (20 points) - more connections = richer network
87
- maxScore += 20;
88
- const synapseDensity = networkStats.totalSynapses / Math.max(1, networkStats.totalNodes);
89
- score += Math.min(20, synapseDensity * 5);
90
-
91
- // Solution Coverage (20 points) - resolved errors vs total
92
- maxScore += 20;
93
- if (summary.errors.total > 0) {
94
- const resolvedRate = 1 - (summary.errors.unresolved / summary.errors.total);
95
- score += resolvedRate * 20;
96
- } else {
97
- score += 10; // No errors = neutral
98
- }
99
-
100
- // Learning Activity (15 points) - active rules + insights
101
- maxScore += 15;
102
- const learningActivity = summary.rules.active + summary.insights.active;
103
- score += Math.min(15, learningActivity * 1.5);
104
-
105
- // Error Trend (15 points) - fewer recent errors = better
106
- maxScore += 15;
107
- if (summary.errors.total > 0) {
108
- const recentRatio = summary.errors.last7d / Math.max(1, summary.errors.total);
109
- // Low recent ratio = health is good (errors decreasing)
110
- score += Math.max(0, 15 - recentRatio * 30);
111
- } else {
112
- score += 15;
113
- }
114
-
115
- return Math.round((score / maxScore) * 100);
116
- }
117
-
118
- getTimeSeries(projectId?: number, days: number = 30): Array<{ date: string; errors: number; solutions: number }> {
119
- const series: Array<{ date: string; errors: number; solutions: number }> = [];
120
-
121
- for (let i = days - 1; i >= 0; i--) {
122
- const dayStart = new Date(Date.now() - (i + 1) * 86400000).toISOString();
123
- const dayEnd = new Date(Date.now() - i * 86400000).toISOString();
124
-
125
- const errorsInDay = this.errorRepo.countSince(dayStart, projectId) - this.errorRepo.countSince(dayEnd, projectId);
126
-
127
- series.push({
128
- date: dayStart.split('T')[0]!,
129
- errors: Math.max(0, errorsInDay),
130
- solutions: 0, // Approximation
131
- });
132
- }
133
-
134
- return series;
135
- }
136
-
137
- explainError(errorId: number): {
138
- error: ErrorRecord | undefined;
139
- solutions: Array<{ id: number; description: string; confidence: number; successRate: number }>;
140
- chain: { parents: ErrorRecord[]; children: ErrorRecord[] };
141
- relatedErrors: Array<{ id: number; type: string; message: string; similarity: number }>;
142
- rules: Array<{ id: number; pattern: string; action: string; confidence: number }>;
143
- insights: Array<{ id: number; type: string; title: string }>;
144
- synapseConnections: number;
145
- } {
146
- const error = this.errorRepo.getById(errorId);
147
- if (!error) {
148
- return {
149
- error: undefined, solutions: [], chain: { parents: [], children: [] },
150
- relatedErrors: [], rules: [], insights: [], synapseConnections: 0,
151
- };
152
- }
153
-
154
- // Solutions
155
- const solutions = this.solutionRepo.findForError(errorId).map(s => ({
156
- id: s.id,
157
- description: s.description,
158
- confidence: s.confidence,
159
- successRate: this.solutionRepo.successRate(s.id),
160
- }));
161
-
162
- // Error chain
163
- const parents = this.errorRepo.findChainParents(errorId);
164
- const children = this.errorRepo.findChainChildren(errorId);
165
-
166
- // Related via synapses
167
- const context = this.synapseManager.getErrorContext(errorId);
168
- const relatedErrors = context.relatedErrors.map(r => {
169
- const e = this.errorRepo.getById(r.node.id);
170
- return {
171
- id: r.node.id,
172
- type: e?.type ?? 'unknown',
173
- message: e?.message ?? '',
174
- similarity: r.activation,
175
- };
176
- });
177
-
178
- // Prevention rules
179
- const matchedRules = this.ruleRepo.findActive(error.project_id);
180
- const rules = matchedRules
181
- .filter(r => {
182
- try { return new RegExp(r.pattern, 'i').test(`${error.type}: ${error.message}`); }
183
- catch { return false; }
184
- })
185
- .map(r => ({ id: r.id, pattern: r.pattern, action: r.action, confidence: r.confidence }));
186
-
187
- // Related insights
188
- const insights = context.insights.map(i => ({
189
- id: i.node.id,
190
- type: i.node.type,
191
- title: `Insight #${i.node.id}`,
192
- }));
193
-
194
- // Total synapse connections
195
- const allConnections = this.synapseManager.activate({ type: 'error', id: errorId });
196
-
197
- return {
198
- error,
199
- solutions,
200
- chain: { parents, children },
201
- relatedErrors,
202
- rules,
203
- insights,
204
- synapseConnections: allConnections.length,
205
- };
206
- }
207
-
208
- getNetworkOverview(limit: number = 10): NetworkOverview {
209
- const stats = this.synapseManager.getNetworkStats();
210
- // Use diverse sampling for dashboard (spread across synapse types)
211
- const diverse = limit >= 30
212
- ? this.synapseManager.getDiverseSynapses(Math.ceil(limit / 3))
213
- : this.synapseManager.getStrongestSynapses(limit);
214
-
215
- return {
216
- stats,
217
- strongestSynapses: diverse.map(s => ({
218
- id: s.id,
219
- source: `${s.source_type}:${s.source_id}`,
220
- target: `${s.target_type}:${s.target_id}`,
221
- type: s.synapse_type,
222
- weight: s.weight,
223
- })),
224
- };
225
- }
226
- }