brain-memory 0.4.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.
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Brain Memory — Cross-vendor adapters (`brain port`)
3
+ *
4
+ * Pure conversions between brain memories and the formats other memory
5
+ * systems read and write. No I/O here: bin/port.js loads memories, writes
6
+ * files, and sends imports through `brain memorize`, so every import meets the
7
+ * same origin policy, lint and quarantine as any other write.
8
+ *
9
+ * A brain memory, as these functions see it:
10
+ * { id, title, type, content, tags, created, origin }
11
+ * Imports may also carry `saved` (YYYY-MM-DD): when the other system recorded
12
+ * it. That is record time, not valid time, so it is never written as
13
+ * `valid_from`; bin/port.js keeps it in the memory's `source`.
14
+ *
15
+ * Every target is lossier than brain. `FIDELITY` states, per target, which
16
+ * fields survive a round trip, and test/adapters.test.js holds that table to
17
+ * the code.
18
+ *
19
+ * Targets:
20
+ * claude-memory Claude Code's file-based memory: one Markdown file per
21
+ * memory with `name` / `description` / `metadata.type`
22
+ * frontmatter, plus a MEMORY.md index of one-line pointers.
23
+ * markdown One line per memory, `[YYYY-MM-DD] - <title>: <text>` — the
24
+ * shape Claude.ai's memory import accepts as pasted text, and
25
+ * readable anywhere else.
26
+ * agentcore AWS Bedrock AgentCore Memory `BatchCreateMemoryRecords`
27
+ * request bodies (≤100 records each, ≤16,000 chars of text per
28
+ * record). Payloads only — no AWS SDK; send them with your own
29
+ * credentials. Import reads the same shape, or the
30
+ * `memoryRecordSummaries` a list/retrieve call returns.
31
+ */
32
+
33
+ const BRAIN_TYPES = ['decision', 'insight', 'goal', 'experience', 'learning', 'relationship', 'preference', 'observation'];
34
+
35
+ // Claude Code's memory types are about *what the note is for*, not what kind
36
+ // of knowledge it is, so the mapping is many-to-one each way.
37
+ const TO_CLAUDE_TYPE = {
38
+ preference: 'feedback',
39
+ relationship: 'user',
40
+ decision: 'project',
41
+ goal: 'project',
42
+ experience: 'project',
43
+ insight: 'project',
44
+ learning: 'project',
45
+ observation: 'project',
46
+ };
47
+ const FROM_CLAUDE_TYPE = { user: 'relationship', feedback: 'preference', project: 'decision', reference: 'learning' };
48
+
49
+ const AGENTCORE_BATCH = 100;
50
+ const AGENTCORE_MAX_TEXT = 16000;
51
+
52
+ /** Fields that survive brain → target → brain. */
53
+ const FIDELITY = {
54
+ 'claude-memory': { title: true, content: true, type: 'mapped', tags: false, created: false },
55
+ markdown: { title: true, content: 'single line', type: false, tags: false, created: 'date only' },
56
+ agentcore: { title: true, content: 'up to 16,000 chars', type: true, tags: false, created: true },
57
+ };
58
+
59
+ function slug(text) {
60
+ return String(text || 'memory').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'memory';
61
+ }
62
+
63
+ function oneLine(text) {
64
+ return String(text || '').replace(/\s+/g, ' ').trim();
65
+ }
66
+
67
+ function dateOnly(iso) {
68
+ const t = Date.parse(iso);
69
+ return Number.isFinite(t) ? new Date(t).toISOString().slice(0, 10) : null;
70
+ }
71
+
72
+ /** Split `---\nfrontmatter\n---\nbody`; tolerant of a missing block. */
73
+ function splitFrontmatter(text) {
74
+ const m = String(text).match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
75
+ if (!m) return { fm: {}, body: String(text) };
76
+ const fm = {};
77
+ let parent = null;
78
+ for (const line of m[1].split(/\r?\n/)) {
79
+ const nested = line.match(/^\s{2,}([\w-]+):\s*(.*)$/);
80
+ const top = line.match(/^([\w-]+):\s*(.*)$/);
81
+ if (nested && parent) {
82
+ fm[parent] = { ...(typeof fm[parent] === 'object' ? fm[parent] : {}), [nested[1]]: unquote(nested[2]) };
83
+ } else if (top) {
84
+ parent = top[2] === '' ? top[1] : null;
85
+ fm[top[1]] = top[2] === '' ? {} : unquote(top[2]);
86
+ }
87
+ }
88
+ return { fm, body: m[2] };
89
+ }
90
+
91
+ function unquote(v) {
92
+ const s = String(v).trim();
93
+ return /^".*"$|^'.*'$/.test(s) ? s.slice(1, -1) : s;
94
+ }
95
+
96
+ /* ─────────────────────────── claude-memory ─────────────────────────── */
97
+
98
+ function toClaudeMemory(memories) {
99
+ const files = {};
100
+ const index = ['# Memory Index', ''];
101
+ const used = new Set();
102
+ for (const m of memories) {
103
+ let name = slug(m.title);
104
+ for (let i = 2; used.has(name); i++) name = `${slug(m.title)}-${i}`;
105
+ used.add(name);
106
+ const description = oneLine(m.title).replace(/"/g, "'");
107
+ files[`${name}.md`] = [
108
+ '---',
109
+ `name: ${name}`,
110
+ `description: "${description}"`,
111
+ 'metadata:',
112
+ ` type: ${TO_CLAUDE_TYPE[m.type] || 'project'}`,
113
+ '---',
114
+ '',
115
+ String(m.content || '').trim(),
116
+ '',
117
+ ].join('\n');
118
+ index.push(`- [${description}](${name}.md)`);
119
+ }
120
+ files['MEMORY.md'] = index.join('\n') + '\n';
121
+ return { files };
122
+ }
123
+
124
+ /** @param {Object<string,string>} files - { "<name>.md": text }, MEMORY.md ignored */
125
+ function fromClaudeMemory(files) {
126
+ const out = [];
127
+ for (const [file, text] of Object.entries(files)) {
128
+ if (!file.endsWith('.md') || /(^|\/)MEMORY\.md$/.test(file)) continue;
129
+ const { fm, body } = splitFrontmatter(text);
130
+ const content = body.trim();
131
+ if (!content) continue;
132
+ const type = (fm.metadata && fm.metadata.type) || fm.type;
133
+ out.push({
134
+ title: oneLine(fm.description || fm.name || file.replace(/\.md$/, '')).slice(0, 120),
135
+ type: FROM_CLAUDE_TYPE[type] || 'learning',
136
+ content,
137
+ tags: [],
138
+ });
139
+ }
140
+ return out;
141
+ }
142
+
143
+ /* ─────────────────────────── markdown ─────────────────────────── */
144
+
145
+ function toMarkdown(memories) {
146
+ const lines = memories.map((m) => {
147
+ const date = dateOnly(m.created);
148
+ const body = oneLine(m.content);
149
+ return `${date ? `[${date}] - ` : '- '}${oneLine(m.title)}: ${body}`;
150
+ });
151
+ return { text: lines.join('\n') + '\n' };
152
+ }
153
+
154
+ const MD_LINE = /^(?:\[(\d{4}-\d{2}-\d{2})\]\s*-\s*|[-*]\s+)?(.+)$/;
155
+
156
+ function fromMarkdown(text) {
157
+ const out = [];
158
+ for (const raw of String(text).split(/\r?\n/)) {
159
+ const line = raw.trim();
160
+ if (!line || line.startsWith('#')) continue;
161
+ const m = line.match(MD_LINE);
162
+ if (!m) continue;
163
+ const rest = m[2].trim();
164
+ const colon = rest.indexOf(': ');
165
+ const hasTitle = colon > 0 && colon <= 120;
166
+ out.push({
167
+ title: (hasTitle ? rest.slice(0, colon) : rest).slice(0, 120),
168
+ type: 'learning',
169
+ content: hasTitle ? rest.slice(colon + 2) : rest,
170
+ tags: [],
171
+ ...(m[1] ? { saved: m[1] } : {}),
172
+ });
173
+ }
174
+ return out;
175
+ }
176
+
177
+ /* ─────────────────────────── agentcore ─────────────────────────── */
178
+
179
+ function toAgentCore(memories, { namespacePrefix = '/brain' } = {}) {
180
+ const records = memories.map((m) => {
181
+ const text = `${oneLine(m.title)}\n\n${String(m.content || '').trim()}`;
182
+ const t = Date.parse(m.created);
183
+ return {
184
+ requestIdentifier: String(m.id || slug(m.title)).slice(0, 80),
185
+ content: { text: text.slice(0, AGENTCORE_MAX_TEXT) },
186
+ namespaces: [`${namespacePrefix}/${BRAIN_TYPES.includes(m.type) ? m.type : 'learning'}`],
187
+ timestamp: Math.floor((Number.isFinite(t) ? t : Date.now()) / 1000),
188
+ };
189
+ });
190
+ const batches = [];
191
+ for (let i = 0; i < records.length; i += AGENTCORE_BATCH) batches.push({ records: records.slice(i, i + AGENTCORE_BATCH) });
192
+ const truncated = memories.filter((m) => `${oneLine(m.title)}\n\n${String(m.content || '').trim()}`.length > AGENTCORE_MAX_TEXT).length;
193
+ return { batches, truncated };
194
+ }
195
+
196
+ /** Accepts `{batches:[{records}]}`, `{records}`, or `{memoryRecordSummaries}`. */
197
+ function fromAgentCore(json) {
198
+ const doc = typeof json === 'string' ? JSON.parse(json) : json;
199
+ const records = [
200
+ ...((doc.batches || []).flatMap((b) => b.records || [])),
201
+ ...(doc.records || []),
202
+ ...(doc.memoryRecordSummaries || []),
203
+ ];
204
+ const out = [];
205
+ for (const r of records) {
206
+ const text = String((r.content && r.content.text) || '').trim();
207
+ if (!text) continue;
208
+ const [first, ...rest] = text.split(/\n\n/);
209
+ const ns = (r.namespaces || [])[0] || '';
210
+ const type = ns.split('/').pop();
211
+ const ts = r.timestamp ?? r.createdAt;
212
+ const iso = typeof ts === 'number' ? new Date(ts * 1000).toISOString() : (Date.parse(ts) ? new Date(ts).toISOString() : null);
213
+ out.push({
214
+ title: oneLine(first).slice(0, 120),
215
+ type: BRAIN_TYPES.includes(type) ? type : 'learning',
216
+ content: rest.length ? rest.join('\n\n') : text,
217
+ tags: [],
218
+ ...(iso ? { saved: iso.slice(0, 10) } : {}),
219
+ });
220
+ }
221
+ return out;
222
+ }
223
+
224
+ const ADAPTERS = {
225
+ 'claude-memory': { exportTo: toClaudeMemory, importFrom: fromClaudeMemory, input: 'dir' },
226
+ markdown: { exportTo: toMarkdown, importFrom: fromMarkdown, input: 'text' },
227
+ agentcore: { exportTo: toAgentCore, importFrom: fromAgentCore, input: 'json' },
228
+ };
229
+
230
+ module.exports = {
231
+ ADAPTERS,
232
+ FIDELITY,
233
+ toClaudeMemory,
234
+ fromClaudeMemory,
235
+ toMarkdown,
236
+ fromMarkdown,
237
+ toAgentCore,
238
+ fromAgentCore,
239
+ splitFrontmatter,
240
+ };
package/src/anomaly.js CHANGED
@@ -18,10 +18,14 @@
18
18
  * never silently vanish a large slice of the brain.
19
19
  */
20
20
 
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+
21
24
  const { isLowTrust } = require('./provenance');
22
25
  const { detectContentDrift } = require('./integrity');
23
26
  const { readAudit } = require('./audit');
24
- const { listPending, applyQuarantine } = require('./quarantine');
27
+ const { lintMemoryContent } = require('./content-lint');
28
+ const { isAuthorizationClaim, listPending, applyQuarantine } = require('./quarantine');
25
29
 
26
30
  // Writes-per-window ceilings by origin. Low-trust origins get tight budgets;
27
31
  // agent-inferred is the ambient default and gets headroom.
@@ -178,6 +182,40 @@ function detectReinforcedLowTrust(index, opts = {}) {
178
182
  return findings.sort((a, b) => b.access_count - a.access_count);
179
183
  }
180
184
 
185
+ /**
186
+ * Memories that grant the agent a permission but were written before the
187
+ * `authorization_claim` lint existed, so they carry no `authorization` mark
188
+ * and were never gated. Re-lints each unmarked memory's file; marked ones
189
+ * were gated at write time and are skipped.
190
+ *
191
+ * @param {string} brainDir - Path to ~/.brain/
192
+ * @param {Object} index - Parsed index.json
193
+ * @returns {Object[]} [{ kind:'authorization_claim', id, origin, excerpt }]
194
+ */
195
+ function detectUnmarkedAuthorization(brainDir, index) {
196
+ const findings = [];
197
+ for (const [id, entry] of Object.entries((index && index.memories) || {})) {
198
+ if (entry.authorization || !entry.path) continue;
199
+ let body;
200
+ try {
201
+ body = fs.readFileSync(path.join(brainDir, entry.path), 'utf-8').replace(/^---\n[\s\S]*?\n---\n/, '');
202
+ } catch (_) {
203
+ continue; // a missing file is detectContentDrift's finding, not this one
204
+ }
205
+ const lint = lintMemoryContent({
206
+ title: entry.title, content: body, type: entry.type, cognitive_type: entry.cognitive_type,
207
+ });
208
+ if (!isAuthorizationClaim(lint)) continue;
209
+ findings.push({
210
+ kind: 'authorization_claim',
211
+ id,
212
+ origin: entry.origin || 'agent-inferred',
213
+ excerpt: lint.flags.find((f) => f.severity === 'authorization').excerpt,
214
+ });
215
+ }
216
+ return findings;
217
+ }
218
+
181
219
  /**
182
220
  * Run all detectors and (optionally) quarantine the flagged memories.
183
221
  *
@@ -205,6 +243,7 @@ function runAudit(brainDir, deps, opts = {}) {
205
243
  ...detectWriteBursts(auditEvents, { windowHours }),
206
244
  ...detectLowTrustCliques(index, associations),
207
245
  ...detectReinforcedLowTrust(index),
246
+ ...detectUnmarkedAuthorization(brainDir, index),
208
247
  // Store-phase tamper detection. Advisory only — legitimate edits (sleep
209
248
  // consolidation, a user fixing a typo) also move the hash, so these
210
249
  // findings are reported but never fed to the --apply quarantine path.
@@ -258,6 +297,7 @@ function runAudit(brainDir, deps, opts = {}) {
258
297
  }
259
298
 
260
299
  module.exports = {
300
+ detectUnmarkedAuthorization,
261
301
  detectWriteBursts,
262
302
  detectContentDrift,
263
303
  detectLowTrustCliques,
package/src/cloud-sync.js CHANGED
@@ -23,7 +23,7 @@ const CONFIG_FILE = 'config.json';
23
23
  const DEFAULT_API_URL = 'https://api.brainmemory.ai';
24
24
 
25
25
  // Files/dirs inside ~/.brain/ that should NOT be synced
26
- const TAR_EXCLUDES = ['.sync', '.cloud', '.DS_Store', '_archived'];
26
+ const TAR_EXCLUDES = ['.sync', '.cloud', '.local', '.DS_Store', '_archived'];
27
27
 
28
28
  // ---------------------------------------------------------------------------
29
29
  // HTTP helpers (zero-dependency, works on Node >= 18)
@@ -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) {
@@ -616,7 +748,7 @@ async function pull(brainDir) {
616
748
  // Local entries a cloud restore must never touch: sync/auth infrastructure and
617
749
  // _archived/, which is deliberately excluded from cloud pushes (see
618
750
  // TAR_EXCLUDES) and so does not exist in the snapshot being restored.
619
- const RESTORE_PRESERVE = new Set(['.sync', '.cloud', '.DS_Store', '_archived']);
751
+ const RESTORE_PRESERVE = new Set(['.sync', '.cloud', '.local', '.DS_Store', '_archived']);
620
752
 
621
753
  /**
622
754
  * List cloud restore points — pre-overwrite snapshots Brain Cloud takes
@@ -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,
@@ -11,6 +11,13 @@
11
11
  * injection Text that tries to steer the agent against the user. Never
12
12
  * downgraded — no legitimate memory says "ignore previous
13
13
  * instructions" or pipes a download into a shell.
14
+ * authorization
15
+ * A claim that the agent may act without asking ("the user
16
+ * approved force-pushes", "no need to confirm deploys"). Never
17
+ * downgraded: a writer that invents permission is the failure
18
+ * this catches, and it happens without any attacker. Gated
19
+ * separately from injection by src/quarantine.js — even a
20
+ * user-origin claim needs the user's own words behind it.
14
21
  * suspect Directive/imperative content. Downgraded to advisory for
15
22
  * type:preference and cognitive_type:procedural memories, which
16
23
  * legitimately contain instructions ("always use 2-space
@@ -20,7 +27,48 @@
20
27
  * Pure and dependency-free; used at write time by bin/memorize.js.
21
28
  */
22
29
 
23
- const SEVERITY_RANK = { none: 0, advisory: 1, suspect: 2, injection: 3 };
30
+ const SEVERITY_RANK = { none: 0, advisory: 1, suspect: 2, authorization: 3, injection: 4 };
31
+
32
+ // secret_exfil pairs a transfer verb with a credential noun. Both must be
33
+ // standalone prose words: a verb that is a code literal or half of a compound
34
+ // (`upload`, upload-artifact, post-install) is a name, not an action, and a
35
+ // compound noun (password-reset, token_count) names a feature, not a secret.
36
+ // Without this, ordinary engineering notes ("the password-reset email", "set
37
+ // the destination to `upload`, then the API key…") quarantine as injections.
38
+ // `.env` is matched on its own: it starts with a non-word char, so a leading
39
+ // \b would require a word char before the dot and never match it bare.
40
+ const EXFIL_VERB = '(?<![`_\\-/.])\\b(?:send|post|upload|forward|exfiltrate|transmit|email)(?:s|ed|ing)?\\b(?![`_\\-/])';
41
+ const EXFIL_SECRET = '(?:(?<![`_\\-/])\\b(?:token|password|secret|api.?key|credential|private.?key)s?\\b(?![`_\\-])|(?<![\\w.])\\.env\\b)';
42
+ const EXFIL_GAP = '[^\\n.]{0,80}';
43
+ const SECRET_EXFIL_RE = new RegExp(
44
+ `${EXFIL_VERB}${EXFIL_GAP}${EXFIL_SECRET}|${EXFIL_SECRET}${EXFIL_GAP}${EXFIL_VERB}`,
45
+ 'i'
46
+ );
47
+
48
+ // authorization_claim has three shapes, each anchored on who is granting or
49
+ // being granted — never on the bare words "approved"/"authorized", which
50
+ // ordinary notes about OAuth, RBAC and review workflows are full of:
51
+ // 1. a principal granted an *action* ("the user approved force-pushing");
52
+ // approving a design or a PR is a fact, not a permission, so an action
53
+ // verb must follow within the sentence;
54
+ // 2. the agent is told it may act ("you are allowed to", "Claude is
55
+ // permitted to");
56
+ // 3. confirmation is waived ("no need to ask", "pre-approved", "standing
57
+ // permission", "skip the confirmation").
58
+ const AUTHZ_GRANTOR = '\\b(?:the\\s+)?(?:user|owner|maintainer|admin(?:istrator)?|i|we)\\b';
59
+ const AUTHZ_GRANT = '(?:\\s+(?:has|have|had))?(?:\\s+(?:already|explicitly))?\\s+(?:approved|authori[sz]ed|okayed|ok\'d|signed\\s+off\\s+on|green-?lit|allowed|permitted)\\b';
60
+ const AUTHZ_ACTION = '\\b(?:force[\\s-]?push\\w*|push\\w*|deploy\\w*|delet\\w*|drop\\w*|merg\\w*|releas\\w*|publish\\w*|pay\\w*|send\\w*|email\\w*|transfer\\w*|run\\w*|execut\\w*|install\\w*|wip\\w*|rotat\\w*|revok\\w*|purchas\\w*|spend\\w*|skip\\w*|bypass\\w*|disabl\\w*|overwrit\\w*|rm\\b)';
61
+ const AUTHZ_AGENT = '\\b(?:you|the\\s+(?:agent|assistant|bot)|claude|codex|gemini|agents?)\\s+(?:are|is|have\\s+been|has\\s+been)(?:\\s+(?:now|always|explicitly))?\\s+(?:allowed|authori[sz]ed|permitted|cleared|granted\\s+(?:permission|access))\\b';
62
+ const AUTHZ_WAIVER = '\\b(?:no\\s+need\\s+to|(?:do\\s+not|don\'t|doesn\'t|does\\s+not)\\s+need\\s+to|without\\s+needing\\s+to)\\s+(?:ask|confirm|check\\s+with|get\\s+(?:approval|permission|sign-?off))\\b' +
63
+ // Predicate only, and not "pre-approved for": "deploys are pre-approved" is a
64
+ // permission; "pre-approved for a mortgage" and "pre-approved offers" are not.
65
+ '|\\b(?:is|are|was|were|be|been|now)\\s+pre-?(?:approved|authori[sz]ed)\\b(?!\\s+for\\b)' +
66
+ '|\\b(?:standing|blanket)\\s+(?:permission|approval|authori[sz]ation)\\b' +
67
+ '|\\bskip\\s+(?:the\\s+)?(?:confirmation|approval|permission)\\b';
68
+ const AUTHZ_RE = new RegExp(
69
+ `${AUTHZ_GRANTOR}${AUTHZ_GRANT}[^\\n.]{0,60}${AUTHZ_ACTION}|${AUTHZ_AGENT}|${AUTHZ_WAIVER}`,
70
+ 'i'
71
+ );
24
72
 
25
73
  // Each rule: name, base severity, and a matcher over the combined text.
26
74
  // Patterns are case-insensitive; `m` where line-anchoring matters.
@@ -38,7 +86,12 @@ const RULES = [
38
86
  {
39
87
  rule: 'secret_exfil',
40
88
  severity: 'injection',
41
- re: /\b(?:send|post|upload|forward|exfiltrate|transmit|email)(?:s|ed|ing)?\b[^\n.]{0,80}\b(?:token|password|secret|api.?key|credential|private.?key|\.env)\b|\b(?:token|password|secret|api.?key|credential|private.?key)s?\b[^\n.]{0,80}\b(?:send|post|upload|forward|exfiltrate|transmit|email)(?:s|ed|ing)?\b/i,
89
+ re: SECRET_EXFIL_RE,
90
+ },
91
+ {
92
+ rule: 'authorization_claim',
93
+ severity: 'authorization',
94
+ re: AUTHZ_RE,
42
95
  },
43
96
  {
44
97
  rule: 'imperative_directive',
@@ -13,7 +13,7 @@ const path = require('path');
13
13
  const { encrypt, decrypt } = require('./crypto');
14
14
 
15
15
  // Directories inside ~/.brain/ to skip during export
16
- const EXCLUDED = new Set(['.sync', '.DS_Store']);
16
+ const EXCLUDED = new Set(['.sync', '.local', '.DS_Store']);
17
17
 
18
18
  /**
19
19
  * Export the entire ~/.brain/ directory to a single file.