brain-memory 0.1.0-beta.4 → 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.
- package/README.md +52 -85
- package/bin/install.js +17 -238
- package/commands/brain/status.md +10 -11
- package/commands/brain/sync.md +126 -124
- package/package.json +8 -5
- package/prompts/claude.md +58 -5
- package/prompts/gemini.md +58 -5
- package/prompts/openai.md +58 -5
- package/src/{sync/crypto-utils.js → crypto.js} +4 -91
- package/src/export-import.js +185 -0
- package/src/git-sync.js +403 -0
- package/src/installer.js +231 -0
- package/hooks/session-end.md +0 -48
- package/hooks/session-start.md +0 -48
- package/src/sync/oauth.js +0 -430
- package/src/sync/provider.js +0 -144
- package/src/sync/providers/dropbox.js +0 -288
- package/src/sync/providers/google-drive.js +0 -496
- package/src/sync/providers/onedrive.js +0 -308
- package/src/sync/sync-engine.js +0 -774
package/src/git-sync.js
ADDED
|
@@ -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
|
+
};
|
package/src/installer.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const os = require('os');
|
|
4
|
+
|
|
5
|
+
const PACKAGE_ROOT = path.resolve(__dirname, '..');
|
|
6
|
+
|
|
7
|
+
const RUNTIMES = {
|
|
8
|
+
claude: {
|
|
9
|
+
name: 'Claude Code',
|
|
10
|
+
globalDir: path.join(os.homedir(), '.claude'),
|
|
11
|
+
localDir: '.claude',
|
|
12
|
+
commandsSubdir: 'commands',
|
|
13
|
+
promptFile: 'CLAUDE.md',
|
|
14
|
+
promptSource: 'claude.md',
|
|
15
|
+
commandStyle: 'flat',
|
|
16
|
+
},
|
|
17
|
+
gemini: {
|
|
18
|
+
name: 'Gemini CLI',
|
|
19
|
+
globalDir: path.join(os.homedir(), '.gemini'),
|
|
20
|
+
localDir: '.gemini',
|
|
21
|
+
commandsSubdir: 'commands',
|
|
22
|
+
promptFile: 'GEMINI.md',
|
|
23
|
+
promptSource: 'gemini.md',
|
|
24
|
+
commandStyle: 'flat',
|
|
25
|
+
},
|
|
26
|
+
openai: {
|
|
27
|
+
name: 'OpenAI Codex CLI',
|
|
28
|
+
globalDir: path.join(os.homedir(), '.codex'),
|
|
29
|
+
localDir: '.codex',
|
|
30
|
+
commandsSubdir: 'skills',
|
|
31
|
+
promptFile: 'AGENTS.md',
|
|
32
|
+
promptSource: 'openai.md',
|
|
33
|
+
commandStyle: 'skills',
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const BRAIN_MARKER_START = '<!-- BRAIN-MEMORY-START -->';
|
|
38
|
+
const BRAIN_MARKER_END = '<!-- BRAIN-MEMORY-END -->';
|
|
39
|
+
|
|
40
|
+
function copyDir(src, dest) {
|
|
41
|
+
fs.mkdirSync(dest, { recursive: true });
|
|
42
|
+
const entries = fs.readdirSync(src, { withFileTypes: true });
|
|
43
|
+
for (const entry of entries) {
|
|
44
|
+
const srcPath = path.join(src, entry.name);
|
|
45
|
+
const destPath = path.join(dest, entry.name);
|
|
46
|
+
if (entry.isDirectory()) {
|
|
47
|
+
copyDir(srcPath, destPath);
|
|
48
|
+
} else {
|
|
49
|
+
fs.copyFileSync(srcPath, destPath);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function installSkills(commandsSrc, skillsDest) {
|
|
55
|
+
const entries = fs.readdirSync(commandsSrc).filter((f) => f.endsWith('.md'));
|
|
56
|
+
for (const file of entries) {
|
|
57
|
+
const name = file.replace('.md', '');
|
|
58
|
+
const skillDir = path.join(skillsDest, `brain-${name}`);
|
|
59
|
+
fs.mkdirSync(skillDir, { recursive: true });
|
|
60
|
+
fs.copyFileSync(
|
|
61
|
+
path.join(commandsSrc, file),
|
|
62
|
+
path.join(skillDir, 'SKILL.md')
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function injectPrompt(targetDir, promptFile, promptSource) {
|
|
68
|
+
const promptContent = fs.readFileSync(
|
|
69
|
+
path.join(PACKAGE_ROOT, 'prompts', promptSource),
|
|
70
|
+
'utf-8'
|
|
71
|
+
);
|
|
72
|
+
const targetPath = path.join(targetDir, promptFile);
|
|
73
|
+
|
|
74
|
+
const wrappedContent = `\n${BRAIN_MARKER_START}\n${promptContent}\n${BRAIN_MARKER_END}\n`;
|
|
75
|
+
|
|
76
|
+
if (fs.existsSync(targetPath)) {
|
|
77
|
+
let existing = fs.readFileSync(targetPath, 'utf-8');
|
|
78
|
+
// Remove old brain section if present
|
|
79
|
+
const startIdx = existing.indexOf(BRAIN_MARKER_START);
|
|
80
|
+
const endIdx = existing.indexOf(BRAIN_MARKER_END);
|
|
81
|
+
if (startIdx !== -1 && endIdx !== -1) {
|
|
82
|
+
existing =
|
|
83
|
+
existing.substring(0, startIdx) +
|
|
84
|
+
existing.substring(endIdx + BRAIN_MARKER_END.length);
|
|
85
|
+
}
|
|
86
|
+
fs.writeFileSync(targetPath, existing.trimEnd() + '\n' + wrappedContent);
|
|
87
|
+
} else {
|
|
88
|
+
fs.writeFileSync(targetPath, wrappedContent.trim() + '\n');
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function installForRuntime(runtime, scope) {
|
|
93
|
+
const config = RUNTIMES[runtime];
|
|
94
|
+
const targetDir = scope === 'global' ? config.globalDir : config.localDir;
|
|
95
|
+
const commandsSrc = path.join(PACKAGE_ROOT, 'commands', 'brain');
|
|
96
|
+
|
|
97
|
+
if (config.commandStyle === 'skills') {
|
|
98
|
+
const skillsDest = path.join(targetDir, config.commandsSubdir);
|
|
99
|
+
installSkills(commandsSrc, skillsDest);
|
|
100
|
+
} else {
|
|
101
|
+
const commandsDest = path.join(targetDir, config.commandsSubdir, 'brain');
|
|
102
|
+
copyDir(commandsSrc, commandsDest);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const promptTarget = scope === 'global' ? config.globalDir : '.';
|
|
106
|
+
injectPrompt(promptTarget, config.promptFile, config.promptSource);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function initializeBrain(projectDir) {
|
|
110
|
+
const brainDir = path.join(projectDir || process.cwd(), '.brain');
|
|
111
|
+
|
|
112
|
+
if (fs.existsSync(brainDir)) {
|
|
113
|
+
return { alreadyExists: true };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const now = new Date().toISOString();
|
|
117
|
+
|
|
118
|
+
// Create directories
|
|
119
|
+
const categories = ['professional', 'personal', 'social', 'family', '_consolidated', '_archived'];
|
|
120
|
+
for (const cat of categories) {
|
|
121
|
+
fs.mkdirSync(path.join(brainDir, cat), { recursive: true });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Create index.json
|
|
125
|
+
const index = {
|
|
126
|
+
version: 2,
|
|
127
|
+
created: now,
|
|
128
|
+
last_updated: now,
|
|
129
|
+
memory_count: 0,
|
|
130
|
+
memories: {},
|
|
131
|
+
config: {
|
|
132
|
+
max_depth: 6,
|
|
133
|
+
consolidation_threshold: 0.3,
|
|
134
|
+
decay_check_interval_days: 7,
|
|
135
|
+
strength_boost_on_recall: 0.05,
|
|
136
|
+
auto_consolidate: true,
|
|
137
|
+
propagation_window_days: 7,
|
|
138
|
+
association_config: {
|
|
139
|
+
co_retrieval_boost: 0.10,
|
|
140
|
+
link_decay_rate: 0.998,
|
|
141
|
+
link_prune_threshold: 0.05,
|
|
142
|
+
spreading_activation_depth: 2,
|
|
143
|
+
spreading_activation_decay: 0.5,
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
fs.writeFileSync(
|
|
148
|
+
path.join(brainDir, 'index.json'),
|
|
149
|
+
JSON.stringify(index, null, 2) + '\n'
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
// Create associations.json
|
|
153
|
+
fs.writeFileSync(
|
|
154
|
+
path.join(brainDir, 'associations.json'),
|
|
155
|
+
JSON.stringify({ version: 1, edges: {} }, null, 2) + '\n'
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
// Create contexts.json
|
|
159
|
+
fs.writeFileSync(
|
|
160
|
+
path.join(brainDir, 'contexts.json'),
|
|
161
|
+
JSON.stringify({ version: 1, sessions: [] }, null, 2) + '\n'
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
// Create review-queue.json
|
|
165
|
+
fs.writeFileSync(
|
|
166
|
+
path.join(brainDir, 'review-queue.json'),
|
|
167
|
+
JSON.stringify({ version: 1, items: [] }, null, 2) + '\n'
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
// Create _archived/index.json
|
|
171
|
+
fs.writeFileSync(
|
|
172
|
+
path.join(brainDir, '_archived', 'index.json'),
|
|
173
|
+
JSON.stringify({ version: 1, archived_count: 0, memories: {} }, null, 2) + '\n'
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
// Load category descriptions from template
|
|
177
|
+
const templatePath = path.join(PACKAGE_ROOT, 'templates', 'default-categories.json');
|
|
178
|
+
let template = { top_categories: [] };
|
|
179
|
+
if (fs.existsSync(templatePath)) {
|
|
180
|
+
template = JSON.parse(fs.readFileSync(templatePath, 'utf-8'));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Create _meta.json for each category
|
|
184
|
+
const mainCategories = ['professional', 'personal', 'social', 'family'];
|
|
185
|
+
for (const cat of mainCategories) {
|
|
186
|
+
const templateCat = template.top_categories.find((c) => c.name === cat) || {};
|
|
187
|
+
const meta = {
|
|
188
|
+
category: cat,
|
|
189
|
+
description: templateCat.description || cat,
|
|
190
|
+
created: now,
|
|
191
|
+
memory_count: 0,
|
|
192
|
+
subcategories: [],
|
|
193
|
+
};
|
|
194
|
+
fs.writeFileSync(
|
|
195
|
+
path.join(brainDir, cat, '_meta.json'),
|
|
196
|
+
JSON.stringify(meta, null, 2) + '\n'
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Create _meta.json for special directories
|
|
201
|
+
for (const special of ['_consolidated', '_archived']) {
|
|
202
|
+
const meta = {
|
|
203
|
+
category: special,
|
|
204
|
+
description:
|
|
205
|
+
special === '_consolidated'
|
|
206
|
+
? 'Merged memories from consolidation operations'
|
|
207
|
+
: 'Archived memories preserved for recovery',
|
|
208
|
+
created: now,
|
|
209
|
+
memory_count: 0,
|
|
210
|
+
subcategories: [],
|
|
211
|
+
};
|
|
212
|
+
fs.writeFileSync(
|
|
213
|
+
path.join(brainDir, special, '_meta.json'),
|
|
214
|
+
JSON.stringify(meta, null, 2) + '\n'
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return { alreadyExists: false, brainDir };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
module.exports = {
|
|
222
|
+
RUNTIMES,
|
|
223
|
+
BRAIN_MARKER_START,
|
|
224
|
+
BRAIN_MARKER_END,
|
|
225
|
+
PACKAGE_ROOT,
|
|
226
|
+
copyDir,
|
|
227
|
+
installSkills,
|
|
228
|
+
injectPrompt,
|
|
229
|
+
installForRuntime,
|
|
230
|
+
initializeBrain,
|
|
231
|
+
};
|
package/hooks/session-end.md
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
# Brain Memory — Session End Hook
|
|
2
|
-
|
|
3
|
-
This hook is triggered at the end of a coding session. Its purpose is to prompt the agent to consider storing important memories and to save session context.
|
|
4
|
-
|
|
5
|
-
## Behavior
|
|
6
|
-
|
|
7
|
-
### Memory Suggestion
|
|
8
|
-
|
|
9
|
-
When a session ends, evaluate whether the session contained any of the following:
|
|
10
|
-
|
|
11
|
-
1. **Decisions** — Architecture choices, technology selections, trade-off resolutions
|
|
12
|
-
2. **Learnings** — New patterns, debugging insights, API discoveries
|
|
13
|
-
3. **Insights** — Realizations about the codebase, project, or process
|
|
14
|
-
4. **Experiences** — Significant events like incidents, deployments, milestones
|
|
15
|
-
5. **Goals** — New objectives discussed or planned
|
|
16
|
-
|
|
17
|
-
If the session contained meaningful content in any of these categories, suggest to the user:
|
|
18
|
-
|
|
19
|
-
```
|
|
20
|
-
💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
|
|
21
|
-
Run /brain:memorize to capture them before this context is lost.
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
### Session Context Capture
|
|
25
|
-
|
|
26
|
-
If `.brain/contexts.json` exists, append a session summary:
|
|
27
|
-
|
|
28
|
-
```json
|
|
29
|
-
{
|
|
30
|
-
"session_id": "<timestamp-based-id>",
|
|
31
|
-
"started": "<session start ISO timestamp>",
|
|
32
|
-
"ended": "<session end ISO timestamp>",
|
|
33
|
-
"project": "<current project name>",
|
|
34
|
-
"topics": ["<key topics discussed>"],
|
|
35
|
-
"task_type": "<primary task type: debugging|implementing|designing|reviewing|discussing|learning>",
|
|
36
|
-
"memories_created": ["<IDs of memories stored this session>"],
|
|
37
|
-
"memories_recalled": ["<IDs of memories retrieved this session>"]
|
|
38
|
-
}
|
|
39
|
-
```
|
|
40
|
-
|
|
41
|
-
Keep only the last 20 session entries in `contexts.json` to prevent unbounded growth.
|
|
42
|
-
|
|
43
|
-
**Rules:**
|
|
44
|
-
- Do NOT auto-memorize without user consent
|
|
45
|
-
- Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
|
|
46
|
-
- Only suggest when there is genuinely valuable context worth preserving
|
|
47
|
-
- Keep the suggestion brief and non-intrusive
|
|
48
|
-
- Always save session context to `contexts.json` regardless of whether the user memorizes anything
|