brain-memory 0.1.0-beta.1

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 ADDED
@@ -0,0 +1,361 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ 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 -->';
44
+
45
+ function createRL() {
46
+ return readline.createInterface({
47
+ input: process.stdin,
48
+ output: process.stdout,
49
+ });
50
+ }
51
+
52
+ function ask(rl, question) {
53
+ return new Promise((resolve) => rl.question(question, resolve));
54
+ }
55
+
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
+ 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';
159
+
160
+ const rl = createRL();
161
+
162
+ try {
163
+ // Interactive runtime selection
164
+ if (runtimes.length === 0) {
165
+ console.log(' Which runtimes would you like to install for?\n');
166
+ console.log(' 1) Claude Code');
167
+ console.log(' 2) Gemini CLI');
168
+ console.log(' 3) OpenAI Codex CLI');
169
+ console.log(' 4) All');
170
+ console.log('');
171
+
172
+ const choice = await ask(rl, ' Select (1/2/3/4): ');
173
+ switch (choice.trim()) {
174
+ case '1':
175
+ runtimes = ['claude'];
176
+ break;
177
+ case '2':
178
+ runtimes = ['gemini'];
179
+ break;
180
+ case '3':
181
+ runtimes = ['openai'];
182
+ break;
183
+ case '4':
184
+ runtimes = ['claude', 'gemini', 'openai'];
185
+ break;
186
+ default:
187
+ console.log(' Invalid choice. Defaulting to Claude Code.');
188
+ runtimes = ['claude'];
189
+ }
190
+ }
191
+
192
+ // Interactive scope selection
193
+ if (!scope) {
194
+ console.log('\n Installation scope:\n');
195
+ console.log(' 1) Global — Available in all projects (~/.claude/, ~/.gemini/, ~/.codex/)');
196
+ console.log(' 2) Local — This project only (./.claude/, ./.gemini/, ./.codex/)');
197
+ console.log('');
198
+
199
+ const choice = await ask(rl, ' Select (1/2): ');
200
+ scope = choice.trim() === '2' ? 'local' : 'global';
201
+ }
202
+
203
+ // Initialize .brain structure?
204
+ console.log('');
205
+ const initBrain = await ask(
206
+ rl,
207
+ ' Initialize .brain/ directory in current project? (Y/n): '
208
+ );
209
+
210
+ // Perform installation
211
+ console.log('\n Installing...');
212
+ for (const runtime of runtimes) {
213
+ installForRuntime(runtime, scope);
214
+ }
215
+
216
+ // Initialize .brain if requested
217
+ if (initBrain.trim().toLowerCase() !== 'n') {
218
+ initializeBrain();
219
+ }
220
+
221
+ console.log(`
222
+ ✓ Installation complete!
223
+
224
+ Available commands:
225
+ /brain:init Initialize brain structure
226
+ /brain:memorize Store a new memory
227
+ /brain:remember Recall relevant memories
228
+ /brain:review Spaced repetition review session
229
+ /brain:explore Browse the brain hierarchy
230
+ /brain:consolidate Merge related memories
231
+ /brain:forget Decay or remove memories
232
+ /brain:sunshine Deep forensic memory erasure
233
+ /brain:sleep Full maintenance cycle
234
+ /brain:status Brain overview dashboard
235
+
236
+ Get started by running /brain:init in your agent session.
237
+ `);
238
+ } finally {
239
+ rl.close();
240
+ }
241
+ }
242
+
243
+ function initializeBrain() {
244
+ const brainDir = path.join(process.cwd(), '.brain');
245
+
246
+ if (fs.existsSync(brainDir)) {
247
+ console.log('\n .brain/ already exists, skipping initialization.');
248
+ return;
249
+ }
250
+
251
+ console.log('\n Creating .brain/ directory structure...');
252
+
253
+ const now = new Date().toISOString();
254
+
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 });
259
+ }
260
+
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
+ );
288
+
289
+ // Create associations.json
290
+ fs.writeFileSync(
291
+ path.join(brainDir, 'associations.json'),
292
+ JSON.stringify({ version: 1, edges: {} }, null, 2) + '\n'
293
+ );
294
+
295
+ // Create contexts.json
296
+ fs.writeFileSync(
297
+ path.join(brainDir, 'contexts.json'),
298
+ JSON.stringify({ version: 1, sessions: [] }, null, 2) + '\n'
299
+ );
300
+
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
+ );
306
+
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
+ );
312
+
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'));
318
+ }
319
+
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
+ );
335
+ }
336
+
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
+ );
353
+ }
354
+
355
+ console.log(' .brain/ initialized successfully.');
356
+ }
357
+
358
+ main().catch((err) => {
359
+ console.error('Installation failed:', err.message);
360
+ process.exit(1);
361
+ });
@@ -0,0 +1,153 @@
1
+ # /brain:consolidate — Merge Related Memories
2
+
3
+ You are consolidating memories in the Brain Memory system. Consolidation combines multiple related or weakening memories into a single stronger, more coherent memory — mimicking how human brains merge similar experiences into generalized knowledge.
4
+
5
+ **Target scope:** $ARGUMENTS
6
+
7
+ ## Steps
8
+
9
+ ### 1. Determine Scope
10
+
11
+ - If $ARGUMENTS specifies a category path, consolidate within that subtree
12
+ - If $ARGUMENTS is empty, scan the entire `.brain/` for consolidation candidates
13
+ - If $ARGUMENTS is "auto", perform automatic consolidation based on thresholds
14
+
15
+ ### 2. Find Consolidation Candidates
16
+
17
+ Read `index.json` and identify candidate groups using these criteria:
18
+
19
+ **Automatic candidates (any of):**
20
+ - Memories with effective (decayed) strength below `consolidation_threshold` (default: 0.3)
21
+ - Clusters of 3+ memories in the same directory with overlapping tags
22
+ - Memories with the same type in the same category that are older than 30 days
23
+
24
+ **Compute decayed strength for each:**
25
+ ```
26
+ days_elapsed = (now - last_accessed) / (1000 * 60 * 60 * 24)
27
+ decayed_strength = strength * (decay_rate ^ days_elapsed)
28
+ ```
29
+
30
+ ### 3. Group Related Memories
31
+
32
+ Group candidates by:
33
+ 1. **Path proximity** — memories in the same or nearby directories
34
+ 2. **Tag overlap** — memories sharing 2+ tags
35
+ 3. **Type similarity** — same memory type
36
+ 4. **Temporal proximity** — created within similar time periods
37
+
38
+ Present the proposed groups to the user:
39
+
40
+ ```
41
+ ## Consolidation Candidates
42
+
43
+ ### Group 1: Kubernetes Deployments (professional/companies/acme/projects/)
44
+ - deployment-v1.md (strength: 0.22, type: experience)
45
+ - deployment-v2.md (strength: 0.18, type: experience)
46
+ - k8s-config-issue.md (strength: 0.15, type: learning)
47
+ → Proposed: Merge into "kubernetes-deployment-lessons.md" (strength: 0.75)
48
+
49
+ ### Group 2: TypeScript Learnings (personal/education/)
50
+ - ts-generics.md (strength: 0.28, type: learning)
51
+ - ts-utility-types.md (strength: 0.25, type: learning)
52
+ → Proposed: Merge into "typescript-advanced-types.md" (strength: 0.65)
53
+ ```
54
+
55
+ ### 4. Get User Approval
56
+
57
+ Ask the user which groups to consolidate. They can:
58
+ - Approve all proposed groups
59
+ - Select specific groups
60
+ - Modify groupings
61
+ - Cancel
62
+
63
+ ### 5. Perform Consolidation
64
+
65
+ For each approved group:
66
+
67
+ 1. **Read all source memories** in the group
68
+ 2. **Synthesize** a new consolidated memory that:
69
+ - Preserves all key details and insights from the sources
70
+ - Identifies patterns and evolution across the memories
71
+ - Creates a coherent narrative or structured summary
72
+ - Is more concise than the sum of its parts
73
+ 3. **Calculate new strength**: `max(source_strengths) + 0.15` (capped at 1.0)
74
+ 4. **Set new decay rate**: Use the slowest decay rate from the sources
75
+ 5. **Merge tags**: Union of all source memory tags
76
+ 6. **Set related**: Include all source memory IDs in the `related` field
77
+ 7. **Salience anchoring**: The highest-salience memory in the group is the "anchor" — its framing and key details take priority in the synthesis. Inherit max salience.
78
+ 8. **Confidence**: Inherit the maximum confidence from the group
79
+ 9. **Cognitive type**: Set to `semantic` (consolidation abstracts knowledge)
80
+
81
+ ### 6. Write Consolidated Memory
82
+
83
+ Create the new memory file in the appropriate location (same directory as the majority of sources, or in `_consolidated/` if sources span categories).
84
+
85
+ Use the standard memory format with an additional section:
86
+
87
+ ```markdown
88
+ ---
89
+ id: mem_<date>_<hex>
90
+ type: consolidated
91
+ cognitive_type: semantic
92
+ created: <now>
93
+ last_accessed: <now>
94
+ access_count: 0
95
+ recall_history: []
96
+ strength: <calculated>
97
+ decay_rate: <calculated>
98
+ salience: <max from sources>
99
+ confidence: <max from sources>
100
+ tags: [<merged tags>]
101
+ related: [<all source IDs>]
102
+ consolidated_from: [<source IDs>]
103
+ source: consolidation
104
+ encoding_context:
105
+ project: <project if shared, otherwise omit>
106
+ topics: [<merged key topics>]
107
+ task_type: <most common from sources>
108
+ ---
109
+
110
+ # <Descriptive Title>
111
+
112
+ <Synthesized summary>
113
+
114
+ ## Key Patterns
115
+
116
+ <Patterns identified across the source memories>
117
+
118
+ ## Timeline
119
+
120
+ <Chronological evolution if applicable>
121
+
122
+ ## Source Memories
123
+
124
+ <List of original memories that were merged, with their dates and original titles>
125
+ ```
126
+
127
+ ### 7. Archive Source Memories
128
+
129
+ Move the original source memory files to a `.brain/_archived/` directory (create if needed), preserving their paths as subdirectories. This keeps them recoverable and searchable via `/brain:remember`.
130
+
131
+ Update `index.json`:
132
+ - Remove archived memory entries from `memories`
133
+ - Add the new consolidated memory
134
+ - Update `memory_count`
135
+ - Update `last_updated`
136
+
137
+ Update `_archived/index.json`:
138
+ - Add entries for each archived memory with original metadata and `archived_reason: "consolidation"`
139
+
140
+ Update `associations.json`:
141
+ - Transfer association edges from source memories to the new consolidated memory
142
+ - Remove edges pointing to archived source memories
143
+
144
+ Update `review-queue.json`:
145
+ - Remove entries for archived source memories
146
+ - Add entry for the new consolidated memory if applicable
147
+
148
+ ### 8. Confirm
149
+
150
+ Print a summary:
151
+ - How many memories were consolidated into how many
152
+ - New consolidated memory titles, paths, and strengths
153
+ - Space saved (number of files reduced)
@@ -0,0 +1,79 @@
1
+ # /brain:explore — Browse the Brain Structure
2
+
3
+ You are exploring the Brain Memory system's hierarchical structure. This gives the user a visual overview of their memory landscape.
4
+
5
+ **Target path:** $ARGUMENTS
6
+
7
+ ## Steps
8
+
9
+ ### 1. Determine Scope
10
+
11
+ - If $ARGUMENTS is empty, show the full top-level overview
12
+ - If $ARGUMENTS specifies a category or path (e.g., "professional" or "professional/companies"), explore that subtree
13
+
14
+ ### 2. Read Structure
15
+
16
+ Read the directory structure of `.brain/` (or the specified subtree). For each directory, read its `_meta.json` to get metadata.
17
+
18
+ ### 3. Display Tree View
19
+
20
+ Present the brain structure as a visual tree with statistics:
21
+
22
+ ```
23
+ 🧠 Brain Memory Overview
24
+ Last updated: <timestamp>
25
+ Total memories: <count>
26
+
27
+ .brain/
28
+ ├── professional/ (12 memories)
29
+ │ ├── companies/ (8 memories)
30
+ │ │ ├── acme-corp/ (5 memories)
31
+ │ │ │ ├── projects/ (3 memories)
32
+ │ │ │ │ ├── alpha-launch.md ⚡ 0.82
33
+ │ │ │ │ ├── beta-planning.md ⚡ 0.65
34
+ │ │ │ │ └── tech-debt-review.md ⚡ 0.41
35
+ │ │ │ ├── team-dynamics.md ⚡ 0.70
36
+ │ │ │ └── joining-decision.md ⚡ 0.88
37
+ │ │ └── prev-startup/ (3 memories)
38
+ │ ├── skills/ (3 memories)
39
+ │ └── career/ (1 memory)
40
+ ├── personal/ (6 memories)
41
+ │ ├── education/ (3 memories)
42
+ │ ├── health/ (2 memories)
43
+ │ └── goals/ (1 memory)
44
+ ├── social/ (2 memories)
45
+ │ └── communities/ (2 memories)
46
+ ├── family/ (3 memories)
47
+ │ └── events/ (3 memories)
48
+ └── _consolidated/ (1 memory)
49
+ ```
50
+
51
+ The ⚡ indicator shows the current effective (decayed) strength of each memory.
52
+
53
+ ### 4. Category Summary
54
+
55
+ For the explored scope, provide:
56
+ - **Strongest memory**: Title and path of the highest-strength memory
57
+ - **Most accessed**: Title and path of the most frequently recalled memory
58
+ - **Needs attention**: Memories with decayed strength below the consolidation threshold (0.3)
59
+ - **Recent additions**: Memories created in the last 7 days
60
+
61
+ ### 5. Offer Navigation
62
+
63
+ Suggest next actions:
64
+ - "Use `/brain:explore <subcategory>` to drill deeper"
65
+ - "Use `/brain:remember <query>` to search for specific memories"
66
+ - "Use `/brain:consolidate <category>` to merge weak memories in a category"
67
+ - "Use `/brain:sleep` to reorganize, consolidate, and detect expertise areas"
68
+
69
+ ### 6. Show Expertise (if available)
70
+
71
+ If any directories in the explored scope contain `_expertise.md` files, display a brief expertise summary:
72
+
73
+ ```
74
+ ## Expertise Areas
75
+ 🟢 Expert — professional/skills/flutter/authentication/ (0.85)
76
+ 🔵 Deep Knowledge — professional/skills/react/ (0.68)
77
+ 🟡 Working Knowledge — personal/education/psychology/ (0.45)
78
+ ⚪ Awareness — social/communities/open-source/ (0.28)
79
+ ```