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

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 +319 -0
  2. package/README.md +379 -95
  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 +251 -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 +22 -9
  57. package/src/skills.js +208 -0
  58. package/src/tfidf.js +501 -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
@@ -0,0 +1,298 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain session-start — budget-aware working-memory payload (CoALA Phase 0).
5
+ *
6
+ * One deterministic call returning everything the agent should internalize at
7
+ * session start, bounded by the working-memory token budget in config.json so
8
+ * Brain can never bloat the host's context window.
9
+ *
10
+ * Usage:
11
+ * brain session-start [--project P] [--topics a,b] [--task T] [--top N]
12
+ *
13
+ * Output (JSON):
14
+ * {
15
+ * memory_count, pinned[], skills_index[], context_recall[],
16
+ * due_for_review, low_confidence_alerts[], budget{}
17
+ * }
18
+ *
19
+ * pinned[] (Phase 1) and skills_index[] (Phase 2) are present but empty here;
20
+ * the budget framework already accounts for them so later phases just fill in.
21
+ */
22
+
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+
26
+ const {
27
+ readSearchIndex,
28
+ writeSearchIndex,
29
+ search,
30
+ bm25Search,
31
+ rebuildIndex,
32
+ isSearchIndexStale,
33
+ } = require('../src/tfidf');
34
+
35
+ const {
36
+ readIndex,
37
+ readAssociations,
38
+ readReviewQueue,
39
+ readConfig,
40
+ getBrainDir,
41
+ } = require('../src/index-manager');
42
+
43
+ const { rankMemories } = require('../src/scorer');
44
+ const { advertisedSummaries } = require('../src/skills');
45
+
46
+ function parseArgs(argv) {
47
+ const args = { project: null, topics: null, task: null, top: 5 };
48
+ for (let i = 0; i < argv.length; i++) {
49
+ switch (argv[i]) {
50
+ case '--project': args.project = argv[++i]; break;
51
+ case '--topics': args.topics = argv[++i]; break;
52
+ case '--task': args.task = argv[++i]; break;
53
+ case '--top': args.top = parseInt(argv[++i], 10) || 5; break;
54
+ default: break;
55
+ }
56
+ }
57
+ return args;
58
+ }
59
+
60
+ /** chars/4 token estimate; falls back to the title line for pre-Phase-0 entries. */
61
+ function estimateTokens(entry) {
62
+ if (typeof entry.token_estimate === 'number') return entry.token_estimate;
63
+ return Math.ceil(((entry.title || '').length + 8) / 4);
64
+ }
65
+
66
+ /**
67
+ * Tier B §10.4 — reorder an importance-sorted list so the top items land at the
68
+ * edges (start + end), where models attend best, leaving the middle for lower
69
+ * ranks. Deterministic. e.g. [1,2,3,4,5] → [1,3,5,4,2].
70
+ */
71
+ function edgeOrder(arr) {
72
+ const front = [];
73
+ const back = [];
74
+ arr.forEach((item, i) => { if (i % 2 === 0) front.push(item); else back.unshift(item); });
75
+ return front.concat(back);
76
+ }
77
+
78
+ /** Read a memory file's body (content after the frontmatter block). */
79
+ function readMemoryBody(brainDir, memPath) {
80
+ try {
81
+ const content = fs.readFileSync(path.join(brainDir, memPath), 'utf-8');
82
+ const first = content.indexOf('---');
83
+ const second = content.indexOf('---', first + 3);
84
+ if (first !== -1 && second !== -1) return content.slice(second + 3).trim();
85
+ return content.trim();
86
+ } catch (_) {
87
+ return '';
88
+ }
89
+ }
90
+
91
+ function buildContextQuery(args) {
92
+ const parts = [];
93
+ if (args.project) parts.push(args.project);
94
+ if (args.topics) parts.push(args.topics);
95
+ if (args.task) parts.push(args.task);
96
+ return parts.length > 0 ? parts.join(' ') : '*';
97
+ }
98
+
99
+ /**
100
+ * Compute the session-start payload for the brain at `projectRoot` (undefined =
101
+ * the real ~/.brain). Pure: performs no console output and never calls exit, so
102
+ * it is directly unit-testable.
103
+ *
104
+ * @param {string} [projectRoot] - Filesystem root whose .brain/ to read
105
+ * @param {Object} [args] - { project, topics, task, top }
106
+ * @returns {Object} The session-start payload
107
+ */
108
+ function computeSessionStart(projectRoot, args = {}) {
109
+ const top = args.top || 5;
110
+ const brainDir = getBrainDir(projectRoot);
111
+ const config = readConfig(projectRoot);
112
+ const cap = config.working_memory_budget_tokens;
113
+
114
+ const empty = {
115
+ memory_count: 0,
116
+ pinned: [], // Phase 1: always-present semantic tier
117
+ skills_index: [], // Phase 2: procedural skill summaries
118
+ context_recall: [],
119
+ due_for_review: 0,
120
+ low_confidence_alerts: [],
121
+ budget: { cap, recall_cap: config.recall_budget_tokens, used: 0, included: 0, excluded: 0 },
122
+ };
123
+
124
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) return empty;
125
+
126
+ const index = readIndex(projectRoot);
127
+ if (!index || !index.memories) return empty;
128
+
129
+ // Note: we proceed even with zero memories — pins and skills are independent
130
+ // of episodic memory and should still be surfaced.
131
+ const memoryCount = Object.keys(index.memories).length;
132
+
133
+ // --- Context recall (deterministic, reuses the recall engine) ---
134
+ // Rebuild when ABSENT *or* STALE — session-start is the first thing a session
135
+ // runs (e.g. right after a `sync pull`), so it is the most likely path to hit
136
+ // a search index that has drifted out of sync with index.json. A present-but-
137
+ // stale index silently zeroes every relevance score (matches recall.js).
138
+ let searchIndex = null;
139
+ try { searchIndex = readSearchIndex(brainDir); } catch (_) { searchIndex = null; }
140
+ if (isSearchIndexStale(searchIndex, index)) {
141
+ searchIndex = rebuildIndex(brainDir, index);
142
+ writeSearchIndex(brainDir, searchIndex);
143
+ }
144
+
145
+ const tfidfScores = bm25Search(searchIndex, buildContextQuery(args));
146
+ const memories = Object.entries(index.memories).map(([id, entry]) => ({ id, ...entry }));
147
+
148
+ let associations = null;
149
+ try { associations = readAssociations(projectRoot); } catch (_) { associations = null; }
150
+
151
+ const recallContext = {};
152
+ if (args.project) recallContext.project = args.project;
153
+ if (args.task) recallContext.task_type = args.task;
154
+ if (args.topics) recallContext.topics = String(args.topics).split(',');
155
+
156
+ const ranked = rankMemories(
157
+ memories,
158
+ (mem) => tfidfScores[mem.id] || 0,
159
+ {
160
+ associations: associations || undefined,
161
+ recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
162
+ }
163
+ );
164
+
165
+ // --- Pinned tier (CoALA Phase 1): always present, scope-filtered, budget-capped ---
166
+ // The index entry is the source of truth (pinned.json is a maintained cache);
167
+ // scanning the index here avoids manifest/index drift.
168
+ const pinnedCandidates = [];
169
+ for (const [id, entry] of Object.entries(index.memories)) {
170
+ if (!entry.pinned) continue;
171
+ const scope = entry.pin_scope || 'global';
172
+ if (scope !== 'global') {
173
+ const scopedProject = scope.startsWith('project:') ? scope.slice('project:'.length) : null;
174
+ if (!args.project || scopedProject !== args.project) continue; // out-of-project pin
175
+ }
176
+ pinnedCandidates.push({ id, entry, scope, priority: entry.pin_priority || 0 });
177
+ }
178
+ pinnedCandidates.sort((a, b) =>
179
+ (b.priority - a.priority) ||
180
+ ((b.entry.strength || 0) - (a.entry.strength || 0)) ||
181
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
182
+ );
183
+
184
+ const pinned = [];
185
+ let pinnedTokens = 0;
186
+ let pinnedExcluded = 0;
187
+ const pinCap = Math.min(config.pin_budget_tokens, cap);
188
+ for (const c of pinnedCandidates) {
189
+ const est = estimateTokens(c.entry);
190
+ if (pinnedTokens + est > pinCap && pinned.length > 0) { pinnedExcluded++; continue; }
191
+ pinned.push({
192
+ id: c.id,
193
+ title: c.entry.title,
194
+ content: readMemoryBody(brainDir, c.entry.path),
195
+ scope: c.scope,
196
+ priority: c.priority,
197
+ tokens: est,
198
+ });
199
+ pinnedTokens += est;
200
+ }
201
+
202
+ // --- Skills index (CoALA Phase 2): advertise name + description only (L0) ---
203
+ const skills_index = [];
204
+ let skillsTokens = 0;
205
+ let skillsExcluded = 0;
206
+ const skillsCap = Math.min(config.skills_index_budget_tokens, Math.max(0, cap - pinnedTokens));
207
+ for (const s of advertisedSummaries(projectRoot)) {
208
+ const est = Math.ceil(((s.name || '').length + (s.description || '').length + 8) / 4);
209
+ if (skillsTokens + est > skillsCap && skills_index.length > 0) { skillsExcluded++; continue; }
210
+ skills_index.push({ name: s.name, description: s.description });
211
+ skillsTokens += est;
212
+ }
213
+
214
+ // --- Budget-bound the recall set with whatever the pin/skills tiers leave ---
215
+ const recallCap = Math.max(0, Math.min(config.recall_budget_tokens, cap - pinnedTokens - skillsTokens));
216
+ const pinnedIds = new Set(pinned.map((p) => p.id));
217
+
218
+ const context_recall = [];
219
+ let used = 0;
220
+ let excluded = 0;
221
+ for (const mem of ranked.slice(0, top)) {
222
+ if (pinnedIds.has(mem.id)) continue; // already presented in the pinned tier
223
+ const est = estimateTokens(mem);
224
+ if (used + est > recallCap && context_recall.length > 0) {
225
+ excluded++;
226
+ continue;
227
+ }
228
+ context_recall.push({
229
+ id: mem.id,
230
+ title: mem.title || path.basename(mem.path || '', '.md'),
231
+ path: mem.path,
232
+ type: mem.type,
233
+ score: mem.score,
234
+ token_estimate: est,
235
+ });
236
+ used += est;
237
+ }
238
+
239
+ // --- Due for review (matches the existing "has items" heuristic) ---
240
+ let dueForReview = 0;
241
+ try {
242
+ const queue = readReviewQueue(projectRoot);
243
+ if (queue && Array.isArray(queue.items)) dueForReview = queue.items.length;
244
+ } catch (_) { dueForReview = 0; }
245
+
246
+ // --- Low-confidence-but-frequently-used alerts ---
247
+ const low_confidence_alerts = [];
248
+ for (const [id, entry] of Object.entries(index.memories)) {
249
+ if ((entry.access_count || 0) >= 3 && (entry.confidence ?? 1) < 0.5) {
250
+ low_confidence_alerts.push({
251
+ id,
252
+ title: entry.title,
253
+ confidence: entry.confidence,
254
+ access_count: entry.access_count,
255
+ });
256
+ }
257
+ }
258
+
259
+ return {
260
+ memory_count: memoryCount,
261
+ pinned,
262
+ skills_index,
263
+ context_recall: edgeOrder(context_recall), // Tier B §10.4: top ranks at the edges
264
+ due_for_review: dueForReview,
265
+ low_confidence_alerts,
266
+ budget: {
267
+ cap,
268
+ pin_cap: pinCap,
269
+ skills_cap: skillsCap,
270
+ recall_cap: recallCap,
271
+ used: pinnedTokens + skillsTokens + used,
272
+ pinned_tokens: pinnedTokens,
273
+ skills_tokens: skillsTokens,
274
+ recall_used: used,
275
+ included: context_recall.length,
276
+ excluded,
277
+ pinned_excluded: pinnedExcluded,
278
+ skills_excluded: skillsExcluded,
279
+ },
280
+ };
281
+ }
282
+
283
+ function main(argv) {
284
+ const args = parseArgs(argv || process.argv.slice(2));
285
+ try {
286
+ const payload = computeSessionStart(undefined, args);
287
+ console.log(JSON.stringify(payload, null, 2));
288
+ } catch (err) {
289
+ console.error(JSON.stringify({ error: err.message }));
290
+ process.exit(1);
291
+ }
292
+ }
293
+
294
+ if (require.main === module) {
295
+ main(process.argv.slice(2));
296
+ }
297
+
298
+ module.exports = { main, computeSessionStart, estimateTokens, parseArgs, edgeOrder };
package/bin/skill.js ADDED
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain skill — manage procedural skills (CoALA Phase 2).
5
+ *
6
+ * Usage:
7
+ * brain skill list Advertised index (name + description)
8
+ * brain skill show <name> Full SKILL.md (L1 disclosure)
9
+ * brain skill use <name> [--failed] Record a use; success strengthens,
10
+ * --failed weakens (demotion feedback)
11
+ * brain skill remove <name> Delete a skill
12
+ * brain skill add Create a skill from JSON on stdin:
13
+ * { name, description, triggers[], body }
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const {
18
+ addSkill, listSkills, showSkill, useSkill, removeSkill, exportSkill,
19
+ } = require('../src/skills');
20
+
21
+ function emit(obj) { console.log(JSON.stringify(obj, null, 2)); }
22
+ function fail(obj) { console.error(JSON.stringify(obj)); process.exit(1); }
23
+ function done(result) { return result && result.error ? fail(result) : emit(result); }
24
+
25
+ const USAGE = 'Usage: brain skill <list|show <name>|use <name> [--failed]|add|remove <name>|export <name> [--target claude|gemini]>';
26
+
27
+ function main(argv) {
28
+ const args = argv || process.argv.slice(2);
29
+ const action = args[0];
30
+ const rest = args.slice(1);
31
+ const firstName = rest.find((a) => !a.startsWith('--'));
32
+
33
+ switch (action) {
34
+ case 'list':
35
+ return emit(listSkills(undefined));
36
+ case 'show':
37
+ if (!firstName) return fail({ error: USAGE });
38
+ return done(showSkill(undefined, firstName));
39
+ case 'use':
40
+ if (!firstName) return fail({ error: USAGE });
41
+ return done(useSkill(undefined, firstName, { failed: rest.includes('--failed') }));
42
+ case 'remove':
43
+ if (!firstName) return fail({ error: USAGE });
44
+ return done(removeSkill(undefined, firstName));
45
+ case 'export': {
46
+ if (!firstName) return fail({ error: 'Usage: brain skill export <name> [--target claude|gemini]' });
47
+ const ti = rest.indexOf('--target');
48
+ const target = ti !== -1 ? rest[ti + 1] : 'claude';
49
+ return done(exportSkill(undefined, firstName, target));
50
+ }
51
+ case 'add': {
52
+ if (process.stdin.isTTY) return fail({ error: 'Pipe a skill JSON via stdin' });
53
+ let input;
54
+ try { input = JSON.parse(fs.readFileSync(0, 'utf-8')); }
55
+ catch (e) { return fail({ error: `Invalid JSON: ${e.message}` }); }
56
+ return done(addSkill(undefined, input));
57
+ }
58
+ default:
59
+ return fail({ error: USAGE });
60
+ }
61
+ }
62
+
63
+ if (require.main === module) {
64
+ main(process.argv.slice(2));
65
+ }
66
+
67
+ module.exports = { main };
package/bin/unpin.js ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain unpin — remove a memory from the always-present semantic tier.
5
+ *
6
+ * Usage:
7
+ * brain unpin <id>
8
+ */
9
+
10
+ const { unpinMemory } = require('../src/pinning');
11
+
12
+ function parseArgs(argv) {
13
+ const args = { id: null };
14
+ for (const a of argv) {
15
+ if (!a.startsWith('--') && !args.id) args.id = a;
16
+ }
17
+ return args;
18
+ }
19
+
20
+ function main(argv) {
21
+ const args = parseArgs(argv || process.argv.slice(2));
22
+ if (!args.id) {
23
+ console.error(JSON.stringify({ error: 'Usage: brain unpin <id>' }));
24
+ process.exit(1);
25
+ }
26
+ const result = unpinMemory(undefined, args.id);
27
+ if (result.error) {
28
+ console.error(JSON.stringify(result));
29
+ process.exit(1);
30
+ }
31
+ console.log(JSON.stringify(result, null, 2));
32
+ }
33
+
34
+ if (require.main === module) {
35
+ main(process.argv.slice(2));
36
+ }
37
+
38
+ module.exports = { main, parseArgs };