brain-memory 0.1.0-beta.11 → 0.1.0-beta.13

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
@@ -110,7 +110,7 @@ Then append the contents of the corresponding prompt file to your agent's instru
110
110
  | Command | Description |
111
111
  |---------|-------------|
112
112
  | `/brain:init` | Initialize `~/.brain/` directory structure with default categories |
113
- | `/brain:memorize [topic]` | Store memories from current session context |
113
+ | `/brain:memorize [topic] [--sync]` | Store memories from current session context (add `--sync` to auto-push) |
114
114
  | `/brain:remember [query]` | Recall relevant memories with spreading activation and context matching |
115
115
  | `/brain:review [scope]` | Spaced repetition review session for due memories |
116
116
  | `/brain:explore [category]` | Browse the brain hierarchy with visual tree view |
@@ -0,0 +1,149 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain-cloud — CLI for Brain Cloud sync
5
+ *
6
+ * Usage:
7
+ * brain-cloud login [--api-url URL] Authenticate via device code flow
8
+ * brain-cloud logout Clear stored credentials
9
+ * brain-cloud push Upload ~/.brain/ to the cloud
10
+ * brain-cloud pull Download from the cloud to ~/.brain/
11
+ * brain-cloud status Show connection and sync status
12
+ */
13
+
14
+ const path = require('path');
15
+ const os = require('os');
16
+ const cloud = require('../src/cloud-sync');
17
+
18
+ const BRAIN_DIR = path.join(os.homedir(), '.brain');
19
+
20
+ async function main() {
21
+ const args = process.argv.slice(2);
22
+ const command = args[0];
23
+
24
+ if (!command || command === '--help' || command === '-h') {
25
+ console.log(`
26
+ brain-cloud — Brain Cloud sync CLI
27
+
28
+ Commands:
29
+ login [--api-url URL] Authenticate via device code flow
30
+ logout Clear stored credentials
31
+ push Upload ~/.brain/ to the cloud
32
+ pull Download from the cloud to ~/.brain/
33
+ status Show connection and sync status
34
+ `.trim());
35
+ process.exit(0);
36
+ }
37
+
38
+ switch (command) {
39
+ case 'login':
40
+ await cmdLogin(args);
41
+ break;
42
+ case 'logout':
43
+ cmdLogout();
44
+ break;
45
+ case 'push':
46
+ await cmdPush();
47
+ break;
48
+ case 'pull':
49
+ await cmdPull();
50
+ break;
51
+ case 'status':
52
+ await cmdStatus();
53
+ break;
54
+ default:
55
+ console.error(`Unknown command: ${command}`);
56
+ process.exit(1);
57
+ }
58
+ }
59
+
60
+ async function cmdLogin(args) {
61
+ let apiUrl;
62
+ const urlIdx = args.indexOf('--api-url');
63
+ if (urlIdx !== -1 && args[urlIdx + 1]) {
64
+ apiUrl = args[urlIdx + 1];
65
+ }
66
+
67
+ console.log('Requesting device code...');
68
+ const loginInfo = await cloud.login(BRAIN_DIR, apiUrl);
69
+
70
+ console.log();
71
+ console.log(' Open this URL in your browser to log in:');
72
+ console.log();
73
+ console.log(` ${loginInfo.verify_url}`);
74
+ console.log();
75
+ console.log(` Your code: ${loginInfo.user_code}`);
76
+ console.log();
77
+ console.log(` Waiting for approval (expires in ${Math.floor(loginInfo.expires_in / 60)} min)...`);
78
+
79
+ await loginInfo.waitForApproval();
80
+
81
+ const config = cloud.readConfig(BRAIN_DIR);
82
+ console.log();
83
+ console.log(`✓ Logged in as ${config.user_email || 'unknown'}`);
84
+ if (config.brain_id) {
85
+ console.log(` Brain ID: ${config.brain_id}`);
86
+ }
87
+ console.log(` API: ${config.api_url}`);
88
+ }
89
+
90
+ function cmdLogout() {
91
+ cloud.logout(BRAIN_DIR);
92
+ console.log('✓ Logged out. Credentials cleared.');
93
+ }
94
+
95
+ async function cmdPush() {
96
+ console.log('Packing ~/.brain/ ...');
97
+ const result = await cloud.push(BRAIN_DIR);
98
+ console.log();
99
+ console.log('✓ Push complete!');
100
+ console.log(` Size: ${formatBytes(result.size_bytes)}`);
101
+ console.log(` Files: ${result.file_count}`);
102
+ console.log(` Checksum: ${result.checksum}`);
103
+ }
104
+
105
+ async function cmdPull() {
106
+ console.log('Downloading from cloud...');
107
+ const result = await cloud.pull(BRAIN_DIR);
108
+ console.log();
109
+ console.log('✓ Pull complete!');
110
+ console.log(` Size: ${formatBytes(result.size_bytes)}`);
111
+ if (result.checksum) {
112
+ console.log(` Checksum: ${result.checksum}`);
113
+ }
114
+ }
115
+
116
+ async function cmdStatus() {
117
+ const s = await cloud.status(BRAIN_DIR);
118
+
119
+ if (!s.connected) {
120
+ console.log('☁️ Not connected to Brain Cloud');
121
+ console.log(' Run: brain-cloud login');
122
+ return;
123
+ }
124
+
125
+ console.log('☁️ Brain Cloud Status');
126
+ console.log('─────────────────────────');
127
+ console.log(` API: ${s.api_url}`);
128
+ console.log(` User: ${s.user_email || 'unknown'}`);
129
+ console.log(` Brain ID: ${s.brain_id || 'none'}`);
130
+ if (s.brain_name) console.log(` Brain Name: ${s.brain_name}`);
131
+ if (s.brain_size !== null) console.log(` Cloud Size: ${formatBytes(s.brain_size)}`);
132
+ if (s.brain_files !== null) console.log(` Cloud Files: ${s.brain_files}`);
133
+ console.log(` Last Push: ${s.last_push || 'never'}`);
134
+ console.log(` Last Pull: ${s.last_pull || 'never'}`);
135
+ console.log(` Last Synced: ${s.last_synced || 'never'}`);
136
+ console.log(` Connected: ${s.connected_at || 'unknown'}`);
137
+ }
138
+
139
+ function formatBytes(bytes) {
140
+ if (bytes === 0 || bytes === null || bytes === undefined) return '0 B';
141
+ const units = ['B', 'KB', 'MB', 'GB'];
142
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
143
+ return `${(bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
144
+ }
145
+
146
+ main().catch((err) => {
147
+ console.error(`Error: ${err.message}`);
148
+ process.exit(1);
149
+ });
@@ -0,0 +1,355 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain-memorize — Store memories from AI agent input
5
+ *
6
+ * Accepts a JSON payload via stdin with memory definitions.
7
+ * Handles all plumbing: ID generation, directory creation, file writing,
8
+ * index updates, association edges, search index, and optional sync.
9
+ *
10
+ * Usage:
11
+ * brain-memorize [--sync] <<'EOF'
12
+ * { "memories": [{ "title": "...", "type": "learning", ... }] }
13
+ * EOF
14
+ *
15
+ * The AI agent decides WHAT to remember. This CLI handles HOW to write it.
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const { execSync } = require('child_process');
21
+ const {
22
+ getBrainDir,
23
+ readIndex,
24
+ writeIndex,
25
+ addMemory,
26
+ generateId,
27
+ readMeta,
28
+ writeMeta,
29
+ readAssociations,
30
+ writeAssociations,
31
+ reinforceEdge,
32
+ atomicWriteSync,
33
+ validateBrainPath,
34
+ } = require('../src/index-manager');
35
+ const { addDocument, createSearchIndex, readSearchIndex, writeSearchIndex } = require('../src/tfidf');
36
+
37
+ // --- Type defaults ---
38
+
39
+ const TYPE_DEFAULTS = {
40
+ decision: { strength: 0.85, decay_rate: 0.995 },
41
+ insight: { strength: 0.90, decay_rate: 0.997 },
42
+ goal: { strength: 0.80, decay_rate: 0.993 },
43
+ experience: { strength: 0.75, decay_rate: 0.985 },
44
+ learning: { strength: 0.70, decay_rate: 0.990 },
45
+ relationship: { strength: 0.70, decay_rate: 0.997 },
46
+ preference: { strength: 0.60, decay_rate: 0.998 },
47
+ observation: { strength: 0.40, decay_rate: 0.950 },
48
+ };
49
+
50
+ const COGNITIVE_ADJUSTMENTS = {
51
+ episodic: { strength_delta: +0.10, decay_multiplier: 0.995 },
52
+ semantic: { strength_delta: 0, decay_multiplier: 1.0 },
53
+ procedural: { strength_delta: -0.10, decay_multiplier: 1.003 },
54
+ };
55
+
56
+ // --- Args ---
57
+
58
+ function parseArgs(argv) {
59
+ const args = { sync: false };
60
+ for (const arg of argv) {
61
+ if (arg === '--sync') args.sync = true;
62
+ }
63
+ return args;
64
+ }
65
+
66
+ // --- Helpers ---
67
+
68
+ function computeStrengthAndDecay(type, cognitiveType, strengthAdjustment = 0) {
69
+ const typeDefaults = TYPE_DEFAULTS[type] || TYPE_DEFAULTS.observation;
70
+ const cogAdj = COGNITIVE_ADJUSTMENTS[cognitiveType] || COGNITIVE_ADJUSTMENTS.semantic;
71
+
72
+ const strength = Math.max(0, Math.min(1.0,
73
+ typeDefaults.strength + cogAdj.strength_delta + strengthAdjustment
74
+ ));
75
+ const decay_rate = typeDefaults.decay_rate * cogAdj.decay_multiplier;
76
+
77
+ return { strength: Math.round(strength * 100) / 100, decay_rate };
78
+ }
79
+
80
+ function buildMemoryFileContent(mem, id, now) {
81
+ const { strength, decay_rate } = computeStrengthAndDecay(
82
+ mem.type, mem.cognitive_type, mem.strength_adjustment
83
+ );
84
+
85
+ const frontmatter = [
86
+ '---',
87
+ `id: ${id}`,
88
+ `type: ${mem.type}`,
89
+ `cognitive_type: ${mem.cognitive_type || 'semantic'}`,
90
+ `created: "${now}"`,
91
+ `last_accessed: "${now}"`,
92
+ `access_count: 0`,
93
+ `recall_history: []`,
94
+ `strength: ${strength}`,
95
+ `decay_rate: ${decay_rate}`,
96
+ `salience: ${mem.salience ?? 0.5}`,
97
+ `confidence: ${mem.confidence ?? 0.7}`,
98
+ `tags: [${(mem.tags || []).map(t => `"${t}"`).join(', ')}]`,
99
+ `related: [${(mem.related || []).map(r => `"${r}"`).join(', ')}]`,
100
+ `source: "${mem.source || ''}"`,
101
+ `encoding_context:`,
102
+ ` project: "${(mem.encoding_context && mem.encoding_context.project) || ''}"`,
103
+ ` topics: [${((mem.encoding_context && mem.encoding_context.topics) || []).map(t => `"${t}"`).join(', ')}]`,
104
+ ` task_type: "${(mem.encoding_context && mem.encoding_context.task_type) || ''}"`,
105
+ '---',
106
+ '',
107
+ ].join('\n');
108
+
109
+ return { fileContent: frontmatter + mem.content + '\n', strength, decay_rate };
110
+ }
111
+
112
+ function buildIndexEntry(mem, id, strength, decayRate, now) {
113
+ return {
114
+ title: mem.title,
115
+ path: mem.path,
116
+ type: mem.type,
117
+ cognitive_type: mem.cognitive_type || 'semantic',
118
+ created: now,
119
+ last_accessed: now,
120
+ access_count: 0,
121
+ strength,
122
+ decay_rate: decayRate,
123
+ salience: mem.salience ?? 0.5,
124
+ confidence: mem.confidence ?? 0.7,
125
+ tags: mem.tags || [],
126
+ related: mem.related || [],
127
+ encoding_context: mem.encoding_context || {},
128
+ };
129
+ }
130
+
131
+ function updateMetaFiles(brainDir, memPath) {
132
+ const parts = memPath.split('/');
133
+ // Walk up the directory chain, updating _meta.json at each level
134
+ for (let i = 1; i <= parts.length - 1; i++) {
135
+ const dirParts = parts.slice(0, i);
136
+ const categoryPath = dirParts.join('/');
137
+ const fullDir = path.join(brainDir, categoryPath);
138
+
139
+ if (!fs.existsSync(fullDir)) continue;
140
+
141
+ const metaPath = path.join(fullDir, '_meta.json');
142
+ let meta;
143
+ try {
144
+ meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
145
+ } catch {
146
+ meta = { description: categoryPath, memory_count: 0, subcategories: [] };
147
+ }
148
+
149
+ meta.memory_count = (meta.memory_count || 0) + 1;
150
+
151
+ // Add subcategory if this isn't the leaf directory
152
+ if (i < parts.length - 1) {
153
+ const subcat = parts[i];
154
+ if (!meta.subcategories) meta.subcategories = [];
155
+ if (!meta.subcategories.includes(subcat)) {
156
+ meta.subcategories.push(subcat);
157
+ }
158
+ }
159
+
160
+ atomicWriteSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
161
+ }
162
+ }
163
+
164
+ function findTagOverlaps(index, newTags, newId, minOverlap = 2) {
165
+ const overlaps = [];
166
+ if (!newTags || newTags.length < minOverlap) return overlaps;
167
+
168
+ const newTagSet = new Set(newTags);
169
+ for (const [id, entry] of Object.entries(index.memories)) {
170
+ if (id === newId) continue;
171
+ const entryTags = entry.tags || [];
172
+ const shared = entryTags.filter(t => newTagSet.has(t));
173
+ if (shared.length >= minOverlap) {
174
+ overlaps.push(id);
175
+ }
176
+ }
177
+ return overlaps;
178
+ }
179
+
180
+ function trySync() {
181
+ const brainDir = getBrainDir();
182
+
183
+ // Try cloud sync first
184
+ const cloudConfig = path.join(brainDir, '.cloud', 'config.json');
185
+ if (fs.existsSync(cloudConfig)) {
186
+ try {
187
+ execSync('brain-cloud push', { stdio: 'pipe', timeout: 30000 });
188
+ return { method: 'cloud', success: true };
189
+ } catch (err) {
190
+ return { method: 'cloud', success: false, error: err.message };
191
+ }
192
+ }
193
+
194
+ // Try git sync
195
+ const gitConfig = path.join(brainDir, '.sync', 'config.json');
196
+ if (fs.existsSync(gitConfig)) {
197
+ try {
198
+ // Use the git-sync module
199
+ const gitSync = require('../src/git-sync');
200
+ // Sync push is async, but we run sync for CLI simplicity
201
+ execSync(`node -e "require('${path.join(__dirname, '..', 'src', 'git-sync.js')}').push('${brainDir}').then(() => process.exit(0)).catch(() => process.exit(1))"`, {
202
+ stdio: 'pipe',
203
+ timeout: 30000,
204
+ });
205
+ return { method: 'git', success: true };
206
+ } catch (err) {
207
+ return { method: 'git', success: false, error: err.message };
208
+ }
209
+ }
210
+
211
+ return { method: 'none', success: false, error: 'No sync configured (cloud or git)' };
212
+ }
213
+
214
+ // --- Main ---
215
+
216
+ async function main() {
217
+ const args = parseArgs(process.argv.slice(2));
218
+
219
+ // Read JSON from stdin
220
+ let inputData = '';
221
+ if (process.stdin.isTTY) {
222
+ console.error(JSON.stringify({ error: 'No input provided. Pipe JSON via stdin.' }));
223
+ process.exit(1);
224
+ }
225
+
226
+ inputData = fs.readFileSync('/dev/stdin', 'utf-8');
227
+
228
+ let input;
229
+ try {
230
+ input = JSON.parse(inputData);
231
+ } catch (err) {
232
+ console.error(JSON.stringify({ error: `Invalid JSON input: ${err.message}` }));
233
+ process.exit(1);
234
+ }
235
+
236
+ if (!input.memories || !Array.isArray(input.memories) || input.memories.length === 0) {
237
+ console.error(JSON.stringify({ error: 'Input must have a non-empty "memories" array' }));
238
+ process.exit(1);
239
+ }
240
+
241
+ const brainDir = getBrainDir();
242
+
243
+ // Validate brain exists
244
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
245
+ console.error(JSON.stringify({ error: `Brain not initialized. Run brain-memory install first.` }));
246
+ process.exit(1);
247
+ }
248
+
249
+ // Read current state
250
+ const index = readIndex();
251
+ let associations = readAssociations() || { version: 1, edges: {} };
252
+ let searchIndex = readSearchIndex(brainDir) || createSearchIndex();
253
+
254
+ const now = new Date().toISOString();
255
+ const results = [];
256
+ const newIds = [];
257
+
258
+ for (const mem of input.memories) {
259
+ // Validate required fields
260
+ if (!mem.title || !mem.type || !mem.path || !mem.content) {
261
+ console.error(JSON.stringify({
262
+ error: `Memory missing required fields (title, type, path, content): ${JSON.stringify(mem.title || 'untitled')}`,
263
+ }));
264
+ process.exit(1);
265
+ }
266
+
267
+ if (!TYPE_DEFAULTS[mem.type]) {
268
+ console.error(JSON.stringify({ error: `Unknown memory type: ${mem.type}` }));
269
+ process.exit(1);
270
+ }
271
+
272
+ // Generate ID
273
+ const id = generateId();
274
+ newIds.push(id);
275
+
276
+ // Compute strength/decay
277
+ const { fileContent, strength, decay_rate } = buildMemoryFileContent(mem, id, now);
278
+
279
+ // Create directories
280
+ const fullPath = path.join(brainDir, mem.path);
281
+ validateBrainPath(fullPath, brainDir);
282
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
283
+
284
+ // Write memory file
285
+ atomicWriteSync(fullPath, fileContent);
286
+
287
+ // Update index
288
+ const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now);
289
+ addMemory(index, id, indexEntry);
290
+
291
+ // Update associations — explicit related links
292
+ for (const relatedId of (mem.related || [])) {
293
+ if (index.memories[relatedId]) {
294
+ reinforceEdge(associations, id, relatedId, 'manual', 0.20);
295
+ }
296
+ }
297
+
298
+ // Update associations — tag overlaps
299
+ const tagOverlaps = findTagOverlaps(index, mem.tags, id);
300
+ for (const overlapId of tagOverlaps) {
301
+ reinforceEdge(associations, id, overlapId, 'tag_overlap', 0.10);
302
+ }
303
+
304
+ // Update search index
305
+ addDocument(searchIndex, id, {
306
+ title: mem.title,
307
+ tags: mem.tags,
308
+ body: mem.content,
309
+ });
310
+
311
+ // Update _meta.json files
312
+ updateMetaFiles(brainDir, mem.path);
313
+
314
+ const edgesCreated = (mem.related || []).filter(r => index.memories[r]).length + tagOverlaps.length;
315
+
316
+ results.push({
317
+ id,
318
+ title: mem.title,
319
+ path: mem.path,
320
+ type: mem.type,
321
+ cognitive_type: mem.cognitive_type || 'semantic',
322
+ strength,
323
+ decay_rate,
324
+ salience: mem.salience ?? 0.5,
325
+ confidence: mem.confidence ?? 0.7,
326
+ tags: mem.tags || [],
327
+ edges_created: edgesCreated,
328
+ });
329
+ }
330
+
331
+ // Write all updated state
332
+ writeIndex(index);
333
+ writeAssociations(associations);
334
+ writeSearchIndex(brainDir, searchIndex);
335
+
336
+ // Build output
337
+ const output = {
338
+ stored: results,
339
+ total: results.length,
340
+ index_count: index.memory_count,
341
+ };
342
+
343
+ // Sync if requested
344
+ if (args.sync || input.auto_sync) {
345
+ const syncResult = trySync();
346
+ output.sync = syncResult;
347
+ }
348
+
349
+ console.log(JSON.stringify(output, null, 2));
350
+ }
351
+
352
+ main().catch((err) => {
353
+ console.error(JSON.stringify({ error: err.message }));
354
+ process.exit(1);
355
+ });