brain-memory 0.5.0 → 0.5.1

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/CHANGELOG.md CHANGED
@@ -6,6 +6,39 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.5.1] - 2026-10-18
10
+
11
+ An account with several brains can now choose which one each device, and the
12
+ connector, syncs with. A device that has just linked a brain can no longer
13
+ overwrite that brain's memories with its first push.
14
+
15
+ ### Added
16
+ - **Choose a brain when an account has several.** `brain cloud login --brain
17
+ NAME|ID` links that brain (creating it when no brain has that name); without
18
+ it, login links the account's first brain as before, and now creates a
19
+ `default` brain for an empty account on the device flow too. `brain cloud
20
+ brains` lists the account's brains, and `brain cloud use NAME|ID [--create]`
21
+ switches which one this device syncs with, leaving `~/.brain/` as it is.
22
+ Names match ignoring case. In the connector, `brain_status` lists the brains
23
+ with the one in use marked, and a new `brain_use` tool switches; the choice is
24
+ kept per user across sessions, and a chosen brain that is deleted falls back
25
+ to the oldest.
26
+
27
+ ### Changed
28
+ - A device that has never synced with its linked brain (a fresh login, or after
29
+ `brain cloud use`) now pushes only into a brain with no archive yet
30
+ (`If-None-Match: *`). Pull first, or `--force`, to replace a brain that has
31
+ memories. Configs that predate conditional sync keep pushing as before.
32
+
33
+ ### Fixed
34
+ - The connector pushes a write to the brain its working copy came from, and
35
+ drops the previous brain's copy when the brain it serves changes, so one
36
+ brain's memories are never shown under or pushed into another.
37
+ - `brain memorize` reads stdin as a stream, so piping into it on macOS can no
38
+ longer fail with `EAGAIN`.
39
+ - The Cursor plugin manifest and the MCP Registry entry (`server.json`) now
40
+ follow the package version on every release.
41
+
9
42
  ## [0.5.0] - 2026-10-18
10
43
 
11
44
  Memory stops being a way to smuggle instructions or permissions into an agent.
package/bin/cloud-sync.js CHANGED
@@ -4,10 +4,13 @@
4
4
  * brain cloud — CLI for syncing with Brain Cloud or a self-hosted brain-store
5
5
  *
6
6
  * Usage:
7
- * brain cloud login [--api-url URL] Authenticate via device code flow
7
+ * brain cloud login [--api-url URL] [--brain NAME|ID]
8
+ * Authenticate via device code flow
8
9
  * brain cloud login --api-url URL --token-stdin
9
10
  * Authenticate to a self-hosted store with a token
10
11
  * brain cloud logout Clear stored credentials
12
+ * brain cloud brains List the account's brains
13
+ * brain cloud use NAME|ID [--create] Sync with another brain
11
14
  * brain cloud push [--force] Upload ~/.brain/ to the cloud
12
15
  * brain cloud pull Download from the cloud to ~/.brain/
13
16
  * brain cloud status Show connection and sync status
@@ -30,7 +33,12 @@ brain cloud — Brain Cloud sync CLI
30
33
 
31
34
  Commands:
32
35
  login [--api-url URL] Authenticate via device code flow
36
+ [--brain NAME|ID] Link this brain (created if no brain has that name);
37
+ without it, the account's first brain
33
38
  logout Clear stored credentials
39
+ brains List the account's brains; * marks the linked one
40
+ use NAME|ID [--create] Sync with another brain. ~/.brain/ is left as it is:
41
+ pull to load that brain, or push into an empty one
34
42
  push [--force] Upload ~/.brain/ to the cloud
35
43
  pull Download from the cloud to ~/.brain/
36
44
  status Show connection and sync status
@@ -54,6 +62,12 @@ push refuses to overwrite changes it has not pulled. --force uploads anyway.
54
62
  case 'logout':
55
63
  cmdLogout();
56
64
  break;
65
+ case 'brains':
66
+ await cmdBrains();
67
+ break;
68
+ case 'use':
69
+ await cmdUse(args);
70
+ break;
57
71
  case 'push':
58
72
  await cmdPush(args);
59
73
  break;
@@ -76,19 +90,22 @@ async function cmdLogin(args) {
76
90
  apiUrl = args[urlIdx + 1];
77
91
  }
78
92
 
93
+ const brain = flagValue(args, '--brain');
94
+
79
95
  const token = await readToken(args);
80
96
  if (token) {
81
97
  const result = await cloud.loginWithToken(BRAIN_DIR, apiUrl, token, {
82
98
  allowHttp: args.includes('--allow-http'),
99
+ brain,
83
100
  });
84
101
  console.log(`✓ Logged in as ${result.user_email || 'unknown'}`);
85
- console.log(` Brain ID: ${result.brain_id}`);
102
+ printLinked(result.brain_id, result.brain_name, result);
86
103
  console.log(` API: ${result.api_url}`);
87
104
  return;
88
105
  }
89
106
 
90
107
  console.log('Requesting device code...');
91
- const loginInfo = await cloud.login(BRAIN_DIR, apiUrl);
108
+ const loginInfo = await cloud.login(BRAIN_DIR, apiUrl, { brain });
92
109
 
93
110
  console.log();
94
111
  console.log(' Open this URL in your browser to log in:');
@@ -99,17 +116,58 @@ async function cmdLogin(args) {
99
116
  console.log();
100
117
  console.log(` Waiting for approval (expires in ${Math.floor(loginInfo.expires_in / 60)} min)...`);
101
118
 
102
- await loginInfo.waitForApproval();
119
+ const choice = await loginInfo.waitForApproval();
103
120
 
104
121
  const config = cloud.readConfig(BRAIN_DIR);
105
122
  console.log();
106
123
  console.log(`✓ Logged in as ${config.user_email || 'unknown'}`);
107
- if (config.brain_id) {
108
- console.log(` Brain ID: ${config.brain_id}`);
109
- }
124
+ printLinked(config.brain_id, config.brain_name, choice || {});
110
125
  console.log(` API: ${config.api_url}`);
111
126
  }
112
127
 
128
+ function flagValue(args, flag) {
129
+ const idx = args.indexOf(flag);
130
+ if (idx === -1) return undefined;
131
+ if (!args[idx + 1] || args[idx + 1].startsWith('--')) throw new Error(`${flag} needs a value.`);
132
+ return args[idx + 1];
133
+ }
134
+
135
+ /** After a login: which brain is linked, and the others an account has. */
136
+ function printLinked(brainId, brainName, { brains = [], created = false }) {
137
+ console.log(` Brain: ${brainName ? `"${brainName}" ` : ''}(${brainId})${created ? ' — new' : ''}`);
138
+ const others = brains.filter((b) => b.id !== brainId);
139
+ if (others.length > 0) {
140
+ console.log(` This account has ${others.length} other brain${others.length === 1 ? '' : 's'}: ${others.map((b) => `"${b.name}"`).join(', ')}`);
141
+ console.log(' Switch with: brain cloud use <name>');
142
+ }
143
+ }
144
+
145
+ async function cmdBrains() {
146
+ const brains = await cloud.listBrains(BRAIN_DIR);
147
+ if (brains.length === 0) {
148
+ console.log('This account has no brains yet. `brain cloud push` creates one.');
149
+ return;
150
+ }
151
+ for (const b of brains) {
152
+ const synced = b.last_synced_at ? `synced ${String(b.last_synced_at).slice(0, 10)}` : 'never synced';
153
+ console.log(`${b.linked ? '*' : ' '} ${b.name} (${b.id}) ${b.file_count || 0} files, ${synced}`);
154
+ }
155
+ }
156
+
157
+ async function cmdUse(args) {
158
+ const selector = args.slice(1).find((a) => !a.startsWith('--'));
159
+ if (!selector) throw new Error('Usage: brain cloud use <name|id> [--create]');
160
+ const result = await cloud.useBrain(BRAIN_DIR, selector, { create: args.includes('--create') });
161
+ if (!result.changed) {
162
+ console.log(`Already syncing with "${result.brain.name}".`);
163
+ return;
164
+ }
165
+ console.log(`✓ Now syncing with "${result.brain.name}" (${result.brain.id})${result.created ? ' — new' : ''}`);
166
+ console.log(' ~/.brain/ is unchanged. Next:');
167
+ console.log(' brain cloud pull replace it with this brain\'s memories');
168
+ console.log(' brain cloud push upload it, if this brain is still empty');
169
+ }
170
+
113
171
  /**
114
172
  * A store token from --token-stdin, --token, or BRAIN_STORE_TOKEN, in that order.
115
173
  * Standard input is preferred: it keeps the token out of shell history and out of
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brain-memory",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "A brain-inspired hierarchical memory system for AI coding agents. Deep nested file structure that mimics human memory with time-decay and strength-based recall.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -63,7 +63,7 @@
63
63
  "release:patch": "npm version patch && npm publish",
64
64
  "release:minor": "npm version minor && npm publish",
65
65
  "release:major": "npm version major && npm publish",
66
- "version": "node scripts/sync-plugin-version.mjs && git add .claude-plugin/plugin.json .claude-plugin/marketplace.json .codex-plugin/plugin.json",
66
+ "version": "node scripts/sync-plugin-version.mjs && git add .claude-plugin/plugin.json .claude-plugin/marketplace.json .codex-plugin/plugin.json integrations/cursor/.cursor-plugin/plugin.json server.json",
67
67
  "test:store": "node --test store/test/store.test.js store/test/oidc.test.js store/conformance/conformance.test.js",
68
68
  "test:conformance": "node --test store/conformance/conformance.test.js"
69
69
  },
package/src/cloud-sync.js CHANGED
@@ -317,9 +317,11 @@ async function pollDeviceCode(apiUrl, deviceCode, interval = 5000, timeout = 600
317
317
  *
318
318
  * @param {string} brainDir
319
319
  * @param {string} [apiUrl]
320
- * @returns {Promise<{user_code: string, verify_url: string, waitForApproval: () => Promise<void>}>}
320
+ * @param {Object} [opts]
321
+ * @param {string} [opts.brain] brain ID or name to link (created when no brain has that name)
322
+ * @returns {Promise<{user_code: string, verify_url: string, waitForApproval: () => Promise<{brain: Object, brains: Object[], created: boolean}>}>}
321
323
  */
322
- async function login(brainDir, apiUrl) {
324
+ async function login(brainDir, apiUrl, opts = {}) {
323
325
  const url = apiUrl || DEFAULT_API_URL;
324
326
  const codeInfo = await requestDeviceCode(url);
325
327
 
@@ -337,21 +339,19 @@ async function login(brainDir, apiUrl) {
337
339
  userEmail = meRes.data.user.email;
338
340
  }
339
341
 
340
- const brainsRes = await jsonRequest(`${url}/api/brains`, 'GET', null, tokens.access_token);
341
- let brainId = null;
342
- if (brainsRes.status === 200 && Array.isArray(brainsRes.data) && brainsRes.data.length > 0) {
343
- brainId = brainsRes.data[0].id;
344
- }
342
+ const choice = await chooseBrain(url, tokens.access_token, opts.brain);
345
343
 
346
344
  writeConfig(brainDir, {
347
345
  api_url: url,
348
346
  access_token: tokens.access_token,
349
347
  refresh_token: tokens.refresh_token,
350
348
  expires_at: tokens.expires_at,
351
- brain_id: brainId,
349
+ brain_id: choice.brain.id,
350
+ brain_name: choice.brain.name || null,
352
351
  user_email: userEmail,
353
352
  connected_at: new Date().toISOString(),
354
353
  });
354
+ return choice;
355
355
  },
356
356
  };
357
357
  }
@@ -369,15 +369,17 @@ function isSecureUrl(url) {
369
369
  /**
370
370
  * Log in to a store with a static bearer token (self-hosted brain-store).
371
371
  *
372
- * Verifies the token, links the user's first brain (creating one when the
373
- * account has none), and saves the config. There is no refresh token.
372
+ * Verifies the token, links a brain (`opts.brain`, else the account's first,
373
+ * creating one when the account has none), and saves the config. There is no
374
+ * refresh token.
374
375
  *
375
376
  * @param {string} brainDir
376
377
  * @param {string} apiUrl
377
378
  * @param {string} token
378
379
  * @param {Object} [opts]
379
380
  * @param {boolean} [opts.allowHttp] permit plain HTTP to a non-local host
380
- * @returns {Promise<{user_email: string, brain_id: string, api_url: string}>}
381
+ * @param {string} [opts.brain] brain ID or name to link (created when no brain has that name)
382
+ * @returns {Promise<{user_email: string, brain_id: string, brain_name: string|null, api_url: string, brains: Object[], created: boolean}>}
381
383
  */
382
384
  async function loginWithToken(brainDir, apiUrl, token, opts = {}) {
383
385
  if (!apiUrl) throw new Error('A token login needs the store address: --api-url URL');
@@ -395,25 +397,26 @@ async function loginWithToken(brainDir, apiUrl, token, opts = {}) {
395
397
  if (meRes.status !== 200) throw new Error(`Login failed (${meRes.status}): ${meRes.data.error || ''}`);
396
398
  const user = meRes.data.user || {};
397
399
 
398
- const brainsRes = await jsonRequest(`${url}/api/brains`, 'GET', null, token);
399
- if (brainsRes.status !== 200) throw new Error(`Could not list brains (${brainsRes.status}).`);
400
- let brainId = Array.isArray(brainsRes.data) && brainsRes.data.length > 0 ? brainsRes.data[0].id : null;
401
- if (!brainId) {
402
- const created = await jsonRequest(`${url}/api/brains`, 'POST', { name: 'default' }, token);
403
- if (created.status !== 201) throw new Error(`Could not create a brain (${created.status}): ${created.data.error || ''}`);
404
- brainId = created.data.id;
405
- }
400
+ const choice = await chooseBrain(url, token, opts.brain);
406
401
 
407
402
  const config = {
408
403
  api_url: url,
409
404
  token_type: 'static',
410
405
  access_token: token,
411
- brain_id: brainId,
406
+ brain_id: choice.brain.id,
407
+ brain_name: choice.brain.name || null,
412
408
  user_email: user.email || user.name || '',
413
409
  connected_at: new Date().toISOString(),
414
410
  };
415
411
  writeConfig(brainDir, config);
416
- return { user_email: config.user_email, brain_id: brainId, api_url: url };
412
+ return {
413
+ user_email: config.user_email,
414
+ brain_id: choice.brain.id,
415
+ brain_name: config.brain_name,
416
+ api_url: url,
417
+ brains: choice.brains,
418
+ created: choice.created,
419
+ };
417
420
  }
418
421
 
419
422
  /**
@@ -421,6 +424,129 @@ async function loginWithToken(brainDir, apiUrl, token, opts = {}) {
421
424
  *
422
425
  * @param {string} brainDir
423
426
  */
427
+ // ---------------------------------------------------------------------------
428
+ // Choosing a brain
429
+ // ---------------------------------------------------------------------------
430
+
431
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
432
+
433
+ /**
434
+ * Find a brain by its ID, or by name ignoring case. Returns null when nothing
435
+ * matches, and throws when a name matches more than one brain.
436
+ *
437
+ * @param {Array<{id: string, name?: string}>} brains
438
+ * @param {string} selector
439
+ */
440
+ function matchBrain(brains, selector) {
441
+ const sel = String(selector || '').trim();
442
+ if (!sel) return null;
443
+ const byId = brains.find((b) => b.id === sel);
444
+ if (byId) return byId;
445
+ const key = sel.toLocaleLowerCase();
446
+ const named = brains.filter((b) => String(b.name || '').trim().toLocaleLowerCase() === key);
447
+ if (named.length > 1) {
448
+ throw new Error(`${named.length} brains are named "${sel}". Choose one by ID: ${named.map((b) => b.id).join(', ')}`);
449
+ }
450
+ return named[0] || null;
451
+ }
452
+
453
+ /** The account's first brain, the one every client links when told nothing else. */
454
+ function oldestBrain(brains) {
455
+ return [...brains].sort((a, b) =>
456
+ String(a.created_at || '').localeCompare(String(b.created_at || '')) || a.id.localeCompare(b.id))[0] || null;
457
+ }
458
+
459
+ async function fetchBrains(url, token) {
460
+ const res = await jsonRequest(`${url}/api/brains`, 'GET', null, token);
461
+ if (res.status !== 200) throw new Error(`Could not list brains (${res.status}).`);
462
+ return Array.isArray(res.data) ? res.data : [];
463
+ }
464
+
465
+ async function createBrain(url, token, name) {
466
+ const res = await jsonRequest(`${url}/api/brains`, 'POST', { name }, token);
467
+ if (res.status !== 201) throw new Error(`Could not create a brain (${res.status}): ${(res.data && res.data.error) || ''}`);
468
+ return res.data;
469
+ }
470
+
471
+ /**
472
+ * The brain a login links. With a selector: the brain it names, or a new brain
473
+ * of that name when none exists (an unknown ID is an error, never a new brain).
474
+ * Without one: the oldest brain, or a new "default" brain for an empty account.
475
+ *
476
+ * @returns {Promise<{brain: Object, brains: Object[], created: boolean}>}
477
+ */
478
+ async function chooseBrain(url, token, selector) {
479
+ const brains = await fetchBrains(url, token);
480
+ if (selector) {
481
+ const found = matchBrain(brains, selector);
482
+ if (found) return { brain: found, brains, created: false };
483
+ const name = String(selector).trim();
484
+ if (UUID_RE.test(name)) throw new Error(`No brain with ID ${name} in this account.`);
485
+ const brain = await createBrain(url, token, name);
486
+ return { brain, brains: [...brains, brain], created: true };
487
+ }
488
+ if (brains.length > 0) return { brain: oldestBrain(brains), brains, created: false };
489
+ const brain = await createBrain(url, token, 'default');
490
+ return { brain, brains: [brain], created: true };
491
+ }
492
+
493
+ /**
494
+ * The account's brains, each marked `linked` when it is the one this device
495
+ * syncs with.
496
+ *
497
+ * @param {string} brainDir
498
+ * @returns {Promise<Object[]>}
499
+ */
500
+ async function listBrains(brainDir) {
501
+ const config = readConfig(brainDir);
502
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
503
+ const token = await getValidToken(brainDir);
504
+ const brains = await fetchBrains(config.api_url, token);
505
+ return brains.map((b) => ({ ...b, linked: b.id === config.brain_id }));
506
+ }
507
+
508
+ /**
509
+ * Link this device to another of the account's brains.
510
+ *
511
+ * Only the link changes; the local ~/.brain/ is left as it is. The sync base is
512
+ * cleared, so the next push succeeds only into a brain that has no archive yet:
513
+ * pushing one brain's memories over another's needs a pull first, or --force.
514
+ *
515
+ * @param {string} brainDir
516
+ * @param {string} selector brain ID or name
517
+ * @param {Object} [opts]
518
+ * @param {boolean} [opts.create] create the brain when no brain has that name
519
+ * @returns {Promise<{brain: Object, previous: string|null, changed: boolean, created: boolean}>}
520
+ */
521
+ async function useBrain(brainDir, selector, opts = {}) {
522
+ const config = readConfig(brainDir);
523
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
524
+ const token = await getValidToken(brainDir);
525
+ const brains = await fetchBrains(config.api_url, token);
526
+
527
+ let brain = matchBrain(brains, selector);
528
+ let created = false;
529
+ if (!brain) {
530
+ if (!opts.create) {
531
+ const names = brains.map((b) => `"${b.name}"`).join(', ') || 'none';
532
+ throw new Error(`No brain named "${selector}". This account has: ${names}. Add --create to make it.`);
533
+ }
534
+ brain = await createBrain(config.api_url, token, String(selector).trim());
535
+ created = true;
536
+ }
537
+
538
+ const previous = config.brain_id || null;
539
+ if (brain.id === previous) return { brain, previous, changed: false, created };
540
+
541
+ config.brain_id = brain.id;
542
+ config.brain_name = brain.name || null;
543
+ delete config.base_checksum;
544
+ delete config.last_push;
545
+ delete config.last_pull;
546
+ writeConfig(brainDir, config);
547
+ return { brain, previous, changed: true, created };
548
+ }
549
+
424
550
  function logout(brainDir) {
425
551
  deleteConfig(brainDir);
426
552
  }
@@ -545,9 +671,15 @@ async function push(brainDir, opts = {}) {
545
671
  const tarSize = fs.statSync(tarPath).size;
546
672
  const url = `${config.api_url}/api/brains/${config.brain_id}/sync`;
547
673
 
548
- const conditional = !opts.force && config.base_checksum
549
- ? { 'If-Match': `"${config.base_checksum}"` }
550
- : null;
674
+ // A brain that has never synced with this link (a fresh login, or
675
+ // `brain cloud use`) may only fill a store brain that is still empty. A
676
+ // config with sync history but no checksum predates conditional sync and
677
+ // pushes unconditionally, as it always did.
678
+ let conditional = null;
679
+ if (!opts.force) {
680
+ if (config.base_checksum) conditional = { 'If-Match': `"${config.base_checksum}"` };
681
+ else if (!config.last_push && !config.last_pull) conditional = { 'If-None-Match': '*' };
682
+ }
551
683
  const res = await uploadFile(url, tarPath, token, conditional);
552
684
 
553
685
  if (res.status === 412) {
@@ -746,7 +878,7 @@ async function status(brainDir) {
746
878
  api_url: config.api_url,
747
879
  user_email: config.user_email || (user && user.email) || null,
748
880
  brain_id: config.brain_id,
749
- brain_name: brain ? brain.name : null,
881
+ brain_name: brain ? brain.name : config.brain_name || null,
750
882
  brain_size: brain ? brain.size_bytes : null,
751
883
  brain_files: brain ? brain.file_count : null,
752
884
  last_synced: brain && brain.last_synced_at ? brain.last_synced_at : null,
@@ -772,6 +904,9 @@ module.exports = {
772
904
  status,
773
905
  readConfig,
774
906
  writeConfig,
907
+ listBrains,
908
+ useBrain,
909
+ matchBrain,
775
910
  // Internal — exported for testing
776
911
  requestDeviceCode,
777
912
  pollDeviceCode,