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.
Files changed (44) hide show
  1. package/README.md +270 -72
  2. package/assets/icon.png +0 -0
  3. package/assets/icon.svg +27 -0
  4. package/bin/brain.js +111 -0
  5. package/bin/cloud-sync.js +149 -0
  6. package/bin/install.js +217 -242
  7. package/bin/memorize.js +433 -0
  8. package/bin/pin.js +44 -0
  9. package/bin/recall.js +237 -0
  10. package/bin/reinforce.js +187 -0
  11. package/bin/session-start.js +292 -0
  12. package/bin/skill.js +67 -0
  13. package/bin/unpin.js +38 -0
  14. package/commands/brain/consolidate.md +7 -2
  15. package/commands/brain/explore.md +7 -2
  16. package/commands/brain/forget.md +7 -2
  17. package/commands/brain/init.md +8 -12
  18. package/commands/brain/memorize.md +76 -144
  19. package/commands/brain/pin.md +37 -0
  20. package/commands/brain/remember.md +48 -105
  21. package/commands/brain/review.md +7 -2
  22. package/commands/brain/skills.md +60 -0
  23. package/commands/brain/sleep.md +68 -27
  24. package/commands/brain/status.md +19 -5
  25. package/commands/brain/sunshine.md +18 -13
  26. package/commands/brain/sync.md +360 -0
  27. package/commands/brain/unpin.md +26 -0
  28. package/package.json +18 -8
  29. package/prompts/claude.md +115 -12
  30. package/prompts/gemini.md +115 -12
  31. package/prompts/openai.md +113 -10
  32. package/prompts/opencode.md +178 -0
  33. package/src/cloud-sync.js +524 -0
  34. package/src/crypto.js +130 -0
  35. package/src/export-import.js +185 -0
  36. package/src/git-sync.js +444 -0
  37. package/src/index-manager.js +205 -18
  38. package/src/installer.js +384 -0
  39. package/src/pinning.js +124 -0
  40. package/src/scorer.js +6 -2
  41. package/src/skills.js +208 -0
  42. package/src/tfidf.js +408 -0
  43. package/hooks/session-end.md +0 -48
  44. package/hooks/session-start.md +0 -48
@@ -0,0 +1,433 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain memorize — Store memories from AI agent input
5
+ *
6
+ * Accepts a JSON payload via stdin with memory definitions.
7
+ * Handles all plumbing: ID generation, directory creation, file writing,
8
+ * index updates, association edges, search index, and optional sync.
9
+ *
10
+ * Usage:
11
+ * brain memorize [--sync] <<'EOF'
12
+ * { "memories": [{ "title": "...", "type": "learning", ... }] }
13
+ * EOF
14
+ *
15
+ * The AI agent decides WHAT to remember. This CLI handles HOW to write it.
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const { execSync } = require('child_process');
21
+ const {
22
+ getBrainDir,
23
+ readIndex,
24
+ writeIndex,
25
+ addMemory,
26
+ generateId,
27
+ readMeta,
28
+ writeMeta,
29
+ readAssociations,
30
+ writeAssociations,
31
+ reinforceEdge,
32
+ readPinned,
33
+ writePinned,
34
+ atomicWriteSync,
35
+ validateBrainPath,
36
+ } = require('../src/index-manager');
37
+ const { addDocument, createSearchIndex, readSearchIndex, writeSearchIndex } = require('../src/tfidf');
38
+
39
+ // --- Type defaults ---
40
+
41
+ const TYPE_DEFAULTS = {
42
+ decision: { strength: 0.85, decay_rate: 0.995 },
43
+ insight: { strength: 0.90, decay_rate: 0.997 },
44
+ goal: { strength: 0.80, decay_rate: 0.993 },
45
+ experience: { strength: 0.75, decay_rate: 0.985 },
46
+ learning: { strength: 0.70, decay_rate: 0.990 },
47
+ relationship: { strength: 0.70, decay_rate: 0.997 },
48
+ preference: { strength: 0.60, decay_rate: 0.998 },
49
+ observation: { strength: 0.40, decay_rate: 0.950 },
50
+ };
51
+
52
+ const COGNITIVE_ADJUSTMENTS = {
53
+ episodic: { strength_delta: +0.10, decay_multiplier: 0.995 },
54
+ semantic: { strength_delta: 0, decay_multiplier: 1.0 },
55
+ procedural: { strength_delta: -0.10, decay_multiplier: 1.003 },
56
+ };
57
+
58
+ // --- Args ---
59
+
60
+ function parseArgs(argv) {
61
+ const args = { sync: false };
62
+ for (const arg of argv) {
63
+ if (arg === '--sync') args.sync = true;
64
+ }
65
+ return args;
66
+ }
67
+
68
+ // --- Helpers ---
69
+
70
+ function computeStrengthAndDecay(type, cognitiveType, strengthAdjustment = 0) {
71
+ const typeDefaults = TYPE_DEFAULTS[type] || TYPE_DEFAULTS.observation;
72
+ const cogAdj = COGNITIVE_ADJUSTMENTS[cognitiveType] || COGNITIVE_ADJUSTMENTS.semantic;
73
+
74
+ const strength = Math.max(0, Math.min(1.0,
75
+ typeDefaults.strength + cogAdj.strength_delta + strengthAdjustment
76
+ ));
77
+ const decay_rate = typeDefaults.decay_rate * cogAdj.decay_multiplier;
78
+
79
+ return { strength: Math.round(strength * 100) / 100, decay_rate };
80
+ }
81
+
82
+ function buildMemoryFileContent(mem, id, now) {
83
+ const { strength, decay_rate } = computeStrengthAndDecay(
84
+ mem.type, mem.cognitive_type, mem.strength_adjustment
85
+ );
86
+
87
+ const fmLines = [
88
+ '---',
89
+ `id: ${id}`,
90
+ `type: ${mem.type}`,
91
+ `cognitive_type: ${mem.cognitive_type || 'semantic'}`,
92
+ `created: "${now}"`,
93
+ `last_accessed: "${now}"`,
94
+ `access_count: 0`,
95
+ `recall_history: []`,
96
+ `strength: ${strength}`,
97
+ `decay_rate: ${decay_rate}`,
98
+ `salience: ${mem.salience ?? 0.5}`,
99
+ `confidence: ${mem.confidence ?? 0.7}`,
100
+ ];
101
+ // CoALA Phase 1: pinned (always-loaded) and stable (decay-exempt) are emitted
102
+ // only when set, so ordinary memories keep their existing frontmatter shape.
103
+ if (mem.pinned) {
104
+ fmLines.push('pinned: true');
105
+ fmLines.push(`pin_scope: "${mem.pin_scope || 'global'}"`);
106
+ fmLines.push(`pin_priority: ${mem.pin_priority || 0}`);
107
+ }
108
+ if (mem.stable) fmLines.push('stable: true');
109
+ fmLines.push(
110
+ `tags: [${(mem.tags || []).map(t => `"${t}"`).join(', ')}]`,
111
+ `related: [${(mem.related || []).map(r => `"${r}"`).join(', ')}]`,
112
+ `source: "${mem.source || ''}"`,
113
+ `encoding_context:`,
114
+ ` project: "${(mem.encoding_context && mem.encoding_context.project) || ''}"`,
115
+ ` topics: [${((mem.encoding_context && mem.encoding_context.topics) || []).map(t => `"${t}"`).join(', ')}]`,
116
+ ` task_type: "${(mem.encoding_context && mem.encoding_context.task_type) || ''}"`,
117
+ '---',
118
+ '',
119
+ );
120
+ const frontmatter = fmLines.join('\n');
121
+
122
+ return { fileContent: frontmatter + mem.content + '\n', strength, decay_rate };
123
+ }
124
+
125
+ function buildIndexEntry(mem, id, strength, decayRate, now) {
126
+ const entry = {
127
+ title: mem.title,
128
+ path: mem.path,
129
+ type: mem.type,
130
+ cognitive_type: mem.cognitive_type || 'semantic',
131
+ created: now,
132
+ last_accessed: now,
133
+ access_count: 0,
134
+ strength,
135
+ decay_rate: decayRate,
136
+ salience: mem.salience ?? 0.5,
137
+ confidence: mem.confidence ?? 0.7,
138
+ tags: mem.tags || [],
139
+ related: mem.related || [],
140
+ encoding_context: mem.encoding_context || {},
141
+ // CoALA Phase 0: cheap chars/4 token estimate for working-memory budgeting.
142
+ token_estimate: Math.ceil((mem.content || '').length / 4),
143
+ };
144
+ // CoALA Phase 1: only set when present — keeps existing index entries lean.
145
+ if (mem.pinned) {
146
+ entry.pinned = true;
147
+ entry.pin_scope = mem.pin_scope || 'global';
148
+ entry.pin_priority = mem.pin_priority || 0;
149
+ }
150
+ if (mem.stable) entry.stable = true;
151
+ return entry;
152
+ }
153
+
154
+ function updateMetaFiles(brainDir, memPath) {
155
+ const parts = memPath.split('/');
156
+ // Walk up the directory chain, updating _meta.json at each level
157
+ for (let i = 1; i <= parts.length - 1; i++) {
158
+ const dirParts = parts.slice(0, i);
159
+ const categoryPath = dirParts.join('/');
160
+ const fullDir = path.join(brainDir, categoryPath);
161
+
162
+ if (!fs.existsSync(fullDir)) continue;
163
+
164
+ const metaPath = path.join(fullDir, '_meta.json');
165
+ let meta;
166
+ try {
167
+ meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
168
+ } catch {
169
+ meta = { description: categoryPath, memory_count: 0, subcategories: [] };
170
+ }
171
+
172
+ meta.memory_count = (meta.memory_count || 0) + 1;
173
+
174
+ // Add subcategory if this isn't the leaf directory
175
+ if (i < parts.length - 1) {
176
+ const subcat = parts[i];
177
+ if (!meta.subcategories) meta.subcategories = [];
178
+ if (!meta.subcategories.includes(subcat)) {
179
+ meta.subcategories.push(subcat);
180
+ }
181
+ }
182
+
183
+ atomicWriteSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
184
+ }
185
+ }
186
+
187
+ function findTagOverlaps(index, newTags, newId, minOverlap = 2) {
188
+ const overlaps = [];
189
+ if (!newTags || newTags.length < minOverlap) return overlaps;
190
+
191
+ const newTagSet = new Set(newTags);
192
+ for (const [id, entry] of Object.entries(index.memories)) {
193
+ if (id === newId) continue;
194
+ const entryTags = entry.tags || [];
195
+ const shared = entryTags.filter(t => newTagSet.has(t));
196
+ if (shared.length >= minOverlap) {
197
+ overlaps.push(id);
198
+ }
199
+ }
200
+ return overlaps;
201
+ }
202
+
203
+ function trySync() {
204
+ const brainDir = getBrainDir();
205
+
206
+ // Try cloud sync first
207
+ const cloudConfig = path.join(brainDir, '.cloud', 'config.json');
208
+ if (fs.existsSync(cloudConfig)) {
209
+ try {
210
+ execSync('brain cloud push', { stdio: 'pipe', timeout: 30000 });
211
+ return { method: 'cloud', success: true };
212
+ } catch (err) {
213
+ return { method: 'cloud', success: false, error: err.message };
214
+ }
215
+ }
216
+
217
+ // Try git sync
218
+ const gitConfig = path.join(brainDir, '.sync', 'config.json');
219
+ if (fs.existsSync(gitConfig)) {
220
+ try {
221
+ // Use the git-sync module
222
+ const gitSync = require('../src/git-sync');
223
+ // Sync push is async, but we run sync for CLI simplicity
224
+ execSync(`node -e "require('${path.join(__dirname, '..', 'src', 'git-sync.js')}').push('${brainDir}').then(() => process.exit(0)).catch(() => process.exit(1))"`, {
225
+ stdio: 'pipe',
226
+ timeout: 30000,
227
+ });
228
+ return { method: 'git', success: true };
229
+ } catch (err) {
230
+ return { method: 'git', success: false, error: err.message };
231
+ }
232
+ }
233
+
234
+ return { method: 'none', success: false, error: 'No sync configured (cloud or git)' };
235
+ }
236
+
237
+ // --- Main ---
238
+
239
+ async function main() {
240
+ const args = parseArgs(process.argv.slice(2));
241
+
242
+ // Read JSON from stdin
243
+ let inputData = '';
244
+ if (process.stdin.isTTY) {
245
+ console.error(JSON.stringify({ error: 'No input provided. Pipe JSON via stdin.' }));
246
+ process.exit(1);
247
+ }
248
+
249
+ inputData = fs.readFileSync('/dev/stdin', 'utf-8');
250
+
251
+ let input;
252
+ try {
253
+ input = JSON.parse(inputData);
254
+ } catch (err) {
255
+ console.error(JSON.stringify({ error: `Invalid JSON input: ${err.message}` }));
256
+ process.exit(1);
257
+ }
258
+
259
+ if (!input.memories || !Array.isArray(input.memories) || input.memories.length === 0) {
260
+ console.error(JSON.stringify({ error: 'Input must have a non-empty "memories" array' }));
261
+ process.exit(1);
262
+ }
263
+
264
+ const brainDir = getBrainDir();
265
+
266
+ // Validate brain exists
267
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
268
+ console.error(JSON.stringify({ error: `Brain not initialized. Run brain install first.` }));
269
+ process.exit(1);
270
+ }
271
+
272
+ // Read current state
273
+ let index;
274
+ try {
275
+ index = readIndex();
276
+ } catch (err) {
277
+ console.error(JSON.stringify({
278
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
279
+ }));
280
+ process.exit(1);
281
+ }
282
+
283
+ let associations;
284
+ try {
285
+ associations = readAssociations() || { version: 1, edges: {} };
286
+ } catch (err) {
287
+ console.error(JSON.stringify({
288
+ error: `Corrupt associations.json in ~/.brain/ — ${err.message}`,
289
+ }));
290
+ process.exit(1);
291
+ }
292
+
293
+ let searchIndex;
294
+ try {
295
+ searchIndex = readSearchIndex(brainDir) || createSearchIndex();
296
+ } catch (err) {
297
+ // Search index is non-critical — rebuild from scratch
298
+ searchIndex = createSearchIndex();
299
+ }
300
+
301
+ const now = new Date().toISOString();
302
+ const results = [];
303
+ const newIds = [];
304
+ const pinnedToAdd = [];
305
+
306
+ for (const mem of input.memories) {
307
+ // Validate required fields
308
+ if (!mem.title || !mem.type || !mem.path || !mem.content) {
309
+ console.error(JSON.stringify({
310
+ error: `Memory missing required fields (title, type, path, content): ${JSON.stringify(mem.title || 'untitled')}`,
311
+ }));
312
+ process.exit(1);
313
+ }
314
+
315
+ if (!TYPE_DEFAULTS[mem.type]) {
316
+ console.error(JSON.stringify({ error: `Unknown memory type: ${mem.type}` }));
317
+ process.exit(1);
318
+ }
319
+
320
+ // Generate ID
321
+ const id = generateId();
322
+ newIds.push(id);
323
+
324
+ // Compute strength/decay
325
+ const { fileContent, strength, decay_rate } = buildMemoryFileContent(mem, id, now);
326
+
327
+ // Create directories
328
+ const fullPath = path.join(brainDir, mem.path);
329
+ validateBrainPath(fullPath, brainDir);
330
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
331
+
332
+ // Write memory file
333
+ atomicWriteSync(fullPath, fileContent);
334
+
335
+ // Update index
336
+ const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now);
337
+ addMemory(index, id, indexEntry);
338
+
339
+ // CoALA Phase 1: register a born-pinned memory in the pinned manifest
340
+ if (mem.pinned) {
341
+ pinnedToAdd.push({
342
+ id,
343
+ scope: mem.pin_scope || 'global',
344
+ priority: mem.pin_priority || 0,
345
+ token_estimate: indexEntry.token_estimate,
346
+ });
347
+ }
348
+
349
+ // Update associations — explicit related links
350
+ for (const relatedId of (mem.related || [])) {
351
+ if (index.memories[relatedId]) {
352
+ reinforceEdge(associations, id, relatedId, 'manual', 0.20);
353
+ }
354
+ }
355
+
356
+ // Update associations — tag overlaps
357
+ const tagOverlaps = findTagOverlaps(index, mem.tags, id);
358
+ for (const overlapId of tagOverlaps) {
359
+ reinforceEdge(associations, id, overlapId, 'tag_overlap', 0.10);
360
+ }
361
+
362
+ // Tier B §10.2: surface potential contradictions with pinned/stable memories
363
+ // (high tag overlap) so the agent can adjudicate — never auto-resolved here.
364
+ const potentialConflicts = tagOverlaps
365
+ .filter((oid) => {
366
+ const e = index.memories[oid];
367
+ return e && (e.pinned || e.stable);
368
+ })
369
+ .map((oid) => ({ id: oid, title: index.memories[oid].title }));
370
+
371
+ // Update search index
372
+ addDocument(searchIndex, id, {
373
+ title: mem.title,
374
+ tags: mem.tags,
375
+ body: mem.content,
376
+ });
377
+
378
+ // Update _meta.json files
379
+ updateMetaFiles(brainDir, mem.path);
380
+
381
+ const edgesCreated = (mem.related || []).filter(r => index.memories[r]).length + tagOverlaps.length;
382
+
383
+ results.push({
384
+ id,
385
+ title: mem.title,
386
+ path: mem.path,
387
+ type: mem.type,
388
+ cognitive_type: mem.cognitive_type || 'semantic',
389
+ strength,
390
+ decay_rate,
391
+ salience: mem.salience ?? 0.5,
392
+ confidence: mem.confidence ?? 0.7,
393
+ tags: mem.tags || [],
394
+ edges_created: edgesCreated,
395
+ ...(potentialConflicts.length ? { potential_conflicts: potentialConflicts } : {}),
396
+ });
397
+ }
398
+
399
+ // Write all updated state
400
+ writeIndex(index);
401
+ writeAssociations(associations);
402
+ writeSearchIndex(brainDir, searchIndex);
403
+
404
+ // CoALA Phase 1: persist any born-pinned memories to the pinned manifest
405
+ if (pinnedToAdd.length > 0) {
406
+ const pinned = readPinned();
407
+ for (const p of pinnedToAdd) {
408
+ pinned.pins = pinned.pins.filter((x) => x.id !== p.id);
409
+ pinned.pins.push(p);
410
+ }
411
+ writePinned(pinned);
412
+ }
413
+
414
+ // Build output
415
+ const output = {
416
+ stored: results,
417
+ total: results.length,
418
+ index_count: index.memory_count,
419
+ };
420
+
421
+ // Sync if requested
422
+ if (args.sync || input.auto_sync) {
423
+ const syncResult = trySync();
424
+ output.sync = syncResult;
425
+ }
426
+
427
+ console.log(JSON.stringify(output, null, 2));
428
+ }
429
+
430
+ main().catch((err) => {
431
+ console.error(JSON.stringify({ error: err.message }));
432
+ process.exit(1);
433
+ });
package/bin/pin.js ADDED
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain pin — pin a memory into the always-present semantic tier (CoALA Phase 1).
5
+ *
6
+ * Usage:
7
+ * brain pin <id> [--scope global|project:<name>] [--priority N]
8
+ */
9
+
10
+ const { pinMemory } = require('../src/pinning');
11
+
12
+ function parseArgs(argv) {
13
+ const args = { id: null, scope: 'global', priority: 0 };
14
+ for (let i = 0; i < argv.length; i++) {
15
+ switch (argv[i]) {
16
+ case '--scope': args.scope = argv[++i]; break;
17
+ case '--priority': args.priority = parseInt(argv[++i], 10) || 0; break;
18
+ default:
19
+ if (!argv[i].startsWith('--') && !args.id) args.id = argv[i];
20
+ break;
21
+ }
22
+ }
23
+ return args;
24
+ }
25
+
26
+ function main(argv) {
27
+ const args = parseArgs(argv || process.argv.slice(2));
28
+ if (!args.id) {
29
+ console.error(JSON.stringify({ error: 'Usage: brain pin <id> [--scope global|project:<name>] [--priority N]' }));
30
+ process.exit(1);
31
+ }
32
+ const result = pinMemory(undefined, args.id, { scope: args.scope, priority: args.priority });
33
+ if (result.error) {
34
+ console.error(JSON.stringify(result));
35
+ process.exit(1);
36
+ }
37
+ console.log(JSON.stringify(result, null, 2));
38
+ }
39
+
40
+ if (require.main === module) {
41
+ main(process.argv.slice(2));
42
+ }
43
+
44
+ module.exports = { main, parseArgs };
package/bin/recall.js ADDED
@@ -0,0 +1,237 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Brain Memory — Deterministic Recall Engine
5
+ *
6
+ * CLI tool that replaces agent-driven scoring with deterministic computation.
7
+ * The agent calls this instead of manually computing the v4 formula.
8
+ *
9
+ * Usage:
10
+ * brain recall "async race conditions"
11
+ * brain recall "database pooling" --project my-app --task implementing --top 5
12
+ * brain recall --context # Session-start mode: auto-detect context
13
+ * brain recall --reindex # Rebuild search index from all memories
14
+ *
15
+ * Output: JSON array of scored results, sorted by score descending.
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const os = require('os');
21
+
22
+ const {
23
+ readSearchIndex,
24
+ writeSearchIndex,
25
+ search,
26
+ rebuildIndex,
27
+ createSearchIndex,
28
+ } = require('../src/tfidf');
29
+
30
+ const {
31
+ readIndex,
32
+ readAssociations,
33
+ getBrainDir,
34
+ } = require('../src/index-manager');
35
+
36
+ const {
37
+ rankMemories,
38
+ } = require('../src/scorer');
39
+
40
+ function main() {
41
+ const args = parseArgs(process.argv.slice(2));
42
+
43
+ const brainDir = getBrainDir();
44
+
45
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
46
+ console.error(JSON.stringify({ error: 'Brain not initialized. Run /brain:init first.' }));
47
+ process.exit(1);
48
+ }
49
+
50
+ // Reindex mode
51
+ if (args.reindex) {
52
+ return handleReindex(brainDir);
53
+ }
54
+
55
+ // Need a query for search
56
+ if (!args.query && !args.context) {
57
+ console.error(JSON.stringify({ error: 'Usage: brain recall "query" or brain recall --context' }));
58
+ process.exit(1);
59
+ }
60
+
61
+ let index;
62
+ try {
63
+ index = readIndex();
64
+ } catch (err) {
65
+ console.error(JSON.stringify({
66
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
67
+ }));
68
+ process.exit(1);
69
+ }
70
+ if (!index || !index.memories || Object.keys(index.memories).length === 0) {
71
+ console.log(JSON.stringify([]));
72
+ return;
73
+ }
74
+
75
+ // Ensure search index exists
76
+ let searchIndex;
77
+ try {
78
+ searchIndex = readSearchIndex(brainDir);
79
+ } catch (_) {
80
+ searchIndex = null;
81
+ }
82
+ if (!searchIndex) {
83
+ searchIndex = rebuildIndex(brainDir, index);
84
+ writeSearchIndex(brainDir, searchIndex);
85
+ }
86
+
87
+ // Context mode: build query from project context
88
+ const query = args.context
89
+ ? buildContextQuery(args)
90
+ : args.query;
91
+
92
+ // Compute TF-IDF relevance scores
93
+ const tfidfScores = search(searchIndex, query);
94
+
95
+ // Build memory list from index
96
+ const memories = Object.entries(index.memories).map(([id, entry]) => ({
97
+ id,
98
+ ...entry,
99
+ }));
100
+
101
+ // Load associations for spreading activation
102
+ let associations;
103
+ try {
104
+ associations = readAssociations();
105
+ } catch (_) {
106
+ associations = null;
107
+ }
108
+
109
+ // Build recall context
110
+ const recallContext = {};
111
+ if (args.project) recallContext.project = args.project;
112
+ if (args.task) recallContext.task_type = args.task;
113
+ if (args.topics) recallContext.topics = args.topics.split(',');
114
+
115
+ // Rank using scorer.js with TF-IDF as the relevance function
116
+ const ranked = rankMemories(
117
+ memories,
118
+ (mem) => tfidfScores[mem.id] || 0,
119
+ {
120
+ associations: associations || undefined,
121
+ recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
122
+ }
123
+ );
124
+
125
+ // Return top N
126
+ const top = args.top || 10;
127
+ const results = ranked.slice(0, top).map((mem) => ({
128
+ id: mem.id,
129
+ title: mem.title || path.basename(mem.path, '.md'),
130
+ path: mem.path,
131
+ type: mem.type,
132
+ score: mem.score,
133
+ relevance: mem.relevance,
134
+ decayed_strength: mem.decayed_strength,
135
+ context_match: mem.context_match,
136
+ spreading_bonus: mem.spreading_bonus,
137
+ confidence: mem.confidence,
138
+ tags: mem.tags,
139
+ }));
140
+
141
+ console.log(JSON.stringify(results, null, 2));
142
+ }
143
+
144
+ /**
145
+ * Rebuild the search index from all memories.
146
+ */
147
+ function handleReindex(brainDir) {
148
+ let index;
149
+ try {
150
+ index = readIndex();
151
+ } catch (err) {
152
+ console.error(JSON.stringify({
153
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
154
+ }));
155
+ process.exit(1);
156
+ }
157
+ if (!index) {
158
+ console.error(JSON.stringify({ error: 'No index.json found.' }));
159
+ process.exit(1);
160
+ }
161
+
162
+ const searchIndex = rebuildIndex(brainDir, index);
163
+ writeSearchIndex(brainDir, searchIndex);
164
+
165
+ console.log(JSON.stringify({
166
+ reindexed: true,
167
+ documents: searchIndex.doc_count,
168
+ terms: Object.keys(searchIndex.df).length,
169
+ }));
170
+ }
171
+
172
+ /**
173
+ * Build a query from context when no explicit query is given.
174
+ * Uses project name and topics as search terms.
175
+ */
176
+ function buildContextQuery(args) {
177
+ const parts = [];
178
+ if (args.project) parts.push(args.project);
179
+ if (args.topics) parts.push(args.topics);
180
+ if (args.task) parts.push(args.task);
181
+
182
+ // If still empty, use a broad query
183
+ return parts.length > 0 ? parts.join(' ') : '*';
184
+ }
185
+
186
+ /**
187
+ * Parse CLI arguments.
188
+ */
189
+ function parseArgs(argv) {
190
+ const args = {
191
+ query: null,
192
+ project: null,
193
+ task: null,
194
+ topics: null,
195
+ top: 10,
196
+ context: false,
197
+ reindex: false,
198
+ };
199
+
200
+ const positional = [];
201
+
202
+ for (let i = 0; i < argv.length; i++) {
203
+ switch (argv[i]) {
204
+ case '--project':
205
+ args.project = argv[++i];
206
+ break;
207
+ case '--task':
208
+ args.task = argv[++i];
209
+ break;
210
+ case '--topics':
211
+ args.topics = argv[++i];
212
+ break;
213
+ case '--top':
214
+ args.top = parseInt(argv[++i], 10);
215
+ break;
216
+ case '--context':
217
+ args.context = true;
218
+ break;
219
+ case '--reindex':
220
+ args.reindex = true;
221
+ break;
222
+ default:
223
+ if (!argv[i].startsWith('--')) {
224
+ positional.push(argv[i]);
225
+ }
226
+ break;
227
+ }
228
+ }
229
+
230
+ if (positional.length > 0) {
231
+ args.query = positional.join(' ');
232
+ }
233
+
234
+ return args;
235
+ }
236
+
237
+ main();