brain-memory 0.1.0-beta.9 → 0.2.0

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 (82) hide show
  1. package/CHANGELOG.md +632 -0
  2. package/README.md +390 -84
  3. package/SECURITY.md +100 -0
  4. package/assets/brand/README.md +28 -0
  5. package/assets/brand/icon-dark.svg +19 -0
  6. package/assets/brand/icon-light.svg +20 -0
  7. package/assets/brand/linkedin_cover.png +0 -0
  8. package/assets/brand/linkedin_cover_light.png +0 -0
  9. package/assets/brand/mark-dark.svg +19 -0
  10. package/assets/brand/mark-light.svg +20 -0
  11. package/assets/brand/png/icon-dark-1024.png +0 -0
  12. package/assets/brand/png/icon-dark-128.png +0 -0
  13. package/assets/brand/png/icon-dark-256.png +0 -0
  14. package/assets/brand/png/icon-dark-512.png +0 -0
  15. package/assets/brand/png/icon-dark-64.png +0 -0
  16. package/assets/brand/png/icon-light-1024.png +0 -0
  17. package/assets/brand/png/icon-light-128.png +0 -0
  18. package/assets/brand/png/icon-light-256.png +0 -0
  19. package/assets/brand/png/icon-light-512.png +0 -0
  20. package/assets/brand/png/icon-light-64.png +0 -0
  21. package/assets/brand/png/mark-dark-1024.png +0 -0
  22. package/assets/brand/png/mark-light-1024.png +0 -0
  23. package/assets/icon.png +0 -0
  24. package/assets/icon.svg +19 -0
  25. package/bin/audit.js +93 -0
  26. package/bin/brain.js +132 -0
  27. package/bin/cloud-sync.js +150 -0
  28. package/bin/forget.js +172 -0
  29. package/bin/import.js +132 -0
  30. package/bin/install.js +63 -31
  31. package/bin/memorize.js +670 -0
  32. package/bin/pin.js +44 -0
  33. package/bin/recall.js +319 -0
  34. package/bin/reinforce.js +191 -0
  35. package/bin/restore.js +122 -0
  36. package/bin/session-start.js +352 -0
  37. package/bin/skill.js +67 -0
  38. package/bin/unpin.js +38 -0
  39. package/bin/verify.js +186 -0
  40. package/commands/brain/forget.md +243 -13
  41. package/commands/brain/import.md +125 -0
  42. package/commands/brain/memorize.md +108 -130
  43. package/commands/brain/pin.md +79 -0
  44. package/commands/brain/remember.md +59 -100
  45. package/commands/brain/skills.md +60 -0
  46. package/commands/brain/sleep.md +93 -6
  47. package/commands/brain/status.md +15 -6
  48. package/commands/brain/sync.md +181 -17
  49. package/commands/brain/verify.md +63 -0
  50. package/integrations/README.md +29 -0
  51. package/integrations/agentskills/brain-memory/SKILL.md +115 -0
  52. package/integrations/agentskills/brain-memory/scripts/session-start.mjs +34 -0
  53. package/package.json +19 -7
  54. package/prompts/antigravity.md +222 -0
  55. package/prompts/claude.md +128 -40
  56. package/prompts/copilot.md +224 -0
  57. package/prompts/kilo.md +223 -0
  58. package/prompts/openai.md +133 -45
  59. package/prompts/opencode.md +221 -0
  60. package/src/anomaly.js +260 -0
  61. package/src/audit.js +71 -0
  62. package/src/cloud-sync.js +672 -0
  63. package/src/content-lint.js +118 -0
  64. package/src/export-import.js +45 -7
  65. package/src/git-sync.js +170 -11
  66. package/src/harvest.js +562 -0
  67. package/src/index-manager.js +250 -11
  68. package/src/installer.js +250 -29
  69. package/src/pinning.js +146 -0
  70. package/src/provenance.js +79 -0
  71. package/src/quarantine.js +111 -0
  72. package/src/receipt.js +87 -0
  73. package/src/scorer.js +137 -12
  74. package/src/skills.js +208 -0
  75. package/src/temporal.js +228 -0
  76. package/src/tfidf.js +520 -0
  77. package/commands/brain/consolidate.md +0 -153
  78. package/commands/brain/explore.md +0 -79
  79. package/commands/brain/init.md +0 -149
  80. package/commands/brain/review.md +0 -130
  81. package/commands/brain/sunshine.md +0 -337
  82. package/prompts/gemini.md +0 -134
@@ -0,0 +1,672 @@
1
+ /**
2
+ * Brain Memory — Cloud Sync Engine
3
+ *
4
+ * Push/pull ~/.brain/ memories via the Brain Cloud API (api.brainmemory.ai).
5
+ * Uses the device code OAuth flow for CLI authentication.
6
+ *
7
+ * Zero external dependencies — uses Node.js built-in https, fs, child_process.
8
+ */
9
+
10
+ const { execFileSync } = require('child_process');
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const os = require('os');
14
+ const https = require('https');
15
+ const http = require('http');
16
+
17
+ const CLOUD_DIR = '.cloud';
18
+ const CONFIG_FILE = 'config.json';
19
+ const DEFAULT_API_URL = 'https://api.brainmemory.ai';
20
+
21
+ // Files/dirs inside ~/.brain/ that should NOT be synced
22
+ const TAR_EXCLUDES = ['.sync', '.cloud', '.DS_Store', '_archived'];
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // HTTP helpers (zero-dependency, works on Node >= 18)
26
+ // ---------------------------------------------------------------------------
27
+
28
+ /**
29
+ * Make an HTTP(S) request. Returns { status, headers, body }.
30
+ *
31
+ * @param {string} url
32
+ * @param {Object} [opts]
33
+ * @param {string} [opts.method='GET']
34
+ * @param {Object} [opts.headers]
35
+ * @param {Buffer|string} [opts.body]
36
+ * @returns {Promise<{status: number, headers: Object, body: string}>}
37
+ */
38
+ function request(url, opts = {}, _redirectCount = 0) {
39
+ return new Promise((resolve, reject) => {
40
+ if (_redirectCount > 5) return reject(new Error('Too many redirects'));
41
+
42
+ const parsed = new URL(url);
43
+ const mod = parsed.protocol === 'https:' ? https : http;
44
+ const reqOpts = {
45
+ method: opts.method || 'GET',
46
+ hostname: parsed.hostname,
47
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
48
+ path: parsed.pathname + parsed.search,
49
+ headers: opts.headers || {},
50
+ };
51
+
52
+ const req = mod.request(reqOpts, (res) => {
53
+ // Follow redirects
54
+ if ([301, 302, 307, 308].includes(res.statusCode) && res.headers.location) {
55
+ const redirectUrl = new URL(res.headers.location, url).href;
56
+ // For 307/308, preserve method and body; for 301/302, switch to GET.
57
+ // When dropping the body we must also drop the body-describing headers,
58
+ // or the redirected GET advertises a Content-Length it never sends and
59
+ // the socket hangs waiting to flush a body that isn't coming.
60
+ let newOpts;
61
+ if ([307, 308].includes(res.statusCode)) {
62
+ newOpts = opts;
63
+ } else {
64
+ const headers = { ...(opts.headers || {}) };
65
+ for (const h of Object.keys(headers)) {
66
+ if (/^content-(length|type)$/i.test(h)) delete headers[h];
67
+ }
68
+ newOpts = { ...opts, method: 'GET', body: undefined, headers };
69
+ }
70
+ res.resume(); // drain the response
71
+ return resolve(request(redirectUrl, newOpts, _redirectCount + 1));
72
+ }
73
+
74
+ const chunks = [];
75
+ res.on('data', (chunk) => chunks.push(chunk));
76
+ res.on('end', () => {
77
+ resolve({
78
+ status: res.statusCode,
79
+ headers: res.headers,
80
+ body: Buffer.concat(chunks).toString('utf8'),
81
+ });
82
+ });
83
+ });
84
+
85
+ req.on('error', reject);
86
+ req.setTimeout(60000, () => { req.destroy(new Error('Request timed out')); });
87
+
88
+ if (opts.body) req.write(opts.body);
89
+ req.end();
90
+ });
91
+ }
92
+
93
+ /**
94
+ * JSON POST/PUT helper.
95
+ */
96
+ async function jsonRequest(url, method, data, token) {
97
+ const headers = { 'Content-Type': 'application/json' };
98
+ if (token) headers['Authorization'] = `Bearer ${token}`;
99
+ const body = data != null ? JSON.stringify(data) : undefined;
100
+ if (body) headers['Content-Length'] = Buffer.byteLength(body).toString();
101
+ const res = await request(url, { method, headers, body });
102
+ try {
103
+ return { status: res.status, data: JSON.parse(res.body) };
104
+ } catch {
105
+ throw new Error(`Non-JSON response (${res.status}) from ${method} ${url}: ${res.body.slice(0, 200)}`);
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Upload a file as multipart/form-data.
111
+ */
112
+ async function uploadFile(url, filePath, token) {
113
+ const boundary = '----BrainCloudUpload' + Date.now();
114
+ const fileContent = fs.readFileSync(filePath);
115
+ const header = Buffer.from(
116
+ `--${boundary}\r\n` +
117
+ `Content-Disposition: form-data; name="brain"; filename="brain.tar.gz"\r\n` +
118
+ `Content-Type: application/gzip\r\n\r\n`
119
+ );
120
+ const footer = Buffer.from(`\r\n--${boundary}--\r\n`);
121
+ const body = Buffer.concat([header, fileContent, footer]);
122
+
123
+ return request(url, {
124
+ method: 'PUT',
125
+ headers: {
126
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,
127
+ 'Content-Length': body.length.toString(),
128
+ 'Authorization': `Bearer ${token}`,
129
+ },
130
+ body,
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Download a file from URL, save to disk.
136
+ */
137
+ function downloadFile(url, destPath, token, _redirectCount = 0) {
138
+ return new Promise((resolve, reject) => {
139
+ if (_redirectCount > 5) return reject(new Error('Too many redirects'));
140
+
141
+ const parsed = new URL(url);
142
+ const mod = parsed.protocol === 'https:' ? https : http;
143
+ const reqOpts = {
144
+ method: 'GET',
145
+ hostname: parsed.hostname,
146
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
147
+ path: parsed.pathname + parsed.search,
148
+ headers: { 'Authorization': `Bearer ${token}` },
149
+ };
150
+
151
+ const req = mod.request(reqOpts, (res) => {
152
+ // Follow redirects
153
+ if ([301, 302, 307, 308].includes(res.statusCode) && res.headers.location) {
154
+ const redirectUrl = new URL(res.headers.location, url).href;
155
+ res.resume();
156
+ return resolve(downloadFile(redirectUrl, destPath, token, _redirectCount + 1));
157
+ }
158
+
159
+ if (res.statusCode !== 200) {
160
+ const chunks = [];
161
+ res.on('data', (c) => chunks.push(c));
162
+ res.on('end', () => {
163
+ reject(new Error(`Download failed (${res.statusCode}): ${Buffer.concat(chunks).toString()}`));
164
+ });
165
+ return;
166
+ }
167
+
168
+ const ws = fs.createWriteStream(destPath);
169
+ res.pipe(ws);
170
+ ws.on('finish', () => {
171
+ ws.close();
172
+ resolve({ checksum: res.headers['x-checksum'] || null });
173
+ });
174
+ ws.on('error', reject);
175
+ });
176
+
177
+ req.on('error', reject);
178
+ req.setTimeout(300000, () => { req.destroy(new Error('Download timed out')); });
179
+ req.end();
180
+ });
181
+ }
182
+
183
+ // ---------------------------------------------------------------------------
184
+ // Config management — stored at ~/.brain/.cloud/config.json
185
+ // ---------------------------------------------------------------------------
186
+
187
+ function resolvePaths(brainDir) {
188
+ const cloudDir = path.join(brainDir, CLOUD_DIR);
189
+ const configPath = path.join(cloudDir, CONFIG_FILE);
190
+ return { cloudDir, configPath };
191
+ }
192
+
193
+ function readConfig(brainDir) {
194
+ const { configPath } = resolvePaths(brainDir);
195
+ try {
196
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
197
+ } catch {
198
+ return null;
199
+ }
200
+ }
201
+
202
+ function writeConfig(brainDir, config) {
203
+ const { cloudDir, configPath } = resolvePaths(brainDir);
204
+ fs.mkdirSync(cloudDir, { recursive: true });
205
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
206
+ }
207
+
208
+ function deleteConfig(brainDir) {
209
+ const { cloudDir } = resolvePaths(brainDir);
210
+ fs.rmSync(cloudDir, { recursive: true, force: true });
211
+ }
212
+
213
+ // ---------------------------------------------------------------------------
214
+ // Token management
215
+ // ---------------------------------------------------------------------------
216
+
217
+ /**
218
+ * Get a valid access token, refreshing if needed.
219
+ *
220
+ * @param {string} brainDir
221
+ * @returns {Promise<string>} access token
222
+ */
223
+ async function getValidToken(brainDir) {
224
+ const config = readConfig(brainDir);
225
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
226
+
227
+ const now = Math.floor(Date.now() / 1000);
228
+
229
+ // Token still valid (with 30s buffer)
230
+ if (config.expires_at && now < config.expires_at - 30) {
231
+ return config.access_token;
232
+ }
233
+
234
+ // Try refresh
235
+ if (!config.refresh_token) {
236
+ throw new Error('Session expired and no refresh token. Run cloud login again.');
237
+ }
238
+
239
+ const res = await jsonRequest(
240
+ `${config.api_url}/auth/refresh`,
241
+ 'POST',
242
+ { refresh_token: config.refresh_token }
243
+ );
244
+
245
+ if (res.status !== 200) {
246
+ throw new Error('Token refresh failed. Run cloud login again.');
247
+ }
248
+
249
+ config.access_token = res.data.access_token;
250
+ config.refresh_token = res.data.refresh_token;
251
+ config.expires_at = res.data.expires_at;
252
+ writeConfig(brainDir, config);
253
+
254
+ return config.access_token;
255
+ }
256
+
257
+ // ---------------------------------------------------------------------------
258
+ // Device code auth flow
259
+ // ---------------------------------------------------------------------------
260
+
261
+ /**
262
+ * Start the device code login flow.
263
+ * Returns the device code info so the caller can display it to the user.
264
+ *
265
+ * @param {string} apiUrl
266
+ * @returns {Promise<{device_code: string, user_code: string, verify_url: string, expires_in: number}>}
267
+ */
268
+ async function requestDeviceCode(apiUrl) {
269
+ const res = await jsonRequest(`${apiUrl}/auth/device/request`, 'POST', {});
270
+ if (res.status !== 200) {
271
+ throw new Error(`Failed to request device code: ${JSON.stringify(res.data)}`);
272
+ }
273
+ return res.data;
274
+ }
275
+
276
+ /**
277
+ * Poll for device code approval.
278
+ *
279
+ * @param {string} apiUrl
280
+ * @param {string} deviceCode
281
+ * @param {number} interval - Poll interval in ms (default 5000)
282
+ * @param {number} timeout - Max wait in ms (default 600000 = 10 min)
283
+ * @returns {Promise<{access_token: string, refresh_token: string, expires_at: number}>}
284
+ */
285
+ async function pollDeviceCode(apiUrl, deviceCode, interval = 5000, timeout = 600000) {
286
+ const deadline = Date.now() + timeout;
287
+
288
+ while (Date.now() < deadline) {
289
+ const res = await jsonRequest(`${apiUrl}/auth/device/poll`, 'POST', { device_code: deviceCode });
290
+
291
+ if (res.status === 200 && res.data.status === 'approved' && res.data.tokens) {
292
+ return res.data.tokens;
293
+ }
294
+
295
+ if (res.status === 404 || (res.data && res.data.error && res.data.error.includes('expired'))) {
296
+ throw new Error('Device code expired. Try again.');
297
+ }
298
+
299
+ // Still pending — wait and retry
300
+ await new Promise((r) => setTimeout(r, interval));
301
+ }
302
+
303
+ throw new Error('Login timed out. Try again.');
304
+ }
305
+
306
+ /**
307
+ * Full login flow: request code, poll, save config.
308
+ *
309
+ * @param {string} brainDir
310
+ * @param {string} [apiUrl]
311
+ * @returns {Promise<{user_code: string, verify_url: string, waitForApproval: () => Promise<void>}>}
312
+ */
313
+ async function login(brainDir, apiUrl) {
314
+ const url = apiUrl || DEFAULT_API_URL;
315
+ const codeInfo = await requestDeviceCode(url);
316
+
317
+ return {
318
+ user_code: codeInfo.user_code,
319
+ verify_url: codeInfo.verify_url,
320
+ expires_in: codeInfo.expires_in,
321
+ waitForApproval: async () => {
322
+ const tokens = await pollDeviceCode(url, codeInfo.device_code);
323
+
324
+ // Fetch user info + default brain
325
+ const meRes = await jsonRequest(`${url}/auth/me`, 'GET', null, tokens.access_token);
326
+ let userEmail = '';
327
+ if (meRes.status === 200 && meRes.data.user) {
328
+ userEmail = meRes.data.user.email;
329
+ }
330
+
331
+ const brainsRes = await jsonRequest(`${url}/api/brains`, 'GET', null, tokens.access_token);
332
+ let brainId = null;
333
+ if (brainsRes.status === 200 && Array.isArray(brainsRes.data) && brainsRes.data.length > 0) {
334
+ brainId = brainsRes.data[0].id;
335
+ }
336
+
337
+ writeConfig(brainDir, {
338
+ api_url: url,
339
+ access_token: tokens.access_token,
340
+ refresh_token: tokens.refresh_token,
341
+ expires_at: tokens.expires_at,
342
+ brain_id: brainId,
343
+ user_email: userEmail,
344
+ connected_at: new Date().toISOString(),
345
+ });
346
+ },
347
+ };
348
+ }
349
+
350
+ /**
351
+ * Logout — clear stored tokens.
352
+ *
353
+ * @param {string} brainDir
354
+ */
355
+ function logout(brainDir) {
356
+ deleteConfig(brainDir);
357
+ }
358
+
359
+ // ---------------------------------------------------------------------------
360
+ // Tar helpers
361
+ // ---------------------------------------------------------------------------
362
+
363
+ /**
364
+ * Fresh unpredictable temp path. A per-call mkdtemp directory (mode 0700)
365
+ * avoids the classic predictable-/tmp-name pre-creation/symlink race that
366
+ * `${Date.now()}` names invite. Clean up with rmTmp().
367
+ */
368
+ function mkTmp(name) {
369
+ return path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'brain-cloud-')), name);
370
+ }
371
+
372
+ function rmTmp(file) {
373
+ try { fs.rmSync(path.dirname(file), { recursive: true, force: true }); } catch { /* ignore */ }
374
+ }
375
+
376
+ function packBrain(brainDir) {
377
+ const tmpFile = mkTmp('upload.tar.gz');
378
+ const excludeArgs = TAR_EXCLUDES.flatMap((e) => ['--exclude', e]);
379
+
380
+ execFileSync('tar', ['czf', tmpFile, ...excludeArgs, '-C', brainDir, '.'], {
381
+ stdio: 'pipe',
382
+ timeout: 120000,
383
+ });
384
+
385
+ return tmpFile;
386
+ }
387
+
388
+ /**
389
+ * Extract a downloaded snapshot into ~/.brain — hardened against hostile
390
+ * archives. The tarball is extracted into a throwaway staging directory
391
+ * first, then only REGULAR FILES and DIRECTORIES are copied across: symlink
392
+ * (and any other special) members are dropped, `..`-shaped names never leave
393
+ * staging, and a pre-existing symlink at a destination is removed rather than
394
+ * written through. A tampered server-side snapshot therefore cannot plant a
395
+ * link that later writes land through, and cannot escape the brain dir.
396
+ */
397
+ function unpackBrain(tarPath, brainDir) {
398
+ const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'brain-extract-'));
399
+ try {
400
+ execFileSync('tar', ['xzf', tarPath, '-C', staging], {
401
+ stdio: 'pipe',
402
+ timeout: 120000,
403
+ });
404
+ copyExtracted(staging, brainDir);
405
+ } finally {
406
+ try { fs.rmSync(staging, { recursive: true, force: true }); } catch { /* ignore */ }
407
+ }
408
+ }
409
+
410
+ function copyExtracted(srcDir, destDir) {
411
+ fs.mkdirSync(destDir, { recursive: true });
412
+ for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) {
413
+ const srcPath = path.join(srcDir, entry.name);
414
+ const destPath = path.join(destDir, entry.name);
415
+ if (entry.isSymbolicLink()) continue;
416
+ if (entry.isDirectory()) {
417
+ copyExtracted(srcPath, destPath);
418
+ } else if (entry.isFile()) {
419
+ try {
420
+ if (fs.lstatSync(destPath).isSymbolicLink()) fs.rmSync(destPath, { force: true });
421
+ } catch (_) { /* destination doesn't exist */ }
422
+ fs.writeFileSync(destPath, fs.readFileSync(srcPath));
423
+ }
424
+ }
425
+ }
426
+
427
+ // ---------------------------------------------------------------------------
428
+ // Push / Pull
429
+ // ---------------------------------------------------------------------------
430
+
431
+ /**
432
+ * Push ~/.brain/ to the cloud.
433
+ *
434
+ * @param {string} brainDir
435
+ * @returns {Promise<{size_bytes: number, file_count: number, checksum: string}>}
436
+ */
437
+ async function push(brainDir) {
438
+ const config = readConfig(brainDir);
439
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
440
+ if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
441
+
442
+ const token = await getValidToken(brainDir);
443
+
444
+ // Pack ~/.brain/ into tar.gz
445
+ const tarPath = packBrain(brainDir);
446
+
447
+ try {
448
+ const tarSize = fs.statSync(tarPath).size;
449
+ const url = `${config.api_url}/api/brains/${config.brain_id}/sync`;
450
+
451
+ const res = await uploadFile(url, tarPath, token);
452
+
453
+ if (res.status !== 200) {
454
+ const data = JSON.parse(res.body);
455
+ throw new Error(`Push failed (${res.status}): ${data.error || res.body}`);
456
+ }
457
+
458
+ const result = JSON.parse(res.body);
459
+
460
+ // Update config with last push time
461
+ config.last_push = new Date().toISOString();
462
+ writeConfig(brainDir, config);
463
+
464
+ return { ...result, local_size: tarSize };
465
+ } finally {
466
+ // Clean up temp file
467
+ rmTmp(tarPath);
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Pull from the cloud into ~/.brain/.
473
+ *
474
+ * @param {string} brainDir
475
+ * @returns {Promise<{size_bytes: number, checksum: string|null}>}
476
+ */
477
+ async function pull(brainDir) {
478
+ const config = readConfig(brainDir);
479
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
480
+ if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
481
+
482
+ const token = await getValidToken(brainDir);
483
+ const url = `${config.api_url}/api/brains/${config.brain_id}/sync`;
484
+ const tmpFile = mkTmp('download.tar.gz');
485
+
486
+ try {
487
+ const { checksum } = await downloadFile(url, tmpFile, token);
488
+ const size = fs.statSync(tmpFile).size;
489
+
490
+ // Extract into ~/.brain/
491
+ unpackBrain(tmpFile, brainDir);
492
+
493
+ // Update config
494
+ config.last_pull = new Date().toISOString();
495
+ writeConfig(brainDir, config);
496
+
497
+ return { size_bytes: size, checksum };
498
+ } finally {
499
+ rmTmp(tmpFile);
500
+ }
501
+ }
502
+
503
+ // ---------------------------------------------------------------------------
504
+ // Versions / Restore
505
+ // ---------------------------------------------------------------------------
506
+
507
+ // Local entries a cloud restore must never touch: sync/auth infrastructure and
508
+ // _archived/, which is deliberately excluded from cloud pushes (see
509
+ // TAR_EXCLUDES) and so does not exist in the snapshot being restored.
510
+ const RESTORE_PRESERVE = new Set(['.sync', '.cloud', '.DS_Store', '_archived']);
511
+
512
+ /**
513
+ * List cloud restore points — pre-overwrite snapshots Brain Cloud takes
514
+ * automatically before every push commit. Newest first.
515
+ *
516
+ * @param {string} brainDir
517
+ * @returns {Promise<Array<{version: string, date: string}>>}
518
+ */
519
+ async function listVersions(brainDir) {
520
+ const config = readConfig(brainDir);
521
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
522
+ if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
523
+
524
+ const token = await getValidToken(brainDir);
525
+ const res = await jsonRequest(
526
+ `${config.api_url}/api/brains/${config.brain_id}/versions`,
527
+ 'GET', null, token
528
+ );
529
+ if (res.status !== 200) {
530
+ throw new Error(`Failed to list versions (${res.status}): ${res.data.error || ''}`);
531
+ }
532
+ return res.data.versions || [];
533
+ }
534
+
535
+ /**
536
+ * Restore ~/.brain/ from a cloud version snapshot.
537
+ *
538
+ * Before touching anything, the current brain is packed into a local backup
539
+ * under .cloud/ (kept for the last 5 restores) so the restore is undoable even
540
+ * without the git sync path. audit.log is carried forward across the swap —
541
+ * the append-only trail records history through a restore, never rolls back.
542
+ * The cloud's live brain is NOT modified; push when satisfied with the result.
543
+ *
544
+ * @param {string} brainDir
545
+ * @param {string} version - Snapshot name from listVersions()
546
+ * @returns {Promise<{restored_version: string, size_bytes: number, backup: string}>}
547
+ */
548
+ async function restoreVersion(brainDir, version) {
549
+ const config = readConfig(brainDir);
550
+ if (!config) throw new Error('Not logged in. Run cloud login first.');
551
+ if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
552
+ if (!version) throw new Error('No version given. List them with versions first.');
553
+
554
+ const token = await getValidToken(brainDir);
555
+ const url = `${config.api_url}/api/brains/${config.brain_id}/sync?version=${encodeURIComponent(version)}`;
556
+ const tmpFile = mkTmp('restore.tar.gz');
557
+
558
+ try {
559
+ await downloadFile(url, tmpFile, token);
560
+ const size = fs.statSync(tmpFile).size;
561
+
562
+ // Local safety backup of the CURRENT state (the download above already
563
+ // succeeded, so a failure past this point can always be rolled forward).
564
+ const { cloudDir } = resolvePaths(brainDir);
565
+ fs.mkdirSync(cloudDir, { recursive: true });
566
+ const backupName = `pre-restore-${new Date().toISOString().replace(/[:.]/g, '')}.tar.gz`;
567
+ const backupPath = path.join(cloudDir, backupName);
568
+ const packed = packBrain(brainDir);
569
+ fs.copyFileSync(packed, backupPath);
570
+ rmTmp(packed);
571
+ const backups = fs.readdirSync(cloudDir).filter((n) => n.startsWith('pre-restore-')).sort();
572
+ while (backups.length > 5) fs.rmSync(path.join(cloudDir, backups.shift()), { force: true });
573
+
574
+ // Carry the append-only audit trail across the swap.
575
+ const auditPath = path.join(brainDir, 'audit.log');
576
+ let auditTrail = null;
577
+ try { auditTrail = fs.readFileSync(auditPath); } catch { auditTrail = null; }
578
+
579
+ for (const entry of fs.readdirSync(brainDir)) {
580
+ if (RESTORE_PRESERVE.has(entry)) continue;
581
+ fs.rmSync(path.join(brainDir, entry), { recursive: true, force: true });
582
+ }
583
+ unpackBrain(tmpFile, brainDir);
584
+ if (auditTrail !== null) fs.writeFileSync(auditPath, auditTrail, { mode: 0o600 });
585
+
586
+ config.last_pull = new Date().toISOString();
587
+ writeConfig(brainDir, config);
588
+
589
+ return { restored_version: version, size_bytes: size, backup: backupPath };
590
+ } finally {
591
+ rmTmp(tmpFile);
592
+ }
593
+ }
594
+
595
+ // ---------------------------------------------------------------------------
596
+ // Status
597
+ // ---------------------------------------------------------------------------
598
+
599
+ /**
600
+ * Get cloud sync status.
601
+ *
602
+ * @param {string} brainDir
603
+ * @returns {Promise<Object>}
604
+ */
605
+ async function status(brainDir) {
606
+ const config = readConfig(brainDir);
607
+ if (!config) {
608
+ return { connected: false };
609
+ }
610
+
611
+ let brain = null;
612
+ let user = null;
613
+
614
+ try {
615
+ const token = await getValidToken(brainDir);
616
+
617
+ const meRes = await jsonRequest(`${config.api_url}/auth/me`, 'GET', null, token);
618
+ if (meRes.status === 200) {
619
+ user = meRes.data.user;
620
+ }
621
+
622
+ if (config.brain_id) {
623
+ const brainRes = await jsonRequest(
624
+ `${config.api_url}/api/brains/${config.brain_id}`,
625
+ 'GET', null, token
626
+ );
627
+ if (brainRes.status === 200) {
628
+ brain = brainRes.data;
629
+ }
630
+ }
631
+ } catch {
632
+ // Token may be expired — still report config
633
+ }
634
+
635
+ return {
636
+ connected: true,
637
+ api_url: config.api_url,
638
+ user_email: config.user_email || (user && user.email) || null,
639
+ brain_id: config.brain_id,
640
+ brain_name: brain ? brain.name : null,
641
+ brain_size: brain ? brain.size_bytes : null,
642
+ brain_files: brain ? brain.file_count : null,
643
+ last_synced: brain && brain.last_synced_at ? brain.last_synced_at : null,
644
+ last_push: config.last_push || null,
645
+ last_pull: config.last_pull || null,
646
+ connected_at: config.connected_at || null,
647
+ };
648
+ }
649
+
650
+ // ---------------------------------------------------------------------------
651
+ // Exports
652
+ // ---------------------------------------------------------------------------
653
+
654
+ module.exports = {
655
+ login,
656
+ logout,
657
+ push,
658
+ pull,
659
+ listVersions,
660
+ restoreVersion,
661
+ status,
662
+ readConfig,
663
+ writeConfig,
664
+ // Internal — exported for testing
665
+ requestDeviceCode,
666
+ pollDeviceCode,
667
+ getValidToken,
668
+ packBrain,
669
+ unpackBrain,
670
+ resolvePaths,
671
+ DEFAULT_API_URL,
672
+ };