brain-memory 0.1.0-beta.5 → 0.1.0-beta.6

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,403 @@
1
+ /**
2
+ * Brain Memory — Git Sync Engine
3
+ *
4
+ * Push/pull .brain/ memories via any Git remote (GitHub, GitLab, Codeberg, etc.).
5
+ * A hidden git repo lives at .brain/.sync/repo/ — the project's own git history
6
+ * is never touched.
7
+ *
8
+ * Zero external dependencies — uses child_process.execFileSync to call the git binary.
9
+ */
10
+
11
+ const { execFileSync } = require('child_process');
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const { encrypt, decrypt } = require('./crypto');
15
+
16
+ const SYNC_DIR = '.sync';
17
+ const REPO_DIR = 'repo';
18
+ const CONFIG_FILE = 'config.json';
19
+
20
+ // Files/dirs inside .brain/ that should NOT be synced
21
+ const EXCLUDED = new Set(['.sync', '.DS_Store']);
22
+
23
+ /**
24
+ * Check whether `git` is available on PATH.
25
+ *
26
+ * @returns {boolean}
27
+ */
28
+ function checkGitAvailable() {
29
+ try {
30
+ execFileSync('git', ['--version'], { stdio: 'pipe' });
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Run a git command inside the sync repo.
39
+ *
40
+ * @param {string} repoDir - Absolute path to .brain/.sync/repo/
41
+ * @param {string[]} args - Git arguments
42
+ * @param {Object} [opts] - Extra execFileSync options
43
+ * @returns {string} stdout (trimmed)
44
+ */
45
+ function git(repoDir, args, opts = {}) {
46
+ return execFileSync('git', args, {
47
+ cwd: repoDir,
48
+ stdio: 'pipe',
49
+ encoding: 'utf8',
50
+ ...opts,
51
+ }).trim();
52
+ }
53
+
54
+ /**
55
+ * Resolve paths for sync infrastructure.
56
+ *
57
+ * @param {string} brainDir - Absolute path to .brain/
58
+ * @returns {{ syncDir: string, repoDir: string, configPath: string }}
59
+ */
60
+ function resolvePaths(brainDir) {
61
+ const syncDir = path.join(brainDir, SYNC_DIR);
62
+ const repoDir = path.join(syncDir, REPO_DIR);
63
+ const configPath = path.join(syncDir, CONFIG_FILE);
64
+ return { syncDir, repoDir, configPath };
65
+ }
66
+
67
+ /**
68
+ * Initialize a git repo inside .brain/.sync/repo/.
69
+ *
70
+ * @param {string} brainDir - Absolute path to .brain/
71
+ * @returns {{ repoDir: string }} Created repo path
72
+ */
73
+ function initSyncRepo(brainDir) {
74
+ const { repoDir } = resolvePaths(brainDir);
75
+ fs.mkdirSync(repoDir, { recursive: true });
76
+
77
+ git(repoDir, ['init', '-b', 'main']);
78
+ git(repoDir, ['config', 'user.email', 'brain-memory@local']);
79
+ git(repoDir, ['config', 'user.name', 'Brain Memory']);
80
+
81
+ return { repoDir };
82
+ }
83
+
84
+ /**
85
+ * Configure (or update) the remote URL for the sync repo.
86
+ *
87
+ * @param {string} brainDir - Absolute path to .brain/
88
+ * @param {string} remoteUrl - Git remote URL (SSH or HTTPS)
89
+ */
90
+ function configureRemote(brainDir, remoteUrl) {
91
+ const { repoDir } = resolvePaths(brainDir);
92
+
93
+ try {
94
+ git(repoDir, ['remote', 'get-url', 'origin']);
95
+ // Remote exists — update it
96
+ git(repoDir, ['remote', 'set-url', 'origin', remoteUrl]);
97
+ } catch {
98
+ // Remote doesn't exist — add it
99
+ git(repoDir, ['remote', 'add', 'origin', remoteUrl]);
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Copy .brain/ files into the sync repo, excluding .sync/.
105
+ * If encryption is enabled, files are encrypted before writing.
106
+ *
107
+ * @param {string} brainDir - Absolute path to .brain/
108
+ * @param {string} repoDir - Absolute path to .brain/.sync/repo/
109
+ * @param {string|null} passphrase - Encryption passphrase or null
110
+ */
111
+ function copyBrainToRepo(brainDir, repoDir, passphrase) {
112
+ // Clean existing tracked files in repo (except .git)
113
+ const entries = fs.readdirSync(repoDir);
114
+ for (const entry of entries) {
115
+ if (entry === '.git') continue;
116
+ fs.rmSync(path.join(repoDir, entry), { recursive: true, force: true });
117
+ }
118
+
119
+ // Recursively copy .brain/ → repo/
120
+ copyDir(brainDir, repoDir, brainDir, passphrase);
121
+ }
122
+
123
+ /**
124
+ * Recursively copy a directory, excluding EXCLUDED entries.
125
+ *
126
+ * @param {string} srcDir - Source directory
127
+ * @param {string} destDir - Destination directory
128
+ * @param {string} brainDir - Root brain dir (for relative path calculation)
129
+ * @param {string|null} passphrase - Encryption passphrase or null
130
+ */
131
+ function copyDir(srcDir, destDir, brainDir, passphrase) {
132
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
133
+ for (const entry of entries) {
134
+ const rel = path.relative(brainDir, path.join(srcDir, entry.name));
135
+ const topLevel = rel.split(path.sep)[0];
136
+ if (EXCLUDED.has(topLevel)) continue;
137
+
138
+ const srcPath = path.join(srcDir, entry.name);
139
+ const destPath = path.join(destDir, entry.name);
140
+
141
+ if (entry.isDirectory()) {
142
+ fs.mkdirSync(destPath, { recursive: true });
143
+ copyDir(srcPath, destPath, brainDir, passphrase);
144
+ } else {
145
+ const content = fs.readFileSync(srcPath);
146
+ if (passphrase) {
147
+ fs.writeFileSync(destPath, encrypt(content.toString('utf8'), passphrase));
148
+ } else {
149
+ fs.writeFileSync(destPath, content);
150
+ }
151
+ }
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Copy files from the sync repo back into .brain/.
157
+ * If encryption is enabled, files are decrypted after reading.
158
+ *
159
+ * @param {string} repoDir - Absolute path to .brain/.sync/repo/
160
+ * @param {string} brainDir - Absolute path to .brain/
161
+ * @param {string|null} passphrase - Decryption passphrase or null
162
+ */
163
+ function copyRepoToBrain(repoDir, brainDir, passphrase) {
164
+ copyRepoDir(repoDir, brainDir, repoDir, passphrase);
165
+ }
166
+
167
+ /**
168
+ * Recursively copy repo files back to brain.
169
+ */
170
+ function copyRepoDir(srcDir, destDir, repoDir, passphrase) {
171
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
172
+ for (const entry of entries) {
173
+ if (entry.name === '.git') continue;
174
+
175
+ const srcPath = path.join(srcDir, entry.name);
176
+ const destPath = path.join(destDir, entry.name);
177
+
178
+ if (entry.isDirectory()) {
179
+ fs.mkdirSync(destPath, { recursive: true });
180
+ copyRepoDir(srcPath, destPath, repoDir, passphrase);
181
+ } else {
182
+ const content = fs.readFileSync(srcPath);
183
+ if (passphrase) {
184
+ fs.writeFileSync(destPath, decrypt(content, passphrase));
185
+ } else {
186
+ fs.writeFileSync(destPath, content);
187
+ }
188
+ }
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Get a summary of local vs remote sync status.
194
+ *
195
+ * @param {string} brainDir - Absolute path to .brain/
196
+ * @returns {{ configured: boolean, remote: string|null, branch: string|null, ahead: number, behind: number, lastPush: string|null }}
197
+ */
198
+ function getStatus(brainDir) {
199
+ const { repoDir, configPath } = resolvePaths(brainDir);
200
+ const config = readConfig(configPath);
201
+
202
+ if (!config) {
203
+ return { configured: false, remote: null, branch: null, ahead: 0, behind: 0, lastPush: null };
204
+ }
205
+
206
+ let ahead = 0;
207
+ let behind = 0;
208
+
209
+ if (fs.existsSync(path.join(repoDir, '.git'))) {
210
+ try {
211
+ git(repoDir, ['fetch', 'origin'], { timeout: 15000 });
212
+ } catch {
213
+ // Offline or remote not reachable — use cached state
214
+ }
215
+
216
+ try {
217
+ const counts = git(repoDir, ['rev-list', '--left-right', '--count', 'main...origin/main']);
218
+ const parts = counts.split(/\s+/);
219
+ ahead = parseInt(parts[0], 10) || 0;
220
+ behind = parseInt(parts[1], 10) || 0;
221
+ } catch {
222
+ // No remote tracking yet (first push not done)
223
+ }
224
+ }
225
+
226
+ return {
227
+ configured: true,
228
+ remote: config.remote || null,
229
+ branch: config.branch || 'main',
230
+ ahead,
231
+ behind,
232
+ lastPush: config.lastPush || null,
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Push .brain/ contents to the remote.
238
+ *
239
+ * @param {string} brainDir - Absolute path to .brain/
240
+ * @param {string} [message] - Commit message (defaults to timestamp)
241
+ * @param {string} [passphrase] - Encryption passphrase (if configured)
242
+ * @returns {{ committed: boolean, pushed: boolean, message: string }}
243
+ */
244
+ function push(brainDir, message, passphrase) {
245
+ const { repoDir, configPath } = resolvePaths(brainDir);
246
+ const config = readConfig(configPath);
247
+ if (!config) throw new Error('Sync not configured. Run /brain:sync setup first.');
248
+
249
+ const pass = config.encrypt ? passphrase : null;
250
+ if (config.encrypt && !passphrase) {
251
+ throw new Error('Encryption is enabled but no passphrase provided.');
252
+ }
253
+
254
+ // Ensure repo exists
255
+ if (!fs.existsSync(path.join(repoDir, '.git'))) {
256
+ initSyncRepo(brainDir);
257
+ if (config.remote) configureRemote(brainDir, config.remote);
258
+ }
259
+
260
+ // Copy brain files into repo
261
+ copyBrainToRepo(brainDir, repoDir, pass);
262
+
263
+ // Stage all changes
264
+ git(repoDir, ['add', '-A']);
265
+
266
+ // Check if there's anything to commit
267
+ const status = git(repoDir, ['status', '--porcelain']);
268
+ if (!status) {
269
+ return { committed: false, pushed: false, message: 'Nothing to push — no changes.' };
270
+ }
271
+
272
+ // Commit
273
+ const commitMsg = message || `brain sync ${new Date().toISOString()}`;
274
+ git(repoDir, ['commit', '-m', commitMsg]);
275
+
276
+ // Push
277
+ let pushed = false;
278
+ if (config.remote) {
279
+ try {
280
+ git(repoDir, ['push', '-u', 'origin', 'main'], { timeout: 30000 });
281
+ pushed = true;
282
+ } catch (err) {
283
+ return { committed: true, pushed: false, message: `Committed locally but push failed: ${err.message}` };
284
+ }
285
+ }
286
+
287
+ // Update lastPush
288
+ config.lastPush = new Date().toISOString();
289
+ writeConfig(configPath, config);
290
+
291
+ return { committed: true, pushed, message: `Pushed successfully at ${config.lastPush}` };
292
+ }
293
+
294
+ /**
295
+ * Pull remote changes into .brain/.
296
+ *
297
+ * @param {string} brainDir - Absolute path to .brain/
298
+ * @param {string} [passphrase] - Decryption passphrase (if configured)
299
+ * @returns {{ pulled: boolean, message: string }}
300
+ */
301
+ function pull(brainDir, passphrase) {
302
+ const { repoDir, configPath } = resolvePaths(brainDir);
303
+ const config = readConfig(configPath);
304
+ if (!config) throw new Error('Sync not configured. Run /brain:sync setup first.');
305
+
306
+ const pass = config.encrypt ? passphrase : null;
307
+ if (config.encrypt && !passphrase) {
308
+ throw new Error('Encryption is enabled but no passphrase provided.');
309
+ }
310
+
311
+ if (!fs.existsSync(path.join(repoDir, '.git'))) {
312
+ initSyncRepo(brainDir);
313
+ if (config.remote) configureRemote(brainDir, config.remote);
314
+ }
315
+
316
+ // Pull
317
+ try {
318
+ git(repoDir, ['pull', 'origin', 'main', '--ff-only'], { timeout: 30000 });
319
+ } catch (err) {
320
+ // Could be first pull (nothing to pull), or merge conflict
321
+ if (err.message && err.message.includes('Not possible to fast-forward')) {
322
+ return { pulled: false, message: 'Merge conflict detected. Push your local changes first, or manually resolve in .brain/.sync/repo/' };
323
+ }
324
+ // First clone — try to set up tracking
325
+ try {
326
+ git(repoDir, ['fetch', 'origin'], { timeout: 15000 });
327
+ git(repoDir, ['merge', 'origin/main', '--ff-only']);
328
+ } catch {
329
+ return { pulled: false, message: 'Remote has no commits yet or is unreachable.' };
330
+ }
331
+ }
332
+
333
+ // Copy repo files back to brain
334
+ copyRepoToBrain(repoDir, brainDir, pass);
335
+
336
+ // Update config
337
+ config.lastPull = new Date().toISOString();
338
+ writeConfig(configPath, config);
339
+
340
+ return { pulled: true, message: `Pulled successfully at ${config.lastPull}` };
341
+ }
342
+
343
+ /**
344
+ * Read sync config from .brain/.sync/config.json.
345
+ *
346
+ * @param {string} configPath - Absolute path to config.json
347
+ * @returns {Object|null}
348
+ */
349
+ function readConfig(configPath) {
350
+ try {
351
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
352
+ } catch {
353
+ return null;
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Write sync config to .brain/.sync/config.json.
359
+ *
360
+ * @param {string} configPath - Absolute path to config.json
361
+ * @param {Object} config
362
+ */
363
+ function writeConfig(configPath, config) {
364
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
365
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
366
+ }
367
+
368
+ /**
369
+ * Read the sync config for a brain directory.
370
+ *
371
+ * @param {string} brainDir - Absolute path to .brain/
372
+ * @returns {Object|null}
373
+ */
374
+ function getSyncConfig(brainDir) {
375
+ const { configPath } = resolvePaths(brainDir);
376
+ return readConfig(configPath);
377
+ }
378
+
379
+ /**
380
+ * Write the sync config for a brain directory.
381
+ *
382
+ * @param {string} brainDir - Absolute path to .brain/
383
+ * @param {Object} config
384
+ */
385
+ function writeSyncConfig(brainDir, config) {
386
+ const { configPath } = resolvePaths(brainDir);
387
+ writeConfig(configPath, config);
388
+ }
389
+
390
+ module.exports = {
391
+ checkGitAvailable,
392
+ initSyncRepo,
393
+ configureRemote,
394
+ getStatus,
395
+ push,
396
+ pull,
397
+ getSyncConfig,
398
+ writeSyncConfig,
399
+ // Internal — exported for testing
400
+ copyBrainToRepo,
401
+ copyRepoToBrain,
402
+ resolvePaths,
403
+ };