brain-memory 0.1.0-beta.8 → 0.1.0
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/CHANGELOG.md +555 -0
- package/README.md +411 -61
- package/SECURITY.md +100 -0
- package/assets/brand/README.md +28 -0
- package/assets/brand/icon-dark.svg +19 -0
- package/assets/brand/icon-light.svg +20 -0
- package/assets/brand/linkedin_cover.png +0 -0
- package/assets/brand/linkedin_cover_light.png +0 -0
- package/assets/brand/mark-dark.svg +19 -0
- package/assets/brand/mark-light.svg +20 -0
- package/assets/brand/png/icon-dark-1024.png +0 -0
- package/assets/brand/png/icon-dark-128.png +0 -0
- package/assets/brand/png/icon-dark-256.png +0 -0
- package/assets/brand/png/icon-dark-512.png +0 -0
- package/assets/brand/png/icon-dark-64.png +0 -0
- package/assets/brand/png/icon-light-1024.png +0 -0
- package/assets/brand/png/icon-light-128.png +0 -0
- package/assets/brand/png/icon-light-256.png +0 -0
- package/assets/brand/png/icon-light-512.png +0 -0
- package/assets/brand/png/icon-light-64.png +0 -0
- package/assets/brand/png/mark-dark-1024.png +0 -0
- package/assets/brand/png/mark-light-1024.png +0 -0
- package/assets/icon.png +0 -0
- package/assets/icon.svg +19 -0
- package/bin/audit.js +93 -0
- package/bin/brain.js +132 -0
- package/bin/cloud-sync.js +150 -0
- package/bin/forget.js +163 -0
- package/bin/import.js +132 -0
- package/bin/install.js +63 -31
- package/bin/memorize.js +637 -0
- package/bin/pin.js +44 -0
- package/bin/recall.js +287 -0
- package/bin/reinforce.js +191 -0
- package/bin/restore.js +122 -0
- package/bin/session-start.js +337 -0
- package/bin/skill.js +67 -0
- package/bin/unpin.js +38 -0
- package/bin/verify.js +154 -0
- package/commands/brain/forget.md +243 -13
- package/commands/brain/import.md +125 -0
- package/commands/brain/memorize.md +95 -137
- package/commands/brain/pin.md +79 -0
- package/commands/brain/remember.md +53 -103
- package/commands/brain/skills.md +60 -0
- package/commands/brain/sleep.md +93 -6
- package/commands/brain/status.md +15 -6
- package/commands/brain/sync.md +181 -17
- package/commands/brain/verify.md +57 -0
- package/integrations/README.md +29 -0
- package/integrations/agentskills/brain-memory/SKILL.md +115 -0
- package/integrations/agentskills/brain-memory/scripts/session-start.mjs +34 -0
- package/package.json +20 -7
- package/prompts/antigravity.md +201 -0
- package/prompts/claude.md +107 -40
- package/prompts/copilot.md +203 -0
- package/prompts/kilo.md +202 -0
- package/prompts/openai.md +112 -45
- package/prompts/opencode.md +200 -0
- package/src/anomaly.js +260 -0
- package/src/audit.js +71 -0
- package/src/cloud-sync.js +672 -0
- package/src/content-lint.js +118 -0
- package/src/export-import.js +45 -7
- package/src/git-sync.js +170 -11
- package/src/harvest.js +562 -0
- package/src/index-manager.js +250 -11
- package/src/installer.js +250 -29
- package/src/pinning.js +146 -0
- package/src/provenance.js +79 -0
- package/src/quarantine.js +111 -0
- package/src/receipt.js +81 -0
- package/src/scorer.js +69 -12
- package/src/skills.js +208 -0
- package/src/tfidf.js +520 -0
- package/commands/brain/consolidate.md +0 -153
- package/commands/brain/explore.md +0 -79
- package/commands/brain/init.md +0 -149
- package/commands/brain/review.md +0 -130
- package/commands/brain/sunshine.md +0 -337
- package/prompts/gemini.md +0 -134
package/bin/recall.js
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
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
|
+
readConfig,
|
|
36
|
+
getBrainDir,
|
|
37
|
+
} = require('../src/index-manager');
|
|
38
|
+
|
|
39
|
+
const {
|
|
40
|
+
rankMemories,
|
|
41
|
+
} = require('../src/scorer');
|
|
42
|
+
|
|
43
|
+
const { receiptFor } = require('../src/receipt');
|
|
44
|
+
const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
|
|
45
|
+
|
|
46
|
+
// Minimum relevance (or spreading bonus) for a memory to appear in explicit-
|
|
47
|
+
// query results. Filters the zero/near-zero-relevance memories that would
|
|
48
|
+
// otherwise pad the top-N purely on strength — an agent trusting those scores
|
|
49
|
+
// injects noise into its context. Context mode (--context) is exempt: there
|
|
50
|
+
// the query is just a topical hint and strength-ranked padding is intended.
|
|
51
|
+
const RELEVANCE_FLOOR = 0.05;
|
|
52
|
+
|
|
53
|
+
function main() {
|
|
54
|
+
const args = parseArgs(process.argv.slice(2));
|
|
55
|
+
|
|
56
|
+
const brainDir = getBrainDir();
|
|
57
|
+
|
|
58
|
+
if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
|
|
59
|
+
console.error(JSON.stringify({ error: 'Brain not initialized. Reinstall with `npx brain-memory`, or run /brain:sync to create it.' }));
|
|
60
|
+
process.exit(1);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Reindex mode
|
|
64
|
+
if (args.reindex) {
|
|
65
|
+
return handleReindex(brainDir);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Need a query for search
|
|
69
|
+
if (!args.query && !args.context) {
|
|
70
|
+
console.error(JSON.stringify({ error: 'Usage: brain recall "query" or brain recall --context' }));
|
|
71
|
+
process.exit(1);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let index;
|
|
75
|
+
try {
|
|
76
|
+
index = readIndex();
|
|
77
|
+
} catch (err) {
|
|
78
|
+
console.error(JSON.stringify({
|
|
79
|
+
error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
|
|
80
|
+
}));
|
|
81
|
+
process.exit(1);
|
|
82
|
+
}
|
|
83
|
+
if (!index || !index.memories || Object.keys(index.memories).length === 0) {
|
|
84
|
+
console.log(JSON.stringify([]));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Ensure search index exists
|
|
89
|
+
let searchIndex;
|
|
90
|
+
try {
|
|
91
|
+
searchIndex = readSearchIndex(brainDir);
|
|
92
|
+
} catch (_) {
|
|
93
|
+
searchIndex = null;
|
|
94
|
+
}
|
|
95
|
+
// Rebuild when ABSENT *or* STALE. The search index drifts out of sync with
|
|
96
|
+
// index.json whenever memories change outside memorize's addDocument path
|
|
97
|
+
// (forget, sleep/consolidate, sync pull, manual edit) — and a present-but-
|
|
98
|
+
// empty index silently makes every relevance score 0. Compare the doc set,
|
|
99
|
+
// not just presence.
|
|
100
|
+
if (isSearchIndexStale(searchIndex, index)) {
|
|
101
|
+
searchIndex = rebuildIndex(brainDir, index);
|
|
102
|
+
writeSearchIndex(brainDir, searchIndex);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Context mode: build query from project context
|
|
106
|
+
const query = args.context
|
|
107
|
+
? buildContextQuery(args)
|
|
108
|
+
: args.query;
|
|
109
|
+
|
|
110
|
+
// Compute relevance scores (BM25 — length-normalized, TF-saturated; better
|
|
111
|
+
// than raw TF-IDF cosine at surfacing long, detailed memories under noise).
|
|
112
|
+
const tfidfScores = bm25Search(searchIndex, query);
|
|
113
|
+
|
|
114
|
+
// Build memory list from index. In enforce mode, quarantined (pending-
|
|
115
|
+
// verification) memories are excluded here — before ranking — which also
|
|
116
|
+
// removes them as spreading-activation sources. readConfig tolerates a
|
|
117
|
+
// missing/corrupt config.json (falls back to the 'flag' default).
|
|
118
|
+
const quarantineMode = readConfig().quarantine_mode || 'flag';
|
|
119
|
+
const memories = Object.entries(index.memories)
|
|
120
|
+
.filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
|
|
121
|
+
.map(([id, entry]) => ({
|
|
122
|
+
id,
|
|
123
|
+
...entry,
|
|
124
|
+
}));
|
|
125
|
+
|
|
126
|
+
// Load associations for spreading activation
|
|
127
|
+
let associations;
|
|
128
|
+
try {
|
|
129
|
+
associations = readAssociations();
|
|
130
|
+
} catch (_) {
|
|
131
|
+
associations = null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Build recall context
|
|
135
|
+
const recallContext = {};
|
|
136
|
+
if (args.project) recallContext.project = args.project;
|
|
137
|
+
if (args.task) recallContext.task_type = args.task;
|
|
138
|
+
if (args.topics) recallContext.topics = args.topics.split(',');
|
|
139
|
+
|
|
140
|
+
// Rank using scorer.js with TF-IDF as the relevance function
|
|
141
|
+
const ranked = rankMemories(
|
|
142
|
+
memories,
|
|
143
|
+
(mem) => tfidfScores[mem.id] || 0,
|
|
144
|
+
{
|
|
145
|
+
associations: associations || undefined,
|
|
146
|
+
recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
|
|
147
|
+
relevanceFloor: args.context ? undefined : RELEVANCE_FLOOR,
|
|
148
|
+
}
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
// Return top N
|
|
152
|
+
const top = args.top || 10;
|
|
153
|
+
const results = ranked.slice(0, top).map((mem) => {
|
|
154
|
+
const title = mem.title || path.basename(mem.path, '.md');
|
|
155
|
+
const origin = mem.origin || DEFAULT_ORIGIN;
|
|
156
|
+
return {
|
|
157
|
+
id: mem.id,
|
|
158
|
+
title,
|
|
159
|
+
path: mem.path,
|
|
160
|
+
type: mem.type,
|
|
161
|
+
score: mem.score,
|
|
162
|
+
relevance: mem.relevance,
|
|
163
|
+
decayed_strength: mem.decayed_strength,
|
|
164
|
+
context_match: mem.context_match,
|
|
165
|
+
spreading_bonus: mem.spreading_bonus,
|
|
166
|
+
confidence: mem.confidence,
|
|
167
|
+
// Provenance travels with every result so the agent can answer
|
|
168
|
+
// "where did you get that?" without opening the memory file.
|
|
169
|
+
origin,
|
|
170
|
+
...(isLowTrust(origin) ? { low_trust: true } : {}),
|
|
171
|
+
// Pending verification (flag mode): recallable but visibly marked, so
|
|
172
|
+
// the agent can caveat an answer built on an unverified memory.
|
|
173
|
+
...(mem.quarantined ? { quarantine_pending: true } : {}),
|
|
174
|
+
// Temporal invalidation: a newer memory replaced this one. Surfaced so
|
|
175
|
+
// the agent can say "this was true until <the successor>" rather than
|
|
176
|
+
// presenting a stale fact as current.
|
|
177
|
+
...(mem.superseded_by ? { superseded_by: mem.superseded_by } : {}),
|
|
178
|
+
tags: mem.tags,
|
|
179
|
+
// Recall receipt — the engine mints it, agents copy it verbatim when
|
|
180
|
+
// this memory materially shapes an answer (so it can't be hallucinated).
|
|
181
|
+
receipt: receiptFor({ ...mem, title }),
|
|
182
|
+
};
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
console.log(JSON.stringify(results, null, 2));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* The TF-IDF search index is stale if it is missing, has a different document
|
|
190
|
+
* count than the live index, or is missing any indexed memory id. Catches the
|
|
191
|
+
* empty-index and add/remove/rename drift cases (in-place same-id body edits
|
|
192
|
+
* are not detected by count alone — acceptable until a version/mtime check).
|
|
193
|
+
*/
|
|
194
|
+
/**
|
|
195
|
+
* Rebuild the search index from all memories.
|
|
196
|
+
*/
|
|
197
|
+
function handleReindex(brainDir) {
|
|
198
|
+
let index;
|
|
199
|
+
try {
|
|
200
|
+
index = readIndex();
|
|
201
|
+
} catch (err) {
|
|
202
|
+
console.error(JSON.stringify({
|
|
203
|
+
error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
|
|
204
|
+
}));
|
|
205
|
+
process.exit(1);
|
|
206
|
+
}
|
|
207
|
+
if (!index) {
|
|
208
|
+
console.error(JSON.stringify({ error: 'No index.json found.' }));
|
|
209
|
+
process.exit(1);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const searchIndex = rebuildIndex(brainDir, index);
|
|
213
|
+
writeSearchIndex(brainDir, searchIndex);
|
|
214
|
+
|
|
215
|
+
console.log(JSON.stringify({
|
|
216
|
+
reindexed: true,
|
|
217
|
+
documents: searchIndex.doc_count,
|
|
218
|
+
terms: Object.keys(searchIndex.df).length,
|
|
219
|
+
}));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Build a query from context when no explicit query is given.
|
|
224
|
+
* Uses project name and topics as search terms.
|
|
225
|
+
*/
|
|
226
|
+
function buildContextQuery(args) {
|
|
227
|
+
const parts = [];
|
|
228
|
+
if (args.project) parts.push(args.project);
|
|
229
|
+
if (args.topics) parts.push(args.topics);
|
|
230
|
+
if (args.task) parts.push(args.task);
|
|
231
|
+
|
|
232
|
+
// If still empty, use a broad query
|
|
233
|
+
return parts.length > 0 ? parts.join(' ') : '*';
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Parse CLI arguments.
|
|
238
|
+
*/
|
|
239
|
+
function parseArgs(argv) {
|
|
240
|
+
const args = {
|
|
241
|
+
query: null,
|
|
242
|
+
project: null,
|
|
243
|
+
task: null,
|
|
244
|
+
topics: null,
|
|
245
|
+
top: 10,
|
|
246
|
+
context: false,
|
|
247
|
+
reindex: false,
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const positional = [];
|
|
251
|
+
|
|
252
|
+
for (let i = 0; i < argv.length; i++) {
|
|
253
|
+
switch (argv[i]) {
|
|
254
|
+
case '--project':
|
|
255
|
+
args.project = argv[++i];
|
|
256
|
+
break;
|
|
257
|
+
case '--task':
|
|
258
|
+
args.task = argv[++i];
|
|
259
|
+
break;
|
|
260
|
+
case '--topics':
|
|
261
|
+
args.topics = argv[++i];
|
|
262
|
+
break;
|
|
263
|
+
case '--top':
|
|
264
|
+
args.top = parseInt(argv[++i], 10);
|
|
265
|
+
break;
|
|
266
|
+
case '--context':
|
|
267
|
+
args.context = true;
|
|
268
|
+
break;
|
|
269
|
+
case '--reindex':
|
|
270
|
+
args.reindex = true;
|
|
271
|
+
break;
|
|
272
|
+
default:
|
|
273
|
+
if (!argv[i].startsWith('--')) {
|
|
274
|
+
positional.push(argv[i]);
|
|
275
|
+
}
|
|
276
|
+
break;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
if (positional.length > 0) {
|
|
281
|
+
args.query = positional.join(' ');
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return args;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
main();
|
package/bin/reinforce.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
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
|
+
validateBrainPath,
|
|
34
|
+
} = require('../src/index-manager');
|
|
35
|
+
|
|
36
|
+
const {
|
|
37
|
+
reinforceStrength,
|
|
38
|
+
improveDecayRate,
|
|
39
|
+
} = require('../src/scorer');
|
|
40
|
+
|
|
41
|
+
function main() {
|
|
42
|
+
const args = parseArgs(process.argv.slice(2));
|
|
43
|
+
|
|
44
|
+
if (args.memoryIds.length === 0) {
|
|
45
|
+
console.error(JSON.stringify({ error: 'Usage: brain reinforce <mem_id1> [mem_id2] ...' }));
|
|
46
|
+
process.exit(1);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const brainDir = getBrainDir();
|
|
50
|
+
let index;
|
|
51
|
+
try {
|
|
52
|
+
index = readIndex();
|
|
53
|
+
} catch (err) {
|
|
54
|
+
console.error(JSON.stringify({
|
|
55
|
+
error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
|
|
56
|
+
}));
|
|
57
|
+
process.exit(1);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (!index) {
|
|
61
|
+
console.error(JSON.stringify({ error: 'Brain not initialized.' }));
|
|
62
|
+
process.exit(1);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const now = new Date();
|
|
66
|
+
const nowISO = now.toISOString();
|
|
67
|
+
const reinforced = [];
|
|
68
|
+
|
|
69
|
+
// Apply spaced reinforcement to each memory
|
|
70
|
+
for (const memId of args.memoryIds) {
|
|
71
|
+
const entry = index.memories[memId];
|
|
72
|
+
if (!entry) continue;
|
|
73
|
+
|
|
74
|
+
const lastAccessed = new Date(entry.last_accessed || entry.created);
|
|
75
|
+
const daysSince = (now - lastAccessed) / (1000 * 60 * 60 * 24);
|
|
76
|
+
const accessCount = entry.access_count || 0;
|
|
77
|
+
|
|
78
|
+
// Compute boost
|
|
79
|
+
const oldStrength = entry.strength;
|
|
80
|
+
const newStrength = reinforceStrength(oldStrength, daysSince, accessCount);
|
|
81
|
+
const newDecayRate = improveDecayRate(entry.decay_rate);
|
|
82
|
+
|
|
83
|
+
// Update index entry
|
|
84
|
+
entry.strength = Math.round(newStrength * 1000) / 1000;
|
|
85
|
+
entry.decay_rate = Math.round(newDecayRate * 10000) / 10000;
|
|
86
|
+
entry.last_accessed = nowISO;
|
|
87
|
+
entry.access_count = accessCount + 1;
|
|
88
|
+
|
|
89
|
+
// Update the memory file's frontmatter on disk
|
|
90
|
+
updateMemoryFile(brainDir, entry.path, {
|
|
91
|
+
strength: entry.strength,
|
|
92
|
+
decay_rate: entry.decay_rate,
|
|
93
|
+
last_accessed: nowISO,
|
|
94
|
+
access_count: entry.access_count,
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
reinforced.push({
|
|
98
|
+
id: memId,
|
|
99
|
+
old_strength: oldStrength,
|
|
100
|
+
new_strength: entry.strength,
|
|
101
|
+
boost: Math.round((newStrength - oldStrength) * 1000) / 1000,
|
|
102
|
+
decay_rate: entry.decay_rate,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Save index
|
|
107
|
+
writeIndex(index);
|
|
108
|
+
|
|
109
|
+
// Hebbian co-retrieval: strengthen edges between all pairs
|
|
110
|
+
let edgesReinforced = 0;
|
|
111
|
+
if (args.memoryIds.length > 1) {
|
|
112
|
+
let associations = readAssociations() || { version: 1, edges: {} };
|
|
113
|
+
|
|
114
|
+
for (let i = 0; i < args.memoryIds.length; i++) {
|
|
115
|
+
for (let j = i + 1; j < args.memoryIds.length; j++) {
|
|
116
|
+
const idA = args.memoryIds[i];
|
|
117
|
+
const idB = args.memoryIds[j];
|
|
118
|
+
// Only reinforce if both exist in index
|
|
119
|
+
if (index.memories[idA] && index.memories[idB]) {
|
|
120
|
+
reinforceEdge(associations, idA, idB, 'co_retrieval');
|
|
121
|
+
edgesReinforced++;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
writeAssociations(associations);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
console.log(JSON.stringify({
|
|
130
|
+
reinforced,
|
|
131
|
+
edges_reinforced: edgesReinforced,
|
|
132
|
+
}, null, 2));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Update a memory file's YAML frontmatter fields on disk.
|
|
137
|
+
*
|
|
138
|
+
* @param {string} brainDir - Path to ~/.brain/
|
|
139
|
+
* @param {string} memPath - Relative path to memory file
|
|
140
|
+
* @param {Object} updates - Fields to update in frontmatter
|
|
141
|
+
*/
|
|
142
|
+
function updateMemoryFile(brainDir, memPath, updates) {
|
|
143
|
+
const fullPath = path.join(brainDir, memPath);
|
|
144
|
+
try {
|
|
145
|
+
// The path comes from index.json — which syncs across devices, so a
|
|
146
|
+
// tampered index entry must not become a write primitive outside ~/.brain.
|
|
147
|
+
validateBrainPath(fullPath, brainDir);
|
|
148
|
+
let content = fs.readFileSync(fullPath, 'utf-8');
|
|
149
|
+
|
|
150
|
+
// Find frontmatter boundaries
|
|
151
|
+
const firstDash = content.indexOf('---');
|
|
152
|
+
const secondDash = content.indexOf('---', firstDash + 3);
|
|
153
|
+
if (firstDash === -1 || secondDash === -1) return;
|
|
154
|
+
|
|
155
|
+
let frontmatter = content.slice(firstDash + 3, secondDash);
|
|
156
|
+
|
|
157
|
+
// Update each field in the YAML
|
|
158
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
159
|
+
const regex = new RegExp(`^(${key}:\\s*).*$`, 'm');
|
|
160
|
+
const formatted = typeof value === 'string' ? `"${value}"` : String(value);
|
|
161
|
+
if (regex.test(frontmatter)) {
|
|
162
|
+
frontmatter = frontmatter.replace(regex, `$1${formatted}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
content = content.slice(0, firstDash + 3) + frontmatter + content.slice(secondDash);
|
|
167
|
+
fs.writeFileSync(fullPath, content);
|
|
168
|
+
} catch { /* skip if file not readable/writable */ }
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Parse CLI arguments.
|
|
173
|
+
*/
|
|
174
|
+
function parseArgs(argv) {
|
|
175
|
+
const args = {
|
|
176
|
+
memoryIds: [],
|
|
177
|
+
project: null,
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
for (let i = 0; i < argv.length; i++) {
|
|
181
|
+
if (argv[i] === '--project') {
|
|
182
|
+
args.project = argv[++i];
|
|
183
|
+
} else if (!argv[i].startsWith('--')) {
|
|
184
|
+
args.memoryIds.push(argv[i]);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return args;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
main();
|
package/bin/restore.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* brain restore — roll the whole brain back to a previous restore point.
|
|
5
|
+
*
|
|
6
|
+
* Two sources of restore points:
|
|
7
|
+
* git (default) Commits in the Git sync history (~/.brain/.sync/repo/) —
|
|
8
|
+
* one per push, plus a pre-restore safety snapshot taken
|
|
9
|
+
* automatically before every restore.
|
|
10
|
+
* cloud Brain Cloud's pre-overwrite snapshots — one is taken
|
|
11
|
+
* server-side before every `brain cloud push` commit.
|
|
12
|
+
*
|
|
13
|
+
* Usage:
|
|
14
|
+
* brain restore --list [--from git|cloud] [--limit N]
|
|
15
|
+
* brain restore --to <commit|version> [--from git|cloud] [--passphrase <p>]
|
|
16
|
+
*
|
|
17
|
+
* Both sources are undoable: git commits a safety snapshot first; cloud writes
|
|
18
|
+
* a local pre-restore backup under ~/.brain/.cloud/. audit.log is carried
|
|
19
|
+
* forward through every restore, and every restore is itself logged there.
|
|
20
|
+
* Output: JSON.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const fs = require('fs');
|
|
24
|
+
const path = require('path');
|
|
25
|
+
|
|
26
|
+
const { listRestorePoints, restoreTo } = require('../src/git-sync');
|
|
27
|
+
const { getBrainDir, readIndex } = require('../src/index-manager');
|
|
28
|
+
const { readSearchIndex, writeSearchIndex, rebuildIndex, isSearchIndexStale } = require('../src/tfidf');
|
|
29
|
+
const { appendAudit } = require('../src/audit');
|
|
30
|
+
|
|
31
|
+
function parseArgs(argv) {
|
|
32
|
+
const args = { list: false, to: null, from: 'git', limit: 20, passphrase: null };
|
|
33
|
+
for (let i = 0; i < argv.length; i++) {
|
|
34
|
+
switch (argv[i]) {
|
|
35
|
+
case '--list': args.list = true; break;
|
|
36
|
+
case '--to': args.to = argv[++i]; break;
|
|
37
|
+
case '--from': args.from = argv[++i]; break;
|
|
38
|
+
case '--limit': args.limit = parseInt(argv[++i], 10) || 20; break;
|
|
39
|
+
case '--passphrase': args.passphrase = argv[++i]; break;
|
|
40
|
+
default: break;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return args;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The restored search index normally matches the restored index.json, but
|
|
48
|
+
* rebuild defensively when it drifted (matches recall.js's staleness rule).
|
|
49
|
+
*/
|
|
50
|
+
function reindexIfStale(brainDir) {
|
|
51
|
+
try {
|
|
52
|
+
const index = readIndex();
|
|
53
|
+
let searchIndex = null;
|
|
54
|
+
try { searchIndex = readSearchIndex(brainDir); } catch { searchIndex = null; }
|
|
55
|
+
if (index && isSearchIndexStale(searchIndex, index)) {
|
|
56
|
+
writeSearchIndex(brainDir, rebuildIndex(brainDir, index));
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
} catch { /* index unreadable — surfaced by the next recall, not here */ }
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function main(argv) {
|
|
64
|
+
const args = parseArgs(argv || process.argv.slice(2));
|
|
65
|
+
const brainDir = getBrainDir();
|
|
66
|
+
|
|
67
|
+
if (args.from !== 'git' && args.from !== 'cloud') {
|
|
68
|
+
console.error(JSON.stringify({ error: `Unknown source "${args.from}" (expected git or cloud)` }));
|
|
69
|
+
process.exit(1);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
if (args.list) {
|
|
74
|
+
if (args.from === 'cloud') {
|
|
75
|
+
const cloud = require('../src/cloud-sync');
|
|
76
|
+
const versions = await cloud.listVersions(brainDir);
|
|
77
|
+
console.log(JSON.stringify({ source: 'cloud', restore_points: versions.slice(0, args.limit), total: versions.length }, null, 2));
|
|
78
|
+
} else {
|
|
79
|
+
const points = listRestorePoints(brainDir, args.limit);
|
|
80
|
+
console.log(JSON.stringify({ source: 'git', restore_points: points, total: points.length }, null, 2));
|
|
81
|
+
}
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!args.to) {
|
|
86
|
+
console.error(JSON.stringify({
|
|
87
|
+
error: 'Usage: brain restore --list [--from git|cloud] | brain restore --to <point> [--from git|cloud] [--passphrase <p>]',
|
|
88
|
+
}));
|
|
89
|
+
process.exit(1);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
let result;
|
|
93
|
+
if (args.from === 'cloud') {
|
|
94
|
+
const cloud = require('../src/cloud-sync');
|
|
95
|
+
result = await cloud.restoreVersion(brainDir, args.to);
|
|
96
|
+
} else {
|
|
97
|
+
result = restoreTo(brainDir, args.to, args.passphrase || undefined);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const reindexed = reindexIfStale(brainDir);
|
|
101
|
+
|
|
102
|
+
appendAudit(brainDir, {
|
|
103
|
+
ts: new Date().toISOString(),
|
|
104
|
+
event: 'restore',
|
|
105
|
+
source: args.from,
|
|
106
|
+
...(args.from === 'cloud'
|
|
107
|
+
? { restored_version: result.restored_version, backup: result.backup }
|
|
108
|
+
: { restored_to: result.restored_to, safety_commit: result.safety_commit, restore_commit: result.restore_commit }),
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
console.log(JSON.stringify({ source: args.from, ...result, reindexed }, null, 2));
|
|
112
|
+
} catch (err) {
|
|
113
|
+
console.error(JSON.stringify({ error: err.message }));
|
|
114
|
+
process.exit(1);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
if (require.main === module) {
|
|
119
|
+
main(process.argv.slice(2));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
module.exports = { main, parseArgs };
|