brain-memory 0.1.0-beta.3 → 0.1.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +339 -0
  2. package/README.md +400 -94
  3. package/SECURITY.md +61 -0
  4. package/assets/brand/README.md +28 -0
  5. package/assets/brand/icon-dark.svg +19 -0
  6. package/assets/brand/icon-light.svg +20 -0
  7. package/assets/brand/linkedin_cover.png +0 -0
  8. package/assets/brand/linkedin_cover_light.png +0 -0
  9. package/assets/brand/mark-dark.svg +19 -0
  10. package/assets/brand/mark-light.svg +20 -0
  11. package/assets/brand/png/icon-dark-1024.png +0 -0
  12. package/assets/brand/png/icon-dark-128.png +0 -0
  13. package/assets/brand/png/icon-dark-256.png +0 -0
  14. package/assets/brand/png/icon-dark-512.png +0 -0
  15. package/assets/brand/png/icon-dark-64.png +0 -0
  16. package/assets/brand/png/icon-light-1024.png +0 -0
  17. package/assets/brand/png/icon-light-128.png +0 -0
  18. package/assets/brand/png/icon-light-256.png +0 -0
  19. package/assets/brand/png/icon-light-512.png +0 -0
  20. package/assets/brand/png/icon-light-64.png +0 -0
  21. package/assets/brand/png/mark-dark-1024.png +0 -0
  22. package/assets/brand/png/mark-light-1024.png +0 -0
  23. package/assets/icon.png +0 -0
  24. package/assets/icon.svg +19 -0
  25. package/bin/brain.js +111 -0
  26. package/bin/cloud-sync.js +150 -0
  27. package/bin/forget.js +122 -0
  28. package/bin/install.js +229 -254
  29. package/bin/memorize.js +458 -0
  30. package/bin/pin.js +44 -0
  31. package/bin/recall.js +259 -0
  32. package/bin/reinforce.js +187 -0
  33. package/bin/session-start.js +298 -0
  34. package/bin/skill.js +67 -0
  35. package/bin/unpin.js +38 -0
  36. package/commands/brain/forget.md +245 -15
  37. package/commands/brain/memorize.md +76 -144
  38. package/commands/brain/pin.md +79 -0
  39. package/commands/brain/remember.md +48 -105
  40. package/commands/brain/skills.md +60 -0
  41. package/commands/brain/sleep.md +69 -28
  42. package/commands/brain/status.md +24 -10
  43. package/commands/brain/sync.md +386 -0
  44. package/package.json +22 -8
  45. package/prompts/antigravity.md +180 -0
  46. package/prompts/claude.md +124 -20
  47. package/prompts/openai.md +124 -20
  48. package/prompts/opencode.md +179 -0
  49. package/src/cloud-sync.js +534 -0
  50. package/src/crypto.js +130 -0
  51. package/src/export-import.js +200 -0
  52. package/src/git-sync.js +444 -0
  53. package/src/index-manager.js +219 -18
  54. package/src/installer.js +444 -0
  55. package/src/pinning.js +124 -0
  56. package/src/scorer.js +45 -11
  57. package/src/skills.js +208 -0
  58. package/src/tfidf.js +520 -0
  59. package/commands/brain/consolidate.md +0 -153
  60. package/commands/brain/explore.md +0 -79
  61. package/commands/brain/init.md +0 -157
  62. package/commands/brain/review.md +0 -130
  63. package/commands/brain/sunshine.md +0 -337
  64. package/hooks/session-end.md +0 -48
  65. package/hooks/session-start.md +0 -48
  66. package/prompts/gemini.md +0 -76
@@ -0,0 +1,444 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+
5
+ const { getBrainDir } = require('./index-manager');
6
+
7
+ const PACKAGE_ROOT = path.resolve(__dirname, '..');
8
+
9
+ // Local-first integration targets, current as of mid-2026. The hosted MCP
10
+ // connector (Brain Cloud) is the universal path for everything else (Claude.ai,
11
+ // ChatGPT, mobile, Antigravity/Gemini-Enterprise via remote MCP); these are the
12
+ // CLIs where a native install adds the ambient zero-config loop MCP can't.
13
+ //
14
+ // `skillsGlobalDir`/`skillsLocalDir` decouple where skills land from where the
15
+ // prompt lands (Codex prompts go to ~/.codex/AGENTS.md but skills go to the
16
+ // cross-tool ~/.agents/skills/). `skillName: true` injects the `name:`
17
+ // frontmatter that Codex/Antigravity require to match the skill folder.
18
+ //
19
+ // Gemini CLI was retired 2026-06-18 (absorbed into Antigravity) and is removed.
20
+ const RUNTIMES = {
21
+ claude: {
22
+ name: 'Claude Code',
23
+ globalDir: path.join(os.homedir(), '.claude'),
24
+ localDir: '.claude',
25
+ commandsSubdir: 'commands',
26
+ promptFile: 'CLAUDE.md',
27
+ promptSource: 'claude.md',
28
+ commandStyle: 'flat',
29
+ },
30
+ openai: {
31
+ name: 'OpenAI Codex CLI',
32
+ globalDir: path.join(os.homedir(), '.codex'),
33
+ localDir: '.codex',
34
+ commandsSubdir: 'skills',
35
+ // Codex reads skills from the cross-tool ~/.agents/skills/, NOT ~/.codex/skills/.
36
+ skillsGlobalDir: path.join(os.homedir(), '.agents', 'skills'),
37
+ skillsLocalDir: path.join('.agents', 'skills'),
38
+ promptFile: 'AGENTS.md',
39
+ promptSource: 'openai.md',
40
+ commandStyle: 'skills',
41
+ skillName: true,
42
+ },
43
+ antigravity: {
44
+ name: 'Google Antigravity',
45
+ // NB: Antigravity reuses ~/.gemini/ and reads GEMINI.md globally + Markdown
46
+ // SKILL.md skills under ~/.gemini/skills/. These paths are community-sourced
47
+ // (official docs are JS SPAs) — VERIFY against a live Antigravity install.
48
+ globalDir: path.join(os.homedir(), '.gemini'),
49
+ localDir: '.',
50
+ commandsSubdir: 'skills',
51
+ skillsGlobalDir: path.join(os.homedir(), '.gemini', 'skills'),
52
+ skillsLocalDir: path.join('.agents', 'skills'),
53
+ promptFile: 'GEMINI.md',
54
+ promptSource: 'antigravity.md',
55
+ commandStyle: 'skills',
56
+ skillName: true,
57
+ },
58
+ opencode: {
59
+ name: 'OpenCode',
60
+ globalDir: path.join(os.homedir(), '.config', 'opencode'),
61
+ localDir: '.opencode',
62
+ commandsSubdir: 'commands',
63
+ promptFile: 'AGENTS.md',
64
+ promptSource: 'opencode.md',
65
+ commandStyle: 'flat',
66
+ },
67
+ };
68
+
69
+ /** Where skills install for a runtime+scope (decoupled from the prompt target). */
70
+ function skillsDestFor(config, scope) {
71
+ if (scope === 'global') {
72
+ return config.skillsGlobalDir || path.join(config.globalDir, config.commandsSubdir);
73
+ }
74
+ return config.skillsLocalDir || path.join(config.localDir, config.commandsSubdir);
75
+ }
76
+
77
+ const BRAIN_MARKER_START = '<!-- BRAIN-MEMORY-START -->';
78
+ const BRAIN_MARKER_END = '<!-- BRAIN-MEMORY-END -->';
79
+
80
+ function copyDir(src, dest, _depth = 0) {
81
+ if (_depth > 20) {
82
+ throw new Error(`copyDir: max depth (20) exceeded at ${src}`);
83
+ }
84
+ fs.mkdirSync(dest, { recursive: true });
85
+ const entries = fs.readdirSync(src, { withFileTypes: true });
86
+ for (const entry of entries) {
87
+ if (entry.isSymbolicLink()) continue;
88
+ const srcPath = path.join(src, entry.name);
89
+ const destPath = path.join(dest, entry.name);
90
+ if (entry.isDirectory()) {
91
+ copyDir(srcPath, destPath, _depth + 1);
92
+ } else {
93
+ fs.copyFileSync(srcPath, destPath);
94
+ }
95
+ }
96
+ }
97
+
98
+ function installSkills(commandsSrc, skillsDest, addName = false) {
99
+ const entries = fs.readdirSync(commandsSrc).filter((f) => f.endsWith('.md'));
100
+ for (const file of entries) {
101
+ const name = file.replace('.md', '');
102
+ const skillFolder = `brain-${name}`;
103
+ const skillDir = path.join(skillsDest, skillFolder);
104
+ fs.mkdirSync(skillDir, { recursive: true });
105
+ let content = fs.readFileSync(path.join(commandsSrc, file), 'utf-8');
106
+ if (addName) content = ensureSkillName(content, skillFolder);
107
+ fs.writeFileSync(path.join(skillDir, 'SKILL.md'), content);
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Codex and Antigravity require a `name:` frontmatter field that matches the
113
+ * skill folder. The source command files only carry `description:`, so inject
114
+ * `name:` as the first frontmatter field (idempotent — skips if already present).
115
+ */
116
+ function ensureSkillName(content, name) {
117
+ if (/^---\s*\n/.test(content)) {
118
+ const end = content.indexOf('\n---', 3);
119
+ const block = end !== -1 ? content.slice(0, end) : content;
120
+ if (/^\s*name\s*:/m.test(block)) return content;
121
+ return content.replace(/^---\s*\n/, `---\nname: ${name}\n`);
122
+ }
123
+ return `---\nname: ${name}\n---\n\n${content}`;
124
+ }
125
+
126
+ function injectPrompt(targetDir, promptFile, promptSource) {
127
+ const promptContent = fs.readFileSync(
128
+ path.join(PACKAGE_ROOT, 'prompts', promptSource),
129
+ 'utf-8'
130
+ );
131
+ const targetPath = path.join(targetDir, promptFile);
132
+ // Ensure the prompt dir exists. Previously this was created as a side-effect
133
+ // of installing commands/skills into the same dir; now that skills can land
134
+ // elsewhere (e.g. Codex skills → ~/.agents/skills), the prompt dir (~/.codex)
135
+ // must be created explicitly.
136
+ fs.mkdirSync(targetDir, { recursive: true });
137
+
138
+ const wrappedContent = `\n${BRAIN_MARKER_START}\n${promptContent}\n${BRAIN_MARKER_END}\n`;
139
+
140
+ if (fs.existsSync(targetPath)) {
141
+ let existing = fs.readFileSync(targetPath, 'utf-8');
142
+ // Remove old brain section if present
143
+ const startIdx = existing.indexOf(BRAIN_MARKER_START);
144
+ const endIdx = existing.indexOf(BRAIN_MARKER_END);
145
+ if (startIdx !== -1 && endIdx !== -1) {
146
+ existing =
147
+ existing.substring(0, startIdx) +
148
+ existing.substring(endIdx + BRAIN_MARKER_END.length);
149
+ }
150
+ fs.writeFileSync(targetPath, existing.trimEnd() + '\n' + wrappedContent);
151
+ } else {
152
+ fs.writeFileSync(targetPath, wrappedContent.trim() + '\n');
153
+ }
154
+ }
155
+
156
+ function detectInstallations() {
157
+ const results = [];
158
+ for (const [runtime, config] of Object.entries(RUNTIMES)) {
159
+ for (const scope of ['global', 'local']) {
160
+ const targetDir = scope === 'global' ? config.globalDir : config.localDir;
161
+ const promptTarget = scope === 'global' ? config.globalDir : '.';
162
+ const promptPath = path.join(promptTarget, config.promptFile);
163
+
164
+ // Check for command files/dirs
165
+ let commandsFound = false;
166
+ if (config.commandStyle === 'skills') {
167
+ const skillsDir = skillsDestFor(config, scope);
168
+ commandsFound = fs.existsSync(skillsDir) &&
169
+ fs.readdirSync(skillsDir).some(
170
+ (d) => d.startsWith('brain-') &&
171
+ fs.existsSync(path.join(skillsDir, d, 'SKILL.md'))
172
+ );
173
+ } else {
174
+ const commandsDir = path.join(targetDir, config.commandsSubdir, 'brain');
175
+ commandsFound = fs.existsSync(commandsDir) &&
176
+ fs.readdirSync(commandsDir).some((f) => f.endsWith('.md'));
177
+ }
178
+
179
+ // Check for prompt markers
180
+ let promptFound = false;
181
+ if (fs.existsSync(promptPath)) {
182
+ const content = fs.readFileSync(promptPath, 'utf-8');
183
+ promptFound = content.includes(BRAIN_MARKER_START) && content.includes(BRAIN_MARKER_END);
184
+ }
185
+
186
+ if (commandsFound || promptFound) {
187
+ results.push({
188
+ runtime,
189
+ scope,
190
+ runtimeName: config.name,
191
+ commandsFound,
192
+ promptFound,
193
+ targetDir,
194
+ promptPath,
195
+ });
196
+ }
197
+ }
198
+ }
199
+ return results;
200
+ }
201
+
202
+ function removePromptSection(promptPath) {
203
+ if (!fs.existsSync(promptPath)) {
204
+ return { removed: false, reason: 'file-not-found' };
205
+ }
206
+
207
+ const content = fs.readFileSync(promptPath, 'utf-8');
208
+ const startIdx = content.indexOf(BRAIN_MARKER_START);
209
+ const endIdx = content.indexOf(BRAIN_MARKER_END);
210
+
211
+ if (startIdx === -1 || endIdx === -1) {
212
+ return { removed: false, reason: 'no-markers' };
213
+ }
214
+
215
+ const before = content.substring(0, startIdx);
216
+ const after = content.substring(endIdx + BRAIN_MARKER_END.length);
217
+ const remaining = (before + after).trim();
218
+
219
+ if (remaining.length === 0) {
220
+ fs.unlinkSync(promptPath);
221
+ return { removed: true, fileDeleted: true };
222
+ }
223
+
224
+ fs.writeFileSync(promptPath, remaining + '\n');
225
+ return { removed: true, fileDeleted: false };
226
+ }
227
+
228
+ function removeCommands(targetDir, config, scope = 'global') {
229
+ const removed = [];
230
+
231
+ if (config.commandStyle === 'skills') {
232
+ // Honor an explicit skills override; otherwise resolve relative to the
233
+ // passed targetDir (so callers that pass a custom targetDir still work).
234
+ const override = scope === 'global' ? config.skillsGlobalDir : config.skillsLocalDir;
235
+ const skillsDir = override || path.join(targetDir, config.commandsSubdir);
236
+ if (fs.existsSync(skillsDir)) {
237
+ const entries = fs.readdirSync(skillsDir).filter((d) => d.startsWith('brain-'));
238
+ for (const entry of entries) {
239
+ const fullPath = path.join(skillsDir, entry);
240
+ fs.rmSync(fullPath, { recursive: true, force: true });
241
+ removed.push(fullPath);
242
+ }
243
+ }
244
+ } else {
245
+ const commandsDir = path.join(targetDir, config.commandsSubdir, 'brain');
246
+ if (fs.existsSync(commandsDir)) {
247
+ removed.push(commandsDir);
248
+ fs.rmSync(commandsDir, { recursive: true, force: true });
249
+ }
250
+ }
251
+
252
+ return removed;
253
+ }
254
+
255
+ function uninstallForRuntime(runtime, scope) {
256
+ if (!Object.keys(RUNTIMES).includes(runtime)) {
257
+ throw new Error(`Unknown runtime: ${runtime}. Valid: ${Object.keys(RUNTIMES).join(', ')}`);
258
+ }
259
+ if (scope !== 'global' && scope !== 'local') {
260
+ throw new Error(`Invalid scope: ${scope}. Must be 'global' or 'local'.`);
261
+ }
262
+ const config = RUNTIMES[runtime];
263
+ const targetDir = scope === 'global' ? config.globalDir : config.localDir;
264
+ const promptTarget = scope === 'global' ? config.globalDir : '.';
265
+ const promptPath = path.join(promptTarget, config.promptFile);
266
+
267
+ const removedCommands = removeCommands(targetDir, config, scope);
268
+ const promptResult = removePromptSection(promptPath);
269
+
270
+ return { removedCommands, promptResult };
271
+ }
272
+
273
+ function installForRuntime(runtime, scope) {
274
+ if (!Object.keys(RUNTIMES).includes(runtime)) {
275
+ throw new Error(`Unknown runtime: ${runtime}. Valid: ${Object.keys(RUNTIMES).join(', ')}`);
276
+ }
277
+ if (scope !== 'global' && scope !== 'local') {
278
+ throw new Error(`Invalid scope: ${scope}. Must be 'global' or 'local'.`);
279
+ }
280
+ const config = RUNTIMES[runtime];
281
+ const targetDir = scope === 'global' ? config.globalDir : config.localDir;
282
+ const commandsSrc = path.join(PACKAGE_ROOT, 'commands', 'brain');
283
+
284
+ if (config.commandStyle === 'skills') {
285
+ const skillsDest = skillsDestFor(config, scope);
286
+ // Clear stale brain-* skill dirs first so renamed/removed commands don't
287
+ // linger across upgrades (e.g. brain-skill → brain-skills).
288
+ if (fs.existsSync(skillsDest)) {
289
+ for (const entry of fs.readdirSync(skillsDest)) {
290
+ if (entry.startsWith('brain-')) {
291
+ fs.rmSync(path.join(skillsDest, entry), { recursive: true, force: true });
292
+ }
293
+ }
294
+ }
295
+ installSkills(commandsSrc, skillsDest, config.skillName);
296
+ } else {
297
+ const commandsDest = path.join(targetDir, config.commandsSubdir, 'brain');
298
+ // Wipe the brain command dir before copying so renamed/removed commands
299
+ // don't linger across upgrades. This is critical on case-insensitive
300
+ // filesystems: a leftover skill.md (== SKILL.md) makes Claude Code treat
301
+ // the whole dir as one skill and hides every /brain:* command.
302
+ fs.rmSync(commandsDest, { recursive: true, force: true });
303
+ copyDir(commandsSrc, commandsDest);
304
+ }
305
+
306
+ const promptTarget = scope === 'global' ? config.globalDir : '.';
307
+ injectPrompt(promptTarget, config.promptFile, config.promptSource);
308
+ }
309
+
310
+ function initializeBrain(overrideBase) {
311
+ // Honors $BRAIN_DIR (via getBrainDir) so a fresh brain is created wherever the
312
+ // user points it — e.g. inside a Google Drive / Dropbox / iCloud synced folder.
313
+ const brainDir = overrideBase ? path.join(overrideBase, '.brain') : getBrainDir();
314
+
315
+ if (fs.existsSync(brainDir)) {
316
+ return { alreadyExists: true };
317
+ }
318
+
319
+ const now = new Date().toISOString();
320
+
321
+ // Create directories
322
+ const categories = ['professional', 'personal', 'social', 'family', '_consolidated', '_archived'];
323
+ for (const cat of categories) {
324
+ fs.mkdirSync(path.join(brainDir, cat), { recursive: true });
325
+ }
326
+
327
+ // Create index.json
328
+ const index = {
329
+ version: 2,
330
+ created: now,
331
+ last_updated: now,
332
+ memory_count: 0,
333
+ memories: {},
334
+ config: {
335
+ max_depth: 6,
336
+ consolidation_threshold: 0.3,
337
+ decay_check_interval_days: 7,
338
+ strength_boost_on_recall: 0.05,
339
+ auto_consolidate: true,
340
+ propagation_window_days: 7,
341
+ association_config: {
342
+ co_retrieval_boost: 0.10,
343
+ link_decay_rate: 0.998,
344
+ link_prune_threshold: 0.05,
345
+ spreading_activation_depth: 2,
346
+ spreading_activation_decay: 0.5,
347
+ },
348
+ },
349
+ };
350
+ fs.writeFileSync(
351
+ path.join(brainDir, 'index.json'),
352
+ JSON.stringify(index, null, 2) + '\n'
353
+ );
354
+
355
+ // Create associations.json
356
+ fs.writeFileSync(
357
+ path.join(brainDir, 'associations.json'),
358
+ JSON.stringify({ version: 1, edges: {} }, null, 2) + '\n'
359
+ );
360
+
361
+ // Create contexts.json
362
+ fs.writeFileSync(
363
+ path.join(brainDir, 'contexts.json'),
364
+ JSON.stringify({ version: 1, sessions: [] }, null, 2) + '\n'
365
+ );
366
+
367
+ // Create review-queue.json
368
+ fs.writeFileSync(
369
+ path.join(brainDir, 'review-queue.json'),
370
+ JSON.stringify({ version: 1, items: [] }, null, 2) + '\n'
371
+ );
372
+
373
+ // Create _archived/index.json
374
+ fs.writeFileSync(
375
+ path.join(brainDir, '_archived', 'index.json'),
376
+ JSON.stringify({ version: 1, archived_count: 0, memories: {} }, null, 2) + '\n'
377
+ );
378
+
379
+ // Create search-index.json (TF-IDF)
380
+ fs.writeFileSync(
381
+ path.join(brainDir, 'search-index.json'),
382
+ JSON.stringify({ version: 1, doc_count: 0, documents: {}, df: {} }, null, 2) + '\n'
383
+ );
384
+
385
+ // Load category descriptions from template
386
+ const templatePath = path.join(PACKAGE_ROOT, 'templates', 'default-categories.json');
387
+ let template = { top_categories: [] };
388
+ if (fs.existsSync(templatePath)) {
389
+ template = JSON.parse(fs.readFileSync(templatePath, 'utf-8'));
390
+ }
391
+
392
+ // Create _meta.json for each category
393
+ const mainCategories = ['professional', 'personal', 'social', 'family'];
394
+ for (const cat of mainCategories) {
395
+ const templateCat = template.top_categories.find((c) => c.name === cat) || {};
396
+ const meta = {
397
+ category: cat,
398
+ description: templateCat.description || cat,
399
+ created: now,
400
+ memory_count: 0,
401
+ subcategories: [],
402
+ };
403
+ fs.writeFileSync(
404
+ path.join(brainDir, cat, '_meta.json'),
405
+ JSON.stringify(meta, null, 2) + '\n'
406
+ );
407
+ }
408
+
409
+ // Create _meta.json for special directories
410
+ for (const special of ['_consolidated', '_archived']) {
411
+ const meta = {
412
+ category: special,
413
+ description:
414
+ special === '_consolidated'
415
+ ? 'Merged memories from consolidation operations'
416
+ : 'Archived memories preserved for recovery',
417
+ created: now,
418
+ memory_count: 0,
419
+ subcategories: [],
420
+ };
421
+ fs.writeFileSync(
422
+ path.join(brainDir, special, '_meta.json'),
423
+ JSON.stringify(meta, null, 2) + '\n'
424
+ );
425
+ }
426
+
427
+ return { alreadyExists: false, brainDir };
428
+ }
429
+
430
+ module.exports = {
431
+ RUNTIMES,
432
+ BRAIN_MARKER_START,
433
+ BRAIN_MARKER_END,
434
+ PACKAGE_ROOT,
435
+ copyDir,
436
+ installSkills,
437
+ injectPrompt,
438
+ installForRuntime,
439
+ initializeBrain,
440
+ detectInstallations,
441
+ removePromptSection,
442
+ removeCommands,
443
+ uninstallForRuntime,
444
+ };
package/src/pinning.js ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Brain Memory — Pinning (CoALA Phase 1)
3
+ *
4
+ * Pin/unpin a memory into the always-present semantic tier. Pinning is the fix
5
+ * for the core reliability hole: a durable convention/preference must apply
6
+ * every session regardless of recall score. A pinned memory is implicitly
7
+ * decay-exempt (the scorer treats pinned || stable as exempt).
8
+ *
9
+ * The index entry is the source of truth read by recall/session-start; the
10
+ * memory file's frontmatter is kept in sync for human-readability and git.
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+
16
+ const {
17
+ getBrainDir,
18
+ readIndex,
19
+ writeIndex,
20
+ readPinned,
21
+ writePinned,
22
+ } = require('./index-manager');
23
+
24
+ /** chars/4 token estimate; falls back to the title line for older entries. */
25
+ function estimateTokens(entry) {
26
+ if (entry && typeof entry.token_estimate === 'number') return entry.token_estimate;
27
+ return Math.ceil((((entry && entry.title) || '').length + 8) / 4);
28
+ }
29
+
30
+ /**
31
+ * Update-or-insert scalar YAML frontmatter fields in a memory file (best effort;
32
+ * the index entry remains the source of truth if the file is unreadable).
33
+ */
34
+ function setFrontmatterFields(brainDir, memPath, fields) {
35
+ const fullPath = path.join(brainDir, memPath);
36
+ let content;
37
+ try { content = fs.readFileSync(fullPath, 'utf-8'); } catch (_) { return; }
38
+
39
+ const first = content.indexOf('---');
40
+ const second = content.indexOf('---', first + 3);
41
+ if (first === -1 || second === -1) return;
42
+
43
+ let fm = content.slice(first + 3, second);
44
+ const inserts = [];
45
+ for (const [key, value] of Object.entries(fields)) {
46
+ const formatted = typeof value === 'string' ? `"${value}"` : String(value);
47
+ const re = new RegExp(`^(${key}:\\s*).*$`, 'm');
48
+ if (re.test(fm)) fm = fm.replace(re, `$1${formatted}`);
49
+ else inserts.push(`${key}: ${formatted}\n`);
50
+ }
51
+ if (inserts.length) fm = fm.replace(/\s*$/, '\n') + inserts.join('');
52
+
53
+ content = content.slice(0, first + 3) + fm + content.slice(second);
54
+ fs.writeFileSync(fullPath, content);
55
+ }
56
+
57
+ /**
58
+ * Pin a memory (always-loaded). Sets pinned/pin_scope/pin_priority on the index
59
+ * entry + frontmatter and records it in pinned.json.
60
+ *
61
+ * @param {string} [projectRoot] - Filesystem root (undefined = real ~/.brain)
62
+ * @param {string} id - Memory ID
63
+ * @param {Object} [opts] - { scope = "global"|"project:<name>", priority = 0 }
64
+ * @returns {Object} Result or { error }
65
+ */
66
+ function pinMemory(projectRoot, id, opts = {}) {
67
+ const scope = opts.scope || 'global';
68
+ const priority = Number.isFinite(opts.priority) ? opts.priority : 0;
69
+
70
+ const index = readIndex(projectRoot);
71
+ if (!index || !index.memories || !index.memories[id]) {
72
+ return { error: `Memory not found: ${id}` };
73
+ }
74
+
75
+ const entry = index.memories[id];
76
+ entry.pinned = true;
77
+ entry.pin_scope = scope;
78
+ entry.pin_priority = priority;
79
+ writeIndex(index, projectRoot);
80
+
81
+ setFrontmatterFields(getBrainDir(projectRoot), entry.path, {
82
+ pinned: true,
83
+ pin_scope: scope,
84
+ pin_priority: priority,
85
+ });
86
+
87
+ const pinned = readPinned(projectRoot);
88
+ pinned.pins = pinned.pins.filter((p) => p.id !== id);
89
+ pinned.pins.push({ id, scope, priority, token_estimate: estimateTokens(entry) });
90
+ writePinned(pinned, projectRoot);
91
+
92
+ return { id, pinned: true, scope, priority };
93
+ }
94
+
95
+ /**
96
+ * Unpin a memory. Clears the pinned flag and removes it from pinned.json. Leaves
97
+ * an independent `stable` flag untouched.
98
+ *
99
+ * @param {string} [projectRoot] - Filesystem root (undefined = real ~/.brain)
100
+ * @param {string} id - Memory ID
101
+ * @returns {Object} Result or { error }
102
+ */
103
+ function unpinMemory(projectRoot, id) {
104
+ const index = readIndex(projectRoot);
105
+ if (!index || !index.memories || !index.memories[id]) {
106
+ return { error: `Memory not found: ${id}` };
107
+ }
108
+
109
+ const entry = index.memories[id];
110
+ const wasPinned = !!entry.pinned;
111
+ entry.pinned = false;
112
+ writeIndex(index, projectRoot);
113
+
114
+ setFrontmatterFields(getBrainDir(projectRoot), entry.path, { pinned: false });
115
+
116
+ const pinned = readPinned(projectRoot);
117
+ const before = pinned.pins.length;
118
+ pinned.pins = pinned.pins.filter((p) => p.id !== id);
119
+ writePinned(pinned, projectRoot);
120
+
121
+ return { id, pinned: false, was_pinned: wasPinned, removed: before !== pinned.pins.length };
122
+ }
123
+
124
+ module.exports = { pinMemory, unpinMemory, estimateTokens, setFrontmatterFields };
package/src/scorer.js CHANGED
@@ -13,9 +13,12 @@
13
13
  * @param {number} baseStrength - Original strength (0.0-1.0)
14
14
  * @param {number} decayRate - Daily decay factor (e.g., 0.995)
15
15
  * @param {string|Date} lastAccessed - ISO timestamp of last access
16
+ * @param {boolean} [exempt=false] - CoALA Phase 1: pinned/stable memories are
17
+ * decay-exempt — their strength never fades (semantic "stable" property).
16
18
  * @returns {number} Effective strength after decay
17
19
  */
18
- function computeDecayedStrength(baseStrength, decayRate, lastAccessed) {
20
+ function computeDecayedStrength(baseStrength, decayRate, lastAccessed, exempt = false) {
21
+ if (exempt) return baseStrength;
19
22
  const lastDate = new Date(lastAccessed);
20
23
  const now = new Date();
21
24
  const daysElapsed = (now - lastDate) / (1000 * 60 * 60 * 24);
@@ -290,6 +293,8 @@ function improveDecayRate(decayRate) {
290
293
  * @returns {number} Consolidated strength (capped at 1.0)
291
294
  */
292
295
  function computeConsolidatedStrength(sourceStrengths) {
296
+ // No sources to consolidate — Math.max(...[]) is -Infinity, so guard explicitly.
297
+ if (!Array.isArray(sourceStrengths) || sourceStrengths.length === 0) return 0;
293
298
  const maxStrength = Math.max(...sourceStrengths);
294
299
  return Math.min(1.0, maxStrength + 0.15);
295
300
  }
@@ -357,18 +362,30 @@ function computeSpreadingActivationBatch(scoredMemories, associations, maxDepth
357
362
  * @param {Object} [options] - Optional scoring parameters
358
363
  * @param {Object} [options.associations] - Associations graph for spreading activation
359
364
  * @param {Object} [options.recallContext] - Current session context for context matching
365
+ * @param {number} [options.relevanceFloor] - Drop memories whose relevance AND
366
+ * spreading_bonus are both below this floor. Without it, zero-relevance
367
+ * memories pad the results purely on strength/recency/salience — a query
368
+ * about things the brain doesn't know still returns confident-looking hits.
369
+ * Memories rescued by spreading activation survive the floor (associative
370
+ * recall of low-relevance neighbors is a feature, not noise).
360
371
  * @returns {Object[]} Scored and sorted memories (highest first)
361
372
  */
362
373
  function rankMemories(memories, relevanceFn, options = {}) {
374
+ // Guard every term against NaN (e.g. a missing/invalid last_accessed or
375
+ // strength) — a single NaN score sorts non-deterministically and can outrank
376
+ // valid results.
377
+ const fin = (x) => (Number.isFinite(x) ? x : 0);
378
+
363
379
  // First pass: compute base scores
364
380
  const scored = memories.map((mem) => {
365
- const decayedStrength = computeDecayedStrength(
381
+ const decayedStrength = fin(computeDecayedStrength(
366
382
  mem.strength,
367
383
  mem.decay_rate,
368
- mem.last_accessed
369
- );
370
- const recencyBonus = computeRecencyBonus(mem.last_accessed);
371
- const relevance = relevanceFn(mem);
384
+ mem.last_accessed,
385
+ !!(mem.stable || mem.pinned) // pinned ⇒ implicitly stable (decay-exempt)
386
+ ));
387
+ const recencyBonus = fin(computeRecencyBonus(mem.last_accessed));
388
+ const relevance = fin(relevanceFn(mem));
372
389
 
373
390
  return {
374
391
  ...mem,
@@ -382,7 +399,15 @@ function rankMemories(memories, relevanceFn, options = {}) {
382
399
 
383
400
  // Second pass: spreading activation (batch — single traversal for all memories)
384
401
  if (options.associations) {
385
- const scoredSummary = scored.map((m) => ({
402
+ // With a relevanceFloor set (query mode), only query-relevant memories may
403
+ // act as activation SOURCES — matching the cognitive model (the cue
404
+ // activates matching memories, activation spreads along associations).
405
+ // Without it, a strong-but-irrelevant memory spreads on strength/recency
406
+ // alone and its whole clique rescues itself past the floor below.
407
+ const sources = options.relevanceFloor != null
408
+ ? scored.filter((m) => m.relevance >= options.relevanceFloor)
409
+ : scored;
410
+ const scoredSummary = sources.map((m) => ({
386
411
  id: m.id,
387
412
  score: 0.55 * m.relevance + 0.30 * m.decayed_strength + 0.15 * m.recency_bonus,
388
413
  }));
@@ -406,20 +431,27 @@ function rankMemories(memories, relevanceFn, options = {}) {
406
431
  }
407
432
  }
408
433
 
434
+ // Relevance floor: gate BEFORE final scoring so strength/salience can't
435
+ // carry an unrelated memory into the results (uses raw, unrounded terms).
436
+ const floor = options.relevanceFloor;
437
+ const gated = floor != null
438
+ ? scored.filter((mem) => mem.relevance >= floor || mem.spreading_bonus >= floor)
439
+ : scored;
440
+
409
441
  // Final score
410
- return scored
442
+ return gated
411
443
  .map((mem) => {
412
444
  const extras = {};
413
445
  if (mem.spreading_bonus > 0) extras.spreadingBonus = mem.spreading_bonus;
414
446
  if (mem.context_match > 0) extras.contextMatch = mem.context_match;
415
447
  if (mem.salience != null) extras.salience = mem.salience;
416
448
 
417
- const score = computeRecallScore(
449
+ const score = fin(computeRecallScore(
418
450
  mem.relevance,
419
451
  mem.decayed_strength,
420
452
  mem.recency_bonus,
421
453
  extras
422
- );
454
+ ));
423
455
 
424
456
  return {
425
457
  ...mem,
@@ -431,7 +463,9 @@ function rankMemories(memories, relevanceFn, options = {}) {
431
463
  score: Math.round(score * 1000) / 1000,
432
464
  };
433
465
  })
434
- .sort((a, b) => b.score - a.score);
466
+ // Deterministic order: score desc, then id asc to break ties (scores are
467
+ // rounded to 3dp, which manufactures ties at scale).
468
+ .sort((a, b) => (b.score - a.score) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
435
469
  }
436
470
 
437
471
  module.exports = {