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 CHANGED
@@ -95,7 +95,38 @@ Then append the contents of the corresponding prompt file to your agent's instru
95
95
  | `/brain:sunshine [target]` | Deep forensic erasure — trace and remove all references |
96
96
  | `/brain:sleep [scope]` | Full maintenance cycle — 9 neuroscience-inspired phases |
97
97
  | `/brain:status` | Dashboard with brain health metrics and recommendations |
98
- | `/brain:sync [subcommand]` | Cloud sync — push/pull memories to Dropbox, Google Drive, or OneDrive |
98
+ | `/brain:sync [subcommand]` | Sync memories via Git remote or export/import for portability |
99
+
100
+ ## Session Lifecycle
101
+
102
+ Brain Memory works automatically in the background — no commands needed for basic context awareness.
103
+
104
+ ### Session Start
105
+
106
+ When a session begins and `.brain/` exists, the agent automatically:
107
+
108
+ 1. Reads the brain index and loads the top 3-5 memories relevant to the current project
109
+ 2. Checks the review queue for memories due for spaced repetition
110
+ 3. Outputs a brief status line:
111
+
112
+ ```
113
+ 🧠 Brain active — 42 memories loaded (8 in current project context)
114
+ 📋 3 memories due for review — run /brain:review
115
+ ```
116
+
117
+ The agent silently internalizes relevant memories and references them naturally during the session — no information dump.
118
+
119
+ ### Session End
120
+
121
+ When a session ends, the agent evaluates whether significant decisions, learnings, insights, or experiences occurred. If so, it suggests:
122
+
123
+ ```
124
+ 💡 This session contained notable decisions and learnings.
125
+ Would you like to store them as brain memories?
126
+ Run /brain:memorize to capture them before this context is lost.
127
+ ```
128
+
129
+ The agent never auto-memorizes without user consent. Session context is always saved to `.brain/contexts.json` for context-dependent recall.
99
130
 
100
131
  ## How It Works
101
132
 
@@ -327,24 +358,28 @@ Each expertise area gets an `_expertise.md` profile documenting what you know we
327
358
 
328
359
  Failed recalls reset the interval to 1 day. Successful recalls extend the interval by the ease factor. This ensures you spend time on memories that need reinforcement, not ones you already know well.
329
360
 
330
- ### Cloud Sync
361
+ ### Portable Sync
362
+
363
+ `/brain:sync` provides two ways to sync memories across devices — no OAuth apps, no cloud provider setup.
331
364
 
332
- `/brain:sync` lets you push and pull your `.brain/` memories to a cloud provider for cross-device access. Supports **Dropbox**, **Google Drive**, and **OneDrive** with zero npm dependencies (uses Node.js 18+ built-in `fetch`).
365
+ **Git remote** — Push/pull `.brain/` to any private Git repository. Works with GitHub, GitLab, Codeberg, or any self-hosted Git server. Uses your existing Git/SSH authentication — no additional credentials needed.
366
+
367
+ **Export/Import** — Pack the entire `.brain/` into a single encrypted file for manual transfer via USB, email, or any file-sharing service.
333
368
 
334
369
  **Key features:**
335
370
  - **Manual push/pull** — No background watchers, no auto-sync. You control when data moves.
336
- - **Three-way diff** — Compares local state, remote state, and last-known sync state to detect changes and conflicts.
337
- - **Conflict resolution** — When the same file is modified locally and remotely, sync detects the conflict and lets you choose: keep local, keep remote, or keep both.
338
- - **Optional encryption** — AES-256-GCM encryption with a user-provided passphrase. When enabled, all files are encrypted before upload and decrypted after download. The cloud provider only ever sees opaque bytes.
339
- - **OAuth2 authentication** — PKCE authorization code flow with a Device Code Flow fallback for headless/SSH environments. Users register their own OAuth app with the provider and supply their client ID.
371
+ - **Optional encryption** — AES-256-GCM encryption with a user-provided passphrase. When enabled, all files are encrypted before committing or exporting.
372
+ - **Merge mode** — Import supports merge mode (only import newer files) or overwrite mode.
373
+ - **Zero dependencies** — Uses Node.js built-in `crypto` and the system `git` binary.
340
374
 
341
375
  **Setup:**
342
- 1. Register an OAuth app with your chosen provider (Dropbox / Google Drive / OneDrive)
343
- 2. Run `/brain:sync login <provider>` and provide your client ID
344
- 3. Authorize in the browser (or enter the device code for headless environments)
345
- 4. Use `/brain:sync push` and `/brain:sync pull` to keep memories in sync
376
+ 1. Create a private Git repo (e.g., `gh repo create brain-data --private`)
377
+ 2. Run `/brain:sync setup git@github.com:you/brain-data.git`
378
+ 3. Use `/brain:sync push` and `/brain:sync pull` to keep memories in sync
379
+
380
+ For one-off transfers, use `/brain:sync export` and `/brain:sync import <path>`.
346
381
 
347
- Sync state is stored locally in `.brain/.sync/` and is never uploaded to the cloud.
382
+ Sync state is stored locally in `.brain/.sync/` and is never pushed to the remote.
348
383
 
349
384
  ## File Structure
350
385
 
@@ -379,10 +414,9 @@ Sync state is stored locally in `.brain/.sync/` and is never uploaded to the clo
379
414
  ├── _archived/ # Decayed memories (recoverable + searchable)
380
415
  │ ├── _meta.json
381
416
  │ └── index.json # Searchable archive index
382
- └── .sync/ # Cloud sync state (never synced, local only)
383
- ├── config.json # Provider, client ID, encryption flag
384
- ├── credentials.enc # AES-256-GCM encrypted OAuth tokens
385
- └── sync-state.json # Per-file revisions, cursor, conflicts
417
+ └── .sync/ # Sync state (local only, never pushed)
418
+ ├── config.json # Remote URL, encryption flag
419
+ └── repo/ # Hidden git repo for sync
386
420
  ```
387
421
 
388
422
  Subdirectories are created **on demand** — the agent decides placement depth based on how specific the memory is. A generic career thought lands in `professional/`, but a specific deployment incident goes to `professional/companies/acme/projects/alpha/`.
@@ -425,76 +459,9 @@ Brain configuration lives in `.brain/index.json` under the `config` key:
425
459
  | `association_config.spreading_activation_depth` | 2 | Maximum hops for spreading activation traversal |
426
460
  | `association_config.spreading_activation_decay` | 0.5 | Decay factor per hop during spreading activation |
427
461
 
428
- ## Project Structure
429
-
430
- ```
431
- brain/
432
- ├── bin/
433
- │ └── install.js # Interactive installer (npx brain-memory)
434
- ├── commands/
435
- │ └── brain/ # Slash command definitions
436
- │ ├── init.md
437
- │ ├── memorize.md
438
- │ ├── remember.md
439
- │ ├── review.md
440
- │ ├── explore.md
441
- │ ├── consolidate.md
442
- │ ├── forget.md
443
- │ ├── sunshine.md
444
- │ ├── sleep.md
445
- │ ├── status.md
446
- │ └── sync.md
447
- ├── prompts/
448
- │ ├── claude.md # CLAUDE.md content (injected by installer)
449
- │ ├── gemini.md # GEMINI.md content (injected by installer)
450
- │ └── openai.md # AGENTS.md content (injected by installer)
451
- ├── hooks/
452
- │ ├── session-start.md # Ambient memory loading + review notifications
453
- │ └── session-end.md # Auto-memorize suggestion + context capture
454
- ├── templates/
455
- │ └── default-categories.json # Default brain category definitions
456
- ├── src/
457
- │ ├── scorer.js # Decay, spreading activation, context matching, spaced reinforcement
458
- │ ├── index-manager.js # Index, associations, contexts, review queue, archive CRUD
459
- │ └── sync/ # Cloud sync module
460
- │ ├── crypto-utils.js # AES-256-GCM encryption + credential storage
461
- │ ├── oauth.js # OAuth2 PKCE + Device Code Flow
462
- │ ├── provider.js # SyncProvider base class + factory
463
- │ ├── sync-engine.js # Local-first sync with 3-way diff
464
- │ └── providers/
465
- │ ├── dropbox.js # Dropbox API v2
466
- │ ├── google-drive.js # Google Drive API v3
467
- │ └── onedrive.js # Microsoft Graph API
468
- ├── CLAUDE.md # Development guide for this repo
469
- ├── package.json
470
- └── README.md
471
- ```
472
-
473
- ## Releasing
462
+ ## Contributing
474
463
 
475
- Tests run automatically before every release via the `prerelease` script.
476
-
477
- ```bash
478
- # Beta release (bumps 0.1.0-beta.3 → 0.1.0-beta.4)
479
- npm run release:beta
480
-
481
- # Stable releases
482
- npm run release:patch # 0.1.0 → 0.1.1
483
- npm run release:minor # 0.1.1 → 0.2.0
484
- npm run release:major # 0.2.0 → 1.0.0
485
- ```
486
-
487
- Each release command:
488
- 1. Runs the full test suite
489
- 2. Bumps the version in `package.json`
490
- 3. Creates a git commit and tag
491
- 4. Publishes to npm
492
-
493
- After publishing, push the commit and tag:
494
-
495
- ```bash
496
- git push && git push --tags
497
- ```
464
+ Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, project structure, and how to submit changes.
498
465
 
499
466
  ## Inspired By
500
467
 
package/bin/install.js CHANGED
@@ -1,46 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const fs = require('fs');
4
- const path = require('path');
5
3
  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 -->';
4
+ const {
5
+ RUNTIMES,
6
+ installForRuntime,
7
+ initializeBrain,
8
+ } = require('../src/installer');
44
9
 
45
10
  function createRL() {
46
11
  return readline.createInterface({
@@ -53,85 +18,6 @@ function ask(rl, question) {
53
18
  return new Promise((resolve) => rl.question(question, resolve));
54
19
  }
55
20
 
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);
64
- } else {
65
- fs.copyFileSync(srcPath, destPath);
66
- }
67
- }
68
- }
69
-
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
- }
81
- }
82
-
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
- }
106
- }
107
-
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!`);
133
- }
134
-
135
21
  async function main() {
136
22
  console.log(`
137
23
  ╔══════════════════════════════════════════════════════╗
@@ -210,12 +96,23 @@ async function main() {
210
96
  // Perform installation
211
97
  console.log('\n Installing...');
212
98
  for (const runtime of runtimes) {
99
+ const config = RUNTIMES[runtime];
100
+ console.log(`\n Installing for ${config.name} (${scope})...`);
213
101
  installForRuntime(runtime, scope);
102
+ console.log(` Done!`);
214
103
  }
215
104
 
216
105
  // Initialize .brain if requested
217
106
  if (initBrain.trim().toLowerCase() !== 'n') {
218
- initializeBrain();
107
+ const result = initializeBrain();
108
+ if (result.alreadyExists) {
109
+ console.log('\n .brain/ already exists, skipping initialization.');
110
+ } else {
111
+ console.log('\n .brain/ initialized successfully.');
112
+ console.log('');
113
+ console.log(' ☁️ Cloud sync is available! Use /brain:sync login to connect');
114
+ console.log(' Dropbox, Google Drive, or OneDrive for cross-device access.');
115
+ }
219
116
  }
220
117
 
221
118
  console.log(`
@@ -241,124 +138,6 @@ async function main() {
241
138
  }
242
139
  }
243
140
 
244
- function initializeBrain() {
245
- const brainDir = path.join(process.cwd(), '.brain');
246
-
247
- if (fs.existsSync(brainDir)) {
248
- console.log('\n .brain/ already exists, skipping initialization.');
249
- return;
250
- }
251
-
252
- console.log('\n Creating .brain/ directory structure...');
253
-
254
- const now = new Date().toISOString();
255
-
256
- // Create directories
257
- const categories = ['professional', 'personal', 'social', 'family', '_consolidated', '_archived'];
258
- for (const cat of categories) {
259
- fs.mkdirSync(path.join(brainDir, cat), { recursive: true });
260
- }
261
-
262
- // Create index.json
263
- const index = {
264
- version: 2,
265
- created: now,
266
- last_updated: now,
267
- memory_count: 0,
268
- memories: {},
269
- config: {
270
- max_depth: 6,
271
- consolidation_threshold: 0.3,
272
- decay_check_interval_days: 7,
273
- strength_boost_on_recall: 0.05,
274
- auto_consolidate: true,
275
- propagation_window_days: 7,
276
- association_config: {
277
- co_retrieval_boost: 0.10,
278
- link_decay_rate: 0.998,
279
- link_prune_threshold: 0.05,
280
- spreading_activation_depth: 2,
281
- spreading_activation_decay: 0.5,
282
- },
283
- },
284
- };
285
- fs.writeFileSync(
286
- path.join(brainDir, 'index.json'),
287
- JSON.stringify(index, null, 2) + '\n'
288
- );
289
-
290
- // Create associations.json
291
- fs.writeFileSync(
292
- path.join(brainDir, 'associations.json'),
293
- JSON.stringify({ version: 1, edges: {} }, null, 2) + '\n'
294
- );
295
-
296
- // Create contexts.json
297
- fs.writeFileSync(
298
- path.join(brainDir, 'contexts.json'),
299
- JSON.stringify({ version: 1, sessions: [] }, null, 2) + '\n'
300
- );
301
-
302
- // Create review-queue.json
303
- fs.writeFileSync(
304
- path.join(brainDir, 'review-queue.json'),
305
- JSON.stringify({ version: 1, items: [] }, null, 2) + '\n'
306
- );
307
-
308
- // Create _archived/index.json
309
- fs.writeFileSync(
310
- path.join(brainDir, '_archived', 'index.json'),
311
- JSON.stringify({ version: 1, archived_count: 0, memories: {} }, null, 2) + '\n'
312
- );
313
-
314
- // Load category descriptions from template
315
- const templatePath = path.join(PACKAGE_ROOT, 'templates', 'default-categories.json');
316
- let template = { top_categories: [] };
317
- if (fs.existsSync(templatePath)) {
318
- template = JSON.parse(fs.readFileSync(templatePath, 'utf-8'));
319
- }
320
-
321
- // Create _meta.json for each category
322
- const mainCategories = ['professional', 'personal', 'social', 'family'];
323
- for (const cat of mainCategories) {
324
- const templateCat = template.top_categories.find((c) => c.name === cat) || {};
325
- const meta = {
326
- category: cat,
327
- description: templateCat.description || cat,
328
- created: now,
329
- memory_count: 0,
330
- subcategories: [],
331
- };
332
- fs.writeFileSync(
333
- path.join(brainDir, cat, '_meta.json'),
334
- JSON.stringify(meta, null, 2) + '\n'
335
- );
336
- }
337
-
338
- // Create _meta.json for special directories
339
- for (const special of ['_consolidated', '_archived']) {
340
- const meta = {
341
- category: special,
342
- description:
343
- special === '_consolidated'
344
- ? 'Merged memories from consolidation operations'
345
- : 'Archived memories preserved for recovery',
346
- created: now,
347
- memory_count: 0,
348
- subcategories: [],
349
- };
350
- fs.writeFileSync(
351
- path.join(brainDir, special, '_meta.json'),
352
- JSON.stringify(meta, null, 2) + '\n'
353
- );
354
- }
355
-
356
- console.log(' .brain/ initialized successfully.');
357
- console.log('');
358
- console.log(' ☁️ Cloud sync is available! Use /brain:sync login to connect');
359
- console.log(' Dropbox, Google Drive, or OneDrive for cross-device access.');
360
- }
361
-
362
141
  main().catch((err) => {
363
142
  console.error('Installation failed:', err.message);
364
143
  process.exit(1);
@@ -12,8 +12,7 @@ Also read (if they exist):
12
12
  - `.brain/associations.json` — for association network stats
13
13
  - `.brain/review-queue.json` — for review schedule info
14
14
  - `.brain/_archived/index.json` — for archive stats
15
- - `.brain/.sync/config.json` — for cloud sync configuration
16
- - `.brain/.sync/sync-state.json` — for sync state and pending changes
15
+ - `.brain/.sync/config.json` — for git sync configuration
17
16
 
18
17
  ### 2. Compute Statistics
19
18
 
@@ -107,12 +106,13 @@ Calculate aggregate stats:
107
106
  + <title> (<path>) — <date>
108
107
  ...
109
108
 
110
- ## Cloud Sync
111
- Provider: <provider or "not configured">
112
- Encryption: <enabled/disabled>
113
- Last Sync: <timestamp or "never">
114
- Pending Changes: <count> files modified since last sync
115
- Conflicts: <count>
109
+ ## Sync
110
+ Remote: <remote URL or "not configured">
111
+ Encryption: <enabled/disabled>
112
+ Last Push: <timestamp or "never">
113
+ Last Pull: <timestamp or "never">
114
+ Ahead: <count> commits
115
+ Behind: <count> commits
116
116
  ```
117
117
 
118
118
  ### 4. Health Check
@@ -128,6 +128,5 @@ Analyze the brain's health and provide recommendations:
128
128
  - **"Needs sleep"** — Multiple flat clusters detected, OR many memories in moderate/weak tiers, OR no `_expertise.md` profiles exist despite having 10+ memories. Suggest `/brain:sleep`
129
129
  - **"Low confidence"** — More than 30% of memories have confidence < 0.5. Suggest reviewing and validating uncertain memories.
130
130
  - **"Review overdue"** — More than 10 memories are past their review date. Suggest `/brain:review`
131
- - **"Sync available"** — Cloud sync is not configured. Suggest `/brain:sync login` for cross-device access.
132
- - **"Sync stale"** — Last sync was more than 7 days ago. Suggest `/brain:sync push` or `/brain:sync pull`.
133
- - **"Sync conflicts"** — Unresolved sync conflicts exist. Suggest `/brain:sync resolve`.
131
+ - **"Sync available"** — Git sync is not configured. Suggest `/brain:sync setup` for cross-device access.
132
+ - **"Sync stale"** — Last push was more than 7 days ago. Suggest `/brain:sync push`.