brain-memory 0.1.0-beta.1 → 0.1.0-beta.10

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/bin/install.js CHANGED
@@ -1,46 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ const readline = require('readline');
3
4
  const fs = require('fs');
4
5
  const path = require('path');
5
- const readline = require('readline');
6
-
7
- const PACKAGE_ROOT = path.resolve(__dirname, '..');
8
-
9
- const RUNTIMES = {
10
- claude: {
11
- name: 'Claude Code',
12
- globalDir: path.join(require('os').homedir(), '.claude'),
13
- localDir: '.claude',
14
- commandsSubdir: 'commands',
15
- promptFile: 'CLAUDE.md',
16
- promptSource: 'claude.md',
17
- settingsFile: 'settings.json',
18
- commandStyle: 'flat',
19
- },
20
- gemini: {
21
- name: 'Gemini CLI',
22
- globalDir: path.join(require('os').homedir(), '.gemini'),
23
- localDir: '.gemini',
24
- commandsSubdir: 'commands',
25
- promptFile: 'GEMINI.md',
26
- promptSource: 'gemini.md',
27
- settingsFile: null,
28
- commandStyle: 'flat',
29
- },
30
- openai: {
31
- name: 'OpenAI Codex CLI',
32
- globalDir: path.join(require('os').homedir(), '.codex'),
33
- localDir: '.codex',
34
- commandsSubdir: 'skills',
35
- promptFile: 'AGENTS.md',
36
- promptSource: 'openai.md',
37
- settingsFile: null,
38
- commandStyle: 'skills',
39
- },
40
- };
41
-
42
- const BRAIN_MARKER_START = '<!-- BRAIN-MEMORY-START -->';
43
- const BRAIN_MARKER_END = '<!-- BRAIN-MEMORY-END -->';
6
+ const os = require('os');
7
+ const {
8
+ RUNTIMES,
9
+ installForRuntime,
10
+ initializeBrain,
11
+ detectInstallations,
12
+ uninstallForRuntime,
13
+ } = require('../src/installer');
44
14
 
45
15
  function createRL() {
46
16
  return readline.createInterface({
@@ -53,109 +23,50 @@ function ask(rl, question) {
53
23
  return new Promise((resolve) => rl.question(question, resolve));
54
24
  }
55
25
 
56
- function copyDir(src, dest) {
57
- fs.mkdirSync(dest, { recursive: true });
58
- const entries = fs.readdirSync(src, { withFileTypes: true });
59
- for (const entry of entries) {
60
- const srcPath = path.join(src, entry.name);
61
- const destPath = path.join(dest, entry.name);
62
- if (entry.isDirectory()) {
63
- copyDir(srcPath, destPath);
26
+ function parseArgs(argv) {
27
+ const args = argv.slice(2);
28
+ const subcommands = ['install', 'update', 'uninstall'];
29
+ let subcommand = 'install';
30
+ const flags = new Set();
31
+
32
+ for (const arg of args) {
33
+ const clean = arg.replace(/^--/, '');
34
+ if (subcommands.includes(clean) && arg === clean) {
35
+ // positional subcommand (no --)
36
+ subcommand = clean;
37
+ } else if (clean === 'update') {
38
+ subcommand = 'update';
39
+ } else if (clean === 'uninstall') {
40
+ subcommand = 'uninstall';
64
41
  } else {
65
- fs.copyFileSync(srcPath, destPath);
42
+ flags.add(clean);
66
43
  }
67
44
  }
68
- }
69
45
 
70
- function installSkills(commandsSrc, skillsDest) {
71
- const entries = fs.readdirSync(commandsSrc).filter((f) => f.endsWith('.md'));
72
- for (const file of entries) {
73
- const name = file.replace('.md', '');
74
- const skillDir = path.join(skillsDest, `brain-${name}`);
75
- fs.mkdirSync(skillDir, { recursive: true });
76
- fs.copyFileSync(
77
- path.join(commandsSrc, file),
78
- path.join(skillDir, 'SKILL.md')
79
- );
80
- }
46
+ return { subcommand, flags };
81
47
  }
82
48
 
83
- function injectPrompt(targetDir, promptFile, promptSource) {
84
- const promptContent = fs.readFileSync(
85
- path.join(PACKAGE_ROOT, 'prompts', promptSource),
86
- 'utf-8'
87
- );
88
- const targetPath = path.join(targetDir, promptFile);
89
-
90
- const wrappedContent = `\n${BRAIN_MARKER_START}\n${promptContent}\n${BRAIN_MARKER_END}\n`;
91
-
92
- if (fs.existsSync(targetPath)) {
93
- let existing = fs.readFileSync(targetPath, 'utf-8');
94
- // Remove old brain section if present
95
- const startIdx = existing.indexOf(BRAIN_MARKER_START);
96
- const endIdx = existing.indexOf(BRAIN_MARKER_END);
97
- if (startIdx !== -1 && endIdx !== -1) {
98
- existing =
99
- existing.substring(0, startIdx) +
100
- existing.substring(endIdx + BRAIN_MARKER_END.length);
101
- }
102
- fs.writeFileSync(targetPath, existing.trimEnd() + '\n' + wrappedContent);
103
- } else {
104
- fs.writeFileSync(targetPath, wrappedContent.trim() + '\n');
105
- }
49
+ function resolveRuntimesFromFlags(flags) {
50
+ const runtimes = [];
51
+ if (flags.has('claude')) runtimes.push('claude');
52
+ if (flags.has('gemini')) runtimes.push('gemini');
53
+ if (flags.has('openai') || flags.has('codex')) runtimes.push('openai');
54
+ if (flags.has('all')) return ['claude', 'gemini', 'openai'];
55
+ return runtimes;
106
56
  }
107
57
 
108
- function installForRuntime(runtime, scope) {
109
- const config = RUNTIMES[runtime];
110
- const targetDir = scope === 'global' ? config.globalDir : config.localDir;
111
- const commandsSrc = path.join(PACKAGE_ROOT, 'commands', 'brain');
112
-
113
- console.log(`\n Installing for ${config.name} (${scope})...`);
114
-
115
- if (config.commandStyle === 'skills') {
116
- // Codex: each command becomes a skill directory with SKILL.md
117
- const skillsDest = path.join(targetDir, config.commandsSubdir);
118
- console.log(` Installing skills to ${skillsDest}`);
119
- installSkills(commandsSrc, skillsDest);
120
- } else {
121
- // Claude / Gemini: flat copy into commands/brain/
122
- const commandsDest = path.join(targetDir, config.commandsSubdir, 'brain');
123
- console.log(` Copying commands to ${commandsDest}`);
124
- copyDir(commandsSrc, commandsDest);
125
- }
126
-
127
- // Inject prompt into CLAUDE.md / GEMINI.md / AGENTS.md
128
- const promptTarget = scope === 'global' ? config.globalDir : '.';
129
- console.log(` Injecting brain context into ${path.join(promptTarget, config.promptFile)}`);
130
- injectPrompt(promptTarget, config.promptFile, config.promptSource);
131
-
132
- console.log(` Done!`);
58
+ function resolveScopeFromFlags(flags) {
59
+ if (flags.has('global')) return 'global';
60
+ if (flags.has('local')) return 'local';
61
+ return null;
133
62
  }
134
63
 
135
- async function main() {
136
- console.log(`
137
- ╔══════════════════════════════════════════════════════╗
138
- ║ ║
139
- ║ 🧠 Brain Memory — Installer ║
140
- ║ ║
141
- ║ Hierarchical memory system for AI coding agents ║
142
- ║ ║
143
- ╚══════════════════════════════════════════════════════╝
144
- `);
145
-
146
- const args = process.argv.slice(2);
147
- const flags = new Set(args.map((a) => a.replace(/^--/, '')));
148
-
149
- let runtimes = [];
150
- let scope = null;
151
-
152
- // Check for non-interactive flags
153
- if (flags.has('claude')) runtimes.push('claude');
154
- if (flags.has('gemini')) runtimes.push('gemini');
155
- if (flags.has('openai') || flags.has('codex')) runtimes.push('openai');
156
- if (flags.has('all')) runtimes = ['claude', 'gemini', 'openai'];
157
- if (flags.has('global')) scope = 'global';
158
- if (flags.has('local')) scope = 'local';
64
+ // ---------------------------------------------------------------------------
65
+ // Install (original behavior, refactored from main)
66
+ // ---------------------------------------------------------------------------
67
+ async function runInstall(flags) {
68
+ let runtimes = resolveRuntimesFromFlags(flags);
69
+ let scope = resolveScopeFromFlags(flags);
159
70
 
160
71
  const rl = createRL();
161
72
 
@@ -204,18 +115,28 @@ async function main() {
204
115
  console.log('');
205
116
  const initBrain = await ask(
206
117
  rl,
207
- ' Initialize .brain/ directory in current project? (Y/n): '
118
+ ' Initialize ~/.brain/ directory? (Y/n): '
208
119
  );
209
120
 
210
121
  // Perform installation
211
122
  console.log('\n Installing...');
212
123
  for (const runtime of runtimes) {
124
+ const config = RUNTIMES[runtime];
125
+ console.log(`\n Installing for ${config.name} (${scope})...`);
213
126
  installForRuntime(runtime, scope);
127
+ console.log(` Done!`);
214
128
  }
215
129
 
216
130
  // Initialize .brain if requested
217
131
  if (initBrain.trim().toLowerCase() !== 'n') {
218
- initializeBrain();
132
+ const result = initializeBrain();
133
+ if (result.alreadyExists) {
134
+ console.log('\n ~/.brain/ already exists, skipping initialization.');
135
+ } else {
136
+ console.log('\n ~/.brain/ initialized successfully.');
137
+ console.log('');
138
+ console.log(' Use /brain:sync to set up portable sync across devices.');
139
+ }
219
140
  }
220
141
 
221
142
  console.log(`
@@ -232,6 +153,7 @@ async function main() {
232
153
  /brain:sunshine Deep forensic memory erasure
233
154
  /brain:sleep Full maintenance cycle
234
155
  /brain:status Brain overview dashboard
156
+ /brain:sync Sync memories via Git remote or export/import
235
157
 
236
158
  Get started by running /brain:init in your agent session.
237
159
  `);
@@ -240,122 +162,170 @@ async function main() {
240
162
  }
241
163
  }
242
164
 
243
- function initializeBrain() {
244
- const brainDir = path.join(process.cwd(), '.brain');
165
+ // ---------------------------------------------------------------------------
166
+ // Update
167
+ // ---------------------------------------------------------------------------
168
+ async function runUpdate(flags) {
169
+ const pkg = JSON.parse(
170
+ fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8')
171
+ );
172
+ const version = pkg.version;
245
173
 
246
- if (fs.existsSync(brainDir)) {
247
- console.log('\n .brain/ already exists, skipping initialization.');
248
- return;
174
+ console.log(' Detecting existing installations...\n');
175
+
176
+ let detections = detectInstallations();
177
+
178
+ // Filter by explicit flags if provided
179
+ const filterRuntimes = resolveRuntimesFromFlags(flags);
180
+ const filterScope = resolveScopeFromFlags(flags);
181
+ if (filterRuntimes.length > 0) {
182
+ detections = detections.filter((d) => filterRuntimes.includes(d.runtime));
183
+ }
184
+ if (filterScope) {
185
+ detections = detections.filter((d) => d.scope === filterScope);
249
186
  }
250
187
 
251
- console.log('\n Creating .brain/ directory structure...');
188
+ if (detections.length === 0) {
189
+ console.log(' No existing brain-memory installations found.\n');
190
+ console.log(' To install, run: npx brain-memory@beta');
191
+ if (filterRuntimes.length > 0) {
192
+ console.log(` (Searched for: ${filterRuntimes.join(', ')})`);
193
+ }
194
+ return;
195
+ }
252
196
 
253
- const now = new Date().toISOString();
197
+ console.log(` Found ${detections.length} installation(s):\n`);
198
+ for (const d of detections) {
199
+ const parts = [];
200
+ if (d.commandsFound) parts.push('commands');
201
+ if (d.promptFound) parts.push('prompt');
202
+ console.log(` ${d.runtimeName} (${d.scope}) — ${parts.join(' + ')}`);
203
+ }
254
204
 
255
- // Create directories
256
- const categories = ['professional', 'personal', 'social', 'family', '_consolidated', '_archived'];
257
- for (const cat of categories) {
258
- fs.mkdirSync(path.join(brainDir, cat), { recursive: true });
205
+ console.log('\n Updating...');
206
+ for (const d of detections) {
207
+ console.log(`\n Updating ${d.runtimeName} (${d.scope})...`);
208
+ installForRuntime(d.runtime, d.scope);
209
+ console.log(' Done!');
259
210
  }
260
211
 
261
- // Create index.json
262
- const index = {
263
- version: 2,
264
- created: now,
265
- last_updated: now,
266
- memory_count: 0,
267
- memories: {},
268
- config: {
269
- max_depth: 6,
270
- consolidation_threshold: 0.3,
271
- decay_check_interval_days: 7,
272
- strength_boost_on_recall: 0.05,
273
- auto_consolidate: true,
274
- propagation_window_days: 7,
275
- association_config: {
276
- co_retrieval_boost: 0.10,
277
- link_decay_rate: 0.998,
278
- link_prune_threshold: 0.05,
279
- spreading_activation_depth: 2,
280
- spreading_activation_decay: 0.5,
281
- },
282
- },
283
- };
284
- fs.writeFileSync(
285
- path.join(brainDir, 'index.json'),
286
- JSON.stringify(index, null, 2) + '\n'
287
- );
212
+ console.log(`\n ✓ Updated to v${version}\n`);
213
+ }
288
214
 
289
- // Create associations.json
290
- fs.writeFileSync(
291
- path.join(brainDir, 'associations.json'),
292
- JSON.stringify({ version: 1, edges: {} }, null, 2) + '\n'
293
- );
215
+ // ---------------------------------------------------------------------------
216
+ // Uninstall
217
+ // ---------------------------------------------------------------------------
218
+ async function runUninstall(flags) {
219
+ console.log(' Detecting existing installations...\n');
294
220
 
295
- // Create contexts.json
296
- fs.writeFileSync(
297
- path.join(brainDir, 'contexts.json'),
298
- JSON.stringify({ version: 1, sessions: [] }, null, 2) + '\n'
299
- );
221
+ let detections = detectInstallations();
300
222
 
301
- // Create review-queue.json
302
- fs.writeFileSync(
303
- path.join(brainDir, 'review-queue.json'),
304
- JSON.stringify({ version: 1, items: [] }, null, 2) + '\n'
305
- );
223
+ // Filter by explicit flags if provided
224
+ const filterRuntimes = resolveRuntimesFromFlags(flags);
225
+ const filterScope = resolveScopeFromFlags(flags);
226
+ if (filterRuntimes.length > 0) {
227
+ detections = detections.filter((d) => filterRuntimes.includes(d.runtime));
228
+ }
229
+ if (filterScope) {
230
+ detections = detections.filter((d) => d.scope === filterScope);
231
+ }
306
232
 
307
- // Create _archived/index.json
308
- fs.writeFileSync(
309
- path.join(brainDir, '_archived', 'index.json'),
310
- JSON.stringify({ version: 1, archived_count: 0, memories: {} }, null, 2) + '\n'
311
- );
233
+ if (detections.length === 0) {
234
+ console.log(' No existing brain-memory installations found. Nothing to uninstall.\n');
235
+ return;
236
+ }
312
237
 
313
- // Load category descriptions from template
314
- const templatePath = path.join(PACKAGE_ROOT, 'templates', 'default-categories.json');
315
- let template = { top_categories: [] };
316
- if (fs.existsSync(templatePath)) {
317
- template = JSON.parse(fs.readFileSync(templatePath, 'utf-8'));
238
+ console.log(` Will remove ${detections.length} installation(s):\n`);
239
+ for (const d of detections) {
240
+ const parts = [];
241
+ if (d.commandsFound) parts.push('commands');
242
+ if (d.promptFound) parts.push('prompt section');
243
+ console.log(` ${d.runtimeName} (${d.scope}) — ${parts.join(' + ')}`);
318
244
  }
319
245
 
320
- // Create _meta.json for each category
321
- const mainCategories = ['professional', 'personal', 'social', 'family'];
322
- for (const cat of mainCategories) {
323
- const templateCat = template.top_categories.find((c) => c.name === cat) || {};
324
- const meta = {
325
- category: cat,
326
- description: templateCat.description || cat,
327
- created: now,
328
- memory_count: 0,
329
- subcategories: [],
330
- };
331
- fs.writeFileSync(
332
- path.join(brainDir, cat, '_meta.json'),
333
- JSON.stringify(meta, null, 2) + '\n'
334
- );
246
+ // Confirm unless --yes
247
+ if (!flags.has('yes') && !flags.has('y')) {
248
+ const rl = createRL();
249
+ try {
250
+ console.log('');
251
+ const answer = await ask(rl, ' Proceed? (y/N): ');
252
+ if (answer.trim().toLowerCase() !== 'y') {
253
+ console.log('\n Cancelled.\n');
254
+ return;
255
+ }
256
+ } finally {
257
+ rl.close();
258
+ }
335
259
  }
336
260
 
337
- // Create _meta.json for special directories
338
- for (const special of ['_consolidated', '_archived']) {
339
- const meta = {
340
- category: special,
341
- description:
342
- special === '_consolidated'
343
- ? 'Merged memories from consolidation operations'
344
- : 'Archived memories preserved for recovery',
345
- created: now,
346
- memory_count: 0,
347
- subcategories: [],
348
- };
349
- fs.writeFileSync(
350
- path.join(brainDir, special, '_meta.json'),
351
- JSON.stringify(meta, null, 2) + '\n'
352
- );
261
+ console.log('\n Uninstalling...');
262
+ for (const d of detections) {
263
+ console.log(`\n Removing ${d.runtimeName} (${d.scope})...`);
264
+ uninstallForRuntime(d.runtime, d.scope);
265
+ console.log(' Done!');
266
+ }
267
+
268
+ // Handle .brain/ data
269
+ const brainDir = path.join(os.homedir(), '.brain');
270
+ if (fs.existsSync(brainDir)) {
271
+ if (flags.has('delete-data')) {
272
+ fs.rmSync(brainDir, { recursive: true, force: true });
273
+ console.log('\n Deleted ~/.brain/ directory.');
274
+ } else if (!flags.has('yes') && !flags.has('y')) {
275
+ const rl = createRL();
276
+ try {
277
+ console.log('');
278
+ const answer = await ask(
279
+ rl,
280
+ ' Delete ~/.brain/ data directory? This removes all memories. (y/N): '
281
+ );
282
+ if (answer.trim().toLowerCase() === 'y') {
283
+ fs.rmSync(brainDir, { recursive: true, force: true });
284
+ console.log(' Deleted ~/.brain/ directory.');
285
+ } else {
286
+ console.log(' Kept ~/.brain/ directory (your memories are preserved).');
287
+ }
288
+ } finally {
289
+ rl.close();
290
+ }
291
+ } else {
292
+ console.log('\n Kept ~/.brain/ directory (use --delete-data to remove memories).');
293
+ }
353
294
  }
354
295
 
355
- console.log(' .brain/ initialized successfully.');
296
+ console.log('\n ✓ Uninstall complete.\n');
297
+ }
298
+
299
+ // ---------------------------------------------------------------------------
300
+ // Main
301
+ // ---------------------------------------------------------------------------
302
+ async function main() {
303
+ console.log(`
304
+ ╔══════════════════════════════════════════════════════╗
305
+ ║ ║
306
+ ║ 🧠 Brain Memory — Installer ║
307
+ ║ ║
308
+ ║ Hierarchical memory system for AI coding agents ║
309
+ ║ ║
310
+ ╚══════════════════════════════════════════════════════╝
311
+ `);
312
+
313
+ const { subcommand, flags } = parseArgs(process.argv);
314
+
315
+ switch (subcommand) {
316
+ case 'update':
317
+ await runUpdate(flags);
318
+ break;
319
+ case 'uninstall':
320
+ await runUninstall(flags);
321
+ break;
322
+ default:
323
+ await runInstall(flags);
324
+ break;
325
+ }
356
326
  }
357
327
 
358
328
  main().catch((err) => {
359
- console.error('Installation failed:', err.message);
329
+ console.error('Operation failed:', err.message);
360
330
  process.exit(1);
361
331
  });