@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,123 +0,0 @@
1
- import type { ResearchConfig } from '../types/config.types.js';
2
- import type { ProjectRepository } from '../db/repositories/project.repository.js';
3
- import type { ErrorRepository } from '../db/repositories/error.repository.js';
4
- import type { SolutionRepository } from '../db/repositories/solution.repository.js';
5
- import type { CodeModuleRepository } from '../db/repositories/code-module.repository.js';
6
- import type { InsightRepository } from '../db/repositories/insight.repository.js';
7
- import { getLogger } from '../utils/logger.js';
8
-
9
- /**
10
- * Generates project suggestions, tool ideas, and optimization hints.
11
- */
12
- export class InsightGenerator {
13
- private logger = getLogger();
14
-
15
- constructor(
16
- private projectRepo: ProjectRepository,
17
- private errorRepo: ErrorRepository,
18
- private solutionRepo: SolutionRepository,
19
- private codeModuleRepo: CodeModuleRepository,
20
- private insightRepo: InsightRepository,
21
- private config: ResearchConfig,
22
- ) {}
23
-
24
- generate(): number {
25
- let insightsCreated = 0;
26
-
27
- insightsCreated += this.suggestRefactoring();
28
- insightsCreated += this.suggestErrorTypeTools();
29
- this.reprioritizeInsights();
30
-
31
- this.logger.info(`Insight generation complete: ${insightsCreated} new insights`);
32
- return insightsCreated;
33
- }
34
-
35
- private suggestRefactoring(): number {
36
- const projects = this.projectRepo.getAll();
37
- let count = 0;
38
- const expiresAt = new Date(Date.now() + this.config.insightExpiryDays * 86400000).toISOString();
39
-
40
- for (const project of projects) {
41
- const modules = this.codeModuleRepo.findByProject(project.id);
42
- const problematic = modules.filter(m =>
43
- (m.complexity ?? 0) > 10 && m.reusability_score < 0.3 && m.lines_of_code > 50,
44
- );
45
-
46
- if (problematic.length > 0) {
47
- this.insightRepo.create({
48
- type: 'optimization',
49
- title: `${problematic.length} complex modules need refactoring in ${project.name}`,
50
- description: `These modules have high complexity (>10), low reusability (<30%), and are non-trivial (>50 LOC). Refactoring would improve maintainability.`,
51
- evidence: JSON.stringify({
52
- modules: problematic.map(m => ({
53
- id: m.id,
54
- name: m.name,
55
- complexity: m.complexity,
56
- reusability: m.reusability_score,
57
- loc: m.lines_of_code,
58
- })),
59
- }),
60
- priority: Math.min(70, 30 + problematic.length * 10),
61
- project_id: project.id,
62
- active: 1,
63
- expires_at: expiresAt,
64
- });
65
- count++;
66
- }
67
- }
68
-
69
- return count;
70
- }
71
-
72
- private suggestErrorTypeTools(): number {
73
- const projects = this.projectRepo.getAll();
74
- let count = 0;
75
- const expiresAt = new Date(Date.now() + this.config.insightExpiryDays * 86400000).toISOString();
76
-
77
- for (const project of projects) {
78
- const errors = this.errorRepo.findByProject(project.id);
79
- if (errors.length < this.config.minDataPoints) continue;
80
-
81
- // Group errors by type
82
- const byType = new Map<string, number>();
83
- for (const error of errors) {
84
- byType.set(error.type, (byType.get(error.type) ?? 0) + error.occurrence_count);
85
- }
86
-
87
- // Find dominant error types
88
- for (const [errorType, totalOccurrences] of byType) {
89
- if (totalOccurrences >= this.config.gapMinOccurrences * 3) {
90
- this.insightRepo.create({
91
- type: 'suggestion',
92
- title: `Frequent error type: ${errorType} in ${project.name}`,
93
- description: `${errorType} has ${totalOccurrences} total occurrences. Consider adding linting rules, type checking, or tooling to prevent this class of errors.`,
94
- evidence: JSON.stringify({ errorType, totalOccurrences, projectId: project.id }),
95
- priority: Math.min(65, 30 + Math.round(totalOccurrences / 5)),
96
- project_id: project.id,
97
- active: 1,
98
- expires_at: expiresAt,
99
- });
100
- count++;
101
- }
102
- }
103
- }
104
-
105
- return count;
106
- }
107
-
108
- private reprioritizeInsights(): void {
109
- const activeInsights = this.insightRepo.findActive();
110
-
111
- for (const insight of activeInsights) {
112
- if (insight.type === 'warning') {
113
- const ageMs = Date.now() - new Date(insight.created_at).getTime();
114
- const ageDays = ageMs / 86400000;
115
- if (ageDays > 3 && insight.priority < 80) {
116
- this.insightRepo.update(insight.id, {
117
- priority: Math.min(85, insight.priority + 10),
118
- });
119
- }
120
- }
121
- }
122
- }
123
- }
@@ -1,116 +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 { CodeModuleRepository } from '../db/repositories/code-module.repository.js';
6
- import type { SynapseRepository } from '../db/repositories/synapse.repository.js';
7
- import type { InsightRepository } from '../db/repositories/insight.repository.js';
8
- import type { SynapseManager } from '../synapses/synapse-manager.js';
9
- import type { ResearchCycleResult } from '../types/research.types.js';
10
- import { TrendAnalyzer } from './trend-analyzer.js';
11
- import { GapAnalyzer } from './gap-analyzer.js';
12
- import { SynergyDetector } from './synergy-detector.js';
13
- import { TemplateExtractor } from './template-extractor.js';
14
- import { InsightGenerator } from './insight-generator.js';
15
- import { getLogger } from '../utils/logger.js';
16
-
17
- export class ResearchEngine {
18
- private timer: ReturnType<typeof setInterval> | null = null;
19
- private delayTimer: ReturnType<typeof setTimeout> | null = null;
20
- private logger = getLogger();
21
-
22
- private trendAnalyzer: TrendAnalyzer;
23
- private gapAnalyzer: GapAnalyzer;
24
- private synergyDetector: SynergyDetector;
25
- private templateExtractor: TemplateExtractor;
26
- private insightGenerator: InsightGenerator;
27
-
28
- constructor(
29
- private config: ResearchConfig,
30
- private errorRepo: ErrorRepository,
31
- private solutionRepo: SolutionRepository,
32
- private projectRepo: ProjectRepository,
33
- private codeModuleRepo: CodeModuleRepository,
34
- private synapseRepo: SynapseRepository,
35
- private insightRepo: InsightRepository,
36
- private synapseManager: SynapseManager,
37
- ) {
38
- this.trendAnalyzer = new TrendAnalyzer(errorRepo, solutionRepo, projectRepo, insightRepo, config);
39
- this.gapAnalyzer = new GapAnalyzer(errorRepo, solutionRepo, synapseRepo, projectRepo, insightRepo, config);
40
- this.synergyDetector = new SynergyDetector(synapseRepo, codeModuleRepo, solutionRepo, errorRepo, projectRepo, insightRepo, config);
41
- this.templateExtractor = new TemplateExtractor(codeModuleRepo, projectRepo, insightRepo, config);
42
- this.insightGenerator = new InsightGenerator(projectRepo, errorRepo, solutionRepo, codeModuleRepo, insightRepo, config);
43
- }
44
-
45
- start(): void {
46
- this.logger.info(`Research engine starting (interval: ${this.config.intervalMs}ms, initial delay: ${this.config.initialDelayMs}ms)`);
47
- this.delayTimer = setTimeout(() => {
48
- this.runCycle();
49
- this.timer = setInterval(() => this.runCycle(), this.config.intervalMs);
50
- }, this.config.initialDelayMs);
51
- }
52
-
53
- stop(): void {
54
- if (this.delayTimer) {
55
- clearTimeout(this.delayTimer);
56
- this.delayTimer = null;
57
- }
58
- if (this.timer) {
59
- clearInterval(this.timer);
60
- this.timer = null;
61
- }
62
- this.logger.info('Research engine stopped');
63
- }
64
-
65
- runCycle(): ResearchCycleResult {
66
- const start = Date.now();
67
- this.logger.info('Research cycle starting');
68
-
69
- const result: ResearchCycleResult = {
70
- insightsGenerated: 0,
71
- patternsFound: 0,
72
- correlationsFound: 0,
73
- duration: 0,
74
- };
75
-
76
- // Phase 1: Trend analysis
77
- const trends = this.trendAnalyzer.analyze();
78
- result.patternsFound += trends;
79
- result.insightsGenerated += trends;
80
-
81
- // Phase 2: Gap analysis
82
- const gaps = this.gapAnalyzer.analyze();
83
- result.insightsGenerated += gaps;
84
-
85
- // Phase 3: Synergy detection
86
- const synergies = this.synergyDetector.detect();
87
- result.correlationsFound += synergies;
88
- result.insightsGenerated += synergies;
89
-
90
- // Phase 4: Template extraction
91
- const templates = this.templateExtractor.extract();
92
- result.patternsFound += templates;
93
- result.insightsGenerated += templates;
94
-
95
- // Phase 5: Insight generation
96
- const generated = this.insightGenerator.generate();
97
- result.insightsGenerated += generated;
98
-
99
- // Phase 6: Insight prioritization (expire old insights)
100
- const expired = this.insightRepo.expire();
101
- if (expired > 0) {
102
- this.logger.info(`Expired ${expired} outdated insights`);
103
- }
104
-
105
- // Phase 7: Synapse maintenance
106
- const decay = this.synapseManager.runDecay();
107
- this.logger.debug(`Synapse maintenance: ${decay.decayed} decayed, ${decay.pruned} pruned`);
108
-
109
- result.duration = Date.now() - start;
110
- this.logger.info(
111
- `Research cycle complete: ${result.insightsGenerated} insights, ${result.patternsFound} patterns, ${result.correlationsFound} correlations (${result.duration}ms)`,
112
- );
113
-
114
- return result;
115
- }
116
- }
@@ -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
- }