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

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
@@ -97,6 +97,37 @@ Then append the contents of the corresponding prompt file to your agent's instru
97
97
  | `/brain:status` | Dashboard with brain health metrics and recommendations |
98
98
  | `/brain:sync [subcommand]` | Cloud sync — push/pull memories to Dropbox, Google Drive, or OneDrive |
99
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.
130
+
100
131
  ## How It Works
101
132
 
102
133
  ### Memory Lifecycle
@@ -425,76 +456,9 @@ Brain configuration lives in `.brain/index.json` under the `config` key:
425
456
  | `association_config.spreading_activation_depth` | 2 | Maximum hops for spreading activation traversal |
426
457
  | `association_config.spreading_activation_decay` | 0.5 | Decay factor per hop during spreading activation |
427
458
 
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
474
-
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
459
+ ## Contributing
492
460
 
493
- After publishing, push the commit and tag:
494
-
495
- ```bash
496
- git push && git push --tags
497
- ```
461
+ Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, project structure, and how to submit changes.
498
462
 
499
463
  ## Inspired By
500
464
 
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);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brain-memory",
3
- "version": "0.1.0-beta.4",
3
+ "version": "0.1.0-beta.5",
4
4
  "description": "A brain-inspired hierarchical memory system for AI coding agents. Deep nested file structure that mimics human memory with time-decay and strength-based recall.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -9,7 +9,11 @@
9
9
  "memory",
10
10
  "ai-agent",
11
11
  "context-engineering",
12
- "hierarchical-memory"
12
+ "hierarchical-memory",
13
+ "neuroscience",
14
+ "spaced-repetition",
15
+ "file-based",
16
+ "slash-commands"
13
17
  ],
14
18
  "author": {
15
19
  "name": "Onur Karali",
@@ -27,7 +31,6 @@
27
31
  "commands/",
28
32
  "prompts/",
29
33
  "templates/",
30
- "hooks/",
31
34
  "src/",
32
35
  "README.md",
33
36
  "LICENSE"
@@ -37,9 +40,9 @@
37
40
  "url": "git+https://github.com/onurkarali/brain.git"
38
41
  },
39
42
  "scripts": {
40
- "test": "node --test test/index-manager.test.js test/scorer.test.js test/functional.test.js test/sunshine.test.js test/stress.test.js test/oauth.test.js test/sync-provider.test.js test/sync-engine.test.js",
43
+ "test": "node --test test/index-manager.test.js test/scorer.test.js test/functional.test.js test/sunshine.test.js test/stress.test.js test/oauth.test.js test/sync-provider.test.js test/sync-engine.test.js test/install.test.js test/prompts.test.js",
41
44
  "prerelease": "npm test",
42
- "release:beta": "npm version prerelease --preid beta && npm publish --tag beta",
45
+ "release:beta": "npm version prerelease --preid beta && npm publish --tag beta && npm dist-tag add brain-memory@$(node -p \"require('./package.json').version\") latest",
43
46
  "release:patch": "npm version patch && npm publish",
44
47
  "release:minor": "npm version minor && npm publish",
45
48
  "release:major": "npm version major && npm publish"
package/prompts/claude.md CHANGED
@@ -60,9 +60,57 @@ Memories store their encoding context (project, topics, task type). During recal
60
60
  - `/brain:status` — Dashboard with brain health overview
61
61
  - `/brain:sync [subcommand]` — Cloud sync: push/pull memories to Dropbox, Google Drive, or OneDrive
62
62
 
63
- ## Auto-Memorize Guidance
64
-
65
- At the end of significant sessions, consider suggesting `/brain:memorize` to the user if important decisions, learnings, or insights occurred during the conversation. Do NOT automatically memorize without the user's awareness.
63
+ ## Session Start Behavior
64
+
65
+ **IMPORTANT: Perform these steps automatically at the beginning of every session.**
66
+
67
+ If `.brain/index.json` exists in the current project:
68
+
69
+ 1. **Read the index** to understand the current brain state (memory count, categories)
70
+ 2. **Identify high-value memories** — the top 3-5 memories by effective strength that are relevant to the current project context
71
+ 3. **Silently internalize** these memories so you can reference them naturally during the session — do NOT dump memory contents
72
+ 4. **Check review queue** — read `.brain/review-queue.json` if it exists for memories due for review
73
+ 5. **Capture session context** — note the current project name, inferred topics, and task type for context-dependent recall
74
+ 6. **Output a brief status** (1-3 lines):
75
+
76
+ If memories are due for review:
77
+ ```
78
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
79
+ 📋 <X> memories due for review — run /brain:review
80
+ ```
81
+
82
+ Otherwise:
83
+ ```
84
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
85
+ ```
86
+
87
+ If any frequently-used memories (access_count >= 3) have confidence < 0.5:
88
+ ```
89
+ ⚠️ <N> frequently-used memories have low confidence — consider verifying
90
+ ```
91
+
92
+ **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. When a situation arises where a past memory is relevant, naturally reference it.
93
+
94
+ ## Session End Behavior
95
+
96
+ When a session is ending or the user signals they are done, evaluate whether the session contained:
97
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
98
+ - **Learnings** — New patterns, debugging insights, API discoveries
99
+ - **Insights** — Realizations about the codebase, project, or process
100
+ - **Experiences** — Significant events like incidents, deployments, milestones
101
+ - **Goals** — New objectives discussed or planned
102
+
103
+ If the session contained meaningful content in any of these categories, suggest:
104
+ ```
105
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
106
+ Run /brain:memorize to capture them before this context is lost.
107
+ ```
108
+
109
+ **Rules:**
110
+ - Do NOT auto-memorize without user consent
111
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
112
+ - Only suggest when there is genuinely valuable context worth preserving
113
+ - Always save session context to `.brain/contexts.json` regardless (append a session summary, keep last 20 entries)
66
114
 
67
115
  ## When Recalling Memories
68
116
 
package/prompts/gemini.md CHANGED
@@ -61,9 +61,57 @@ Commands are available via `/brain:` prefix:
61
61
  - `/brain:status` — Dashboard with brain health overview
62
62
  - `/brain:sync [subcommand]` — Cloud sync: push/pull memories to Dropbox, Google Drive, or OneDrive
63
63
 
64
- ## Auto-Memorize Guidance
65
-
66
- At the end of significant sessions, consider suggesting `/brain:memorize` to the user if important decisions, learnings, or insights occurred during the conversation. Do NOT automatically memorize without the user's awareness.
64
+ ## Session Start Behavior
65
+
66
+ **IMPORTANT: Perform these steps automatically at the beginning of every session.**
67
+
68
+ If `.brain/index.json` exists in the current project:
69
+
70
+ 1. **Read the index** to understand the current brain state (memory count, categories)
71
+ 2. **Identify high-value memories** — the top 3-5 memories by effective strength that are relevant to the current project context
72
+ 3. **Silently internalize** these memories so you can reference them naturally during the session — do NOT dump memory contents
73
+ 4. **Check review queue** — read `.brain/review-queue.json` if it exists for memories due for review
74
+ 5. **Capture session context** — note the current project name, inferred topics, and task type for context-dependent recall
75
+ 6. **Output a brief status** (1-3 lines):
76
+
77
+ If memories are due for review:
78
+ ```
79
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
80
+ 📋 <X> memories due for review — run /brain:review
81
+ ```
82
+
83
+ Otherwise:
84
+ ```
85
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
86
+ ```
87
+
88
+ If any frequently-used memories (access_count >= 3) have confidence < 0.5:
89
+ ```
90
+ ⚠️ <N> frequently-used memories have low confidence — consider verifying
91
+ ```
92
+
93
+ **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. When a situation arises where a past memory is relevant, naturally reference it.
94
+
95
+ ## Session End Behavior
96
+
97
+ When a session is ending or the user signals they are done, evaluate whether the session contained:
98
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
99
+ - **Learnings** — New patterns, debugging insights, API discoveries
100
+ - **Insights** — Realizations about the codebase, project, or process
101
+ - **Experiences** — Significant events like incidents, deployments, milestones
102
+ - **Goals** — New objectives discussed or planned
103
+
104
+ If the session contained meaningful content in any of these categories, suggest:
105
+ ```
106
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
107
+ Run /brain:memorize to capture them before this context is lost.
108
+ ```
109
+
110
+ **Rules:**
111
+ - Do NOT auto-memorize without user consent
112
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
113
+ - Only suggest when there is genuinely valuable context worth preserving
114
+ - Always save session context to `.brain/contexts.json` regardless (append a session summary, keep last 20 entries)
67
115
 
68
116
  ## When Recalling Memories
69
117
 
package/prompts/openai.md CHANGED
@@ -61,9 +61,57 @@ Brain skills are available via `/brain-` prefix:
61
61
  - `/brain-status` — Dashboard with brain health overview
62
62
  - `/brain-sync [subcommand]` — Cloud sync: push/pull memories to Dropbox, Google Drive, or OneDrive
63
63
 
64
- ## Auto-Memorize Guidance
65
-
66
- At the end of significant sessions, consider suggesting `/brain-memorize` to the user if important decisions, learnings, or insights occurred during the conversation. Do NOT automatically memorize without the user's awareness.
64
+ ## Session Start Behavior
65
+
66
+ **IMPORTANT: Perform these steps automatically at the beginning of every session.**
67
+
68
+ If `.brain/index.json` exists in the current project:
69
+
70
+ 1. **Read the index** to understand the current brain state (memory count, categories)
71
+ 2. **Identify high-value memories** — the top 3-5 memories by effective strength that are relevant to the current project context
72
+ 3. **Silently internalize** these memories so you can reference them naturally during the session — do NOT dump memory contents
73
+ 4. **Check review queue** — read `.brain/review-queue.json` if it exists for memories due for review
74
+ 5. **Capture session context** — note the current project name, inferred topics, and task type for context-dependent recall
75
+ 6. **Output a brief status** (1-3 lines):
76
+
77
+ If memories are due for review:
78
+ ```
79
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
80
+ 📋 <X> memories due for review — run /brain-review
81
+ ```
82
+
83
+ Otherwise:
84
+ ```
85
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
86
+ ```
87
+
88
+ If any frequently-used memories (access_count >= 3) have confidence < 0.5:
89
+ ```
90
+ ⚠️ <N> frequently-used memories have low confidence — consider verifying
91
+ ```
92
+
93
+ **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. When a situation arises where a past memory is relevant, naturally reference it.
94
+
95
+ ## Session End Behavior
96
+
97
+ When a session is ending or the user signals they are done, evaluate whether the session contained:
98
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
99
+ - **Learnings** — New patterns, debugging insights, API discoveries
100
+ - **Insights** — Realizations about the codebase, project, or process
101
+ - **Experiences** — Significant events like incidents, deployments, milestones
102
+ - **Goals** — New objectives discussed or planned
103
+
104
+ If the session contained meaningful content in any of these categories, suggest:
105
+ ```
106
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
107
+ Run /brain-memorize to capture them before this context is lost.
108
+ ```
109
+
110
+ **Rules:**
111
+ - Do NOT auto-memorize without user consent
112
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
113
+ - Only suggest when there is genuinely valuable context worth preserving
114
+ - Always save session context to `.brain/contexts.json` regardless (append a session summary, keep last 20 entries)
67
115
 
68
116
  ## When Recalling Memories
69
117
 
@@ -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
+ };
@@ -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
@@ -1,48 +0,0 @@
1
- # Brain Memory — Session Start Hook
2
-
3
- This hook is triggered at the start of a coding session. Its purpose is to load relevant context from the brain memory system and capture session context for context-dependent recall.
4
-
5
- ## Behavior
6
-
7
- At session start, if `.brain/index.json` exists:
8
-
9
- 1. **Read the index** to understand the current brain state
10
- 2. **Identify high-value memories** — the top 3-5 memories by effective strength that are relevant to the current project
11
- 3. **Silently load context** — internalize these memories so you can reference them naturally during the session
12
- 4. **Do NOT dump memories** — do not print memory contents at session start unless the user asks
13
-
14
- ### Context Capture
15
-
16
- Capture the current session context for context-dependent recall:
17
- - **Project name**: from the current working directory or project config
18
- - **Topics**: inferred from recent files, open issues, or conversation
19
- - **Task type**: will be determined as the session progresses
20
-
21
- This context is used by `/brain:remember` to boost memories that were encoded in a similar context.
22
-
23
- ### Review Queue Check
24
-
25
- Read `.brain/review-queue.json` if it exists. If there are memories due for review:
26
-
27
- ```
28
- 🧠 Brain active — <N> memories loaded (<M> in current project context)
29
- 📋 <X> memories due for review — run /brain:review
30
- ```
31
-
32
- Otherwise:
33
-
34
- ```
35
- 🧠 Brain active — <N> memories loaded (<M> in current project context)
36
- ```
37
-
38
- ### Low-Confidence Alert
39
-
40
- If any frequently-used memories (access_count >= 3) have confidence < 0.5, briefly note:
41
-
42
- ```
43
- ⚠️ <N> frequently-used memories have low confidence — consider verifying
44
- ```
45
-
46
- **The goal is ambient awareness** — you should know about important past decisions, learnings, and preferences without explicitly reciting them. If a situation arises where a past memory is relevant, naturally reference it.
47
-
48
- Keep the status output to 1-3 lines. The user can run `/brain:status` for details.