brain-memory 0.1.0-beta.12 → 0.1.0-beta.14
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 +20 -12
- package/bin/install.js +19 -14
- package/bin/memorize.js +379 -0
- package/bin/recall.js +30 -4
- package/bin/reinforce.js +9 -1
- package/commands/brain/memorize.md +57 -187
- package/commands/brain/sync.md +16 -28
- package/package.json +4 -2
- package/prompts/claude.md +11 -20
- package/prompts/gemini.md +11 -20
- package/prompts/openai.md +12 -21
- package/prompts/opencode.md +176 -0
- package/src/installer.js +9 -0
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
A hierarchical, file-system-based memory plugin for AI coding agents. Inspired by human neuroscience — memories are organized into deep nested life-domain categories, connected via associative networks, strengthened through spaced recall, and naturally decay over time.
|
|
14
14
|
|
|
15
|
-
Works with **Claude Code**, **Gemini CLI**,
|
|
15
|
+
Works with **Claude Code**, **Gemini CLI**, **OpenAI Codex CLI**, and **OpenCode**.
|
|
16
16
|
|
|
17
17
|
```
|
|
18
18
|
~/.brain/
|
|
@@ -51,35 +51,43 @@ Existing AI memory solutions use flat databases with tag-based retrieval. Brain
|
|
|
51
51
|
## Install
|
|
52
52
|
|
|
53
53
|
```bash
|
|
54
|
-
|
|
54
|
+
npm install -g brain-memory@beta
|
|
55
|
+
brain-memory
|
|
55
56
|
```
|
|
56
57
|
|
|
57
|
-
The
|
|
58
|
+
The first command installs the package globally — this gives you both the interactive setup wizard and the CLI tools (`brain-memorize`, `brain-recall`, `brain-reinforce`) that agents rely on for deterministic scoring.
|
|
59
|
+
|
|
60
|
+
The second command runs the setup wizard, which asks which runtime(s) to configure (Claude Code, Gemini CLI, OpenAI Codex CLI, or all) and whether to install globally or for the current project.
|
|
58
61
|
|
|
59
62
|
### Non-interactive
|
|
60
63
|
|
|
61
64
|
```bash
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
65
|
+
brain-memory --claude --global # Claude Code, global
|
|
66
|
+
brain-memory --gemini --local # Gemini CLI, local project
|
|
67
|
+
brain-memory --codex --global # OpenAI Codex CLI, global
|
|
68
|
+
brain-memory --opencode --global # OpenCode, global
|
|
69
|
+
brain-memory --all --global # All runtimes, global
|
|
66
70
|
```
|
|
67
71
|
|
|
68
72
|
### Update
|
|
69
73
|
|
|
70
74
|
```bash
|
|
71
|
-
|
|
75
|
+
npm install -g brain-memory@beta
|
|
76
|
+
brain-memory update
|
|
72
77
|
```
|
|
73
78
|
|
|
74
|
-
|
|
79
|
+
The first command updates the package and CLI tools. The second command refreshes the slash command prompts for your installed runtimes. Target specific runtimes with `--claude`, `--gemini`, `--openai`, or `--all`.
|
|
80
|
+
|
|
81
|
+
> **Why not `npx`?** `npx` runs the setup wizard in a temporary directory that is discarded after execution. The CLI tools (`brain-memorize`, `brain-recall`, `brain-reinforce`) won't be available in your PATH, which means agents will fall back to less reliable manual file operations. Always use `npm install -g` to ensure everything works correctly.
|
|
75
82
|
|
|
76
83
|
### Uninstall
|
|
77
84
|
|
|
78
85
|
```bash
|
|
79
|
-
|
|
86
|
+
brain-memory uninstall
|
|
87
|
+
npm uninstall -g brain-memory
|
|
80
88
|
```
|
|
81
89
|
|
|
82
|
-
|
|
90
|
+
The first command removes slash commands and prompt sections from your agent configs. The second removes the package and CLI tools. Your `~/.brain/` directory (memories) is preserved by default. Add `--delete-data` to the uninstall command to remove it too. Use `--yes` to skip confirmation prompts.
|
|
83
91
|
|
|
84
92
|
### Manual Install
|
|
85
93
|
|
|
@@ -110,7 +118,7 @@ Then append the contents of the corresponding prompt file to your agent's instru
|
|
|
110
118
|
| Command | Description |
|
|
111
119
|
|---------|-------------|
|
|
112
120
|
| `/brain:init` | Initialize `~/.brain/` directory structure with default categories |
|
|
113
|
-
| `/brain:memorize [topic]` | Store memories from current session context |
|
|
121
|
+
| `/brain:memorize [topic] [--sync]` | Store memories from current session context (add `--sync` to auto-push) |
|
|
114
122
|
| `/brain:remember [query]` | Recall relevant memories with spreading activation and context matching |
|
|
115
123
|
| `/brain:review [scope]` | Spaced repetition review session for due memories |
|
|
116
124
|
| `/brain:explore [category]` | Browse the brain hierarchy with visual tree view |
|
package/bin/install.js
CHANGED
|
@@ -51,7 +51,8 @@ function resolveRuntimesFromFlags(flags) {
|
|
|
51
51
|
if (flags.has('claude')) runtimes.push('claude');
|
|
52
52
|
if (flags.has('gemini')) runtimes.push('gemini');
|
|
53
53
|
if (flags.has('openai') || flags.has('codex')) runtimes.push('openai');
|
|
54
|
-
if (flags.has('
|
|
54
|
+
if (flags.has('opencode')) runtimes.push('opencode');
|
|
55
|
+
if (flags.has('all')) return ['claude', 'gemini', 'openai', 'opencode'];
|
|
55
56
|
return runtimes;
|
|
56
57
|
}
|
|
57
58
|
|
|
@@ -73,14 +74,15 @@ async function runInstall(flags) {
|
|
|
73
74
|
try {
|
|
74
75
|
// Interactive runtime selection
|
|
75
76
|
if (runtimes.length === 0) {
|
|
76
|
-
console.log('
|
|
77
|
-
console.log('
|
|
78
|
-
console.log('
|
|
79
|
-
console.log('
|
|
80
|
-
console.log('
|
|
77
|
+
console.log(' Which runtimes would you like to install for?\n');
|
|
78
|
+
console.log(' 1) Claude Code');
|
|
79
|
+
console.log(' 2) Gemini CLI');
|
|
80
|
+
console.log(' 3) OpenAI Codex CLI');
|
|
81
|
+
console.log(' 4) OpenCode');
|
|
82
|
+
console.log(' 5) All');
|
|
81
83
|
console.log('');
|
|
82
84
|
|
|
83
|
-
const choice = await ask(rl, '
|
|
85
|
+
const choice = await ask(rl, ' Select (1/2/3/4/5): ');
|
|
84
86
|
switch (choice.trim()) {
|
|
85
87
|
case '1':
|
|
86
88
|
runtimes = ['claude'];
|
|
@@ -92,22 +94,25 @@ async function runInstall(flags) {
|
|
|
92
94
|
runtimes = ['openai'];
|
|
93
95
|
break;
|
|
94
96
|
case '4':
|
|
95
|
-
runtimes = ['
|
|
97
|
+
runtimes = ['opencode'];
|
|
98
|
+
break;
|
|
99
|
+
case '5':
|
|
100
|
+
runtimes = ['claude', 'gemini', 'openai', 'opencode'];
|
|
96
101
|
break;
|
|
97
102
|
default:
|
|
98
|
-
console.log('
|
|
103
|
+
console.log(' Invalid choice. Defaulting to Claude Code.');
|
|
99
104
|
runtimes = ['claude'];
|
|
100
105
|
}
|
|
101
106
|
}
|
|
102
107
|
|
|
103
108
|
// Interactive scope selection
|
|
104
109
|
if (!scope) {
|
|
105
|
-
console.log('\n
|
|
106
|
-
console.log('
|
|
107
|
-
console.log('
|
|
110
|
+
console.log('\n Installation scope:\n');
|
|
111
|
+
console.log(' 1) Global — Available in all projects (~/.claude/, ~/.gemini/, ~/.codex/, ~/.config/opencode/)');
|
|
112
|
+
console.log(' 2) Local — This project only (./.claude/, ./.gemini/, ./.codex/, ./.opencode/)');
|
|
108
113
|
console.log('');
|
|
109
114
|
|
|
110
|
-
const choice = await ask(rl, '
|
|
115
|
+
const choice = await ask(rl, ' Select (1/2): ');
|
|
111
116
|
scope = choice.trim() === '2' ? 'local' : 'global';
|
|
112
117
|
}
|
|
113
118
|
|
|
@@ -187,7 +192,7 @@ async function runUpdate(flags) {
|
|
|
187
192
|
|
|
188
193
|
if (detections.length === 0) {
|
|
189
194
|
console.log(' No existing brain-memory installations found.\n');
|
|
190
|
-
console.log(' To install, run:
|
|
195
|
+
console.log(' To install, run: npm install -g brain-memory@beta && brain-memory');
|
|
191
196
|
if (filterRuntimes.length > 0) {
|
|
192
197
|
console.log(` (Searched for: ${filterRuntimes.join(', ')})`);
|
|
193
198
|
}
|
package/bin/memorize.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
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
|
+
let index;
|
|
251
|
+
try {
|
|
252
|
+
index = readIndex();
|
|
253
|
+
} catch (err) {
|
|
254
|
+
console.error(JSON.stringify({
|
|
255
|
+
error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
|
|
256
|
+
}));
|
|
257
|
+
process.exit(1);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
let associations;
|
|
261
|
+
try {
|
|
262
|
+
associations = readAssociations() || { version: 1, edges: {} };
|
|
263
|
+
} catch (err) {
|
|
264
|
+
console.error(JSON.stringify({
|
|
265
|
+
error: `Corrupt associations.json in ~/.brain/ — ${err.message}`,
|
|
266
|
+
}));
|
|
267
|
+
process.exit(1);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
let searchIndex;
|
|
271
|
+
try {
|
|
272
|
+
searchIndex = readSearchIndex(brainDir) || createSearchIndex();
|
|
273
|
+
} catch (err) {
|
|
274
|
+
// Search index is non-critical — rebuild from scratch
|
|
275
|
+
searchIndex = createSearchIndex();
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const now = new Date().toISOString();
|
|
279
|
+
const results = [];
|
|
280
|
+
const newIds = [];
|
|
281
|
+
|
|
282
|
+
for (const mem of input.memories) {
|
|
283
|
+
// Validate required fields
|
|
284
|
+
if (!mem.title || !mem.type || !mem.path || !mem.content) {
|
|
285
|
+
console.error(JSON.stringify({
|
|
286
|
+
error: `Memory missing required fields (title, type, path, content): ${JSON.stringify(mem.title || 'untitled')}`,
|
|
287
|
+
}));
|
|
288
|
+
process.exit(1);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (!TYPE_DEFAULTS[mem.type]) {
|
|
292
|
+
console.error(JSON.stringify({ error: `Unknown memory type: ${mem.type}` }));
|
|
293
|
+
process.exit(1);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Generate ID
|
|
297
|
+
const id = generateId();
|
|
298
|
+
newIds.push(id);
|
|
299
|
+
|
|
300
|
+
// Compute strength/decay
|
|
301
|
+
const { fileContent, strength, decay_rate } = buildMemoryFileContent(mem, id, now);
|
|
302
|
+
|
|
303
|
+
// Create directories
|
|
304
|
+
const fullPath = path.join(brainDir, mem.path);
|
|
305
|
+
validateBrainPath(fullPath, brainDir);
|
|
306
|
+
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
|
307
|
+
|
|
308
|
+
// Write memory file
|
|
309
|
+
atomicWriteSync(fullPath, fileContent);
|
|
310
|
+
|
|
311
|
+
// Update index
|
|
312
|
+
const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now);
|
|
313
|
+
addMemory(index, id, indexEntry);
|
|
314
|
+
|
|
315
|
+
// Update associations — explicit related links
|
|
316
|
+
for (const relatedId of (mem.related || [])) {
|
|
317
|
+
if (index.memories[relatedId]) {
|
|
318
|
+
reinforceEdge(associations, id, relatedId, 'manual', 0.20);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Update associations — tag overlaps
|
|
323
|
+
const tagOverlaps = findTagOverlaps(index, mem.tags, id);
|
|
324
|
+
for (const overlapId of tagOverlaps) {
|
|
325
|
+
reinforceEdge(associations, id, overlapId, 'tag_overlap', 0.10);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Update search index
|
|
329
|
+
addDocument(searchIndex, id, {
|
|
330
|
+
title: mem.title,
|
|
331
|
+
tags: mem.tags,
|
|
332
|
+
body: mem.content,
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
// Update _meta.json files
|
|
336
|
+
updateMetaFiles(brainDir, mem.path);
|
|
337
|
+
|
|
338
|
+
const edgesCreated = (mem.related || []).filter(r => index.memories[r]).length + tagOverlaps.length;
|
|
339
|
+
|
|
340
|
+
results.push({
|
|
341
|
+
id,
|
|
342
|
+
title: mem.title,
|
|
343
|
+
path: mem.path,
|
|
344
|
+
type: mem.type,
|
|
345
|
+
cognitive_type: mem.cognitive_type || 'semantic',
|
|
346
|
+
strength,
|
|
347
|
+
decay_rate,
|
|
348
|
+
salience: mem.salience ?? 0.5,
|
|
349
|
+
confidence: mem.confidence ?? 0.7,
|
|
350
|
+
tags: mem.tags || [],
|
|
351
|
+
edges_created: edgesCreated,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Write all updated state
|
|
356
|
+
writeIndex(index);
|
|
357
|
+
writeAssociations(associations);
|
|
358
|
+
writeSearchIndex(brainDir, searchIndex);
|
|
359
|
+
|
|
360
|
+
// Build output
|
|
361
|
+
const output = {
|
|
362
|
+
stored: results,
|
|
363
|
+
total: results.length,
|
|
364
|
+
index_count: index.memory_count,
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
// Sync if requested
|
|
368
|
+
if (args.sync || input.auto_sync) {
|
|
369
|
+
const syncResult = trySync();
|
|
370
|
+
output.sync = syncResult;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
console.log(JSON.stringify(output, null, 2));
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
main().catch((err) => {
|
|
377
|
+
console.error(JSON.stringify({ error: err.message }));
|
|
378
|
+
process.exit(1);
|
|
379
|
+
});
|
package/bin/recall.js
CHANGED
|
@@ -58,14 +58,27 @@ function main() {
|
|
|
58
58
|
process.exit(1);
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
let index;
|
|
62
|
+
try {
|
|
63
|
+
index = readIndex();
|
|
64
|
+
} catch (err) {
|
|
65
|
+
console.error(JSON.stringify({
|
|
66
|
+
error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
|
|
67
|
+
}));
|
|
68
|
+
process.exit(1);
|
|
69
|
+
}
|
|
62
70
|
if (!index || !index.memories || Object.keys(index.memories).length === 0) {
|
|
63
71
|
console.log(JSON.stringify([]));
|
|
64
72
|
return;
|
|
65
73
|
}
|
|
66
74
|
|
|
67
75
|
// Ensure search index exists
|
|
68
|
-
let searchIndex
|
|
76
|
+
let searchIndex;
|
|
77
|
+
try {
|
|
78
|
+
searchIndex = readSearchIndex(brainDir);
|
|
79
|
+
} catch (_) {
|
|
80
|
+
searchIndex = null;
|
|
81
|
+
}
|
|
69
82
|
if (!searchIndex) {
|
|
70
83
|
searchIndex = rebuildIndex(brainDir, index);
|
|
71
84
|
writeSearchIndex(brainDir, searchIndex);
|
|
@@ -86,7 +99,12 @@ function main() {
|
|
|
86
99
|
}));
|
|
87
100
|
|
|
88
101
|
// Load associations for spreading activation
|
|
89
|
-
|
|
102
|
+
let associations;
|
|
103
|
+
try {
|
|
104
|
+
associations = readAssociations();
|
|
105
|
+
} catch (_) {
|
|
106
|
+
associations = null;
|
|
107
|
+
}
|
|
90
108
|
|
|
91
109
|
// Build recall context
|
|
92
110
|
const recallContext = {};
|
|
@@ -127,7 +145,15 @@ function main() {
|
|
|
127
145
|
* Rebuild the search index from all memories.
|
|
128
146
|
*/
|
|
129
147
|
function handleReindex(brainDir) {
|
|
130
|
-
|
|
148
|
+
let index;
|
|
149
|
+
try {
|
|
150
|
+
index = readIndex();
|
|
151
|
+
} catch (err) {
|
|
152
|
+
console.error(JSON.stringify({
|
|
153
|
+
error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
|
|
154
|
+
}));
|
|
155
|
+
process.exit(1);
|
|
156
|
+
}
|
|
131
157
|
if (!index) {
|
|
132
158
|
console.error(JSON.stringify({ error: 'No index.json found.' }));
|
|
133
159
|
process.exit(1);
|
package/bin/reinforce.js
CHANGED
|
@@ -46,7 +46,15 @@ function main() {
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
const brainDir = getBrainDir();
|
|
49
|
-
|
|
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
|
+
}
|
|
50
58
|
|
|
51
59
|
if (!index) {
|
|
52
60
|
console.error(JSON.stringify({ error: 'Brain not initialized.' }));
|