brain-memory 0.1.0-beta.13 → 0.1.0-beta.15

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 CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  A hierarchical, file-system-based memory plugin for AI coding agents. Inspired by human neuroscience — memories are organized into deep nested life-domain categories, connected via associative networks, strengthened through spaced recall, and naturally decay over time.
14
14
 
15
- Works with **Claude Code**, **Gemini CLI**, and **OpenAI Codex CLI**.
15
+ Works with **Claude Code**, **Gemini CLI**, **OpenAI Codex CLI**, and **OpenCode**.
16
16
 
17
17
  ```
18
18
  ~/.brain/
@@ -51,35 +51,43 @@ Existing AI memory solutions use flat databases with tag-based retrieval. Brain
51
51
  ## Install
52
52
 
53
53
  ```bash
54
- npx brain-memory@beta
54
+ npm install -g brain-memory@beta
55
+ brain
55
56
  ```
56
57
 
57
- The interactive installer asks which runtime(s) to configure (Claude Code, Gemini CLI, OpenAI Codex CLI, or all) and whether to install globally or for the current project.
58
+ The first command installs the package globally — this gives you both the interactive setup wizard and the `brain` CLI (`brain recall`, `brain memorize`, `brain reinforce`, …) that agents rely on for deterministic scoring.
59
+
60
+ The second command runs the setup wizard, which asks which runtime(s) to configure (Claude Code, Gemini CLI, OpenAI Codex CLI, or all) and whether to install globally or for the current project.
58
61
 
59
62
  ### Non-interactive
60
63
 
61
64
  ```bash
62
- npx brain-memory --claude --global # Claude Code, global
63
- npx brain-memory --gemini --local # Gemini CLI, local project
64
- npx brain-memory --codex --global # OpenAI Codex CLI, global
65
- npx brain-memory --all --global # All runtimes, global
65
+ brain --claude --global # Claude Code, global
66
+ brain --gemini --local # Gemini CLI, local project
67
+ brain --codex --global # OpenAI Codex CLI, global
68
+ brain --opencode --global # OpenCode, global
69
+ brain --all --global # All runtimes, global
66
70
  ```
67
71
 
68
72
  ### Update
69
73
 
70
74
  ```bash
71
- npx brain-memory@beta update
75
+ npm install -g brain-memory@beta
76
+ brain update
72
77
  ```
73
78
 
74
- Auto-detects installed runtimes and refreshes commands + prompt sections. Target specific runtimes with `--claude`, `--gemini`, `--openai`, or `--all`.
79
+ The first command updates the package and the `brain` CLI. The second command refreshes the slash command prompts for your installed runtimes. Target specific runtimes with `--claude`, `--gemini`, `--openai`, or `--all`.
80
+
81
+ > **Why not `npx`?** `npx` runs the setup wizard in a temporary directory that is discarded after execution. The `brain` CLI (`brain recall`, `brain memorize`, `brain reinforce`) won't be available in your PATH, which means agents will fall back to less reliable manual file operations. Always use `npm install -g` to ensure everything works correctly.
75
82
 
76
83
  ### Uninstall
77
84
 
78
85
  ```bash
79
- npx brain-memory@beta uninstall
86
+ brain uninstall
87
+ npm uninstall -g brain-memory
80
88
  ```
81
89
 
82
- Removes commands and prompt sections. Your `~/.brain/` directory (memories) is preserved by default. Add `--delete-data` to remove it too. Use `--yes` to skip confirmation prompts.
90
+ The first command removes slash commands and prompt sections from your agent configs. The second removes the package and CLI tools. Your `~/.brain/` directory (memories) is preserved by default. Add `--delete-data` to the uninstall command to remove it too. Use `--yes` to skip confirmation prompts.
83
91
 
84
92
  ### Manual Install
85
93
 
package/assets/icon.png CHANGED
Binary file
@@ -0,0 +1,21 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
2
+ <rect x="0" y="0" width="1024" height="1024" rx="224" ry="224" fill="#F0EFE8"/>
3
+ <g stroke="#1A1A1A" stroke-width="20" stroke-linecap="round">
4
+ <line x1="512" y1="512" x2="512" y2="232"/>
5
+ <line x1="512" y1="512" x2="754.49" y2="372"/>
6
+ <line x1="512" y1="512" x2="754.49" y2="652"/>
7
+ <line x1="512" y1="512" x2="512" y2="792"/>
8
+ <line x1="512" y1="512" x2="269.51" y2="652"/>
9
+ <line x1="512" y1="512" x2="269.51" y2="372"/>
10
+ </g>
11
+ <g fill="#1A1A1A">
12
+ <circle cx="512" cy="232" r="44"/>
13
+ <circle cx="754.49" cy="372" r="44"/>
14
+ <circle cx="754.49" cy="652" r="44"/>
15
+ <circle cx="512" cy="792" r="44"/>
16
+ <circle cx="269.51" cy="652" r="44"/>
17
+ <circle cx="269.51" cy="372" r="44"/>
18
+ </g>
19
+ <circle cx="512" cy="512" r="98" fill="#1A1A1A"/>
20
+ <circle cx="512" cy="512" r="58" fill="#E7B300"/>
21
+ </svg>
package/bin/brain.js ADDED
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain — unified CLI dispatcher for the Brain Memory system.
5
+ *
6
+ * Routes subcommands to their implementations, replacing the former per-binary
7
+ * surface (brain-recall, brain-reinforce, brain-memorize, brain-cloud). Each
8
+ * delegate module still runs on load and remains invokable as `node bin/<file>`,
9
+ * so direct invocation and the existing test suite are unaffected.
10
+ *
11
+ * Usage:
12
+ * brain Interactive installer (also: brain install)
13
+ * brain install|update|uninstall [flags]
14
+ * brain recall "<query>" [--project P] [--task T] [--top N] [--context] [--reindex]
15
+ * brain memorize [--sync] Store memories from a JSON payload on stdin
16
+ * brain reinforce <id> [<id>...] Spaced reinforcement + Hebbian co-retrieval
17
+ * brain cloud <login|logout|push|pull|status>
18
+ * brain --help | brain --version
19
+ */
20
+
21
+ const path = require('path');
22
+
23
+ const VERSION = require('../package.json').version;
24
+
25
+ // Subcommands whose modules read process.argv.slice(2) directly. We strip the
26
+ // leading subcommand token, then require the module (which executes on load).
27
+ const DELEGATED = {
28
+ recall: 'recall.js',
29
+ reinforce: 'reinforce.js',
30
+ memorize: 'memorize.js',
31
+ cloud: 'cloud-sync.js',
32
+ 'session-start': 'session-start.js',
33
+ pin: 'pin.js',
34
+ unpin: 'unpin.js',
35
+ skill: 'skill.js',
36
+ };
37
+
38
+ // install.js finds its positional subcommand from process.argv itself, so it is
39
+ // required without stripping anything. Bare `brain` also routes here, preserving
40
+ // `npx brain-memory` via npm's single-bin fallback.
41
+ const INSTALLER = new Set(['install', 'update', 'uninstall']);
42
+
43
+ const HELP = `🧠 brain — Brain Memory CLI
44
+
45
+ Usage: brain <command> [options]
46
+
47
+ Memory
48
+ recall "<query>" [--project P] [--task T] [--top N]
49
+ Deterministic recall (TF-IDF + decay + spreading)
50
+ recall --context Session-start recall from project context
51
+ recall --reindex Rebuild the search index
52
+ memorize [--sync] Store memories from a JSON payload on stdin
53
+ reinforce <id> [<id>...] Spaced reinforcement + Hebbian co-retrieval
54
+ pin <id> [--scope global|project:<name>] [--priority N]
55
+ Pin a memory into the always-present tier
56
+ unpin <id> Remove a memory from the always-present tier
57
+ skill <list|show|use|add|remove|export>
58
+ Manage procedural skills (progressive disclosure)
59
+ session-start [--project P] [--task T] [--top N]
60
+ Budget-bounded startup payload (agent-invoked)
61
+
62
+ Sync
63
+ cloud <login|logout|push|pull|status>
64
+
65
+ Setup
66
+ install Interactive installer (default when no command)
67
+ update Update an existing installation
68
+ uninstall [--delete-data] Remove the installation
69
+
70
+ Other
71
+ --help, -h Show this help
72
+ --version, -v Show version
73
+ `;
74
+
75
+ function main() {
76
+ const sub = process.argv[2];
77
+
78
+ if (sub === '--version' || sub === '-v') {
79
+ console.log(VERSION);
80
+ return;
81
+ }
82
+
83
+ if (sub === '--help' || sub === '-h' || sub === 'help') {
84
+ console.log(HELP);
85
+ return;
86
+ }
87
+
88
+ // Bare `brain` or an installer subcommand → run the installer.
89
+ if (sub === undefined || INSTALLER.has(sub)) {
90
+ require(path.join(__dirname, 'install.js'));
91
+ return;
92
+ }
93
+
94
+ const file = DELEGATED[sub];
95
+ if (file) {
96
+ process.argv.splice(2, 1); // drop the subcommand token
97
+ const mod = require(path.join(__dirname, file));
98
+ // Modules guarded with `require.main === module` (e.g. session-start) export
99
+ // a main() that we must invoke; legacy modules already ran on require.
100
+ if (mod && typeof mod.main === 'function') {
101
+ mod.main(process.argv.slice(2));
102
+ }
103
+ return;
104
+ }
105
+
106
+ console.error(`Unknown command: ${sub}\n`);
107
+ console.error(HELP);
108
+ process.exit(1);
109
+ }
110
+
111
+ main();
package/bin/cloud-sync.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * brain-cloud — CLI for Brain Cloud sync
4
+ * brain cloud — CLI for Brain Cloud sync
5
5
  *
6
6
  * Usage:
7
- * brain-cloud login [--api-url URL] Authenticate via device code flow
8
- * brain-cloud logout Clear stored credentials
9
- * brain-cloud push Upload ~/.brain/ to the cloud
10
- * brain-cloud pull Download from the cloud to ~/.brain/
11
- * brain-cloud status Show connection and sync status
7
+ * brain cloud login [--api-url URL] Authenticate via device code flow
8
+ * brain cloud logout Clear stored credentials
9
+ * brain cloud push Upload ~/.brain/ to the cloud
10
+ * brain cloud pull Download from the cloud to ~/.brain/
11
+ * brain cloud status Show connection and sync status
12
12
  */
13
13
 
14
14
  const path = require('path');
@@ -23,7 +23,7 @@ async function main() {
23
23
 
24
24
  if (!command || command === '--help' || command === '-h') {
25
25
  console.log(`
26
- brain-cloud — Brain Cloud sync CLI
26
+ brain cloud — Brain Cloud sync CLI
27
27
 
28
28
  Commands:
29
29
  login [--api-url URL] Authenticate via device code flow
@@ -118,7 +118,7 @@ async function cmdStatus() {
118
118
 
119
119
  if (!s.connected) {
120
120
  console.log('☁️ Not connected to Brain Cloud');
121
- console.log(' Run: brain-cloud login');
121
+ console.log(' Run: brain cloud login');
122
122
  return;
123
123
  }
124
124
 
package/bin/install.js CHANGED
@@ -51,7 +51,8 @@ function resolveRuntimesFromFlags(flags) {
51
51
  if (flags.has('claude')) runtimes.push('claude');
52
52
  if (flags.has('gemini')) runtimes.push('gemini');
53
53
  if (flags.has('openai') || flags.has('codex')) runtimes.push('openai');
54
- if (flags.has('all')) return ['claude', 'gemini', 'openai'];
54
+ if (flags.has('opencode')) runtimes.push('opencode');
55
+ if (flags.has('all')) return ['claude', 'gemini', 'openai', 'opencode'];
55
56
  return runtimes;
56
57
  }
57
58
 
@@ -73,14 +74,15 @@ async function runInstall(flags) {
73
74
  try {
74
75
  // Interactive runtime selection
75
76
  if (runtimes.length === 0) {
76
- console.log(' Which runtimes would you like to install for?\n');
77
- console.log(' 1) Claude Code');
78
- console.log(' 2) Gemini CLI');
79
- console.log(' 3) OpenAI Codex CLI');
80
- console.log(' 4) All');
77
+ console.log(' Which runtimes would you like to install for?\n');
78
+ console.log(' 1) Claude Code');
79
+ console.log(' 2) Gemini CLI');
80
+ console.log(' 3) OpenAI Codex CLI');
81
+ console.log(' 4) OpenCode');
82
+ console.log(' 5) All');
81
83
  console.log('');
82
84
 
83
- const choice = await ask(rl, ' Select (1/2/3/4): ');
85
+ const choice = await ask(rl, ' Select (1/2/3/4/5): ');
84
86
  switch (choice.trim()) {
85
87
  case '1':
86
88
  runtimes = ['claude'];
@@ -92,22 +94,25 @@ async function runInstall(flags) {
92
94
  runtimes = ['openai'];
93
95
  break;
94
96
  case '4':
95
- runtimes = ['claude', 'gemini', 'openai'];
97
+ runtimes = ['opencode'];
98
+ break;
99
+ case '5':
100
+ runtimes = ['claude', 'gemini', 'openai', 'opencode'];
96
101
  break;
97
102
  default:
98
- console.log(' Invalid choice. Defaulting to Claude Code.');
103
+ console.log(' Invalid choice. Defaulting to Claude Code.');
99
104
  runtimes = ['claude'];
100
105
  }
101
106
  }
102
107
 
103
108
  // Interactive scope selection
104
109
  if (!scope) {
105
- console.log('\n Installation scope:\n');
106
- console.log(' 1) Global — Available in all projects (~/.claude/, ~/.gemini/, ~/.codex/)');
107
- console.log(' 2) Local — This project only (./.claude/, ./.gemini/, ./.codex/)');
110
+ console.log('\n Installation scope:\n');
111
+ console.log(' 1) Global — Available in all projects (~/.claude/, ~/.gemini/, ~/.codex/, ~/.config/opencode/)');
112
+ console.log(' 2) Local — This project only (./.claude/, ./.gemini/, ./.codex/, ./.opencode/)');
108
113
  console.log('');
109
114
 
110
- const choice = await ask(rl, ' Select (1/2): ');
115
+ const choice = await ask(rl, ' Select (1/2): ');
111
116
  scope = choice.trim() === '2' ? 'local' : 'global';
112
117
  }
113
118
 
@@ -187,7 +192,7 @@ async function runUpdate(flags) {
187
192
 
188
193
  if (detections.length === 0) {
189
194
  console.log(' No existing brain-memory installations found.\n');
190
- console.log(' To install, run: npx brain-memory@beta');
195
+ console.log(' To install, run: npm install -g brain-memory@beta && brain-memory');
191
196
  if (filterRuntimes.length > 0) {
192
197
  console.log(` (Searched for: ${filterRuntimes.join(', ')})`);
193
198
  }
package/bin/memorize.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * brain-memorize — Store memories from AI agent input
4
+ * brain memorize — Store memories from AI agent input
5
5
  *
6
6
  * Accepts a JSON payload via stdin with memory definitions.
7
7
  * Handles all plumbing: ID generation, directory creation, file writing,
8
8
  * index updates, association edges, search index, and optional sync.
9
9
  *
10
10
  * Usage:
11
- * brain-memorize [--sync] <<'EOF'
11
+ * brain memorize [--sync] <<'EOF'
12
12
  * { "memories": [{ "title": "...", "type": "learning", ... }] }
13
13
  * EOF
14
14
  *
@@ -29,6 +29,8 @@ const {
29
29
  readAssociations,
30
30
  writeAssociations,
31
31
  reinforceEdge,
32
+ readPinned,
33
+ writePinned,
32
34
  atomicWriteSync,
33
35
  validateBrainPath,
34
36
  } = require('../src/index-manager');
@@ -82,7 +84,7 @@ function buildMemoryFileContent(mem, id, now) {
82
84
  mem.type, mem.cognitive_type, mem.strength_adjustment
83
85
  );
84
86
 
85
- const frontmatter = [
87
+ const fmLines = [
86
88
  '---',
87
89
  `id: ${id}`,
88
90
  `type: ${mem.type}`,
@@ -95,6 +97,16 @@ function buildMemoryFileContent(mem, id, now) {
95
97
  `decay_rate: ${decay_rate}`,
96
98
  `salience: ${mem.salience ?? 0.5}`,
97
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(
98
110
  `tags: [${(mem.tags || []).map(t => `"${t}"`).join(', ')}]`,
99
111
  `related: [${(mem.related || []).map(r => `"${r}"`).join(', ')}]`,
100
112
  `source: "${mem.source || ''}"`,
@@ -104,13 +116,14 @@ function buildMemoryFileContent(mem, id, now) {
104
116
  ` task_type: "${(mem.encoding_context && mem.encoding_context.task_type) || ''}"`,
105
117
  '---',
106
118
  '',
107
- ].join('\n');
119
+ );
120
+ const frontmatter = fmLines.join('\n');
108
121
 
109
122
  return { fileContent: frontmatter + mem.content + '\n', strength, decay_rate };
110
123
  }
111
124
 
112
125
  function buildIndexEntry(mem, id, strength, decayRate, now) {
113
- return {
126
+ const entry = {
114
127
  title: mem.title,
115
128
  path: mem.path,
116
129
  type: mem.type,
@@ -125,7 +138,17 @@ function buildIndexEntry(mem, id, strength, decayRate, now) {
125
138
  tags: mem.tags || [],
126
139
  related: mem.related || [],
127
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),
128
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;
129
152
  }
130
153
 
131
154
  function updateMetaFiles(brainDir, memPath) {
@@ -184,7 +207,7 @@ function trySync() {
184
207
  const cloudConfig = path.join(brainDir, '.cloud', 'config.json');
185
208
  if (fs.existsSync(cloudConfig)) {
186
209
  try {
187
- execSync('brain-cloud push', { stdio: 'pipe', timeout: 30000 });
210
+ execSync('brain cloud push', { stdio: 'pipe', timeout: 30000 });
188
211
  return { method: 'cloud', success: true };
189
212
  } catch (err) {
190
213
  return { method: 'cloud', success: false, error: err.message };
@@ -242,18 +265,43 @@ async function main() {
242
265
 
243
266
  // Validate brain exists
244
267
  if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
245
- console.error(JSON.stringify({ error: `Brain not initialized. Run brain-memory install first.` }));
268
+ console.error(JSON.stringify({ error: `Brain not initialized. Run brain install first.` }));
246
269
  process.exit(1);
247
270
  }
248
271
 
249
272
  // Read current state
250
- const index = readIndex();
251
- let associations = readAssociations() || { version: 1, edges: {} };
252
- let searchIndex = readSearchIndex(brainDir) || createSearchIndex();
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
+ }
253
300
 
254
301
  const now = new Date().toISOString();
255
302
  const results = [];
256
303
  const newIds = [];
304
+ const pinnedToAdd = [];
257
305
 
258
306
  for (const mem of input.memories) {
259
307
  // Validate required fields
@@ -288,6 +336,16 @@ async function main() {
288
336
  const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now);
289
337
  addMemory(index, id, indexEntry);
290
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
+
291
349
  // Update associations — explicit related links
292
350
  for (const relatedId of (mem.related || [])) {
293
351
  if (index.memories[relatedId]) {
@@ -301,6 +359,15 @@ async function main() {
301
359
  reinforceEdge(associations, id, overlapId, 'tag_overlap', 0.10);
302
360
  }
303
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
+
304
371
  // Update search index
305
372
  addDocument(searchIndex, id, {
306
373
  title: mem.title,
@@ -325,6 +392,7 @@ async function main() {
325
392
  confidence: mem.confidence ?? 0.7,
326
393
  tags: mem.tags || [],
327
394
  edges_created: edgesCreated,
395
+ ...(potentialConflicts.length ? { potential_conflicts: potentialConflicts } : {}),
328
396
  });
329
397
  }
330
398
 
@@ -333,6 +401,16 @@ async function main() {
333
401
  writeAssociations(associations);
334
402
  writeSearchIndex(brainDir, searchIndex);
335
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
+
336
414
  // Build output
337
415
  const output = {
338
416
  stored: results,
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 CHANGED
@@ -7,10 +7,10 @@
7
7
  * The agent calls this instead of manually computing the v4 formula.
8
8
  *
9
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
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
14
  *
15
15
  * Output: JSON array of scored results, sorted by score descending.
16
16
  */
@@ -54,18 +54,31 @@ function main() {
54
54
 
55
55
  // Need a query for search
56
56
  if (!args.query && !args.context) {
57
- console.error(JSON.stringify({ error: 'Usage: brain-recall "query" or brain-recall --context' }));
57
+ console.error(JSON.stringify({ error: 'Usage: brain recall "query" or brain recall --context' }));
58
58
  process.exit(1);
59
59
  }
60
60
 
61
- const index = readIndex();
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
+ }
62
70
  if (!index || !index.memories || Object.keys(index.memories).length === 0) {
63
71
  console.log(JSON.stringify([]));
64
72
  return;
65
73
  }
66
74
 
67
75
  // Ensure search index exists
68
- let searchIndex = readSearchIndex(brainDir);
76
+ let searchIndex;
77
+ try {
78
+ searchIndex = readSearchIndex(brainDir);
79
+ } catch (_) {
80
+ searchIndex = null;
81
+ }
69
82
  if (!searchIndex) {
70
83
  searchIndex = rebuildIndex(brainDir, index);
71
84
  writeSearchIndex(brainDir, searchIndex);
@@ -86,7 +99,12 @@ function main() {
86
99
  }));
87
100
 
88
101
  // Load associations for spreading activation
89
- const associations = readAssociations();
102
+ let associations;
103
+ try {
104
+ associations = readAssociations();
105
+ } catch (_) {
106
+ associations = null;
107
+ }
90
108
 
91
109
  // Build recall context
92
110
  const recallContext = {};
@@ -127,7 +145,15 @@ function main() {
127
145
  * Rebuild the search index from all memories.
128
146
  */
129
147
  function handleReindex(brainDir) {
130
- const index = readIndex();
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
+ }
131
157
  if (!index) {
132
158
  console.error(JSON.stringify({ error: 'No index.json found.' }));
133
159
  process.exit(1);
package/bin/reinforce.js CHANGED
@@ -8,8 +8,8 @@
8
8
  * results instead of manually updating frontmatter.
9
9
  *
10
10
  * Usage:
11
- * brain-reinforce mem_123 mem_456 mem_789
12
- * brain-reinforce mem_123 --project my-app
11
+ * brain reinforce mem_123 mem_456 mem_789
12
+ * brain reinforce mem_123 --project my-app
13
13
  *
14
14
  * Effects:
15
15
  * - Spaced reinforcement boost to each memory's strength
@@ -41,12 +41,20 @@ function main() {
41
41
  const args = parseArgs(process.argv.slice(2));
42
42
 
43
43
  if (args.memoryIds.length === 0) {
44
- console.error(JSON.stringify({ error: 'Usage: brain-reinforce <mem_id1> [mem_id2] ...' }));
44
+ console.error(JSON.stringify({ error: 'Usage: brain reinforce <mem_id1> [mem_id2] ...' }));
45
45
  process.exit(1);
46
46
  }
47
47
 
48
48
  const brainDir = getBrainDir();
49
- const index = readIndex();
49
+ let index;
50
+ try {
51
+ index = readIndex();
52
+ } catch (err) {
53
+ console.error(JSON.stringify({
54
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
55
+ }));
56
+ process.exit(1);
57
+ }
50
58
 
51
59
  if (!index) {
52
60
  console.error(JSON.stringify({ error: 'Brain not initialized.' }));