brain-memory 0.1.0-beta.2 → 0.1.0-beta.20
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 +270 -72
- package/assets/icon.png +0 -0
- package/assets/icon.svg +27 -0
- package/bin/brain.js +111 -0
- package/bin/cloud-sync.js +149 -0
- package/bin/install.js +217 -242
- package/bin/memorize.js +433 -0
- package/bin/pin.js +44 -0
- package/bin/recall.js +237 -0
- package/bin/reinforce.js +187 -0
- package/bin/session-start.js +292 -0
- package/bin/skill.js +67 -0
- package/bin/unpin.js +38 -0
- package/commands/brain/consolidate.md +7 -2
- package/commands/brain/explore.md +7 -2
- package/commands/brain/forget.md +7 -2
- package/commands/brain/init.md +8 -12
- package/commands/brain/memorize.md +76 -144
- package/commands/brain/pin.md +37 -0
- package/commands/brain/remember.md +48 -105
- package/commands/brain/review.md +7 -2
- package/commands/brain/skills.md +60 -0
- package/commands/brain/sleep.md +68 -27
- package/commands/brain/status.md +19 -5
- package/commands/brain/sunshine.md +18 -13
- package/commands/brain/sync.md +360 -0
- package/commands/brain/unpin.md +26 -0
- package/package.json +18 -8
- package/prompts/claude.md +115 -12
- package/prompts/gemini.md +115 -12
- package/prompts/openai.md +113 -10
- package/prompts/opencode.md +178 -0
- package/src/cloud-sync.js +524 -0
- package/src/crypto.js +130 -0
- package/src/export-import.js +185 -0
- package/src/git-sync.js +444 -0
- package/src/index-manager.js +205 -18
- package/src/installer.js +384 -0
- package/src/pinning.js +124 -0
- package/src/scorer.js +6 -2
- package/src/skills.js +208 -0
- package/src/tfidf.js +408 -0
- package/hooks/session-end.md +0 -48
- package/hooks/session-start.md +0 -48
package/src/index-manager.js
CHANGED
|
@@ -1,28 +1,74 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Brain Memory — Index Manager
|
|
3
3
|
*
|
|
4
|
-
* Utilities for reading, updating, and maintaining the
|
|
4
|
+
* Utilities for reading, updating, and maintaining the ~/.brain/index.json
|
|
5
5
|
* file. Used by hooks and external integrations.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
const fs = require('fs');
|
|
9
9
|
const path = require('path');
|
|
10
|
+
const os = require('os');
|
|
11
|
+
const crypto = require('crypto');
|
|
10
12
|
|
|
11
|
-
const DEFAULT_BRAIN_DIR = '.brain';
|
|
13
|
+
const DEFAULT_BRAIN_DIR = path.join(os.homedir(), '.brain');
|
|
12
14
|
const INDEX_FILE = 'index.json';
|
|
13
15
|
const ASSOCIATIONS_FILE = 'associations.json';
|
|
14
16
|
const CONTEXTS_FILE = 'contexts.json';
|
|
15
17
|
const REVIEW_QUEUE_FILE = 'review-queue.json';
|
|
16
18
|
const ARCHIVE_INDEX_FILE = '_archived/index.json';
|
|
19
|
+
const SEARCH_INDEX_FILE = 'search-index.json';
|
|
20
|
+
const CONFIG_FILE = 'config.json';
|
|
21
|
+
const PINNED_FILE = 'pinned.json';
|
|
22
|
+
const SKILLS_INDEX_FILE = 'skills-index.json';
|
|
23
|
+
|
|
24
|
+
// CoALA Phase 0 — working-memory budget (token estimates, chars/4 heuristic).
|
|
25
|
+
// All values are conservative caps; the session-start aggregator never exceeds
|
|
26
|
+
// working_memory_budget_tokens and reports overflow rather than dropping silently.
|
|
27
|
+
const DEFAULT_CONFIG = {
|
|
28
|
+
working_memory_budget_tokens: 3000,
|
|
29
|
+
pin_budget_tokens: 1500,
|
|
30
|
+
skills_index_budget_tokens: 800,
|
|
31
|
+
recall_budget_tokens: 700,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Write data to a file atomically by writing to a temp file first,
|
|
36
|
+
* then renaming. Prevents corruption if the process crashes mid-write.
|
|
37
|
+
*
|
|
38
|
+
* @param {string} filePath - Target file path
|
|
39
|
+
* @param {string} data - Data to write
|
|
40
|
+
*/
|
|
41
|
+
function atomicWriteSync(filePath, data) {
|
|
42
|
+
const tmpPath = filePath + '.tmp.' + crypto.randomBytes(4).toString('hex');
|
|
43
|
+
fs.writeFileSync(tmpPath, data);
|
|
44
|
+
fs.renameSync(tmpPath, filePath);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Validate that a target path is within the brain directory.
|
|
49
|
+
* Prevents path traversal attacks (e.g. categoryPath = '../../etc/passwd').
|
|
50
|
+
*
|
|
51
|
+
* @param {string} targetPath - The resolved path to validate
|
|
52
|
+
* @param {string} brainDir - The brain directory root
|
|
53
|
+
* @throws {Error} if targetPath is outside brainDir
|
|
54
|
+
*/
|
|
55
|
+
function validateBrainPath(targetPath, brainDir) {
|
|
56
|
+
const resolved = path.resolve(targetPath);
|
|
57
|
+
const resolvedBrain = path.resolve(brainDir);
|
|
58
|
+
if (!resolved.startsWith(resolvedBrain + path.sep) && resolved !== resolvedBrain) {
|
|
59
|
+
throw new Error(`Path traversal detected: ${targetPath} is outside ${brainDir}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
17
62
|
|
|
18
63
|
/**
|
|
19
64
|
* Resolve the brain directory path.
|
|
20
65
|
*
|
|
21
|
-
* @param {string} [
|
|
22
|
-
* @returns {string} Absolute path to
|
|
66
|
+
* @param {string} [overrideBase] - Override base directory (for testing)
|
|
67
|
+
* @returns {string} Absolute path to ~/.brain/ (or overrideBase/.brain/ if provided)
|
|
23
68
|
*/
|
|
24
|
-
function getBrainDir(
|
|
25
|
-
return path.join(
|
|
69
|
+
function getBrainDir(overrideBase) {
|
|
70
|
+
if (overrideBase) return path.join(overrideBase, '.brain');
|
|
71
|
+
return DEFAULT_BRAIN_DIR;
|
|
26
72
|
}
|
|
27
73
|
|
|
28
74
|
/**
|
|
@@ -46,7 +92,7 @@ function readIndex(projectRoot) {
|
|
|
46
92
|
function writeIndex(index, projectRoot) {
|
|
47
93
|
const indexPath = path.join(getBrainDir(projectRoot), INDEX_FILE);
|
|
48
94
|
index.last_updated = new Date().toISOString();
|
|
49
|
-
|
|
95
|
+
atomicWriteSync(indexPath, JSON.stringify(index, null, 2) + '\n');
|
|
50
96
|
}
|
|
51
97
|
|
|
52
98
|
/**
|
|
@@ -106,27 +152,35 @@ function generateId() {
|
|
|
106
152
|
/**
|
|
107
153
|
* Read a _meta.json file from a brain subdirectory.
|
|
108
154
|
*
|
|
109
|
-
* @param {string} categoryPath - Relative path within
|
|
155
|
+
* @param {string} categoryPath - Relative path within ~/.brain/
|
|
110
156
|
* @param {string} [projectRoot] - Project root directory
|
|
111
157
|
* @returns {Object|null} Parsed meta or null
|
|
112
158
|
*/
|
|
113
159
|
function readMeta(categoryPath, projectRoot) {
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
160
|
+
const brainDir = getBrainDir(projectRoot);
|
|
161
|
+
const metaPath = path.join(brainDir, categoryPath, '_meta.json');
|
|
162
|
+
validateBrainPath(metaPath, brainDir);
|
|
163
|
+
try {
|
|
164
|
+
return JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
|
|
165
|
+
} catch (err) {
|
|
166
|
+
if (err.code === 'ENOENT') return null;
|
|
167
|
+
throw err;
|
|
168
|
+
}
|
|
117
169
|
}
|
|
118
170
|
|
|
119
171
|
/**
|
|
120
172
|
* Write a _meta.json file to a brain subdirectory.
|
|
121
173
|
*
|
|
122
|
-
* @param {string} categoryPath - Relative path within
|
|
174
|
+
* @param {string} categoryPath - Relative path within ~/.brain/
|
|
123
175
|
* @param {Object} meta - Meta object to write
|
|
124
176
|
* @param {string} [projectRoot] - Project root directory
|
|
125
177
|
*/
|
|
126
178
|
function writeMeta(categoryPath, meta, projectRoot) {
|
|
127
|
-
const
|
|
179
|
+
const brainDir = getBrainDir(projectRoot);
|
|
180
|
+
const metaPath = path.join(brainDir, categoryPath, '_meta.json');
|
|
181
|
+
validateBrainPath(metaPath, brainDir);
|
|
128
182
|
fs.mkdirSync(path.dirname(metaPath), { recursive: true });
|
|
129
|
-
|
|
183
|
+
atomicWriteSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
|
|
130
184
|
}
|
|
131
185
|
|
|
132
186
|
/**
|
|
@@ -167,7 +221,7 @@ function readAssociations(projectRoot) {
|
|
|
167
221
|
*/
|
|
168
222
|
function writeAssociations(associations, projectRoot) {
|
|
169
223
|
const filePath = path.join(getBrainDir(projectRoot), ASSOCIATIONS_FILE);
|
|
170
|
-
|
|
224
|
+
atomicWriteSync(filePath, JSON.stringify(associations, null, 2) + '\n');
|
|
171
225
|
}
|
|
172
226
|
|
|
173
227
|
/**
|
|
@@ -273,7 +327,7 @@ function readContexts(projectRoot) {
|
|
|
273
327
|
*/
|
|
274
328
|
function writeContexts(contexts, projectRoot) {
|
|
275
329
|
const filePath = path.join(getBrainDir(projectRoot), CONTEXTS_FILE);
|
|
276
|
-
|
|
330
|
+
atomicWriteSync(filePath, JSON.stringify(contexts, null, 2) + '\n');
|
|
277
331
|
}
|
|
278
332
|
|
|
279
333
|
// --- Review Queue (Phase 4: Spaced Repetition) ---
|
|
@@ -298,7 +352,7 @@ function readReviewQueue(projectRoot) {
|
|
|
298
352
|
*/
|
|
299
353
|
function writeReviewQueue(queue, projectRoot) {
|
|
300
354
|
const filePath = path.join(getBrainDir(projectRoot), REVIEW_QUEUE_FILE);
|
|
301
|
-
|
|
355
|
+
atomicWriteSync(filePath, JSON.stringify(queue, null, 2) + '\n');
|
|
302
356
|
}
|
|
303
357
|
|
|
304
358
|
// --- Archive Index (Phase 4: Archive Search) ---
|
|
@@ -324,7 +378,7 @@ function readArchiveIndex(projectRoot) {
|
|
|
324
378
|
function writeArchiveIndex(archiveIndex, projectRoot) {
|
|
325
379
|
const filePath = path.join(getBrainDir(projectRoot), ARCHIVE_INDEX_FILE);
|
|
326
380
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
327
|
-
|
|
381
|
+
atomicWriteSync(filePath, JSON.stringify(archiveIndex, null, 2) + '\n');
|
|
328
382
|
}
|
|
329
383
|
|
|
330
384
|
/**
|
|
@@ -370,8 +424,135 @@ function removeFromReviewQueue(queue, memoryId) {
|
|
|
370
424
|
return queue;
|
|
371
425
|
}
|
|
372
426
|
|
|
427
|
+
// --- Search Index (TF-IDF) ---
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Read the TF-IDF search index.
|
|
431
|
+
*
|
|
432
|
+
* @param {string} [projectRoot] - Project root directory
|
|
433
|
+
* @returns {Object|null} Parsed search index or null
|
|
434
|
+
*/
|
|
435
|
+
function readSearchIndex(projectRoot) {
|
|
436
|
+
const filePath = path.join(getBrainDir(projectRoot), SEARCH_INDEX_FILE);
|
|
437
|
+
try {
|
|
438
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
439
|
+
} catch (err) {
|
|
440
|
+
if (err.code === 'ENOENT') return null;
|
|
441
|
+
throw err;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Write the TF-IDF search index to disk.
|
|
447
|
+
*
|
|
448
|
+
* @param {Object} searchIndex - The search index object
|
|
449
|
+
* @param {string} [projectRoot] - Project root directory
|
|
450
|
+
*/
|
|
451
|
+
function writeSearchIndex(searchIndex, projectRoot) {
|
|
452
|
+
const filePath = path.join(getBrainDir(projectRoot), SEARCH_INDEX_FILE);
|
|
453
|
+
atomicWriteSync(filePath, JSON.stringify(searchIndex, null, 2) + '\n');
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// --- Config (CoALA Phase 0: working-memory budget) ---
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Read the brain config, merged over safe defaults. Created lazily — a missing
|
|
460
|
+
* or unreadable config falls back to DEFAULT_CONFIG so session-start is robust.
|
|
461
|
+
*
|
|
462
|
+
* @param {string} [projectRoot] - Project root directory
|
|
463
|
+
* @returns {Object} Config with all budget keys guaranteed present
|
|
464
|
+
*/
|
|
465
|
+
function readConfig(projectRoot) {
|
|
466
|
+
const filePath = path.join(getBrainDir(projectRoot), CONFIG_FILE);
|
|
467
|
+
let onDisk = {};
|
|
468
|
+
try {
|
|
469
|
+
onDisk = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
470
|
+
} catch (_) {
|
|
471
|
+
// ENOENT (not yet created) or corrupt JSON → fall back to defaults.
|
|
472
|
+
// Budgets are non-critical; a broken config must not break startup.
|
|
473
|
+
onDisk = {};
|
|
474
|
+
}
|
|
475
|
+
return { ...DEFAULT_CONFIG, ...onDisk };
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Write the brain config to disk atomically.
|
|
480
|
+
*
|
|
481
|
+
* @param {Object} config - The config object
|
|
482
|
+
* @param {string} [projectRoot] - Project root directory
|
|
483
|
+
*/
|
|
484
|
+
function writeConfig(config, projectRoot) {
|
|
485
|
+
const filePath = path.join(getBrainDir(projectRoot), CONFIG_FILE);
|
|
486
|
+
atomicWriteSync(filePath, JSON.stringify(config, null, 2) + '\n');
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// --- Pinned manifest (CoALA Phase 1: always-present semantic tier) ---
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Read the pinned-memory manifest. Lets session-start load pins without
|
|
493
|
+
* scanning the whole index. Missing/corrupt → empty manifest.
|
|
494
|
+
*
|
|
495
|
+
* @param {string} [projectRoot] - Project root directory
|
|
496
|
+
* @returns {Object} { version, pins: [{ id, scope, priority, token_estimate }] }
|
|
497
|
+
*/
|
|
498
|
+
function readPinned(projectRoot) {
|
|
499
|
+
const filePath = path.join(getBrainDir(projectRoot), PINNED_FILE);
|
|
500
|
+
try {
|
|
501
|
+
const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
502
|
+
if (data && Array.isArray(data.pins)) return data;
|
|
503
|
+
} catch (_) { /* fall through */ }
|
|
504
|
+
return { version: 1, pins: [] };
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Write the pinned-memory manifest to disk atomically.
|
|
509
|
+
*
|
|
510
|
+
* @param {Object} pinned - The pinned manifest
|
|
511
|
+
* @param {string} [projectRoot] - Project root directory
|
|
512
|
+
*/
|
|
513
|
+
function writePinned(pinned, projectRoot) {
|
|
514
|
+
const filePath = path.join(getBrainDir(projectRoot), PINNED_FILE);
|
|
515
|
+
atomicWriteSync(filePath, JSON.stringify(pinned, null, 2) + '\n');
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// --- Skills index (CoALA Phase 2: procedural progressive disclosure) ---
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Read the lightweight skills index (the L0 advertised list). Missing/corrupt
|
|
522
|
+
* → empty index.
|
|
523
|
+
*
|
|
524
|
+
* @param {string} [projectRoot] - Project root directory
|
|
525
|
+
* @returns {Object} { version, skills: [{ name, description, triggers, path, strength, use_count, fail_count, last_used }] }
|
|
526
|
+
*/
|
|
527
|
+
function readSkillsIndex(projectRoot) {
|
|
528
|
+
const filePath = path.join(getBrainDir(projectRoot), SKILLS_INDEX_FILE);
|
|
529
|
+
try {
|
|
530
|
+
const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
531
|
+
if (data && Array.isArray(data.skills)) return data;
|
|
532
|
+
} catch (_) { /* fall through */ }
|
|
533
|
+
return { version: 1, skills: [] };
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Write the skills index to disk atomically.
|
|
538
|
+
*
|
|
539
|
+
* @param {Object} skillsIndex - The skills index
|
|
540
|
+
* @param {string} [projectRoot] - Project root directory
|
|
541
|
+
*/
|
|
542
|
+
function writeSkillsIndex(skillsIndex, projectRoot) {
|
|
543
|
+
const filePath = path.join(getBrainDir(projectRoot), SKILLS_INDEX_FILE);
|
|
544
|
+
atomicWriteSync(filePath, JSON.stringify(skillsIndex, null, 2) + '\n');
|
|
545
|
+
}
|
|
546
|
+
|
|
373
547
|
module.exports = {
|
|
374
548
|
getBrainDir,
|
|
549
|
+
DEFAULT_CONFIG,
|
|
550
|
+
readConfig,
|
|
551
|
+
writeConfig,
|
|
552
|
+
readPinned,
|
|
553
|
+
writePinned,
|
|
554
|
+
readSkillsIndex,
|
|
555
|
+
writeSkillsIndex,
|
|
375
556
|
readIndex,
|
|
376
557
|
writeIndex,
|
|
377
558
|
addMemory,
|
|
@@ -395,7 +576,13 @@ module.exports = {
|
|
|
395
576
|
writeReviewQueue,
|
|
396
577
|
readArchiveIndex,
|
|
397
578
|
writeArchiveIndex,
|
|
579
|
+
// Search Index (TF-IDF)
|
|
580
|
+
readSearchIndex,
|
|
581
|
+
writeSearchIndex,
|
|
398
582
|
// Deep erasure utilities
|
|
399
583
|
removeEdgesForMemory,
|
|
400
584
|
removeFromReviewQueue,
|
|
585
|
+
// Security utilities
|
|
586
|
+
atomicWriteSync,
|
|
587
|
+
validateBrainPath,
|
|
401
588
|
};
|
package/src/installer.js
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const os = require('os');
|
|
4
|
+
|
|
5
|
+
const PACKAGE_ROOT = path.resolve(__dirname, '..');
|
|
6
|
+
|
|
7
|
+
const RUNTIMES = {
|
|
8
|
+
claude: {
|
|
9
|
+
name: 'Claude Code',
|
|
10
|
+
globalDir: path.join(os.homedir(), '.claude'),
|
|
11
|
+
localDir: '.claude',
|
|
12
|
+
commandsSubdir: 'commands',
|
|
13
|
+
promptFile: 'CLAUDE.md',
|
|
14
|
+
promptSource: 'claude.md',
|
|
15
|
+
commandStyle: 'flat',
|
|
16
|
+
},
|
|
17
|
+
gemini: {
|
|
18
|
+
name: 'Gemini CLI',
|
|
19
|
+
globalDir: path.join(os.homedir(), '.gemini'),
|
|
20
|
+
localDir: '.gemini',
|
|
21
|
+
commandsSubdir: 'commands',
|
|
22
|
+
promptFile: 'GEMINI.md',
|
|
23
|
+
promptSource: 'gemini.md',
|
|
24
|
+
commandStyle: 'flat',
|
|
25
|
+
},
|
|
26
|
+
openai: {
|
|
27
|
+
name: 'OpenAI Codex CLI',
|
|
28
|
+
globalDir: path.join(os.homedir(), '.codex'),
|
|
29
|
+
localDir: '.codex',
|
|
30
|
+
commandsSubdir: 'skills',
|
|
31
|
+
promptFile: 'AGENTS.md',
|
|
32
|
+
promptSource: 'openai.md',
|
|
33
|
+
commandStyle: 'skills',
|
|
34
|
+
},
|
|
35
|
+
opencode: {
|
|
36
|
+
name: 'OpenCode',
|
|
37
|
+
globalDir: path.join(os.homedir(), '.config', 'opencode'),
|
|
38
|
+
localDir: '.opencode',
|
|
39
|
+
commandsSubdir: 'commands',
|
|
40
|
+
promptFile: 'AGENTS.md',
|
|
41
|
+
promptSource: 'opencode.md',
|
|
42
|
+
commandStyle: 'flat',
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const BRAIN_MARKER_START = '<!-- BRAIN-MEMORY-START -->';
|
|
47
|
+
const BRAIN_MARKER_END = '<!-- BRAIN-MEMORY-END -->';
|
|
48
|
+
|
|
49
|
+
function copyDir(src, dest, _depth = 0) {
|
|
50
|
+
if (_depth > 20) {
|
|
51
|
+
throw new Error(`copyDir: max depth (20) exceeded at ${src}`);
|
|
52
|
+
}
|
|
53
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
54
|
+
const entries = fs.readdirSync(src, { withFileTypes: true });
|
|
55
|
+
for (const entry of entries) {
|
|
56
|
+
if (entry.isSymbolicLink()) continue;
|
|
57
|
+
const srcPath = path.join(src, entry.name);
|
|
58
|
+
const destPath = path.join(dest, entry.name);
|
|
59
|
+
if (entry.isDirectory()) {
|
|
60
|
+
copyDir(srcPath, destPath, _depth + 1);
|
|
61
|
+
} else {
|
|
62
|
+
fs.copyFileSync(srcPath, destPath);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function installSkills(commandsSrc, skillsDest) {
|
|
68
|
+
const entries = fs.readdirSync(commandsSrc).filter((f) => f.endsWith('.md'));
|
|
69
|
+
for (const file of entries) {
|
|
70
|
+
const name = file.replace('.md', '');
|
|
71
|
+
const skillDir = path.join(skillsDest, `brain-${name}`);
|
|
72
|
+
fs.mkdirSync(skillDir, { recursive: true });
|
|
73
|
+
fs.copyFileSync(
|
|
74
|
+
path.join(commandsSrc, file),
|
|
75
|
+
path.join(skillDir, 'SKILL.md')
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function injectPrompt(targetDir, promptFile, promptSource) {
|
|
81
|
+
const promptContent = fs.readFileSync(
|
|
82
|
+
path.join(PACKAGE_ROOT, 'prompts', promptSource),
|
|
83
|
+
'utf-8'
|
|
84
|
+
);
|
|
85
|
+
const targetPath = path.join(targetDir, promptFile);
|
|
86
|
+
|
|
87
|
+
const wrappedContent = `\n${BRAIN_MARKER_START}\n${promptContent}\n${BRAIN_MARKER_END}\n`;
|
|
88
|
+
|
|
89
|
+
if (fs.existsSync(targetPath)) {
|
|
90
|
+
let existing = fs.readFileSync(targetPath, 'utf-8');
|
|
91
|
+
// Remove old brain section if present
|
|
92
|
+
const startIdx = existing.indexOf(BRAIN_MARKER_START);
|
|
93
|
+
const endIdx = existing.indexOf(BRAIN_MARKER_END);
|
|
94
|
+
if (startIdx !== -1 && endIdx !== -1) {
|
|
95
|
+
existing =
|
|
96
|
+
existing.substring(0, startIdx) +
|
|
97
|
+
existing.substring(endIdx + BRAIN_MARKER_END.length);
|
|
98
|
+
}
|
|
99
|
+
fs.writeFileSync(targetPath, existing.trimEnd() + '\n' + wrappedContent);
|
|
100
|
+
} else {
|
|
101
|
+
fs.writeFileSync(targetPath, wrappedContent.trim() + '\n');
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function detectInstallations() {
|
|
106
|
+
const results = [];
|
|
107
|
+
for (const [runtime, config] of Object.entries(RUNTIMES)) {
|
|
108
|
+
for (const scope of ['global', 'local']) {
|
|
109
|
+
const targetDir = scope === 'global' ? config.globalDir : config.localDir;
|
|
110
|
+
const promptTarget = scope === 'global' ? config.globalDir : '.';
|
|
111
|
+
const promptPath = path.join(promptTarget, config.promptFile);
|
|
112
|
+
|
|
113
|
+
// Check for command files/dirs
|
|
114
|
+
let commandsFound = false;
|
|
115
|
+
if (config.commandStyle === 'skills') {
|
|
116
|
+
const skillsDir = path.join(targetDir, config.commandsSubdir);
|
|
117
|
+
commandsFound = fs.existsSync(path.join(skillsDir, 'brain-init', 'SKILL.md'));
|
|
118
|
+
} else {
|
|
119
|
+
const commandsDir = path.join(targetDir, config.commandsSubdir, 'brain');
|
|
120
|
+
commandsFound = fs.existsSync(commandsDir) &&
|
|
121
|
+
fs.readdirSync(commandsDir).some((f) => f.endsWith('.md'));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Check for prompt markers
|
|
125
|
+
let promptFound = false;
|
|
126
|
+
if (fs.existsSync(promptPath)) {
|
|
127
|
+
const content = fs.readFileSync(promptPath, 'utf-8');
|
|
128
|
+
promptFound = content.includes(BRAIN_MARKER_START) && content.includes(BRAIN_MARKER_END);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (commandsFound || promptFound) {
|
|
132
|
+
results.push({
|
|
133
|
+
runtime,
|
|
134
|
+
scope,
|
|
135
|
+
runtimeName: config.name,
|
|
136
|
+
commandsFound,
|
|
137
|
+
promptFound,
|
|
138
|
+
targetDir,
|
|
139
|
+
promptPath,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return results;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function removePromptSection(promptPath) {
|
|
148
|
+
if (!fs.existsSync(promptPath)) {
|
|
149
|
+
return { removed: false, reason: 'file-not-found' };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const content = fs.readFileSync(promptPath, 'utf-8');
|
|
153
|
+
const startIdx = content.indexOf(BRAIN_MARKER_START);
|
|
154
|
+
const endIdx = content.indexOf(BRAIN_MARKER_END);
|
|
155
|
+
|
|
156
|
+
if (startIdx === -1 || endIdx === -1) {
|
|
157
|
+
return { removed: false, reason: 'no-markers' };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const before = content.substring(0, startIdx);
|
|
161
|
+
const after = content.substring(endIdx + BRAIN_MARKER_END.length);
|
|
162
|
+
const remaining = (before + after).trim();
|
|
163
|
+
|
|
164
|
+
if (remaining.length === 0) {
|
|
165
|
+
fs.unlinkSync(promptPath);
|
|
166
|
+
return { removed: true, fileDeleted: true };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
fs.writeFileSync(promptPath, remaining + '\n');
|
|
170
|
+
return { removed: true, fileDeleted: false };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function removeCommands(targetDir, config) {
|
|
174
|
+
const removed = [];
|
|
175
|
+
|
|
176
|
+
if (config.commandStyle === 'skills') {
|
|
177
|
+
const skillsDir = path.join(targetDir, config.commandsSubdir);
|
|
178
|
+
if (fs.existsSync(skillsDir)) {
|
|
179
|
+
const entries = fs.readdirSync(skillsDir).filter((d) => d.startsWith('brain-'));
|
|
180
|
+
for (const entry of entries) {
|
|
181
|
+
const fullPath = path.join(skillsDir, entry);
|
|
182
|
+
fs.rmSync(fullPath, { recursive: true, force: true });
|
|
183
|
+
removed.push(fullPath);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
} else {
|
|
187
|
+
const commandsDir = path.join(targetDir, config.commandsSubdir, 'brain');
|
|
188
|
+
if (fs.existsSync(commandsDir)) {
|
|
189
|
+
removed.push(commandsDir);
|
|
190
|
+
fs.rmSync(commandsDir, { recursive: true, force: true });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return removed;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function uninstallForRuntime(runtime, scope) {
|
|
198
|
+
if (!Object.keys(RUNTIMES).includes(runtime)) {
|
|
199
|
+
throw new Error(`Unknown runtime: ${runtime}. Valid: ${Object.keys(RUNTIMES).join(', ')}`);
|
|
200
|
+
}
|
|
201
|
+
if (scope !== 'global' && scope !== 'local') {
|
|
202
|
+
throw new Error(`Invalid scope: ${scope}. Must be 'global' or 'local'.`);
|
|
203
|
+
}
|
|
204
|
+
const config = RUNTIMES[runtime];
|
|
205
|
+
const targetDir = scope === 'global' ? config.globalDir : config.localDir;
|
|
206
|
+
const promptTarget = scope === 'global' ? config.globalDir : '.';
|
|
207
|
+
const promptPath = path.join(promptTarget, config.promptFile);
|
|
208
|
+
|
|
209
|
+
const removedCommands = removeCommands(targetDir, config);
|
|
210
|
+
const promptResult = removePromptSection(promptPath);
|
|
211
|
+
|
|
212
|
+
return { removedCommands, promptResult };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function installForRuntime(runtime, scope) {
|
|
216
|
+
if (!Object.keys(RUNTIMES).includes(runtime)) {
|
|
217
|
+
throw new Error(`Unknown runtime: ${runtime}. Valid: ${Object.keys(RUNTIMES).join(', ')}`);
|
|
218
|
+
}
|
|
219
|
+
if (scope !== 'global' && scope !== 'local') {
|
|
220
|
+
throw new Error(`Invalid scope: ${scope}. Must be 'global' or 'local'.`);
|
|
221
|
+
}
|
|
222
|
+
const config = RUNTIMES[runtime];
|
|
223
|
+
const targetDir = scope === 'global' ? config.globalDir : config.localDir;
|
|
224
|
+
const commandsSrc = path.join(PACKAGE_ROOT, 'commands', 'brain');
|
|
225
|
+
|
|
226
|
+
if (config.commandStyle === 'skills') {
|
|
227
|
+
const skillsDest = path.join(targetDir, config.commandsSubdir);
|
|
228
|
+
// Clear stale brain-* skill dirs first so renamed/removed commands don't
|
|
229
|
+
// linger across upgrades (e.g. brain-skill → brain-skills).
|
|
230
|
+
if (fs.existsSync(skillsDest)) {
|
|
231
|
+
for (const entry of fs.readdirSync(skillsDest)) {
|
|
232
|
+
if (entry.startsWith('brain-')) {
|
|
233
|
+
fs.rmSync(path.join(skillsDest, entry), { recursive: true, force: true });
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
installSkills(commandsSrc, skillsDest);
|
|
238
|
+
} else {
|
|
239
|
+
const commandsDest = path.join(targetDir, config.commandsSubdir, 'brain');
|
|
240
|
+
// Wipe the brain command dir before copying so renamed/removed commands
|
|
241
|
+
// don't linger across upgrades. This is critical on case-insensitive
|
|
242
|
+
// filesystems: a leftover skill.md (== SKILL.md) makes Claude Code treat
|
|
243
|
+
// the whole dir as one skill and hides every /brain:* command.
|
|
244
|
+
fs.rmSync(commandsDest, { recursive: true, force: true });
|
|
245
|
+
copyDir(commandsSrc, commandsDest);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const promptTarget = scope === 'global' ? config.globalDir : '.';
|
|
249
|
+
injectPrompt(promptTarget, config.promptFile, config.promptSource);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function initializeBrain(overrideBase) {
|
|
253
|
+
const brainDir = path.join(overrideBase || os.homedir(), '.brain');
|
|
254
|
+
|
|
255
|
+
if (fs.existsSync(brainDir)) {
|
|
256
|
+
return { alreadyExists: true };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const now = new Date().toISOString();
|
|
260
|
+
|
|
261
|
+
// Create directories
|
|
262
|
+
const categories = ['professional', 'personal', 'social', 'family', '_consolidated', '_archived'];
|
|
263
|
+
for (const cat of categories) {
|
|
264
|
+
fs.mkdirSync(path.join(brainDir, cat), { recursive: true });
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Create index.json
|
|
268
|
+
const index = {
|
|
269
|
+
version: 2,
|
|
270
|
+
created: now,
|
|
271
|
+
last_updated: now,
|
|
272
|
+
memory_count: 0,
|
|
273
|
+
memories: {},
|
|
274
|
+
config: {
|
|
275
|
+
max_depth: 6,
|
|
276
|
+
consolidation_threshold: 0.3,
|
|
277
|
+
decay_check_interval_days: 7,
|
|
278
|
+
strength_boost_on_recall: 0.05,
|
|
279
|
+
auto_consolidate: true,
|
|
280
|
+
propagation_window_days: 7,
|
|
281
|
+
association_config: {
|
|
282
|
+
co_retrieval_boost: 0.10,
|
|
283
|
+
link_decay_rate: 0.998,
|
|
284
|
+
link_prune_threshold: 0.05,
|
|
285
|
+
spreading_activation_depth: 2,
|
|
286
|
+
spreading_activation_decay: 0.5,
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
fs.writeFileSync(
|
|
291
|
+
path.join(brainDir, 'index.json'),
|
|
292
|
+
JSON.stringify(index, null, 2) + '\n'
|
|
293
|
+
);
|
|
294
|
+
|
|
295
|
+
// Create associations.json
|
|
296
|
+
fs.writeFileSync(
|
|
297
|
+
path.join(brainDir, 'associations.json'),
|
|
298
|
+
JSON.stringify({ version: 1, edges: {} }, null, 2) + '\n'
|
|
299
|
+
);
|
|
300
|
+
|
|
301
|
+
// Create contexts.json
|
|
302
|
+
fs.writeFileSync(
|
|
303
|
+
path.join(brainDir, 'contexts.json'),
|
|
304
|
+
JSON.stringify({ version: 1, sessions: [] }, null, 2) + '\n'
|
|
305
|
+
);
|
|
306
|
+
|
|
307
|
+
// Create review-queue.json
|
|
308
|
+
fs.writeFileSync(
|
|
309
|
+
path.join(brainDir, 'review-queue.json'),
|
|
310
|
+
JSON.stringify({ version: 1, items: [] }, null, 2) + '\n'
|
|
311
|
+
);
|
|
312
|
+
|
|
313
|
+
// Create _archived/index.json
|
|
314
|
+
fs.writeFileSync(
|
|
315
|
+
path.join(brainDir, '_archived', 'index.json'),
|
|
316
|
+
JSON.stringify({ version: 1, archived_count: 0, memories: {} }, null, 2) + '\n'
|
|
317
|
+
);
|
|
318
|
+
|
|
319
|
+
// Create search-index.json (TF-IDF)
|
|
320
|
+
fs.writeFileSync(
|
|
321
|
+
path.join(brainDir, 'search-index.json'),
|
|
322
|
+
JSON.stringify({ version: 1, doc_count: 0, documents: {}, df: {} }, null, 2) + '\n'
|
|
323
|
+
);
|
|
324
|
+
|
|
325
|
+
// Load category descriptions from template
|
|
326
|
+
const templatePath = path.join(PACKAGE_ROOT, 'templates', 'default-categories.json');
|
|
327
|
+
let template = { top_categories: [] };
|
|
328
|
+
if (fs.existsSync(templatePath)) {
|
|
329
|
+
template = JSON.parse(fs.readFileSync(templatePath, 'utf-8'));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Create _meta.json for each category
|
|
333
|
+
const mainCategories = ['professional', 'personal', 'social', 'family'];
|
|
334
|
+
for (const cat of mainCategories) {
|
|
335
|
+
const templateCat = template.top_categories.find((c) => c.name === cat) || {};
|
|
336
|
+
const meta = {
|
|
337
|
+
category: cat,
|
|
338
|
+
description: templateCat.description || cat,
|
|
339
|
+
created: now,
|
|
340
|
+
memory_count: 0,
|
|
341
|
+
subcategories: [],
|
|
342
|
+
};
|
|
343
|
+
fs.writeFileSync(
|
|
344
|
+
path.join(brainDir, cat, '_meta.json'),
|
|
345
|
+
JSON.stringify(meta, null, 2) + '\n'
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// Create _meta.json for special directories
|
|
350
|
+
for (const special of ['_consolidated', '_archived']) {
|
|
351
|
+
const meta = {
|
|
352
|
+
category: special,
|
|
353
|
+
description:
|
|
354
|
+
special === '_consolidated'
|
|
355
|
+
? 'Merged memories from consolidation operations'
|
|
356
|
+
: 'Archived memories preserved for recovery',
|
|
357
|
+
created: now,
|
|
358
|
+
memory_count: 0,
|
|
359
|
+
subcategories: [],
|
|
360
|
+
};
|
|
361
|
+
fs.writeFileSync(
|
|
362
|
+
path.join(brainDir, special, '_meta.json'),
|
|
363
|
+
JSON.stringify(meta, null, 2) + '\n'
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
return { alreadyExists: false, brainDir };
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
module.exports = {
|
|
371
|
+
RUNTIMES,
|
|
372
|
+
BRAIN_MARKER_START,
|
|
373
|
+
BRAIN_MARKER_END,
|
|
374
|
+
PACKAGE_ROOT,
|
|
375
|
+
copyDir,
|
|
376
|
+
installSkills,
|
|
377
|
+
injectPrompt,
|
|
378
|
+
installForRuntime,
|
|
379
|
+
initializeBrain,
|
|
380
|
+
detectInstallations,
|
|
381
|
+
removePromptSection,
|
|
382
|
+
removeCommands,
|
|
383
|
+
uninstallForRuntime,
|
|
384
|
+
};
|