brain-memory 0.1.0-beta.3 → 0.1.0-beta.31

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +339 -0
  2. package/README.md +400 -94
  3. package/SECURITY.md +61 -0
  4. package/assets/brand/README.md +28 -0
  5. package/assets/brand/icon-dark.svg +19 -0
  6. package/assets/brand/icon-light.svg +20 -0
  7. package/assets/brand/linkedin_cover.png +0 -0
  8. package/assets/brand/linkedin_cover_light.png +0 -0
  9. package/assets/brand/mark-dark.svg +19 -0
  10. package/assets/brand/mark-light.svg +20 -0
  11. package/assets/brand/png/icon-dark-1024.png +0 -0
  12. package/assets/brand/png/icon-dark-128.png +0 -0
  13. package/assets/brand/png/icon-dark-256.png +0 -0
  14. package/assets/brand/png/icon-dark-512.png +0 -0
  15. package/assets/brand/png/icon-dark-64.png +0 -0
  16. package/assets/brand/png/icon-light-1024.png +0 -0
  17. package/assets/brand/png/icon-light-128.png +0 -0
  18. package/assets/brand/png/icon-light-256.png +0 -0
  19. package/assets/brand/png/icon-light-512.png +0 -0
  20. package/assets/brand/png/icon-light-64.png +0 -0
  21. package/assets/brand/png/mark-dark-1024.png +0 -0
  22. package/assets/brand/png/mark-light-1024.png +0 -0
  23. package/assets/icon.png +0 -0
  24. package/assets/icon.svg +19 -0
  25. package/bin/brain.js +111 -0
  26. package/bin/cloud-sync.js +150 -0
  27. package/bin/forget.js +122 -0
  28. package/bin/install.js +229 -254
  29. package/bin/memorize.js +458 -0
  30. package/bin/pin.js +44 -0
  31. package/bin/recall.js +259 -0
  32. package/bin/reinforce.js +187 -0
  33. package/bin/session-start.js +298 -0
  34. package/bin/skill.js +67 -0
  35. package/bin/unpin.js +38 -0
  36. package/commands/brain/forget.md +245 -15
  37. package/commands/brain/memorize.md +76 -144
  38. package/commands/brain/pin.md +79 -0
  39. package/commands/brain/remember.md +48 -105
  40. package/commands/brain/skills.md +60 -0
  41. package/commands/brain/sleep.md +69 -28
  42. package/commands/brain/status.md +24 -10
  43. package/commands/brain/sync.md +386 -0
  44. package/package.json +22 -8
  45. package/prompts/antigravity.md +180 -0
  46. package/prompts/claude.md +124 -20
  47. package/prompts/openai.md +124 -20
  48. package/prompts/opencode.md +179 -0
  49. package/src/cloud-sync.js +534 -0
  50. package/src/crypto.js +130 -0
  51. package/src/export-import.js +200 -0
  52. package/src/git-sync.js +444 -0
  53. package/src/index-manager.js +219 -18
  54. package/src/installer.js +444 -0
  55. package/src/pinning.js +124 -0
  56. package/src/scorer.js +45 -11
  57. package/src/skills.js +208 -0
  58. package/src/tfidf.js +520 -0
  59. package/commands/brain/consolidate.md +0 -153
  60. package/commands/brain/explore.md +0 -79
  61. package/commands/brain/init.md +0 -157
  62. package/commands/brain/review.md +0 -130
  63. package/commands/brain/sunshine.md +0 -337
  64. package/hooks/session-end.md +0 -48
  65. package/hooks/session-start.md +0 -48
  66. package/prompts/gemini.md +0 -76
package/bin/recall.js ADDED
@@ -0,0 +1,259 @@
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
+ bm25Search,
27
+ rebuildIndex,
28
+ createSearchIndex,
29
+ isSearchIndexStale,
30
+ } = require('../src/tfidf');
31
+
32
+ const {
33
+ readIndex,
34
+ readAssociations,
35
+ getBrainDir,
36
+ } = require('../src/index-manager');
37
+
38
+ const {
39
+ rankMemories,
40
+ } = require('../src/scorer');
41
+
42
+ // Minimum relevance (or spreading bonus) for a memory to appear in explicit-
43
+ // query results. Filters the zero/near-zero-relevance memories that would
44
+ // otherwise pad the top-N purely on strength — an agent trusting those scores
45
+ // injects noise into its context. Context mode (--context) is exempt: there
46
+ // the query is just a topical hint and strength-ranked padding is intended.
47
+ const RELEVANCE_FLOOR = 0.05;
48
+
49
+ function main() {
50
+ const args = parseArgs(process.argv.slice(2));
51
+
52
+ const brainDir = getBrainDir();
53
+
54
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
55
+ console.error(JSON.stringify({ error: 'Brain not initialized. Reinstall with `npx brain-memory`, or run /brain:sync to create it.' }));
56
+ process.exit(1);
57
+ }
58
+
59
+ // Reindex mode
60
+ if (args.reindex) {
61
+ return handleReindex(brainDir);
62
+ }
63
+
64
+ // Need a query for search
65
+ if (!args.query && !args.context) {
66
+ console.error(JSON.stringify({ error: 'Usage: brain recall "query" or brain recall --context' }));
67
+ process.exit(1);
68
+ }
69
+
70
+ let index;
71
+ try {
72
+ index = readIndex();
73
+ } catch (err) {
74
+ console.error(JSON.stringify({
75
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
76
+ }));
77
+ process.exit(1);
78
+ }
79
+ if (!index || !index.memories || Object.keys(index.memories).length === 0) {
80
+ console.log(JSON.stringify([]));
81
+ return;
82
+ }
83
+
84
+ // Ensure search index exists
85
+ let searchIndex;
86
+ try {
87
+ searchIndex = readSearchIndex(brainDir);
88
+ } catch (_) {
89
+ searchIndex = null;
90
+ }
91
+ // Rebuild when ABSENT *or* STALE. The search index drifts out of sync with
92
+ // index.json whenever memories change outside memorize's addDocument path
93
+ // (forget, sleep/consolidate, sync pull, manual edit) — and a present-but-
94
+ // empty index silently makes every relevance score 0. Compare the doc set,
95
+ // not just presence.
96
+ if (isSearchIndexStale(searchIndex, index)) {
97
+ searchIndex = rebuildIndex(brainDir, index);
98
+ writeSearchIndex(brainDir, searchIndex);
99
+ }
100
+
101
+ // Context mode: build query from project context
102
+ const query = args.context
103
+ ? buildContextQuery(args)
104
+ : args.query;
105
+
106
+ // Compute relevance scores (BM25 — length-normalized, TF-saturated; better
107
+ // than raw TF-IDF cosine at surfacing long, detailed memories under noise).
108
+ const tfidfScores = bm25Search(searchIndex, query);
109
+
110
+ // Build memory list from index
111
+ const memories = Object.entries(index.memories).map(([id, entry]) => ({
112
+ id,
113
+ ...entry,
114
+ }));
115
+
116
+ // Load associations for spreading activation
117
+ let associations;
118
+ try {
119
+ associations = readAssociations();
120
+ } catch (_) {
121
+ associations = null;
122
+ }
123
+
124
+ // Build recall context
125
+ const recallContext = {};
126
+ if (args.project) recallContext.project = args.project;
127
+ if (args.task) recallContext.task_type = args.task;
128
+ if (args.topics) recallContext.topics = args.topics.split(',');
129
+
130
+ // Rank using scorer.js with TF-IDF as the relevance function
131
+ const ranked = rankMemories(
132
+ memories,
133
+ (mem) => tfidfScores[mem.id] || 0,
134
+ {
135
+ associations: associations || undefined,
136
+ recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
137
+ relevanceFloor: args.context ? undefined : RELEVANCE_FLOOR,
138
+ }
139
+ );
140
+
141
+ // Return top N
142
+ const top = args.top || 10;
143
+ const results = ranked.slice(0, top).map((mem) => ({
144
+ id: mem.id,
145
+ title: mem.title || path.basename(mem.path, '.md'),
146
+ path: mem.path,
147
+ type: mem.type,
148
+ score: mem.score,
149
+ relevance: mem.relevance,
150
+ decayed_strength: mem.decayed_strength,
151
+ context_match: mem.context_match,
152
+ spreading_bonus: mem.spreading_bonus,
153
+ confidence: mem.confidence,
154
+ tags: mem.tags,
155
+ }));
156
+
157
+ console.log(JSON.stringify(results, null, 2));
158
+ }
159
+
160
+ /**
161
+ * The TF-IDF search index is stale if it is missing, has a different document
162
+ * count than the live index, or is missing any indexed memory id. Catches the
163
+ * empty-index and add/remove/rename drift cases (in-place same-id body edits
164
+ * are not detected by count alone — acceptable until a version/mtime check).
165
+ */
166
+ /**
167
+ * Rebuild the search index from all memories.
168
+ */
169
+ function handleReindex(brainDir) {
170
+ let index;
171
+ try {
172
+ index = readIndex();
173
+ } catch (err) {
174
+ console.error(JSON.stringify({
175
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
176
+ }));
177
+ process.exit(1);
178
+ }
179
+ if (!index) {
180
+ console.error(JSON.stringify({ error: 'No index.json found.' }));
181
+ process.exit(1);
182
+ }
183
+
184
+ const searchIndex = rebuildIndex(brainDir, index);
185
+ writeSearchIndex(brainDir, searchIndex);
186
+
187
+ console.log(JSON.stringify({
188
+ reindexed: true,
189
+ documents: searchIndex.doc_count,
190
+ terms: Object.keys(searchIndex.df).length,
191
+ }));
192
+ }
193
+
194
+ /**
195
+ * Build a query from context when no explicit query is given.
196
+ * Uses project name and topics as search terms.
197
+ */
198
+ function buildContextQuery(args) {
199
+ const parts = [];
200
+ if (args.project) parts.push(args.project);
201
+ if (args.topics) parts.push(args.topics);
202
+ if (args.task) parts.push(args.task);
203
+
204
+ // If still empty, use a broad query
205
+ return parts.length > 0 ? parts.join(' ') : '*';
206
+ }
207
+
208
+ /**
209
+ * Parse CLI arguments.
210
+ */
211
+ function parseArgs(argv) {
212
+ const args = {
213
+ query: null,
214
+ project: null,
215
+ task: null,
216
+ topics: null,
217
+ top: 10,
218
+ context: false,
219
+ reindex: false,
220
+ };
221
+
222
+ const positional = [];
223
+
224
+ for (let i = 0; i < argv.length; i++) {
225
+ switch (argv[i]) {
226
+ case '--project':
227
+ args.project = argv[++i];
228
+ break;
229
+ case '--task':
230
+ args.task = argv[++i];
231
+ break;
232
+ case '--topics':
233
+ args.topics = argv[++i];
234
+ break;
235
+ case '--top':
236
+ args.top = parseInt(argv[++i], 10);
237
+ break;
238
+ case '--context':
239
+ args.context = true;
240
+ break;
241
+ case '--reindex':
242
+ args.reindex = true;
243
+ break;
244
+ default:
245
+ if (!argv[i].startsWith('--')) {
246
+ positional.push(argv[i]);
247
+ }
248
+ break;
249
+ }
250
+ }
251
+
252
+ if (positional.length > 0) {
253
+ args.query = positional.join(' ');
254
+ }
255
+
256
+ return args;
257
+ }
258
+
259
+ main();
@@ -0,0 +1,187 @@
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
+ let index;
50
+ try {
51
+ index = readIndex();
52
+ } catch (err) {
53
+ console.error(JSON.stringify({
54
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
55
+ }));
56
+ process.exit(1);
57
+ }
58
+
59
+ if (!index) {
60
+ console.error(JSON.stringify({ error: 'Brain not initialized.' }));
61
+ process.exit(1);
62
+ }
63
+
64
+ const now = new Date();
65
+ const nowISO = now.toISOString();
66
+ const reinforced = [];
67
+
68
+ // Apply spaced reinforcement to each memory
69
+ for (const memId of args.memoryIds) {
70
+ const entry = index.memories[memId];
71
+ if (!entry) continue;
72
+
73
+ const lastAccessed = new Date(entry.last_accessed || entry.created);
74
+ const daysSince = (now - lastAccessed) / (1000 * 60 * 60 * 24);
75
+ const accessCount = entry.access_count || 0;
76
+
77
+ // Compute boost
78
+ const oldStrength = entry.strength;
79
+ const newStrength = reinforceStrength(oldStrength, daysSince, accessCount);
80
+ const newDecayRate = improveDecayRate(entry.decay_rate);
81
+
82
+ // Update index entry
83
+ entry.strength = Math.round(newStrength * 1000) / 1000;
84
+ entry.decay_rate = Math.round(newDecayRate * 10000) / 10000;
85
+ entry.last_accessed = nowISO;
86
+ entry.access_count = accessCount + 1;
87
+
88
+ // Update the memory file's frontmatter on disk
89
+ updateMemoryFile(brainDir, entry.path, {
90
+ strength: entry.strength,
91
+ decay_rate: entry.decay_rate,
92
+ last_accessed: nowISO,
93
+ access_count: entry.access_count,
94
+ });
95
+
96
+ reinforced.push({
97
+ id: memId,
98
+ old_strength: oldStrength,
99
+ new_strength: entry.strength,
100
+ boost: Math.round((newStrength - oldStrength) * 1000) / 1000,
101
+ decay_rate: entry.decay_rate,
102
+ });
103
+ }
104
+
105
+ // Save index
106
+ writeIndex(index);
107
+
108
+ // Hebbian co-retrieval: strengthen edges between all pairs
109
+ let edgesReinforced = 0;
110
+ if (args.memoryIds.length > 1) {
111
+ let associations = readAssociations() || { version: 1, edges: {} };
112
+
113
+ for (let i = 0; i < args.memoryIds.length; i++) {
114
+ for (let j = i + 1; j < args.memoryIds.length; j++) {
115
+ const idA = args.memoryIds[i];
116
+ const idB = args.memoryIds[j];
117
+ // Only reinforce if both exist in index
118
+ if (index.memories[idA] && index.memories[idB]) {
119
+ reinforceEdge(associations, idA, idB, 'co_retrieval');
120
+ edgesReinforced++;
121
+ }
122
+ }
123
+ }
124
+
125
+ writeAssociations(associations);
126
+ }
127
+
128
+ console.log(JSON.stringify({
129
+ reinforced,
130
+ edges_reinforced: edgesReinforced,
131
+ }, null, 2));
132
+ }
133
+
134
+ /**
135
+ * Update a memory file's YAML frontmatter fields on disk.
136
+ *
137
+ * @param {string} brainDir - Path to ~/.brain/
138
+ * @param {string} memPath - Relative path to memory file
139
+ * @param {Object} updates - Fields to update in frontmatter
140
+ */
141
+ function updateMemoryFile(brainDir, memPath, updates) {
142
+ const fullPath = path.join(brainDir, memPath);
143
+ try {
144
+ let content = fs.readFileSync(fullPath, 'utf-8');
145
+
146
+ // Find frontmatter boundaries
147
+ const firstDash = content.indexOf('---');
148
+ const secondDash = content.indexOf('---', firstDash + 3);
149
+ if (firstDash === -1 || secondDash === -1) return;
150
+
151
+ let frontmatter = content.slice(firstDash + 3, secondDash);
152
+
153
+ // Update each field in the YAML
154
+ for (const [key, value] of Object.entries(updates)) {
155
+ const regex = new RegExp(`^(${key}:\\s*).*$`, 'm');
156
+ const formatted = typeof value === 'string' ? `"${value}"` : String(value);
157
+ if (regex.test(frontmatter)) {
158
+ frontmatter = frontmatter.replace(regex, `$1${formatted}`);
159
+ }
160
+ }
161
+
162
+ content = content.slice(0, firstDash + 3) + frontmatter + content.slice(secondDash);
163
+ fs.writeFileSync(fullPath, content);
164
+ } catch { /* skip if file not readable/writable */ }
165
+ }
166
+
167
+ /**
168
+ * Parse CLI arguments.
169
+ */
170
+ function parseArgs(argv) {
171
+ const args = {
172
+ memoryIds: [],
173
+ project: null,
174
+ };
175
+
176
+ for (let i = 0; i < argv.length; i++) {
177
+ if (argv[i] === '--project') {
178
+ args.project = argv[++i];
179
+ } else if (!argv[i].startsWith('--')) {
180
+ args.memoryIds.push(argv[i]);
181
+ }
182
+ }
183
+
184
+ return args;
185
+ }
186
+
187
+ main();