@timmeck/brain 1.9.0 → 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.
- package/README.md +19 -0
- package/brain.log +1164 -0
- package/{src/cli/commands/dashboard.ts → dashboard.html} +688 -807
- package/dist/api/server.d.ts +4 -18
- package/dist/api/server.js +4 -173
- package/dist/api/server.js.map +1 -1
- package/dist/brain.d.ts +1 -0
- package/dist/brain.js +6 -1
- package/dist/brain.js.map +1 -1
- package/dist/cli/colors.d.ts +4 -25
- package/dist/cli/colors.js +3 -89
- package/dist/cli/colors.js.map +1 -1
- package/dist/cli/commands/peers.d.ts +2 -0
- package/dist/cli/commands/peers.js +38 -0
- package/dist/cli/commands/peers.js.map +1 -0
- package/dist/db/connection.d.ts +1 -2
- package/dist/db/connection.js +1 -18
- package/dist/db/connection.js.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/ipc/__tests__/protocol.test.d.ts +1 -0
- package/dist/ipc/__tests__/protocol.test.js +117 -0
- package/dist/ipc/__tests__/protocol.test.js.map +1 -0
- package/dist/ipc/client.d.ts +1 -16
- package/dist/ipc/client.js +1 -100
- package/dist/ipc/client.js.map +1 -1
- package/dist/ipc/protocol.d.ts +1 -8
- package/dist/ipc/protocol.js +1 -28
- package/dist/ipc/protocol.js.map +1 -1
- package/dist/ipc/router.js +8 -0
- package/dist/ipc/router.js.map +1 -1
- package/dist/ipc/server.d.ts +1 -22
- package/dist/ipc/server.js +1 -163
- package/dist/ipc/server.js.map +1 -1
- package/dist/mcp/http-server.d.ts +1 -7
- package/dist/mcp/http-server.js +6 -117
- package/dist/mcp/http-server.js.map +1 -1
- package/dist/mcp/server.js +5 -61
- package/dist/mcp/server.js.map +1 -1
- package/dist/signals/__tests__/fingerprint.test.d.ts +1 -0
- package/dist/signals/__tests__/fingerprint.test.js +118 -0
- package/dist/signals/__tests__/fingerprint.test.js.map +1 -0
- package/dist/types/ipc.types.d.ts +1 -11
- package/dist/utils/__tests__/hash.test.d.ts +1 -0
- package/dist/utils/__tests__/hash.test.js +32 -0
- package/dist/utils/__tests__/hash.test.js.map +1 -0
- package/dist/utils/__tests__/paths.test.d.ts +1 -0
- package/dist/utils/__tests__/paths.test.js +75 -0
- package/dist/utils/__tests__/paths.test.js.map +1 -0
- package/dist/utils/events.d.ts +4 -8
- package/dist/utils/events.js +2 -14
- package/dist/utils/events.js.map +1 -1
- package/dist/utils/hash.d.ts +1 -1
- package/dist/utils/hash.js +1 -4
- package/dist/utils/hash.js.map +1 -1
- package/dist/utils/logger.d.ts +3 -2
- package/dist/utils/logger.js +8 -35
- package/dist/utils/logger.js.map +1 -1
- package/dist/utils/paths.d.ts +2 -1
- package/dist/utils/paths.js +4 -13
- package/dist/utils/paths.js.map +1 -1
- package/package.json +2 -1
- package/BRAIN_PLAN.md +0 -3324
- package/reddit_post.md +0 -45
- package/src/api/server.ts +0 -395
- package/src/brain.ts +0 -313
- package/src/cli/colors.ts +0 -116
- package/src/cli/commands/config.ts +0 -169
- package/src/cli/commands/doctor.ts +0 -124
- package/src/cli/commands/explain.ts +0 -83
- package/src/cli/commands/export.ts +0 -31
- package/src/cli/commands/import.ts +0 -199
- package/src/cli/commands/insights.ts +0 -65
- package/src/cli/commands/learn.ts +0 -24
- package/src/cli/commands/modules.ts +0 -53
- package/src/cli/commands/network.ts +0 -67
- package/src/cli/commands/projects.ts +0 -42
- package/src/cli/commands/query.ts +0 -120
- package/src/cli/commands/start.ts +0 -105
- package/src/cli/commands/status.ts +0 -75
- package/src/cli/commands/stop.ts +0 -34
- package/src/cli/ipc-helper.ts +0 -22
- package/src/cli/update-check.ts +0 -63
- package/src/code/analyzer.ts +0 -117
- package/src/code/fingerprint.ts +0 -87
- package/src/code/matcher.ts +0 -129
- package/src/code/parsers/generic.ts +0 -29
- package/src/code/parsers/python.ts +0 -54
- package/src/code/parsers/typescript.ts +0 -65
- package/src/code/registry.ts +0 -60
- package/src/code/scorer.ts +0 -120
- package/src/config.ts +0 -135
- package/src/dashboard/server.ts +0 -142
- package/src/db/connection.ts +0 -22
- package/src/db/migrations/001_core_schema.ts +0 -120
- package/src/db/migrations/002_learning_schema.ts +0 -38
- package/src/db/migrations/003_code_schema.ts +0 -53
- package/src/db/migrations/004_synapses_schema.ts +0 -57
- package/src/db/migrations/005_fts_indexes.ts +0 -78
- package/src/db/migrations/006_synapses_phase3.ts +0 -17
- package/src/db/migrations/007_feedback.ts +0 -13
- package/src/db/migrations/008_git_integration.ts +0 -38
- package/src/db/migrations/009_embeddings.ts +0 -8
- package/src/db/migrations/index.ts +0 -70
- package/src/db/repositories/antipattern.repository.ts +0 -66
- package/src/db/repositories/code-module.repository.ts +0 -142
- package/src/db/repositories/error.repository.ts +0 -189
- package/src/db/repositories/insight.repository.ts +0 -99
- package/src/db/repositories/notification.repository.ts +0 -66
- package/src/db/repositories/project.repository.ts +0 -93
- package/src/db/repositories/rule.repository.ts +0 -108
- package/src/db/repositories/solution.repository.ts +0 -154
- package/src/db/repositories/synapse.repository.ts +0 -163
- package/src/db/repositories/terminal.repository.ts +0 -101
- package/src/embeddings/engine.ts +0 -238
- package/src/hooks/post-tool-use.ts +0 -92
- package/src/hooks/post-write.ts +0 -129
- package/src/index.ts +0 -63
- package/src/ipc/client.ts +0 -118
- package/src/ipc/protocol.ts +0 -35
- package/src/ipc/router.ts +0 -133
- package/src/ipc/server.ts +0 -176
- package/src/learning/confidence-scorer.ts +0 -80
- package/src/learning/decay.ts +0 -46
- package/src/learning/learning-engine.ts +0 -170
- package/src/learning/pattern-extractor.ts +0 -90
- package/src/learning/rule-generator.ts +0 -74
- package/src/main.rs:10:5 +0 -0
- package/src/matching/error-matcher.ts +0 -166
- package/src/matching/fingerprint.ts +0 -34
- package/src/matching/similarity.ts +0 -61
- package/src/matching/tfidf.ts +0 -74
- package/src/matching/tokenizer.ts +0 -41
- package/src/mcp/auto-detect.ts +0 -93
- package/src/mcp/http-server.ts +0 -140
- package/src/mcp/server.ts +0 -73
- package/src/mcp/tools.ts +0 -328
- package/src/parsing/error-parser.ts +0 -28
- package/src/parsing/parsers/compiler.ts +0 -93
- package/src/parsing/parsers/generic.ts +0 -28
- package/src/parsing/parsers/go.ts +0 -97
- package/src/parsing/parsers/node.ts +0 -69
- package/src/parsing/parsers/python.ts +0 -62
- package/src/parsing/parsers/rust.ts +0 -50
- package/src/parsing/parsers/shell.ts +0 -42
- package/src/parsing/types.ts +0 -47
- package/src/research/gap-analyzer.ts +0 -135
- package/src/research/insight-generator.ts +0 -123
- package/src/research/research-engine.ts +0 -116
- package/src/research/synergy-detector.ts +0 -126
- package/src/research/template-extractor.ts +0 -130
- package/src/research/trend-analyzer.ts +0 -127
- package/src/services/analytics.service.ts +0 -226
- package/src/services/code.service.ts +0 -271
- package/src/services/error.service.ts +0 -266
- package/src/services/git.service.ts +0 -132
- package/src/services/notification.service.ts +0 -41
- package/src/services/prevention.service.ts +0 -159
- package/src/services/research.service.ts +0 -98
- package/src/services/solution.service.ts +0 -174
- package/src/services/synapse.service.ts +0 -59
- package/src/services/terminal.service.ts +0 -81
- package/src/synapses/activation.ts +0 -80
- package/src/synapses/decay.ts +0 -38
- package/src/synapses/hebbian.ts +0 -69
- package/src/synapses/pathfinder.ts +0 -81
- package/src/synapses/synapse-manager.ts +0 -113
- package/src/types/code.types.ts +0 -52
- package/src/types/config.types.ts +0 -103
- package/src/types/error.types.ts +0 -67
- package/src/types/ipc.types.ts +0 -8
- package/src/types/mcp.types.ts +0 -53
- package/src/types/research.types.ts +0 -28
- package/src/types/solution.types.ts +0 -30
- package/src/types/synapse.types.ts +0 -50
- package/src/utils/events.ts +0 -45
- package/src/utils/hash.ts +0 -5
- package/src/utils/logger.ts +0 -48
- package/src/utils/paths.ts +0 -19
- package/tests/e2e/test_code_intelligence.py +0 -1015
- package/tests/e2e/test_error_memory.py +0 -451
- package/tests/e2e/test_full_integration.py +0 -534
- package/tests/fixtures/code-modules/modules.ts +0 -83
- package/tests/fixtures/errors/go.ts +0 -9
- package/tests/fixtures/errors/node.ts +0 -24
- package/tests/fixtures/errors/python.ts +0 -21
- package/tests/fixtures/errors/rust.ts +0 -25
- package/tests/fixtures/errors/shell.ts +0 -15
- package/tests/fixtures/solutions/solutions.ts +0 -27
- package/tests/helpers/setup-db.ts +0 -52
- package/tests/integration/code-flow.test.ts +0 -86
- package/tests/integration/error-flow.test.ts +0 -83
- package/tests/integration/ipc-flow.test.ts +0 -166
- package/tests/integration/learning-cycle.test.ts +0 -82
- package/tests/integration/synapse-flow.test.ts +0 -117
- package/tests/unit/code/analyzer.test.ts +0 -58
- package/tests/unit/code/fingerprint.test.ts +0 -51
- package/tests/unit/code/scorer.test.ts +0 -55
- package/tests/unit/learning/confidence-scorer.test.ts +0 -60
- package/tests/unit/learning/decay.test.ts +0 -45
- package/tests/unit/learning/pattern-extractor.test.ts +0 -50
- package/tests/unit/matching/error-matcher.test.ts +0 -69
- package/tests/unit/matching/fingerprint.test.ts +0 -47
- package/tests/unit/matching/similarity.test.ts +0 -65
- package/tests/unit/matching/tfidf.test.ts +0 -71
- package/tests/unit/matching/tokenizer.test.ts +0 -83
- package/tests/unit/parsing/parsers.test.ts +0 -113
- package/tests/unit/research/gap-analyzer.test.ts +0 -45
- package/tests/unit/research/trend-analyzer.test.ts +0 -45
- package/tests/unit/synapses/activation.test.ts +0 -80
- package/tests/unit/synapses/decay.test.ts +0 -27
- package/tests/unit/synapses/hebbian.test.ts +0 -96
- package/tests/unit/synapses/pathfinder.test.ts +0 -72
- package/tsconfig.json +0 -18
package/src/embeddings/engine.ts
DELETED
|
@@ -1,238 +0,0 @@
|
|
|
1
|
-
import path from 'node:path';
|
|
2
|
-
import type Database from 'better-sqlite3';
|
|
3
|
-
import { getLogger } from '../utils/logger.js';
|
|
4
|
-
|
|
5
|
-
export interface EmbeddingConfig {
|
|
6
|
-
enabled: boolean;
|
|
7
|
-
modelName: string;
|
|
8
|
-
cacheDir: string;
|
|
9
|
-
sweepIntervalMs: number;
|
|
10
|
-
batchSize: number;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
14
|
-
type Pipeline = any;
|
|
15
|
-
|
|
16
|
-
export class EmbeddingEngine {
|
|
17
|
-
private pipeline: Pipeline = null;
|
|
18
|
-
private ready = false;
|
|
19
|
-
private loading = false;
|
|
20
|
-
private logger = getLogger();
|
|
21
|
-
private sweepTimer: ReturnType<typeof setInterval> | null = null;
|
|
22
|
-
|
|
23
|
-
constructor(
|
|
24
|
-
private config: EmbeddingConfig,
|
|
25
|
-
private db: Database.Database,
|
|
26
|
-
) {}
|
|
27
|
-
|
|
28
|
-
async initialize(): Promise<void> {
|
|
29
|
-
if (!this.config.enabled || this.loading || this.ready) return;
|
|
30
|
-
|
|
31
|
-
this.loading = true;
|
|
32
|
-
try {
|
|
33
|
-
const { pipeline, env } = await import('@huggingface/transformers');
|
|
34
|
-
env.cacheDir = this.config.cacheDir;
|
|
35
|
-
|
|
36
|
-
this.pipeline = await pipeline(
|
|
37
|
-
'feature-extraction',
|
|
38
|
-
this.config.modelName,
|
|
39
|
-
{ dtype: 'q8' },
|
|
40
|
-
);
|
|
41
|
-
|
|
42
|
-
this.ready = true;
|
|
43
|
-
this.logger.info(`Embedding model loaded: ${this.config.modelName}`);
|
|
44
|
-
} catch (err) {
|
|
45
|
-
this.logger.warn(`Failed to load embedding model (will retry): ${err}`);
|
|
46
|
-
this.ready = false;
|
|
47
|
-
} finally {
|
|
48
|
-
this.loading = false;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/** Start background embedding sweep */
|
|
53
|
-
start(): void {
|
|
54
|
-
if (!this.config.enabled) return;
|
|
55
|
-
|
|
56
|
-
// Initialize model in background
|
|
57
|
-
this.initialize().then(() => {
|
|
58
|
-
if (this.ready) {
|
|
59
|
-
// Run initial sweep
|
|
60
|
-
this.sweep().catch(err => this.logger.error('Embedding sweep error:', err));
|
|
61
|
-
}
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
// Periodic sweep for new entries
|
|
65
|
-
this.sweepTimer = setInterval(() => {
|
|
66
|
-
if (this.ready) {
|
|
67
|
-
this.sweep().catch(err => this.logger.error('Embedding sweep error:', err));
|
|
68
|
-
}
|
|
69
|
-
}, this.config.sweepIntervalMs);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
stop(): void {
|
|
73
|
-
if (this.sweepTimer) {
|
|
74
|
-
clearInterval(this.sweepTimer);
|
|
75
|
-
this.sweepTimer = null;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
isReady(): boolean {
|
|
80
|
-
return this.ready;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/** Generate embedding for a single text */
|
|
84
|
-
async embed(text: string): Promise<Float32Array | null> {
|
|
85
|
-
if (!this.ready || !this.pipeline) return null;
|
|
86
|
-
|
|
87
|
-
try {
|
|
88
|
-
const output = await this.pipeline(text, { pooling: 'mean', normalize: true });
|
|
89
|
-
const data = output.tolist()[0] as number[];
|
|
90
|
-
return new Float32Array(data);
|
|
91
|
-
} catch (err) {
|
|
92
|
-
this.logger.error(`Embedding error: ${err}`);
|
|
93
|
-
return null;
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** Generate embeddings for a batch of texts */
|
|
98
|
-
async embedBatch(texts: string[]): Promise<(Float32Array | null)[]> {
|
|
99
|
-
if (!this.ready || !this.pipeline || texts.length === 0) return texts.map(() => null);
|
|
100
|
-
|
|
101
|
-
try {
|
|
102
|
-
const output = await this.pipeline(texts, { pooling: 'mean', normalize: true });
|
|
103
|
-
const list = output.tolist() as number[][];
|
|
104
|
-
return list.map(v => new Float32Array(v));
|
|
105
|
-
} catch (err) {
|
|
106
|
-
this.logger.error(`Batch embedding error: ${err}`);
|
|
107
|
-
return texts.map(() => null);
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** Compute and store embeddings for entries that don't have them yet */
|
|
112
|
-
async sweep(): Promise<{ errors: number; modules: number }> {
|
|
113
|
-
let errorsProcessed = 0;
|
|
114
|
-
let modulesProcessed = 0;
|
|
115
|
-
|
|
116
|
-
// Process errors without embeddings
|
|
117
|
-
const pendingErrors = this.db.prepare(
|
|
118
|
-
'SELECT id, type, message, context FROM errors WHERE embedding IS NULL ORDER BY id DESC LIMIT ?'
|
|
119
|
-
).all(this.config.batchSize) as Array<{ id: number; type: string; message: string; context: string | null }>;
|
|
120
|
-
|
|
121
|
-
if (pendingErrors.length > 0) {
|
|
122
|
-
const texts = pendingErrors.map(e =>
|
|
123
|
-
[e.type, e.message, e.context].filter(Boolean).join(' ')
|
|
124
|
-
);
|
|
125
|
-
const embeddings = await this.embedBatch(texts);
|
|
126
|
-
|
|
127
|
-
const updateStmt = this.db.prepare('UPDATE errors SET embedding = ? WHERE id = ?');
|
|
128
|
-
for (let i = 0; i < pendingErrors.length; i++) {
|
|
129
|
-
const emb = embeddings[i];
|
|
130
|
-
if (emb) {
|
|
131
|
-
updateStmt.run(EmbeddingEngine.serialize(emb), pendingErrors[i]!.id);
|
|
132
|
-
errorsProcessed++;
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// Process code modules without embeddings
|
|
138
|
-
const pendingModules = this.db.prepare(
|
|
139
|
-
'SELECT id, name, description, file_path FROM code_modules WHERE embedding IS NULL ORDER BY id DESC LIMIT ?'
|
|
140
|
-
).all(this.config.batchSize) as Array<{ id: number; name: string; description: string | null; file_path: string }>;
|
|
141
|
-
|
|
142
|
-
if (pendingModules.length > 0) {
|
|
143
|
-
const texts = pendingModules.map(m =>
|
|
144
|
-
[m.name, m.description, m.file_path].filter(Boolean).join(' ')
|
|
145
|
-
);
|
|
146
|
-
const embeddings = await this.embedBatch(texts);
|
|
147
|
-
|
|
148
|
-
const updateStmt = this.db.prepare('UPDATE code_modules SET embedding = ? WHERE id = ?');
|
|
149
|
-
for (let i = 0; i < pendingModules.length; i++) {
|
|
150
|
-
const emb = embeddings[i];
|
|
151
|
-
if (emb) {
|
|
152
|
-
updateStmt.run(EmbeddingEngine.serialize(emb), pendingModules[i]!.id);
|
|
153
|
-
modulesProcessed++;
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
if (errorsProcessed > 0 || modulesProcessed > 0) {
|
|
159
|
-
this.logger.info(`Embedding sweep: ${errorsProcessed} errors, ${modulesProcessed} modules processed`);
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
return { errors: errorsProcessed, modules: modulesProcessed };
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/** Load vector scores for error matching (sync - reads pre-computed embeddings from DB) */
|
|
166
|
-
computeErrorVectorScores(errorId: number, projectId: number): Map<number, number> {
|
|
167
|
-
const scores = new Map<number, number>();
|
|
168
|
-
|
|
169
|
-
const errorRow = this.db.prepare(
|
|
170
|
-
'SELECT embedding FROM errors WHERE id = ?'
|
|
171
|
-
).get(errorId) as { embedding: Buffer | null } | undefined;
|
|
172
|
-
|
|
173
|
-
if (!errorRow?.embedding) return scores;
|
|
174
|
-
|
|
175
|
-
const incoming = EmbeddingEngine.deserialize(errorRow.embedding);
|
|
176
|
-
|
|
177
|
-
const candidates = this.db.prepare(
|
|
178
|
-
'SELECT id, embedding FROM errors WHERE project_id = ? AND id != ? AND embedding IS NOT NULL'
|
|
179
|
-
).all(projectId, errorId) as Array<{ id: number; embedding: Buffer }>;
|
|
180
|
-
|
|
181
|
-
for (const c of candidates) {
|
|
182
|
-
const candidate = EmbeddingEngine.deserialize(c.embedding);
|
|
183
|
-
scores.set(c.id, EmbeddingEngine.similarity(incoming, candidate));
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
return scores;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** Load vector scores for module-to-module matching (sync - reads pre-computed embeddings from DB) */
|
|
190
|
-
computeModuleVectorScores(moduleId: number, language?: string): Map<number, number> {
|
|
191
|
-
const scores = new Map<number, number>();
|
|
192
|
-
|
|
193
|
-
const moduleRow = this.db.prepare(
|
|
194
|
-
'SELECT embedding FROM code_modules WHERE id = ?'
|
|
195
|
-
).get(moduleId) as { embedding: Buffer | null } | undefined;
|
|
196
|
-
|
|
197
|
-
if (!moduleRow?.embedding) return scores;
|
|
198
|
-
|
|
199
|
-
const incoming = EmbeddingEngine.deserialize(moduleRow.embedding);
|
|
200
|
-
|
|
201
|
-
let sql = 'SELECT id, embedding FROM code_modules WHERE id != ? AND embedding IS NOT NULL';
|
|
202
|
-
const params: unknown[] = [moduleId];
|
|
203
|
-
if (language) {
|
|
204
|
-
sql += ' AND language = ?';
|
|
205
|
-
params.push(language);
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
const candidates = this.db.prepare(sql).all(...params) as Array<{ id: number; embedding: Buffer }>;
|
|
209
|
-
|
|
210
|
-
for (const c of candidates) {
|
|
211
|
-
const candidate = EmbeddingEngine.deserialize(c.embedding);
|
|
212
|
-
scores.set(c.id, EmbeddingEngine.similarity(incoming, candidate));
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
return scores;
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
/** Serialize Float32Array to Buffer for SQLite BLOB storage */
|
|
219
|
-
static serialize(embedding: Float32Array): Buffer {
|
|
220
|
-
return Buffer.from(embedding.buffer, embedding.byteOffset, embedding.byteLength);
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/** Deserialize SQLite BLOB to Float32Array */
|
|
224
|
-
static deserialize(buffer: Buffer): Float32Array {
|
|
225
|
-
const copy = Buffer.from(buffer);
|
|
226
|
-
return new Float32Array(copy.buffer, copy.byteOffset, copy.length / 4);
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
/** Cosine similarity (embeddings are L2-normalized, so dot product = cosine) */
|
|
230
|
-
static similarity(a: Float32Array, b: Float32Array): number {
|
|
231
|
-
if (a.length !== b.length) return 0;
|
|
232
|
-
let dot = 0;
|
|
233
|
-
for (let i = 0; i < a.length; i++) {
|
|
234
|
-
dot += a[i]! * b[i]!;
|
|
235
|
-
}
|
|
236
|
-
return Math.max(0, Math.min(1, dot));
|
|
237
|
-
}
|
|
238
|
-
}
|
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// PostToolUse hook for Bash tool — auto-detects errors and reports to Brain
|
|
4
|
-
// Configured in .claude/settings.json:
|
|
5
|
-
// { "hooks": { "PostToolUse": [{ "matcher": { "tool_name": "Bash" }, "command": "node <brain-dist>/hooks/post-tool-use.js" }] } }
|
|
6
|
-
|
|
7
|
-
import { IpcClient } from '../ipc/client.js';
|
|
8
|
-
import { getPipeName } from '../utils/paths.js';
|
|
9
|
-
|
|
10
|
-
interface HookInput {
|
|
11
|
-
tool_name: string;
|
|
12
|
-
tool_input: { command?: string };
|
|
13
|
-
tool_output: string;
|
|
14
|
-
exit_code?: number;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
const ERROR_PATTERNS = [
|
|
18
|
-
/Error:/i,
|
|
19
|
-
/error\[E\d+\]/,
|
|
20
|
-
/Traceback \(most recent call last\)/,
|
|
21
|
-
/FATAL|PANIC/i,
|
|
22
|
-
/npm ERR!/,
|
|
23
|
-
/SyntaxError|TypeError|ReferenceError|RangeError/,
|
|
24
|
-
/ENOENT|EACCES|ECONNREFUSED|ETIMEDOUT/,
|
|
25
|
-
/ModuleNotFoundError|ImportError/,
|
|
26
|
-
/failed to compile/i,
|
|
27
|
-
/BUILD FAILED/i,
|
|
28
|
-
/Cannot find module/,
|
|
29
|
-
/command not found/,
|
|
30
|
-
/Permission denied/,
|
|
31
|
-
];
|
|
32
|
-
|
|
33
|
-
function isError(input: HookInput): boolean {
|
|
34
|
-
if (input.exit_code !== undefined && input.exit_code !== 0) return true;
|
|
35
|
-
return ERROR_PATTERNS.some(p => p.test(input.tool_output));
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function readStdin(): Promise<string> {
|
|
39
|
-
return new Promise((resolve) => {
|
|
40
|
-
let data = '';
|
|
41
|
-
process.stdin.setEncoding('utf8');
|
|
42
|
-
process.stdin.on('data', (chunk) => { data += chunk; });
|
|
43
|
-
process.stdin.on('end', () => resolve(data));
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
async function main(): Promise<void> {
|
|
48
|
-
const raw = await readStdin();
|
|
49
|
-
if (!raw.trim()) return;
|
|
50
|
-
|
|
51
|
-
let input: HookInput;
|
|
52
|
-
try {
|
|
53
|
-
input = JSON.parse(raw);
|
|
54
|
-
} catch {
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
if (!isError(input)) return;
|
|
59
|
-
|
|
60
|
-
const client = new IpcClient(getPipeName(), 3000);
|
|
61
|
-
try {
|
|
62
|
-
await client.connect();
|
|
63
|
-
|
|
64
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
65
|
-
const result: any = await client.request('error.report', {
|
|
66
|
-
project: 'auto-detected',
|
|
67
|
-
errorOutput: input.tool_output,
|
|
68
|
-
command: input.tool_input?.command,
|
|
69
|
-
workingDirectory: process.cwd(),
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
if (result.matches?.length > 0) {
|
|
73
|
-
const best = result.matches[0];
|
|
74
|
-
process.stderr.write(`Brain: Similar error found (#${best.errorId}, ${Math.round(best.score * 100)}% match)\n`);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
78
|
-
const antipatterns: any = await client.request('prevention.antipatterns', {
|
|
79
|
-
errorType: '',
|
|
80
|
-
message: input.tool_output,
|
|
81
|
-
});
|
|
82
|
-
if (antipatterns?.length > 0 && antipatterns[0].matched) {
|
|
83
|
-
process.stderr.write(`Brain WARNING: Known anti-pattern: ${antipatterns[0].description}\n`);
|
|
84
|
-
}
|
|
85
|
-
} catch {
|
|
86
|
-
// Hook must never block workflow
|
|
87
|
-
} finally {
|
|
88
|
-
client.disconnect();
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
main();
|
package/src/hooks/post-write.ts
DELETED
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
// PostToolUse hook for Write/Edit tool — auto-analyzes code for reusability
|
|
4
|
-
// Configured in .claude/settings.json:
|
|
5
|
-
// { "hooks": { "PostToolUse": [{ "matcher": { "tool_name": "Write" }, "command": "node <brain-dist>/hooks/post-write.js" }] } }
|
|
6
|
-
|
|
7
|
-
import { IpcClient } from '../ipc/client.js';
|
|
8
|
-
import { getPipeName } from '../utils/paths.js';
|
|
9
|
-
|
|
10
|
-
interface HookInput {
|
|
11
|
-
tool_name: string;
|
|
12
|
-
tool_input: { file_path?: string; content?: string };
|
|
13
|
-
tool_output: string;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const SOURCE_EXTENSIONS = new Set([
|
|
17
|
-
'.ts', '.tsx', '.js', '.jsx', '.py', '.rs', '.go',
|
|
18
|
-
'.java', '.c', '.cpp', '.h', '.hpp', '.rb', '.sh',
|
|
19
|
-
]);
|
|
20
|
-
|
|
21
|
-
const IGNORE_PATHS = [
|
|
22
|
-
'node_modules', 'dist', '.git', '__pycache__',
|
|
23
|
-
'vendor', 'build', '.next', 'coverage',
|
|
24
|
-
];
|
|
25
|
-
|
|
26
|
-
function isSourceFile(filePath: string): boolean {
|
|
27
|
-
const ext = filePath.slice(filePath.lastIndexOf('.'));
|
|
28
|
-
if (!SOURCE_EXTENSIONS.has(ext)) return false;
|
|
29
|
-
return !IGNORE_PATHS.some(p => filePath.includes(p));
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function detectProject(filePath: string): string {
|
|
33
|
-
const normalized = filePath.replace(/\\/g, '/');
|
|
34
|
-
// Extract project name from path — look for common project root indicators
|
|
35
|
-
const parts = normalized.split('/');
|
|
36
|
-
// Find the directory just above src/, lib/, app/ etc., or use the parent of the file
|
|
37
|
-
for (let i = parts.length - 1; i >= 0; i--) {
|
|
38
|
-
if (['src', 'lib', 'app', 'components', 'pages', 'tests', 'test'].includes(parts[i]) && i > 0) {
|
|
39
|
-
return parts[i - 1];
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
// Fallback: use the directory two levels up from the file, or immediate parent
|
|
43
|
-
return parts[Math.max(parts.length - 3, 0)] || 'default';
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
function detectLanguage(filePath: string): string {
|
|
47
|
-
const ext = filePath.split('.').pop()?.toLowerCase() ?? '';
|
|
48
|
-
const map: Record<string, string> = {
|
|
49
|
-
ts: 'typescript', tsx: 'typescript', js: 'javascript', jsx: 'javascript',
|
|
50
|
-
py: 'python', rs: 'rust', go: 'go', java: 'java',
|
|
51
|
-
c: 'c', cpp: 'cpp', h: 'c', hpp: 'cpp',
|
|
52
|
-
rb: 'ruby', sh: 'shell',
|
|
53
|
-
};
|
|
54
|
-
return map[ext] ?? ext;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
function readStdin(): Promise<string> {
|
|
58
|
-
return new Promise((resolve) => {
|
|
59
|
-
let data = '';
|
|
60
|
-
process.stdin.setEncoding('utf8');
|
|
61
|
-
process.stdin.on('data', (chunk) => { data += chunk; });
|
|
62
|
-
process.stdin.on('end', () => resolve(data));
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
async function main(): Promise<void> {
|
|
67
|
-
const raw = await readStdin();
|
|
68
|
-
if (!raw.trim()) return;
|
|
69
|
-
|
|
70
|
-
let input: HookInput;
|
|
71
|
-
try {
|
|
72
|
-
input = JSON.parse(raw);
|
|
73
|
-
} catch {
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const filePath = input.tool_input?.file_path;
|
|
78
|
-
if (!filePath || !isSourceFile(filePath)) return;
|
|
79
|
-
|
|
80
|
-
const client = new IpcClient(getPipeName(), 3000);
|
|
81
|
-
try {
|
|
82
|
-
await client.connect();
|
|
83
|
-
|
|
84
|
-
// Check for similar existing code
|
|
85
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
86
|
-
const similarities: any = await client.request('code.similarity', {
|
|
87
|
-
source: input.tool_input.content ?? '',
|
|
88
|
-
language: detectLanguage(filePath),
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
if (similarities?.length > 0) {
|
|
92
|
-
const best = similarities[0];
|
|
93
|
-
if (best.score > 0.8) {
|
|
94
|
-
process.stderr.write(`Brain: Very similar code exists (module #${best.moduleId}, ${Math.round(best.score * 100)}% match). Consider reusing.\n`);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// Proactive Prevention: check if written code matches error-causing patterns
|
|
99
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
100
|
-
const prevention: any = await client.request('prevention.checkCode', {
|
|
101
|
-
source: input.tool_input.content ?? '',
|
|
102
|
-
filePath,
|
|
103
|
-
});
|
|
104
|
-
if (prevention?.warnings?.length > 0) {
|
|
105
|
-
for (const warning of prevention.warnings.slice(0, 3)) {
|
|
106
|
-
process.stderr.write(`Brain WARNING: ${warning.message}\n`);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// Auto-register the written file into Brain
|
|
111
|
-
const fileName = filePath.replace(/\\/g, '/').split('/').pop() ?? 'unknown';
|
|
112
|
-
const projectName = detectProject(filePath);
|
|
113
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
114
|
-
const result: any = await client.request('code.analyze', {
|
|
115
|
-
project: projectName,
|
|
116
|
-
name: fileName,
|
|
117
|
-
filePath,
|
|
118
|
-
language: detectLanguage(filePath),
|
|
119
|
-
source: input.tool_input.content ?? '',
|
|
120
|
-
});
|
|
121
|
-
process.stderr.write(`Brain: Registered ${fileName} (score: ${result.reusabilityScore?.toFixed(2) ?? '?'}, ${result.isNew ? 'new' : 'updated'})\n`);
|
|
122
|
-
} catch {
|
|
123
|
-
// Hook must never block workflow
|
|
124
|
-
} finally {
|
|
125
|
-
client.disconnect();
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
main();
|
package/src/index.ts
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
import { Command } from 'commander';
|
|
4
|
-
import { startCommand } from './cli/commands/start.js';
|
|
5
|
-
import { stopCommand } from './cli/commands/stop.js';
|
|
6
|
-
import { statusCommand } from './cli/commands/status.js';
|
|
7
|
-
import { queryCommand } from './cli/commands/query.js';
|
|
8
|
-
import { modulesCommand } from './cli/commands/modules.js';
|
|
9
|
-
import { insightsCommand } from './cli/commands/insights.js';
|
|
10
|
-
import { networkCommand } from './cli/commands/network.js';
|
|
11
|
-
import { exportCommand } from './cli/commands/export.js';
|
|
12
|
-
import { importCommand } from './cli/commands/import.js';
|
|
13
|
-
import { dashboardCommand } from './cli/commands/dashboard.js';
|
|
14
|
-
import { learnCommand } from './cli/commands/learn.js';
|
|
15
|
-
import { configCommand } from './cli/commands/config.js';
|
|
16
|
-
import { projectsCommand } from './cli/commands/projects.js';
|
|
17
|
-
import { doctorCommand } from './cli/commands/doctor.js';
|
|
18
|
-
import { explainCommand } from './cli/commands/explain.js';
|
|
19
|
-
|
|
20
|
-
const program = new Command();
|
|
21
|
-
|
|
22
|
-
program
|
|
23
|
-
.name('brain')
|
|
24
|
-
.description('Brain — Adaptive Error Memory & Code Intelligence System')
|
|
25
|
-
.version('1.8.1');
|
|
26
|
-
|
|
27
|
-
program.addCommand(startCommand());
|
|
28
|
-
program.addCommand(stopCommand());
|
|
29
|
-
program.addCommand(statusCommand());
|
|
30
|
-
program.addCommand(queryCommand());
|
|
31
|
-
program.addCommand(modulesCommand());
|
|
32
|
-
program.addCommand(insightsCommand());
|
|
33
|
-
program.addCommand(networkCommand());
|
|
34
|
-
program.addCommand(exportCommand());
|
|
35
|
-
program.addCommand(importCommand());
|
|
36
|
-
program.addCommand(dashboardCommand());
|
|
37
|
-
program.addCommand(learnCommand());
|
|
38
|
-
program.addCommand(configCommand());
|
|
39
|
-
program.addCommand(projectsCommand());
|
|
40
|
-
program.addCommand(doctorCommand());
|
|
41
|
-
program.addCommand(explainCommand());
|
|
42
|
-
|
|
43
|
-
// Hidden command: run MCP server (called by Claude Code)
|
|
44
|
-
program
|
|
45
|
-
.command('mcp-server')
|
|
46
|
-
.description('Start MCP server (stdio transport, used by Claude Code)')
|
|
47
|
-
.action(async () => {
|
|
48
|
-
const { startMcpServer } = await import('./mcp/server.js');
|
|
49
|
-
await startMcpServer();
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
// Hidden command: run daemon in foreground (called by start command)
|
|
53
|
-
program
|
|
54
|
-
.command('daemon')
|
|
55
|
-
.description('Run daemon in foreground')
|
|
56
|
-
.option('-c, --config <path>', 'Config file path')
|
|
57
|
-
.action(async (opts) => {
|
|
58
|
-
const { BrainCore } = await import('./brain.js');
|
|
59
|
-
const core = new BrainCore();
|
|
60
|
-
core.start(opts.config);
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
program.parse();
|
package/src/ipc/client.ts
DELETED
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
import net from 'node:net';
|
|
2
|
-
import { randomUUID } from 'node:crypto';
|
|
3
|
-
import type { IpcMessage } from '../types/ipc.types.js';
|
|
4
|
-
import { encodeMessage, MessageDecoder } from './protocol.js';
|
|
5
|
-
import { getPipeName } from '../utils/paths.js';
|
|
6
|
-
|
|
7
|
-
interface PendingRequest {
|
|
8
|
-
resolve: (result: unknown) => void;
|
|
9
|
-
reject: (err: Error) => void;
|
|
10
|
-
timer: ReturnType<typeof setTimeout>;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export class IpcClient {
|
|
14
|
-
private socket: net.Socket | null = null;
|
|
15
|
-
private decoder = new MessageDecoder();
|
|
16
|
-
private pending = new Map<string, PendingRequest>();
|
|
17
|
-
private onNotification?: (msg: IpcMessage) => void;
|
|
18
|
-
|
|
19
|
-
constructor(
|
|
20
|
-
private pipeName: string = getPipeName(),
|
|
21
|
-
private timeout: number = 5000,
|
|
22
|
-
) {}
|
|
23
|
-
|
|
24
|
-
connect(): Promise<void> {
|
|
25
|
-
return new Promise((resolve, reject) => {
|
|
26
|
-
this.socket = net.createConnection(this.pipeName, () => {
|
|
27
|
-
resolve();
|
|
28
|
-
});
|
|
29
|
-
|
|
30
|
-
this.socket.on('data', (chunk) => {
|
|
31
|
-
const messages = this.decoder.feed(chunk);
|
|
32
|
-
for (const msg of messages) {
|
|
33
|
-
this.handleMessage(msg);
|
|
34
|
-
}
|
|
35
|
-
});
|
|
36
|
-
|
|
37
|
-
this.socket.on('error', (err) => {
|
|
38
|
-
reject(err);
|
|
39
|
-
// Reject all pending requests
|
|
40
|
-
for (const [id, req] of this.pending) {
|
|
41
|
-
clearTimeout(req.timer);
|
|
42
|
-
req.reject(new Error(`Connection error: ${err.message}`));
|
|
43
|
-
this.pending.delete(id);
|
|
44
|
-
}
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
this.socket.on('close', () => {
|
|
48
|
-
for (const [id, req] of this.pending) {
|
|
49
|
-
clearTimeout(req.timer);
|
|
50
|
-
req.reject(new Error('Connection closed'));
|
|
51
|
-
this.pending.delete(id);
|
|
52
|
-
}
|
|
53
|
-
this.socket = null;
|
|
54
|
-
});
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
request(method: string, params?: unknown): Promise<unknown> {
|
|
59
|
-
return new Promise((resolve, reject) => {
|
|
60
|
-
if (!this.socket || this.socket.destroyed) {
|
|
61
|
-
return reject(new Error('Not connected'));
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
const id = randomUUID();
|
|
65
|
-
const timer = setTimeout(() => {
|
|
66
|
-
this.pending.delete(id);
|
|
67
|
-
reject(new Error(`Request timeout: ${method} (${this.timeout}ms)`));
|
|
68
|
-
}, this.timeout);
|
|
69
|
-
|
|
70
|
-
this.pending.set(id, { resolve, reject, timer });
|
|
71
|
-
|
|
72
|
-
const msg: IpcMessage = {
|
|
73
|
-
id,
|
|
74
|
-
type: 'request',
|
|
75
|
-
method,
|
|
76
|
-
params,
|
|
77
|
-
};
|
|
78
|
-
this.socket.write(encodeMessage(msg));
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
setNotificationHandler(handler: (msg: IpcMessage) => void): void {
|
|
83
|
-
this.onNotification = handler;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
disconnect(): void {
|
|
87
|
-
for (const [id, req] of this.pending) {
|
|
88
|
-
clearTimeout(req.timer);
|
|
89
|
-
req.reject(new Error('Client disconnecting'));
|
|
90
|
-
this.pending.delete(id);
|
|
91
|
-
}
|
|
92
|
-
this.socket?.destroy();
|
|
93
|
-
this.socket = null;
|
|
94
|
-
this.decoder.reset();
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
get connected(): boolean {
|
|
98
|
-
return this.socket !== null && !this.socket.destroyed;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
private handleMessage(msg: IpcMessage): void {
|
|
102
|
-
if (msg.type === 'response') {
|
|
103
|
-
const req = this.pending.get(msg.id);
|
|
104
|
-
if (!req) return;
|
|
105
|
-
|
|
106
|
-
clearTimeout(req.timer);
|
|
107
|
-
this.pending.delete(msg.id);
|
|
108
|
-
|
|
109
|
-
if (msg.error) {
|
|
110
|
-
req.reject(new Error(msg.error.message));
|
|
111
|
-
} else {
|
|
112
|
-
req.resolve(msg.result);
|
|
113
|
-
}
|
|
114
|
-
} else if (msg.type === 'notification') {
|
|
115
|
-
this.onNotification?.(msg);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
}
|
package/src/ipc/protocol.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
import { Buffer } from 'node:buffer';
|
|
2
|
-
import type { IpcMessage } from '../types/ipc.types.js';
|
|
3
|
-
|
|
4
|
-
export function encodeMessage(msg: IpcMessage): Buffer {
|
|
5
|
-
const json = JSON.stringify(msg);
|
|
6
|
-
const payload = Buffer.from(json, 'utf8');
|
|
7
|
-
const frame = Buffer.alloc(4 + payload.length);
|
|
8
|
-
frame.writeUInt32BE(payload.length, 0);
|
|
9
|
-
payload.copy(frame, 4);
|
|
10
|
-
return frame;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export class MessageDecoder {
|
|
14
|
-
private buffer = Buffer.alloc(0);
|
|
15
|
-
|
|
16
|
-
feed(chunk: Buffer): IpcMessage[] {
|
|
17
|
-
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
18
|
-
const messages: IpcMessage[] = [];
|
|
19
|
-
|
|
20
|
-
while (this.buffer.length >= 4) {
|
|
21
|
-
const length = this.buffer.readUInt32BE(0);
|
|
22
|
-
if (this.buffer.length < 4 + length) break;
|
|
23
|
-
|
|
24
|
-
const json = this.buffer.subarray(4, 4 + length).toString('utf8');
|
|
25
|
-
this.buffer = this.buffer.subarray(4 + length);
|
|
26
|
-
messages.push(JSON.parse(json) as IpcMessage);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
return messages;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
reset(): void {
|
|
33
|
-
this.buffer = Buffer.alloc(0);
|
|
34
|
-
}
|
|
35
|
-
}
|