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/recall.js ADDED
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Brain Memory — Deterministic Recall Engine
5
+ *
6
+ * CLI tool that replaces agent-driven scoring with deterministic computation.
7
+ * The agent calls this instead of manually computing the v4 formula.
8
+ *
9
+ * Usage:
10
+ * brain-recall "async race conditions"
11
+ * brain-recall "database pooling" --project my-app --task implementing --top 5
12
+ * brain-recall --context # Session-start mode: auto-detect context
13
+ * brain-recall --reindex # Rebuild search index from all memories
14
+ *
15
+ * Output: JSON array of scored results, sorted by score descending.
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const os = require('os');
21
+
22
+ const {
23
+ readSearchIndex,
24
+ writeSearchIndex,
25
+ search,
26
+ rebuildIndex,
27
+ createSearchIndex,
28
+ } = require('../src/tfidf');
29
+
30
+ const {
31
+ readIndex,
32
+ readAssociations,
33
+ getBrainDir,
34
+ } = require('../src/index-manager');
35
+
36
+ const {
37
+ rankMemories,
38
+ } = require('../src/scorer');
39
+
40
+ function main() {
41
+ const args = parseArgs(process.argv.slice(2));
42
+
43
+ const brainDir = getBrainDir();
44
+
45
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
46
+ console.error(JSON.stringify({ error: 'Brain not initialized. Run /brain:init first.' }));
47
+ process.exit(1);
48
+ }
49
+
50
+ // Reindex mode
51
+ if (args.reindex) {
52
+ return handleReindex(brainDir);
53
+ }
54
+
55
+ // Need a query for search
56
+ if (!args.query && !args.context) {
57
+ console.error(JSON.stringify({ error: 'Usage: brain-recall "query" or brain-recall --context' }));
58
+ process.exit(1);
59
+ }
60
+
61
+ const index = readIndex();
62
+ if (!index || !index.memories || Object.keys(index.memories).length === 0) {
63
+ console.log(JSON.stringify([]));
64
+ return;
65
+ }
66
+
67
+ // Ensure search index exists
68
+ let searchIndex = readSearchIndex(brainDir);
69
+ if (!searchIndex) {
70
+ searchIndex = rebuildIndex(brainDir, index);
71
+ writeSearchIndex(brainDir, searchIndex);
72
+ }
73
+
74
+ // Context mode: build query from project context
75
+ const query = args.context
76
+ ? buildContextQuery(args)
77
+ : args.query;
78
+
79
+ // Compute TF-IDF relevance scores
80
+ const tfidfScores = search(searchIndex, query);
81
+
82
+ // Build memory list from index
83
+ const memories = Object.entries(index.memories).map(([id, entry]) => ({
84
+ id,
85
+ ...entry,
86
+ }));
87
+
88
+ // Load associations for spreading activation
89
+ const associations = readAssociations();
90
+
91
+ // Build recall context
92
+ const recallContext = {};
93
+ if (args.project) recallContext.project = args.project;
94
+ if (args.task) recallContext.task_type = args.task;
95
+ if (args.topics) recallContext.topics = args.topics.split(',');
96
+
97
+ // Rank using scorer.js with TF-IDF as the relevance function
98
+ const ranked = rankMemories(
99
+ memories,
100
+ (mem) => tfidfScores[mem.id] || 0,
101
+ {
102
+ associations: associations || undefined,
103
+ recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
104
+ }
105
+ );
106
+
107
+ // Return top N
108
+ const top = args.top || 10;
109
+ const results = ranked.slice(0, top).map((mem) => ({
110
+ id: mem.id,
111
+ title: mem.title || path.basename(mem.path, '.md'),
112
+ path: mem.path,
113
+ type: mem.type,
114
+ score: mem.score,
115
+ relevance: mem.relevance,
116
+ decayed_strength: mem.decayed_strength,
117
+ context_match: mem.context_match,
118
+ spreading_bonus: mem.spreading_bonus,
119
+ confidence: mem.confidence,
120
+ tags: mem.tags,
121
+ }));
122
+
123
+ console.log(JSON.stringify(results, null, 2));
124
+ }
125
+
126
+ /**
127
+ * Rebuild the search index from all memories.
128
+ */
129
+ function handleReindex(brainDir) {
130
+ const index = readIndex();
131
+ if (!index) {
132
+ console.error(JSON.stringify({ error: 'No index.json found.' }));
133
+ process.exit(1);
134
+ }
135
+
136
+ const searchIndex = rebuildIndex(brainDir, index);
137
+ writeSearchIndex(brainDir, searchIndex);
138
+
139
+ console.log(JSON.stringify({
140
+ reindexed: true,
141
+ documents: searchIndex.doc_count,
142
+ terms: Object.keys(searchIndex.df).length,
143
+ }));
144
+ }
145
+
146
+ /**
147
+ * Build a query from context when no explicit query is given.
148
+ * Uses project name and topics as search terms.
149
+ */
150
+ function buildContextQuery(args) {
151
+ const parts = [];
152
+ if (args.project) parts.push(args.project);
153
+ if (args.topics) parts.push(args.topics);
154
+ if (args.task) parts.push(args.task);
155
+
156
+ // If still empty, use a broad query
157
+ return parts.length > 0 ? parts.join(' ') : '*';
158
+ }
159
+
160
+ /**
161
+ * Parse CLI arguments.
162
+ */
163
+ function parseArgs(argv) {
164
+ const args = {
165
+ query: null,
166
+ project: null,
167
+ task: null,
168
+ topics: null,
169
+ top: 10,
170
+ context: false,
171
+ reindex: false,
172
+ };
173
+
174
+ const positional = [];
175
+
176
+ for (let i = 0; i < argv.length; i++) {
177
+ switch (argv[i]) {
178
+ case '--project':
179
+ args.project = argv[++i];
180
+ break;
181
+ case '--task':
182
+ args.task = argv[++i];
183
+ break;
184
+ case '--topics':
185
+ args.topics = argv[++i];
186
+ break;
187
+ case '--top':
188
+ args.top = parseInt(argv[++i], 10);
189
+ break;
190
+ case '--context':
191
+ args.context = true;
192
+ break;
193
+ case '--reindex':
194
+ args.reindex = true;
195
+ break;
196
+ default:
197
+ if (!argv[i].startsWith('--')) {
198
+ positional.push(argv[i]);
199
+ }
200
+ break;
201
+ }
202
+ }
203
+
204
+ if (positional.length > 0) {
205
+ args.query = positional.join(' ');
206
+ }
207
+
208
+ return args;
209
+ }
210
+
211
+ main();
@@ -0,0 +1,179 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Brain Memory — Deterministic Reinforcement Engine
5
+ *
6
+ * Applies spaced reinforcement and Hebbian co-retrieval strengthening
7
+ * to recalled memories. The agent calls this after presenting recall
8
+ * results instead of manually updating frontmatter.
9
+ *
10
+ * Usage:
11
+ * brain-reinforce mem_123 mem_456 mem_789
12
+ * brain-reinforce mem_123 --project my-app
13
+ *
14
+ * Effects:
15
+ * - Spaced reinforcement boost to each memory's strength
16
+ * - Decay rate improvement (more forgetting-resistant)
17
+ * - access_count++, last_accessed = now
18
+ * - Hebbian co-retrieval: strengthens association edges between all pairs
19
+ * - Updates index.json, associations.json, and memory files
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const os = require('os');
25
+
26
+ const {
27
+ readIndex,
28
+ writeIndex,
29
+ readAssociations,
30
+ writeAssociations,
31
+ reinforceEdge,
32
+ getBrainDir,
33
+ } = require('../src/index-manager');
34
+
35
+ const {
36
+ reinforceStrength,
37
+ improveDecayRate,
38
+ } = require('../src/scorer');
39
+
40
+ function main() {
41
+ const args = parseArgs(process.argv.slice(2));
42
+
43
+ if (args.memoryIds.length === 0) {
44
+ console.error(JSON.stringify({ error: 'Usage: brain-reinforce <mem_id1> [mem_id2] ...' }));
45
+ process.exit(1);
46
+ }
47
+
48
+ const brainDir = getBrainDir();
49
+ const index = readIndex();
50
+
51
+ if (!index) {
52
+ console.error(JSON.stringify({ error: 'Brain not initialized.' }));
53
+ process.exit(1);
54
+ }
55
+
56
+ const now = new Date();
57
+ const nowISO = now.toISOString();
58
+ const reinforced = [];
59
+
60
+ // Apply spaced reinforcement to each memory
61
+ for (const memId of args.memoryIds) {
62
+ const entry = index.memories[memId];
63
+ if (!entry) continue;
64
+
65
+ const lastAccessed = new Date(entry.last_accessed || entry.created);
66
+ const daysSince = (now - lastAccessed) / (1000 * 60 * 60 * 24);
67
+ const accessCount = entry.access_count || 0;
68
+
69
+ // Compute boost
70
+ const oldStrength = entry.strength;
71
+ const newStrength = reinforceStrength(oldStrength, daysSince, accessCount);
72
+ const newDecayRate = improveDecayRate(entry.decay_rate);
73
+
74
+ // Update index entry
75
+ entry.strength = Math.round(newStrength * 1000) / 1000;
76
+ entry.decay_rate = Math.round(newDecayRate * 10000) / 10000;
77
+ entry.last_accessed = nowISO;
78
+ entry.access_count = accessCount + 1;
79
+
80
+ // Update the memory file's frontmatter on disk
81
+ updateMemoryFile(brainDir, entry.path, {
82
+ strength: entry.strength,
83
+ decay_rate: entry.decay_rate,
84
+ last_accessed: nowISO,
85
+ access_count: entry.access_count,
86
+ });
87
+
88
+ reinforced.push({
89
+ id: memId,
90
+ old_strength: oldStrength,
91
+ new_strength: entry.strength,
92
+ boost: Math.round((newStrength - oldStrength) * 1000) / 1000,
93
+ decay_rate: entry.decay_rate,
94
+ });
95
+ }
96
+
97
+ // Save index
98
+ writeIndex(index);
99
+
100
+ // Hebbian co-retrieval: strengthen edges between all pairs
101
+ let edgesReinforced = 0;
102
+ if (args.memoryIds.length > 1) {
103
+ let associations = readAssociations() || { version: 1, edges: {} };
104
+
105
+ for (let i = 0; i < args.memoryIds.length; i++) {
106
+ for (let j = i + 1; j < args.memoryIds.length; j++) {
107
+ const idA = args.memoryIds[i];
108
+ const idB = args.memoryIds[j];
109
+ // Only reinforce if both exist in index
110
+ if (index.memories[idA] && index.memories[idB]) {
111
+ reinforceEdge(associations, idA, idB, 'co_retrieval');
112
+ edgesReinforced++;
113
+ }
114
+ }
115
+ }
116
+
117
+ writeAssociations(associations);
118
+ }
119
+
120
+ console.log(JSON.stringify({
121
+ reinforced,
122
+ edges_reinforced: edgesReinforced,
123
+ }, null, 2));
124
+ }
125
+
126
+ /**
127
+ * Update a memory file's YAML frontmatter fields on disk.
128
+ *
129
+ * @param {string} brainDir - Path to ~/.brain/
130
+ * @param {string} memPath - Relative path to memory file
131
+ * @param {Object} updates - Fields to update in frontmatter
132
+ */
133
+ function updateMemoryFile(brainDir, memPath, updates) {
134
+ const fullPath = path.join(brainDir, memPath);
135
+ try {
136
+ let content = fs.readFileSync(fullPath, 'utf-8');
137
+
138
+ // Find frontmatter boundaries
139
+ const firstDash = content.indexOf('---');
140
+ const secondDash = content.indexOf('---', firstDash + 3);
141
+ if (firstDash === -1 || secondDash === -1) return;
142
+
143
+ let frontmatter = content.slice(firstDash + 3, secondDash);
144
+
145
+ // Update each field in the YAML
146
+ for (const [key, value] of Object.entries(updates)) {
147
+ const regex = new RegExp(`^(${key}:\\s*).*$`, 'm');
148
+ const formatted = typeof value === 'string' ? `"${value}"` : String(value);
149
+ if (regex.test(frontmatter)) {
150
+ frontmatter = frontmatter.replace(regex, `$1${formatted}`);
151
+ }
152
+ }
153
+
154
+ content = content.slice(0, firstDash + 3) + frontmatter + content.slice(secondDash);
155
+ fs.writeFileSync(fullPath, content);
156
+ } catch { /* skip if file not readable/writable */ }
157
+ }
158
+
159
+ /**
160
+ * Parse CLI arguments.
161
+ */
162
+ function parseArgs(argv) {
163
+ const args = {
164
+ memoryIds: [],
165
+ project: null,
166
+ };
167
+
168
+ for (let i = 0; i < argv.length; i++) {
169
+ if (argv[i] === '--project') {
170
+ args.project = argv[++i];
171
+ } else if (!argv[i].startsWith('--')) {
172
+ args.memoryIds.push(argv[i]);
173
+ }
174
+ }
175
+
176
+ return args;
177
+ }
178
+
179
+ main();
@@ -9,7 +9,7 @@ You are consolidating memories in the Brain Memory system. Consolidation combine
9
9
  ### 1. Determine Scope
10
10
 
11
11
  - If $ARGUMENTS specifies a category path, consolidate within that subtree
12
- - If $ARGUMENTS is empty, scan the entire `.brain/` for consolidation candidates
12
+ - If $ARGUMENTS is empty, scan the entire `~/.brain/` for consolidation candidates
13
13
  - If $ARGUMENTS is "auto", perform automatic consolidation based on thresholds
14
14
 
15
15
  ### 2. Find Consolidation Candidates
@@ -126,7 +126,7 @@ encoding_context:
126
126
 
127
127
  ### 7. Archive Source Memories
128
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`.
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
130
 
131
131
  Update `index.json`:
132
132
  - Remove archived memory entries from `memories`
@@ -13,7 +13,7 @@ You are exploring the Brain Memory system's hierarchical structure. This gives t
13
13
 
14
14
  ### 2. Read Structure
15
15
 
16
- Read the directory structure of `.brain/` (or the specified subtree). For each directory, read its `_meta.json` to get metadata.
16
+ Read the directory structure of `~/.brain/` (or the specified subtree). For each directory, read its `_meta.json` to get metadata.
17
17
 
18
18
  ### 3. Display Tree View
19
19
 
@@ -24,7 +24,7 @@ Present the brain structure as a visual tree with statistics:
24
24
  Last updated: <timestamp>
25
25
  Total memories: <count>
26
26
 
27
- .brain/
27
+ ~/.brain/
28
28
  ├── professional/ (12 memories)
29
29
  │ ├── companies/ (8 memories)
30
30
  │ │ ├── acme-corp/ (5 memories)
@@ -64,8 +64,8 @@ The user must explicitly choose an action. Default to **archive** (safest).
64
64
  ### 5. Execute
65
65
 
66
66
  **Archive:**
67
- - Move memory files to `.brain/_archived/<original-path>/`
68
- - Add entry to `.brain/_archived/index.json` with all original metadata:
67
+ - Move memory files to `~/.brain/_archived/<original-path>/`
68
+ - Add entry to `~/.brain/_archived/index.json` with all original metadata:
69
69
  ```json
70
70
  {
71
71
  "<memory_id>": {
@@ -1,12 +1,12 @@
1
1
  # /brain:init — Initialize Brain Memory Structure
2
2
 
3
- You are initializing the Brain Memory system. This creates a `.brain/` directory that serves as a hierarchical, file-system-based memory store inspired by human cognition.
3
+ You are initializing the Brain Memory system. This creates a `~/.brain/` directory that serves as a hierarchical, file-system-based memory store inspired by human cognition.
4
4
 
5
5
  ## Steps
6
6
 
7
7
  ### 1. Check for Existing Brain
8
8
 
9
- Check if `.brain/` directory already exists in the current project root.
9
+ Check if `~/.brain/` directory already exists in the user's home directory.
10
10
 
11
11
  - If it exists, inform the user and ask if they want to reset or keep it.
12
12
  - If not, proceed with creation.
@@ -16,7 +16,7 @@ Check if `.brain/` directory already exists in the current project root.
16
16
  Create the following structure:
17
17
 
18
18
  ```
19
- .brain/
19
+ ~/.brain/
20
20
  ├── index.json
21
21
  ├── associations.json
22
22
  ├── contexts.json
@@ -131,7 +131,7 @@ If the user provides custom categories or subcategories, create them with approp
131
131
 
132
132
  ### 10. Add .brain to .gitignore (Optional)
133
133
 
134
- Ask the user if they want `.brain/` added to `.gitignore` (some users may want to track their memory in git, others may not).
134
+ Ask the user if they want `~/.brain/` added to `.gitignore` (some users may want to track their memory in git, others may not).
135
135
 
136
136
  ### 11. Confirm
137
137
 
@@ -147,11 +147,3 @@ Print a summary of what was created, including the full tree structure. Inform t
147
147
  - `/brain:status` — View brain overview
148
148
  - `/brain:review` — Spaced repetition review of memories due for reinforcement
149
149
 
150
- ### Migration Note
151
-
152
- If upgrading an existing v1 brain, the first `/brain:sleep` after upgrade will run a **Migration phase** (Phase 0) that:
153
- - Creates `associations.json` from existing `related` fields
154
- - Creates `contexts.json`, `review-queue.json`, and `_archived/index.json`
155
- - Backfills `recall_history` from `access_count` (using `last_accessed` as sole entry)
156
- - Sets default values for new frontmatter fields (`cognitive_type: semantic`, `salience: 0.5`, `confidence: 0.8`)
157
- - Bumps `index.json` version to 2
@@ -1,6 +1,6 @@
1
1
  # /brain:memorize — Store a New Memory
2
2
 
3
- You are storing a new memory in the Brain Memory system. Memories are filed into the `.brain/` hierarchical directory structure based on their semantic content.
3
+ You are storing a new memory in the Brain Memory system. Memories are filed into the `~/.brain/` hierarchical directory structure based on their semantic content.
4
4
 
5
5
  **User input:** $ARGUMENTS
6
6
 
@@ -49,7 +49,7 @@ For each memory to store, determine:
49
49
 
50
50
  ### 3. Determine File Path (Categorization)
51
51
 
52
- Choose the most appropriate path in the `.brain/` hierarchy. This is the most critical step.
52
+ Choose the most appropriate path in the `~/.brain/` hierarchy. This is the most critical step.
53
53
 
54
54
  **Rules for path selection:**
55
55
  1. Start with the top-level category: `professional/`, `personal/`, `social/`, `family/`
@@ -118,12 +118,12 @@ encoding_context:
118
118
 
119
119
  ### 6. Update Index
120
120
 
121
- Read `.brain/index.json` and add an entry:
121
+ Read `~/.brain/index.json` and add an entry:
122
122
 
123
123
  ```json
124
124
  {
125
125
  "<memory_id>": {
126
- "path": "<relative path from .brain/>",
126
+ "path": "<relative path from ~/.brain/>",
127
127
  "title": "<short title>",
128
128
  "type": "<memory_type>",
129
129
  "cognitive_type": "<episodic|semantic|procedural>",
@@ -148,7 +148,7 @@ Increment `memory_count`. Update `last_updated`.
148
148
 
149
149
  ### 7. Update Associations
150
150
 
151
- Read `.brain/associations.json` and create edges for this memory:
151
+ Read `~/.brain/associations.json` and create edges for this memory:
152
152
 
153
153
  **A. Explicit `related` links:** For each ID in the `related` field, create an edge with weight 0.20 and origin `manual`.
154
154
 
@@ -158,13 +158,28 @@ Use the `reinforceEdge()` function — if an edge already exists (e.g., the rela
158
158
 
159
159
  Write the updated `associations.json`.
160
160
 
161
- ### 8. Update _meta.json
161
+ ### 8. Update Search Index
162
+
163
+ If `~/.brain/search-index.json` exists, update it so the new memory is discoverable by the recall engine. Run:
164
+
165
+ ```bash
166
+ node <brain-memory-install-path>/bin/recall.js --reindex
167
+ ```
168
+
169
+ Or if globally installed:
170
+ ```bash
171
+ brain-recall --reindex
172
+ ```
173
+
174
+ This rebuilds the TF-IDF search index from all memories, enabling deterministic semantic search via the recall engine.
175
+
176
+ ### 9. Update _meta.json
162
177
 
163
178
  Update the `_meta.json` in each directory along the path:
164
179
  - Increment `memory_count`
165
180
  - Add new subcategories to the `subcategories` array if any were created
166
181
 
167
- ### 9. Confirm
182
+ ### 10. Confirm
168
183
 
169
184
  Print what was stored:
170
185
  - Memory title and ID