crbro-memory 1.10.0 → 1.11.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/bin/crbro.mjs CHANGED
@@ -1,424 +1,485 @@
1
- #!/usr/bin/env node
2
-
3
- // ─── CRBRO CLI ───────────────────────────────────────────────────
4
- // Command-line interface for CRBRO memory system
5
- // Supports: init, status, mine, setup-miner, miner-status,
6
- // remove-miner, and MCP server mode (default)
7
-
8
- import { platform, homedir } from 'os';
9
- import { join, dirname } from 'path';
10
- import { existsSync, readFileSync } from 'fs';
11
- import { fileURLToPath } from 'url';
12
-
13
- // The release that is running, read from the package itself. The manifest
14
- // version stamps the brain format and has not moved since 1.0.0, so showing
15
- // only that one told everyone they were on 1.0.0 forever.
16
- function pkgVersion() {
17
- try {
18
- const here = dirname(fileURLToPath(import.meta.url));
19
- return JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8')).version;
20
- } catch {
21
- return 'unknown';
22
- }
23
- }
24
-
25
- const args = process.argv.slice(2);
26
- const command = args[0];
27
-
28
- // ─── IDE Detection ──────────────────────────────────────────────
29
- const IDE_CONFIGS = [
30
- {
31
- name: 'Antigravity (Google Gemini)',
32
- id: 'antigravity',
33
- configPath: () => join(homedir(), '.gemini', 'antigravity', 'mcp_config.json'),
34
- configFormat: 'mcpServers',
35
- },
36
- {
37
- name: 'Cursor',
38
- id: 'cursor',
39
- configPath: () => join(homedir(), '.cursor', 'mcp.json'),
40
- configFormat: 'mcpServers',
41
- },
42
- {
43
- name: 'Windsurf',
44
- id: 'windsurf',
45
- configPath: () => join(homedir(), '.windsurf', 'mcp.json'),
46
- configFormat: 'mcpServers',
47
- },
48
- {
49
- name: 'Claude Desktop',
50
- id: 'claude-desktop',
51
- configPath: () => {
52
- if (platform() === 'win32') {
53
- return join(process.env.APPDATA || '', 'Claude', 'claude_desktop_config.json');
54
- }
55
- return join(homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
56
- },
57
- configFormat: 'mcpServers',
58
- },
59
- {
60
- name: 'Claude Code (user scope)',
61
- id: 'claude-code',
62
- configPath: () => join(homedir(), '.claude.json'),
63
- configFormat: 'mcpServers',
64
- },
65
- {
66
- name: 'VS Code + Continue',
67
- id: 'continue',
68
- configPath: () => join(homedir(), '.continue', 'config.json'),
69
- configFormat: 'mcpServers',
70
- },
71
- {
72
- name: 'ChatGPT Desktop',
73
- id: 'chatgpt',
74
- configPath: () => {
75
- if (platform() === 'win32') {
76
- return join(process.env.APPDATA || '', 'ChatGPT', 'mcp_config.json');
77
- }
78
- return join(homedir(), 'Library', 'Application Support', 'ChatGPT', 'mcp_config.json');
79
- },
80
- configFormat: 'mcpServers',
81
- },
82
- ];
83
-
84
- function detectIDEs() {
85
- const detected = [];
86
- for (const ide of IDE_CONFIGS) {
87
- try {
88
- const configPath = ide.configPath();
89
- if (existsSync(configPath)) {
90
- detected.push({ ...ide, configPath: configPath, exists: true });
91
- } else {
92
- // Check if the parent directory exists (IDE installed but no config yet)
93
- const parentDir = configPath.split(/[/\\]/).slice(0, -1).join(platform() === 'win32' ? '\\' : '/');
94
- if (existsSync(parentDir)) {
95
- detected.push({ ...ide, configPath: configPath, exists: false });
96
- }
97
- }
98
- } catch { /* skip */ }
99
- }
100
- return detected;
101
- }
102
-
103
- function generateMCPSnippet(envVars) {
104
- return JSON.stringify({
105
- "crbro": {
106
- "command": "npx",
107
- "args": ["-y", "crbro-memory"],
108
- ...(envVars ? { "env": envVars } : {})
109
- }
110
- }, null, 2);
111
- }
112
-
113
- // ─── Commands ───────────────────────────────────────────────────
114
-
115
- if (command === 'init') {
116
- // ─── Initialize brain + IDE detection ──────────────────────────
117
- import('../dist/engine/brain.js').then(async ({ Brain }) => {
118
- const brain = new Brain();
119
- const manifest = await brain.initialize();
120
-
121
- console.log('');
122
- console.log(' 🧠 CRBRO brain initialized!');
123
- console.log(` Path: ${manifest.brain_path}`);
124
- console.log('');
125
-
126
- // Detect IDEs
127
- const ides = detectIDEs();
128
-
129
- if (ides.length > 0) {
130
- console.log(' 📡 Detected IDEs:');
131
- console.log('');
132
- for (const ide of ides) {
133
- const status = ide.exists ? '✅ config exists' : '📝 needs config';
134
- console.log(` ${ide.name}: ${status}`);
135
- console.log(` → ${ide.configPath}`);
136
- }
137
- console.log('');
138
- console.log(' Add this to your MCP config (inside "mcpServers"):');
139
- } else {
140
- console.log(' ⚠️ No IDE detected. Add this to your MCP config manually:');
141
- }
142
-
143
- console.log('');
144
- console.log(' ' + generateMCPSnippet().split('\n').join('\n '));
145
- console.log('');
146
- console.log(' Next steps:');
147
- console.log(' 1. Add the config above to your IDE\'s MCP settings');
148
- console.log(' 2. (Optional) npx crbro-memory setup-miner');
149
- console.log(' 3. Restart your IDE — CRBRO boots automatically!');
150
- console.log('');
151
- }).catch(console.error);
152
-
153
- } else if (command === 'status') {
154
- // ─── Show brain status ─────────────────────────────────────────
155
- import('../dist/engine/brain.js').then(async ({ Brain }) => {
156
- const brain = new Brain();
157
- try {
158
- const manifest = await brain.getManifest();
159
- console.log('');
160
- console.log(' 🧠 CRBRO Brain Status');
161
- console.log(' ─────────────────────');
162
- console.log(` CRBRO: ${pkgVersion()}`);
163
- console.log(` Brain format: ${manifest.version}`);
164
- console.log(` Path: ${manifest.brain_path}`);
165
- console.log(` Neurons: ${manifest.total_neurons}`);
166
- console.log(` Synapses: ${manifest.total_synapses}`);
167
- console.log(` Sessions: ${manifest.total_sessions}`);
168
- console.log(` Last Boot: ${manifest.last_boot || 'never'}`);
169
- console.log(` Last Consolidate: ${manifest.last_consolidation || 'never'}`);
170
- console.log('');
171
-
172
- // Show detected IDEs
173
- const ides = detectIDEs();
174
- if (ides.length > 0) {
175
- console.log(' 📡 Connected IDEs:');
176
- for (const ide of ides) {
177
- console.log(` ${ide.exists ? '✅' : '⚠️ '} ${ide.name}`);
178
- }
179
- console.log('');
180
- }
181
- } catch {
182
- console.log('');
183
- console.log(' 🧠 CRBRO brain not initialized.');
184
- console.log(' Run: npx crbro-memory init');
185
- console.log('');
186
- }
187
- }).catch(console.error);
188
-
189
- } else if (command === 'activate') {
190
- // ─── Legacy command (pre-1.4.0) — CRBRO is now fully free ──────
191
- console.log('');
192
- console.log(' ✅ Good news: since v1.4.0 CRBRO is fully free.');
193
- console.log(' All 15 tools are available — no license key needed.');
194
- console.log('');
195
-
196
- } else if (command === 'mine') {
197
- // ─── One-shot mining ───────────────────────────────────────────
198
- const targetDir = args[1];
199
-
200
- import('../dist/miner/index.js').then(async ({ Miner }) => {
201
- console.log('');
202
- console.log(' ⛏️ CRBRO Miner — Scanning for knowledge...');
203
- console.log('');
204
-
205
- const miner = new Miner();
206
- const result = await miner.mine(targetDir);
207
-
208
- console.log(' ────────────────────────────────');
209
- console.log(` Files scanned: ${result.scanned}`);
210
- console.log(` New files mined: ${result.new_files}`);
211
- console.log(` Neurons created: ${result.neurons_created}`);
212
- console.log(` Neurons updated: ${result.neurons_updated}`);
213
- console.log(` Facts added: ${result.facts_added}`);
214
- console.log(` Decisions found: ${result.decisions_added}`);
215
-
216
- if (result.technologies_found.length > 0) {
217
- console.log(` Technologies: ${result.technologies_found.slice(0, 10).join(', ')}`);
218
- }
219
-
220
- if (result.errors.length > 0) {
221
- console.log('');
222
- console.log(' ⚠️ Errors:');
223
- for (const err of result.errors.slice(0, 5)) {
224
- console.log(` ${err}`);
225
- }
226
- }
227
-
228
- console.log('');
229
- }).catch(console.error);
230
-
231
- } else if (command === 'setup-miner') {
232
- // ─── Setup automatic mining ────────────────────────────────────
233
- import('../dist/miner/scheduler.js').then(async ({ setupScheduler }) => {
234
- console.log('');
235
- console.log(' ⏰ Setting up CRBRO Auto-Miner...');
236
- console.log('');
237
-
238
- const result = await setupScheduler();
239
- console.log(result.message);
240
- console.log('');
241
- }).catch(console.error);
242
-
243
- } else if (command === 'miner-status') {
244
- // ─── Check miner status ────────────────────────────────────────
245
- Promise.all([
246
- import('../dist/miner/scheduler.js'),
247
- import('../dist/miner/index.js'),
248
- ]).then(async ([{ getSchedulerStatus }, { Miner }]) => {
249
- console.log('');
250
- console.log(' ⛏️ CRBRO Miner Status');
251
- console.log(' ─────────────────────');
252
-
253
- // Scheduler status
254
- const schedStatus = await getSchedulerStatus();
255
- console.log(` Scheduler: ${schedStatus.installed ? '✅ Installed' : '❌ Not installed'}`);
256
- console.log(` Platform: ${schedStatus.platform}`);
257
- if (schedStatus.details) {
258
- console.log(` Details: ${schedStatus.details}`);
259
- }
260
-
261
- // Miner state
262
- const miner = new Miner();
263
- const status = await miner.getStatus();
264
- console.log('');
265
- console.log(` Last run: ${status.state.last_run || 'never'}`);
266
- console.log(` Total mined: ${status.state.total_mined} files`);
267
- console.log(` Tracked: ${Object.keys(status.state.mined_files).length} files`);
268
- console.log('');
269
-
270
- if (status.detected_dirs.length > 0) {
271
- console.log(' 📂 Scan directories:');
272
- for (const dir of status.detected_dirs) {
273
- console.log(` ${dir}`);
274
- }
275
- } else {
276
- console.log(' ⚠️ No IDE directories detected.');
277
- }
278
- console.log('');
279
- }).catch(console.error);
280
-
281
- } else if (command === 'remove-miner') {
282
- // ─── Remove automatic mining ───────────────────────────────────
283
- import('../dist/miner/scheduler.js').then(async ({ removeScheduler }) => {
284
- const result = await removeScheduler();
285
- console.log('');
286
- console.log(result.success ? ` ✅ ${result.message}` : ` ❌ ${result.message}`);
287
- console.log('');
288
- }).catch(console.error);
289
-
290
- } else if (command === 'reindex') {
291
- // ─── Rebuild the search index from the cortex ──────────────────
292
- Promise.all([
293
- import('../dist/engine/brain.js'),
294
- import('../dist/search/index.js'),
295
- ]).then(async ([{ Brain }, { SearchEngine }]) => {
296
- const brain = new Brain();
297
- const engine = new SearchEngine(brain);
298
-
299
- console.log('');
300
- console.log(' 🔁 Rebuilding the CRBRO search index...');
301
- const started = Date.now();
302
- const indexed = await engine.rebuild();
303
- const seconds = ((Date.now() - started) / 1000).toFixed(1);
304
-
305
- console.log('');
306
- console.log(` ✅ ${indexed} chunks indexed in ${seconds}s`);
307
- console.log(' Every fact, decision and pattern is now searchable on its own,');
308
- console.log(' so a big neuron is no longer buried by short ones.');
309
- console.log('');
310
- }).catch(console.error);
311
-
312
- } else if (command === 'eval') {
313
- // ─── Measure retrieval quality against a query set ─────────────
314
- //
315
- // Without a number you cannot tell a fix from a feeling. The file is
316
- // .crbro/.eval/queries.json — a list of { query, expect_neuron } and
317
- // optionally expect_contains, the substring the matched fact should carry.
318
- Promise.all([
319
- import('../dist/engine/brain.js'),
320
- import('../dist/search/index.js'),
321
- import('fs/promises'),
322
- ]).then(async ([{ Brain }, { SearchEngine }, fsp]) => {
323
- const brain = new Brain();
324
- const evalPath = join(brain.paths.root, '.eval', 'queries.json');
325
-
326
- let queries;
327
- try {
328
- queries = JSON.parse(await fsp.readFile(evalPath, 'utf-8'));
329
- } catch {
330
- console.log('');
331
- console.log(` No query set found at ${evalPath}`);
332
- console.log(' Create it as a JSON array, for example:');
333
- console.log('');
334
- console.log(' [');
335
- console.log(' { "query": "how we deploy the api", "expect_neuron": "project_octochat",');
336
- console.log(' "expect_contains": "Cloud Run" }');
337
- console.log(' ]');
338
- console.log('');
339
- console.log(' Build it from facts you already saved: take six or eight words');
340
- console.log(' out of a real fact and name the neuron that holds it.');
341
- console.log('');
342
- return;
343
- }
344
-
345
- const engine = new SearchEngine(brain);
346
- await engine.init();
347
-
348
- let atOne = 0, atThree = 0, reciprocal = 0, contentOk = 0;
349
- const misses = [];
350
-
351
- for (const q of queries) {
352
- const results = await engine.search(q.query, { limit: 10 });
353
- const rank = results.findIndex(r => r.neuron_id === q.expect_neuron);
354
-
355
- if (rank === 0) atOne++;
356
- if (rank >= 0 && rank < 3) atThree++;
357
- if (rank >= 0) reciprocal += 1 / (rank + 1);
358
-
359
- if (rank === 0 && q.expect_contains) {
360
- if (results[0].matching_content.includes(q.expect_contains)) contentOk++;
361
- else misses.push(` ~ "${q.query}" — right neuron, wrong fact returned`);
362
- }
363
-
364
- if (rank !== 0) {
365
- const got = results[0] ? results[0].neuron_id : '(nothing)';
366
- misses.push(` ✗ "${q.query}" — expected ${q.expect_neuron}, got ${got}` +
367
- (rank > 0 ? ` (it was #${rank + 1})` : ''));
368
- }
369
- }
370
-
371
- const n = queries.length;
372
- const pct = (x) => `${((x / n) * 100).toFixed(1)}%`;
373
-
374
- console.log('');
375
- console.log(' 📊 CRBRO retrieval eval');
376
- console.log(' ───────────────────────');
377
- console.log(` Queries: ${n}`);
378
- console.log(` Right first hit: ${atOne}/${n} (${pct(atOne)})`);
379
- console.log(` In the top 3: ${atThree}/${n} (${pct(atThree)})`);
380
- console.log(` MRR: ${(reciprocal / n).toFixed(3)}`);
381
- if (queries.some(q => q.expect_contains)) {
382
- const withContent = queries.filter(q => q.expect_contains).length;
383
- console.log(` Right fact shown: ${contentOk}/${withContent}`);
384
- }
385
-
386
- if (misses.length > 0) {
387
- console.log('');
388
- console.log(' Misses:');
389
- for (const m of misses.slice(0, 25)) console.log(m);
390
- if (misses.length > 25) console.log(` ... and ${misses.length - 25} more`);
391
- }
392
- console.log('');
393
- }).catch(console.error);
394
-
395
- } else if (command === '--help' || command === '-h') {
396
- // ─── Help ──────────────────────────────────────────────────────
397
- console.log('');
398
- console.log(' 🧠 CRBRO Persistent Neural Memory for AI');
399
- console.log(' ═══════════════════════════════════════════');
400
- console.log('');
401
- console.log(' Setup:');
402
- console.log(' npx crbro-memory init Initialize brain + detect IDEs');
403
- console.log(' npx crbro-memory status Show brain status');
404
- console.log('');
405
- console.log(' Auto-Mining:');
406
- console.log(' npx crbro-memory mine [dir] One-shot mining of artifacts');
407
- console.log(' npx crbro-memory setup-miner Install scheduled auto-miner');
408
- console.log(' npx crbro-memory miner-status Check auto-miner status');
409
- console.log(' npx crbro-memory remove-miner Remove auto-miner');
410
- console.log('');
411
- console.log(' Search:');
412
- console.log(' npx crbro-memory reindex Rebuild the search index');
413
- console.log(' npx crbro-memory eval Measure retrieval against .crbro/.eval/queries.json');
414
- console.log('');
415
- console.log(' Server:');
416
- console.log(' npx crbro-memory Start MCP server (stdio)');
417
- console.log('');
418
- console.log(' Open source (MIT) — https://github.com/Octonove/crbro-memory');
419
- console.log('');
420
-
421
- } else {
422
- // ─── Default: start MCP server ─────────────────────────────────
423
- import('../dist/index.js').catch(console.error);
424
- }
1
+ #!/usr/bin/env node
2
+
3
+ // ─── CRBRO CLI ───────────────────────────────────────────────────
4
+ // Command-line interface for CRBRO memory system
5
+ // Supports: init, status, mine, setup-miner, miner-status,
6
+ // remove-miner, and MCP server mode (default)
7
+
8
+ import { platform, homedir } from 'os';
9
+ import { join, dirname } from 'path';
10
+ import { existsSync, readFileSync } from 'fs';
11
+ import { fileURLToPath } from 'url';
12
+
13
+ // The release that is running, read from the package itself. The manifest
14
+ // version stamps the brain format and has not moved since 1.0.0, so showing
15
+ // only that one told everyone they were on 1.0.0 forever.
16
+ function pkgVersion() {
17
+ try {
18
+ const here = dirname(fileURLToPath(import.meta.url));
19
+ return JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8')).version;
20
+ } catch {
21
+ return 'unknown';
22
+ }
23
+ }
24
+
25
+ const args = process.argv.slice(2);
26
+ const command = args[0];
27
+
28
+ // ─── IDE Detection ──────────────────────────────────────────────
29
+ const IDE_CONFIGS = [
30
+ {
31
+ name: 'Antigravity (Google Gemini)',
32
+ id: 'antigravity',
33
+ configPath: () => join(homedir(), '.gemini', 'antigravity', 'mcp_config.json'),
34
+ configFormat: 'mcpServers',
35
+ },
36
+ {
37
+ name: 'Cursor',
38
+ id: 'cursor',
39
+ configPath: () => join(homedir(), '.cursor', 'mcp.json'),
40
+ configFormat: 'mcpServers',
41
+ },
42
+ {
43
+ name: 'Windsurf',
44
+ id: 'windsurf',
45
+ configPath: () => join(homedir(), '.windsurf', 'mcp.json'),
46
+ configFormat: 'mcpServers',
47
+ },
48
+ {
49
+ name: 'Claude Desktop',
50
+ id: 'claude-desktop',
51
+ configPath: () => {
52
+ if (platform() === 'win32') {
53
+ return join(process.env.APPDATA || '', 'Claude', 'claude_desktop_config.json');
54
+ }
55
+ return join(homedir(), 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
56
+ },
57
+ configFormat: 'mcpServers',
58
+ },
59
+ {
60
+ name: 'Claude Code (user scope)',
61
+ id: 'claude-code',
62
+ configPath: () => join(homedir(), '.claude.json'),
63
+ configFormat: 'mcpServers',
64
+ },
65
+ {
66
+ name: 'VS Code + Continue',
67
+ id: 'continue',
68
+ configPath: () => join(homedir(), '.continue', 'config.json'),
69
+ configFormat: 'mcpServers',
70
+ },
71
+ {
72
+ name: 'ChatGPT Desktop',
73
+ id: 'chatgpt',
74
+ configPath: () => {
75
+ if (platform() === 'win32') {
76
+ return join(process.env.APPDATA || '', 'ChatGPT', 'mcp_config.json');
77
+ }
78
+ return join(homedir(), 'Library', 'Application Support', 'ChatGPT', 'mcp_config.json');
79
+ },
80
+ configFormat: 'mcpServers',
81
+ },
82
+ ];
83
+
84
+ function detectIDEs() {
85
+ const detected = [];
86
+ for (const ide of IDE_CONFIGS) {
87
+ try {
88
+ const configPath = ide.configPath();
89
+ if (existsSync(configPath)) {
90
+ detected.push({ ...ide, configPath: configPath, exists: true });
91
+ } else {
92
+ // Check if the parent directory exists (IDE installed but no config yet)
93
+ const parentDir = configPath.split(/[/\\]/).slice(0, -1).join(platform() === 'win32' ? '\\' : '/');
94
+ if (existsSync(parentDir)) {
95
+ detected.push({ ...ide, configPath: configPath, exists: false });
96
+ }
97
+ }
98
+ } catch { /* skip */ }
99
+ }
100
+ return detected;
101
+ }
102
+
103
+ function generateMCPSnippet(envVars) {
104
+ return JSON.stringify({
105
+ "crbro": {
106
+ "command": "npx",
107
+ "args": ["-y", "crbro-memory"],
108
+ ...(envVars ? { "env": envVars } : {})
109
+ }
110
+ }, null, 2);
111
+ }
112
+
113
+ // ─── Commands ───────────────────────────────────────────────────
114
+
115
+ if (command === 'init') {
116
+ // ─── Initialize brain + IDE detection ──────────────────────────
117
+ import('../dist/engine/brain.js').then(async ({ Brain }) => {
118
+ const brain = new Brain();
119
+ const manifest = await brain.initialize();
120
+
121
+ console.log('');
122
+ console.log(' 🧠 CRBRO brain initialized!');
123
+ console.log(` Path: ${manifest.brain_path}`);
124
+ console.log('');
125
+
126
+ // Detect IDEs
127
+ const ides = detectIDEs();
128
+
129
+ if (ides.length > 0) {
130
+ console.log(' 📡 Detected IDEs:');
131
+ console.log('');
132
+ for (const ide of ides) {
133
+ const status = ide.exists ? '✅ config exists' : '📝 needs config';
134
+ console.log(` ${ide.name}: ${status}`);
135
+ console.log(` → ${ide.configPath}`);
136
+ }
137
+ console.log('');
138
+ console.log(' Add this to your MCP config (inside "mcpServers"):');
139
+ } else {
140
+ console.log(' ⚠️ No IDE detected. Add this to your MCP config manually:');
141
+ }
142
+
143
+ console.log('');
144
+ console.log(' ' + generateMCPSnippet().split('\n').join('\n '));
145
+ console.log('');
146
+ console.log(' Next steps:');
147
+ console.log(' 1. Add the config above to your IDE\'s MCP settings');
148
+ console.log(' 2. (Optional) npx crbro-memory setup-miner');
149
+ console.log(' 3. Restart your IDE — CRBRO boots automatically!');
150
+ console.log('');
151
+ }).catch(console.error);
152
+
153
+ } else if (command === 'status') {
154
+ // ─── Show brain status ─────────────────────────────────────────
155
+ import('../dist/engine/brain.js').then(async ({ Brain }) => {
156
+ const brain = new Brain();
157
+ try {
158
+ const manifest = await brain.getManifest();
159
+ console.log('');
160
+ console.log(' 🧠 CRBRO Brain Status');
161
+ console.log(' ─────────────────────');
162
+ console.log(` CRBRO: ${pkgVersion()}`);
163
+ console.log(` Brain format: ${manifest.version}`);
164
+ console.log(` Path: ${manifest.brain_path}`);
165
+ console.log(` Neurons: ${manifest.total_neurons}`);
166
+ console.log(` Synapses: ${manifest.total_synapses}`);
167
+ console.log(` Sessions: ${manifest.total_sessions}`);
168
+ console.log(` Last Boot: ${manifest.last_boot || 'never'}`);
169
+ console.log(` Last Consolidate: ${manifest.last_consolidation || 'never'}`);
170
+ console.log('');
171
+
172
+ // Show detected IDEs
173
+ const ides = detectIDEs();
174
+ if (ides.length > 0) {
175
+ console.log(' 📡 Connected IDEs:');
176
+ for (const ide of ides) {
177
+ console.log(` ${ide.exists ? '✅' : '⚠️ '} ${ide.name}`);
178
+ }
179
+ console.log('');
180
+ }
181
+ } catch {
182
+ console.log('');
183
+ console.log(' 🧠 CRBRO brain not initialized.');
184
+ console.log(' Run: npx crbro-memory init');
185
+ console.log('');
186
+ }
187
+ }).catch(console.error);
188
+
189
+ } else if (command === 'activate') {
190
+ // ─── Legacy command (pre-1.4.0) — CRBRO is now fully free ──────
191
+ console.log('');
192
+ console.log(' ✅ Good news: since v1.4.0 CRBRO is fully free.');
193
+ console.log(' All 15 tools are available — no license key needed.');
194
+ console.log('');
195
+
196
+ } else if (command === 'mine') {
197
+ // ─── One-shot mining ───────────────────────────────────────────
198
+ const targetDir = args[1];
199
+
200
+ import('../dist/miner/index.js').then(async ({ Miner }) => {
201
+ console.log('');
202
+ console.log(' ⛏️ CRBRO Miner — Scanning for knowledge...');
203
+ console.log('');
204
+
205
+ const miner = new Miner();
206
+ const result = await miner.mine(targetDir);
207
+
208
+ console.log(' ────────────────────────────────');
209
+ console.log(` Files scanned: ${result.scanned}`);
210
+ console.log(` New files mined: ${result.new_files}`);
211
+ console.log(` Neurons created: ${result.neurons_created}`);
212
+ console.log(` Neurons updated: ${result.neurons_updated}`);
213
+ console.log(` Facts added: ${result.facts_added}`);
214
+ console.log(` Decisions found: ${result.decisions_added}`);
215
+
216
+ if (result.technologies_found.length > 0) {
217
+ console.log(` Technologies: ${result.technologies_found.slice(0, 10).join(', ')}`);
218
+ }
219
+
220
+ if (result.errors.length > 0) {
221
+ console.log('');
222
+ console.log(' ⚠️ Errors:');
223
+ for (const err of result.errors.slice(0, 5)) {
224
+ console.log(` ${err}`);
225
+ }
226
+ }
227
+
228
+ console.log('');
229
+ }).catch(console.error);
230
+
231
+ } else if (command === 'setup-miner') {
232
+ // ─── Setup automatic mining ────────────────────────────────────
233
+ import('../dist/miner/scheduler.js').then(async ({ setupScheduler }) => {
234
+ console.log('');
235
+ console.log(' ⏰ Setting up CRBRO Auto-Miner...');
236
+ console.log('');
237
+
238
+ const result = await setupScheduler();
239
+ console.log(result.message);
240
+ console.log('');
241
+ }).catch(console.error);
242
+
243
+ } else if (command === 'miner-status') {
244
+ // ─── Check miner status ────────────────────────────────────────
245
+ Promise.all([
246
+ import('../dist/miner/scheduler.js'),
247
+ import('../dist/miner/index.js'),
248
+ ]).then(async ([{ getSchedulerStatus }, { Miner }]) => {
249
+ console.log('');
250
+ console.log(' ⛏️ CRBRO Miner Status');
251
+ console.log(' ─────────────────────');
252
+
253
+ // Scheduler status
254
+ const schedStatus = await getSchedulerStatus();
255
+ console.log(` Scheduler: ${schedStatus.installed ? '✅ Installed' : '❌ Not installed'}`);
256
+ console.log(` Platform: ${schedStatus.platform}`);
257
+ if (schedStatus.details) {
258
+ console.log(` Details: ${schedStatus.details}`);
259
+ }
260
+
261
+ // Miner state
262
+ const miner = new Miner();
263
+ const status = await miner.getStatus();
264
+ console.log('');
265
+ console.log(` Last run: ${status.state.last_run || 'never'}`);
266
+ console.log(` Total mined: ${status.state.total_mined} files`);
267
+ console.log(` Tracked: ${Object.keys(status.state.mined_files).length} files`);
268
+ console.log('');
269
+
270
+ if (status.detected_dirs.length > 0) {
271
+ console.log(' 📂 Scan directories:');
272
+ for (const dir of status.detected_dirs) {
273
+ console.log(` ${dir}`);
274
+ }
275
+ } else {
276
+ console.log(' ⚠️ No IDE directories detected.');
277
+ }
278
+ console.log('');
279
+ }).catch(console.error);
280
+
281
+ } else if (command === 'remove-miner') {
282
+ // ─── Remove automatic mining ───────────────────────────────────
283
+ import('../dist/miner/scheduler.js').then(async ({ removeScheduler }) => {
284
+ const result = await removeScheduler();
285
+ console.log('');
286
+ console.log(result.success ? ` ✅ ${result.message}` : ` ❌ ${result.message}`);
287
+ console.log('');
288
+ }).catch(console.error);
289
+
290
+ } else if (command === 'reindex') {
291
+ // ─── Rebuild the search index from the cortex ──────────────────
292
+ Promise.all([
293
+ import('../dist/engine/brain.js'),
294
+ import('../dist/search/index.js'),
295
+ ]).then(async ([{ Brain }, { SearchEngine }]) => {
296
+ const brain = new Brain();
297
+ const engine = new SearchEngine(brain);
298
+
299
+ console.log('');
300
+ console.log(' 🔁 Rebuilding the CRBRO search index...');
301
+ const started = Date.now();
302
+ const indexed = await engine.rebuild();
303
+ const seconds = ((Date.now() - started) / 1000).toFixed(1);
304
+
305
+ console.log('');
306
+ console.log(` ✅ ${indexed} chunks indexed in ${seconds}s`);
307
+ console.log(' Every fact, decision and pattern is now searchable on its own,');
308
+ console.log(' so a big neuron is no longer buried by short ones.');
309
+ console.log('');
310
+ }).catch(console.error);
311
+
312
+ } else if (command === 'eval') {
313
+ // ─── Measure retrieval quality against a query set ─────────────
314
+ //
315
+ // Without a number you cannot tell a fix from a feeling. The file is
316
+ // .crbro/.eval/queries.json — a list of { query, expect_neuron } and
317
+ // optionally expect_contains, the substring the matched fact should carry.
318
+ Promise.all([
319
+ import('../dist/engine/brain.js'),
320
+ import('../dist/search/index.js'),
321
+ import('fs/promises'),
322
+ ]).then(async ([{ Brain }, { SearchEngine }, fsp]) => {
323
+ const brain = new Brain();
324
+ const evalPath = join(brain.paths.root, '.eval', 'queries.json');
325
+
326
+ let queries;
327
+ try {
328
+ queries = JSON.parse(await fsp.readFile(evalPath, 'utf-8'));
329
+ } catch {
330
+ console.log('');
331
+ console.log(` No query set found at ${evalPath}`);
332
+ console.log(' Create it as a JSON array, for example:');
333
+ console.log('');
334
+ console.log(' [');
335
+ console.log(' { "query": "how we deploy the api", "expect_neuron": "project_octochat",');
336
+ console.log(' "expect_contains": "Cloud Run" }');
337
+ console.log(' ]');
338
+ console.log('');
339
+ console.log(' Build it from facts you already saved: take six or eight words');
340
+ console.log(' out of a real fact and name the neuron that holds it.');
341
+ console.log('');
342
+ return;
343
+ }
344
+
345
+ const engine = new SearchEngine(brain);
346
+ await engine.init();
347
+
348
+ let atOne = 0, atThree = 0, reciprocal = 0, contentOk = 0;
349
+ const misses = [];
350
+
351
+ for (const q of queries) {
352
+ const results = await engine.search(q.query, { limit: 10 });
353
+ const rank = results.findIndex(r => r.neuron_id === q.expect_neuron);
354
+
355
+ if (rank === 0) atOne++;
356
+ if (rank >= 0 && rank < 3) atThree++;
357
+ if (rank >= 0) reciprocal += 1 / (rank + 1);
358
+
359
+ if (rank === 0 && q.expect_contains) {
360
+ if (results[0].matching_content.includes(q.expect_contains)) contentOk++;
361
+ else misses.push(` ~ "${q.query}" — right neuron, wrong fact returned`);
362
+ }
363
+
364
+ if (rank !== 0) {
365
+ const got = results[0] ? results[0].neuron_id : '(nothing)';
366
+ misses.push(` ✗ "${q.query}" — expected ${q.expect_neuron}, got ${got}` +
367
+ (rank > 0 ? ` (it was #${rank + 1})` : ''));
368
+ }
369
+ }
370
+
371
+ const n = queries.length;
372
+ const pct = (x) => `${((x / n) * 100).toFixed(1)}%`;
373
+
374
+ console.log('');
375
+ console.log(' 📊 CRBRO retrieval eval');
376
+ console.log(' ───────────────────────');
377
+ console.log(` Queries: ${n}`);
378
+ console.log(` Right first hit: ${atOne}/${n} (${pct(atOne)})`);
379
+ console.log(` In the top 3: ${atThree}/${n} (${pct(atThree)})`);
380
+ console.log(` MRR: ${(reciprocal / n).toFixed(3)}`);
381
+ if (queries.some(q => q.expect_contains)) {
382
+ const withContent = queries.filter(q => q.expect_contains).length;
383
+ console.log(` Right fact shown: ${contentOk}/${withContent}`);
384
+ }
385
+
386
+ if (misses.length > 0) {
387
+ console.log('');
388
+ console.log(' Misses:');
389
+ for (const m of misses.slice(0, 25)) console.log(m);
390
+ if (misses.length > 25) console.log(` ... and ${misses.length - 25} more`);
391
+ }
392
+ console.log('');
393
+ }).catch(console.error);
394
+
395
+ } else if (command === 'install-hooks') {
396
+ // ─── Wire the SubagentStart hook into Claude Code ──────────────
397
+ //
398
+ // SessionStart context never reaches Task-spawned subagents, so without
399
+ // this every subagent runs without the behavioral protocols the session
400
+ // was booted with. This registers hooks/crbro-subagent.mjs, which reads
401
+ // the same protocol neurons crbro_boot reads — one source of truth.
402
+ //
403
+ // Merges into ~/.claude/settings.json without touching anything else.
404
+ // Idempotent: running it twice changes nothing the second time.
405
+ import('fs').then(async fs => {
406
+ const settingsPath = join(homedir(), '.claude', 'settings.json');
407
+ const here = dirname(fileURLToPath(import.meta.url));
408
+ const source = join(here, '..', 'hooks', 'crbro-subagent.mjs');
409
+
410
+ // Copy the hook to a stable location. When CRBRO runs from the npx
411
+ // cache, `here` changes with every release and the stale path would
412
+ // break the hook silently on the next update.
413
+ const hookDir = join(homedir(), '.claude', 'crbro-hooks');
414
+ const hookScript = join(hookDir, 'crbro-subagent.mjs');
415
+ fs.mkdirSync(hookDir, { recursive: true });
416
+ fs.copyFileSync(source, hookScript);
417
+ const hookCmd = `node "${hookScript.split('\\').join('/')}"`;
418
+
419
+ let settings = {};
420
+ try {
421
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8').replace(/^/, ''));
422
+ } catch (e) {
423
+ if (fs.existsSync(settingsPath)) {
424
+ console.error(` ❌ ${settingsPath} exists but could not be parsed — not touching it.`);
425
+ console.error(` ${e.message}`);
426
+ process.exit(1);
427
+ }
428
+ }
429
+
430
+ settings.hooks = settings.hooks || {};
431
+ const list = settings.hooks.SubagentStart = settings.hooks.SubagentStart || [];
432
+ const yaEsta = JSON.stringify(list).includes('crbro-subagent');
433
+ if (yaEsta) {
434
+ console.log(' ✅ SubagentStart hook already installed. Nothing to do.');
435
+ return;
436
+ }
437
+ list.push({
438
+ hooks: [{
439
+ type: 'command',
440
+ command: hookCmd,
441
+ timeout: 5,
442
+ statusMessage: 'Inyectando protocolos CRBRO en el subagente...',
443
+ }],
444
+ });
445
+
446
+ const tmp = settingsPath + '.' + process.pid + '.tmp';
447
+ fs.writeFileSync(tmp, JSON.stringify(settings, null, 2), 'utf8');
448
+ fs.renameSync(tmp, settingsPath);
449
+ console.log(' ✅ SubagentStart hook installed.');
450
+ console.log(` ${settingsPath}`);
451
+ console.log(' Every Task-spawned subagent now receives the same behavioral');
452
+ console.log(' protocols the session boots with. Scope it with the');
453
+ console.log(' CRBRO_SUBAGENT_MATCHER env var (regex on agent_type) if needed.');
454
+ }).catch(console.error);
455
+
456
+ } else if (command === '--help' || command === '-h') {
457
+ // ─── Help ──────────────────────────────────────────────────────
458
+ console.log('');
459
+ console.log(' 🧠 CRBRO — Persistent Neural Memory for AI');
460
+ console.log(' ═══════════════════════════════════════════');
461
+ console.log('');
462
+ console.log(' Setup:');
463
+ console.log(' npx crbro-memory init Initialize brain + detect IDEs');
464
+ console.log(' npx crbro-memory status Show brain status');
465
+ console.log('');
466
+ console.log(' Auto-Mining:');
467
+ console.log(' npx crbro-memory mine [dir] One-shot mining of artifacts');
468
+ console.log(' npx crbro-memory setup-miner Install scheduled auto-miner');
469
+ console.log(' npx crbro-memory miner-status Check auto-miner status');
470
+ console.log(' npx crbro-memory remove-miner Remove auto-miner');
471
+ console.log('');
472
+ console.log(' Search:');
473
+ console.log(' npx crbro-memory reindex Rebuild the search index');
474
+ console.log(' npx crbro-memory eval Measure retrieval against .crbro/.eval/queries.json');
475
+ console.log('');
476
+ console.log(' Server:');
477
+ console.log(' npx crbro-memory Start MCP server (stdio)');
478
+ console.log('');
479
+ console.log(' Open source (MIT) — https://github.com/Octonove/crbro-memory');
480
+ console.log('');
481
+
482
+ } else {
483
+ // ─── Default: start MCP server ─────────────────────────────────
484
+ import('../dist/index.js').catch(console.error);
485
+ }