brain-memory 0.1.0-beta.9 → 0.2.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.
Files changed (82) hide show
  1. package/CHANGELOG.md +632 -0
  2. package/README.md +390 -84
  3. package/SECURITY.md +100 -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/audit.js +93 -0
  26. package/bin/brain.js +132 -0
  27. package/bin/cloud-sync.js +150 -0
  28. package/bin/forget.js +172 -0
  29. package/bin/import.js +132 -0
  30. package/bin/install.js +63 -31
  31. package/bin/memorize.js +670 -0
  32. package/bin/pin.js +44 -0
  33. package/bin/recall.js +319 -0
  34. package/bin/reinforce.js +191 -0
  35. package/bin/restore.js +122 -0
  36. package/bin/session-start.js +352 -0
  37. package/bin/skill.js +67 -0
  38. package/bin/unpin.js +38 -0
  39. package/bin/verify.js +186 -0
  40. package/commands/brain/forget.md +243 -13
  41. package/commands/brain/import.md +125 -0
  42. package/commands/brain/memorize.md +108 -130
  43. package/commands/brain/pin.md +79 -0
  44. package/commands/brain/remember.md +59 -100
  45. package/commands/brain/skills.md +60 -0
  46. package/commands/brain/sleep.md +93 -6
  47. package/commands/brain/status.md +15 -6
  48. package/commands/brain/sync.md +181 -17
  49. package/commands/brain/verify.md +63 -0
  50. package/integrations/README.md +29 -0
  51. package/integrations/agentskills/brain-memory/SKILL.md +115 -0
  52. package/integrations/agentskills/brain-memory/scripts/session-start.mjs +34 -0
  53. package/package.json +19 -7
  54. package/prompts/antigravity.md +222 -0
  55. package/prompts/claude.md +128 -40
  56. package/prompts/copilot.md +224 -0
  57. package/prompts/kilo.md +223 -0
  58. package/prompts/openai.md +133 -45
  59. package/prompts/opencode.md +221 -0
  60. package/src/anomaly.js +260 -0
  61. package/src/audit.js +71 -0
  62. package/src/cloud-sync.js +672 -0
  63. package/src/content-lint.js +118 -0
  64. package/src/export-import.js +45 -7
  65. package/src/git-sync.js +170 -11
  66. package/src/harvest.js +562 -0
  67. package/src/index-manager.js +250 -11
  68. package/src/installer.js +250 -29
  69. package/src/pinning.js +146 -0
  70. package/src/provenance.js +79 -0
  71. package/src/quarantine.js +111 -0
  72. package/src/receipt.js +87 -0
  73. package/src/scorer.js +137 -12
  74. package/src/skills.js +208 -0
  75. package/src/temporal.js +228 -0
  76. package/src/tfidf.js +520 -0
  77. package/commands/brain/consolidate.md +0 -153
  78. package/commands/brain/explore.md +0 -79
  79. package/commands/brain/init.md +0 -149
  80. package/commands/brain/review.md +0 -130
  81. package/commands/brain/sunshine.md +0 -337
  82. package/prompts/gemini.md +0 -134
package/bin/pin.js ADDED
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain pin — pin a memory into the always-present semantic tier (CoALA Phase 1).
5
+ *
6
+ * Usage:
7
+ * brain pin <id> [--scope global|project:<name>] [--priority N]
8
+ */
9
+
10
+ const { pinMemory } = require('../src/pinning');
11
+
12
+ function parseArgs(argv) {
13
+ const args = { id: null, scope: 'global', priority: 0 };
14
+ for (let i = 0; i < argv.length; i++) {
15
+ switch (argv[i]) {
16
+ case '--scope': args.scope = argv[++i]; break;
17
+ case '--priority': args.priority = parseInt(argv[++i], 10) || 0; break;
18
+ default:
19
+ if (!argv[i].startsWith('--') && !args.id) args.id = argv[i];
20
+ break;
21
+ }
22
+ }
23
+ return args;
24
+ }
25
+
26
+ function main(argv) {
27
+ const args = parseArgs(argv || process.argv.slice(2));
28
+ if (!args.id) {
29
+ console.error(JSON.stringify({ error: 'Usage: brain pin <id> [--scope global|project:<name>] [--priority N]' }));
30
+ process.exit(1);
31
+ }
32
+ const result = pinMemory(undefined, args.id, { scope: args.scope, priority: args.priority });
33
+ if (result.error) {
34
+ console.error(JSON.stringify(result));
35
+ process.exit(1);
36
+ }
37
+ console.log(JSON.stringify(result, null, 2));
38
+ }
39
+
40
+ if (require.main === module) {
41
+ main(process.argv.slice(2));
42
+ }
43
+
44
+ module.exports = { main, parseArgs };
package/bin/recall.js ADDED
@@ -0,0 +1,319 @@
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
+ * brain recall "deploy target" --as-of 2026-03-01
15
+ * # Valid time: what was TRUE then
16
+ * brain recall "deploy target" --as-known-of 2026-03-01
17
+ * # Record time: what the brain KNEW then
18
+ *
19
+ * Output: JSON array of scored results, sorted by score descending.
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const os = require('os');
25
+
26
+ const {
27
+ readSearchIndex,
28
+ writeSearchIndex,
29
+ search,
30
+ bm25Search,
31
+ rebuildIndex,
32
+ createSearchIndex,
33
+ isSearchIndexStale,
34
+ } = require('../src/tfidf');
35
+
36
+ const {
37
+ readIndex,
38
+ readAssociations,
39
+ readConfig,
40
+ getBrainDir,
41
+ } = require('../src/index-manager');
42
+
43
+ const {
44
+ rankMemories,
45
+ } = require('../src/scorer');
46
+
47
+ const { receiptFor } = require('../src/receipt');
48
+ const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
49
+ const { parseInstant } = require('../src/temporal');
50
+
51
+ // Minimum relevance (or spreading bonus) for a memory to appear in explicit-
52
+ // query results. Filters the zero/near-zero-relevance memories that would
53
+ // otherwise pad the top-N purely on strength — an agent trusting those scores
54
+ // injects noise into its context. Context mode (--context) is exempt: there
55
+ // the query is just a topical hint and strength-ranked padding is intended.
56
+ const RELEVANCE_FLOOR = 0.05;
57
+
58
+ function main() {
59
+ const args = parseArgs(process.argv.slice(2));
60
+
61
+ const brainDir = getBrainDir();
62
+
63
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
64
+ console.error(JSON.stringify({ error: 'Brain not initialized. Reinstall with `npx brain-memory`, or run /brain:sync to create it.' }));
65
+ process.exit(1);
66
+ }
67
+
68
+ // Reindex mode
69
+ if (args.reindex) {
70
+ return handleReindex(brainDir);
71
+ }
72
+
73
+ // An unparseable time-travel bound must fail loudly: silently ignoring it
74
+ // would answer a point-in-time question with present-day memories.
75
+ for (const [flag, value] of [['--as-of', args.asOf], ['--as-known-of', args.asKnownOf]]) {
76
+ if (value != null && parseInstant(value) == null) {
77
+ console.error(JSON.stringify({ error: `Invalid ${flag} value: ${JSON.stringify(value)} — expected an ISO date (e.g. 2026-03-01)` }));
78
+ process.exit(1);
79
+ }
80
+ }
81
+
82
+ // Need a query for search
83
+ if (!args.query && !args.context) {
84
+ console.error(JSON.stringify({ error: 'Usage: brain recall "query" or brain recall --context' }));
85
+ process.exit(1);
86
+ }
87
+
88
+ let index;
89
+ try {
90
+ index = readIndex();
91
+ } catch (err) {
92
+ console.error(JSON.stringify({
93
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
94
+ }));
95
+ process.exit(1);
96
+ }
97
+ if (!index || !index.memories || Object.keys(index.memories).length === 0) {
98
+ console.log(JSON.stringify([]));
99
+ return;
100
+ }
101
+
102
+ // Ensure search index exists
103
+ let searchIndex;
104
+ try {
105
+ searchIndex = readSearchIndex(brainDir);
106
+ } catch (_) {
107
+ searchIndex = null;
108
+ }
109
+ // Rebuild when ABSENT *or* STALE. The search index drifts out of sync with
110
+ // index.json whenever memories change outside memorize's addDocument path
111
+ // (forget, sleep/consolidate, sync pull, manual edit) — and a present-but-
112
+ // empty index silently makes every relevance score 0. Compare the doc set,
113
+ // not just presence.
114
+ if (isSearchIndexStale(searchIndex, index)) {
115
+ searchIndex = rebuildIndex(brainDir, index);
116
+ writeSearchIndex(brainDir, searchIndex);
117
+ }
118
+
119
+ // Context mode: build query from project context
120
+ const query = args.context
121
+ ? buildContextQuery(args)
122
+ : args.query;
123
+
124
+ // Compute relevance scores (BM25 — length-normalized, TF-saturated; better
125
+ // than raw TF-IDF cosine at surfacing long, detailed memories under noise).
126
+ const tfidfScores = bm25Search(searchIndex, query);
127
+
128
+ // Build memory list from index. In enforce mode, quarantined (pending-
129
+ // verification) memories are excluded here — before ranking — which also
130
+ // removes them as spreading-activation sources. readConfig tolerates a
131
+ // missing/corrupt config.json (falls back to the 'flag' default).
132
+ const quarantineMode = readConfig().quarantine_mode || 'flag';
133
+ const memories = Object.entries(index.memories)
134
+ .filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
135
+ .map(([id, entry]) => ({
136
+ id,
137
+ ...entry,
138
+ }));
139
+
140
+ // Load associations for spreading activation
141
+ let associations;
142
+ try {
143
+ associations = readAssociations();
144
+ } catch (_) {
145
+ associations = null;
146
+ }
147
+
148
+ // Build recall context
149
+ const recallContext = {};
150
+ if (args.project) recallContext.project = args.project;
151
+ if (args.task) recallContext.task_type = args.task;
152
+ if (args.topics) recallContext.topics = args.topics.split(',');
153
+
154
+ // Rank using scorer.js with TF-IDF as the relevance function
155
+ const ranked = rankMemories(
156
+ memories,
157
+ (mem) => tfidfScores[mem.id] || 0,
158
+ {
159
+ associations: associations || undefined,
160
+ recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
161
+ relevanceFloor: args.context ? undefined : RELEVANCE_FLOOR,
162
+ // Bitemporal travel: --as-of filters on valid time (the fact was true
163
+ // then), --as-known-of on record time (the brain had it by then).
164
+ asOf: args.asOf,
165
+ asKnownOf: args.asKnownOf,
166
+ }
167
+ );
168
+
169
+ // Return top N
170
+ const top = args.top || 10;
171
+ const results = ranked.slice(0, top).map((mem) => {
172
+ const title = mem.title || path.basename(mem.path, '.md');
173
+ const origin = mem.origin || DEFAULT_ORIGIN;
174
+ return {
175
+ id: mem.id,
176
+ title,
177
+ path: mem.path,
178
+ type: mem.type,
179
+ score: mem.score,
180
+ relevance: mem.relevance,
181
+ decayed_strength: mem.decayed_strength,
182
+ context_match: mem.context_match,
183
+ spreading_bonus: mem.spreading_bonus,
184
+ confidence: mem.confidence,
185
+ // Provenance travels with every result so the agent can answer
186
+ // "where did you get that?" without opening the memory file.
187
+ origin,
188
+ ...(isLowTrust(origin) ? { low_trust: true } : {}),
189
+ // Pending verification (flag mode): recallable but visibly marked, so
190
+ // the agent can caveat an answer built on an unverified memory.
191
+ ...(mem.quarantined ? { quarantine_pending: true } : {}),
192
+ // Temporal invalidation: a newer memory replaced this one. Surfaced so
193
+ // the agent can say "this was true until <the successor>" rather than
194
+ // presenting a stale fact as current.
195
+ ...(mem.superseded_by ? { superseded_by: mem.superseded_by } : {}),
196
+ // Bitemporal valid time — when the fact was true, as distinct from
197
+ // `created` (when it was recorded). `expired` means the window has
198
+ // closed: answer with "that was true until <valid_until>", not as fact.
199
+ ...(mem.valid_from ? { valid_from: mem.valid_from } : {}),
200
+ ...(mem.valid_until ? { valid_until: mem.valid_until } : {}),
201
+ ...(mem.temporal_state === 'expired' ? { expired: true } : {}),
202
+ tags: mem.tags,
203
+ // Recall receipt — the engine mints it, agents copy it verbatim when
204
+ // this memory materially shapes an answer (so it can't be hallucinated).
205
+ receipt: receiptFor({ ...mem, title }),
206
+ };
207
+ });
208
+
209
+ console.log(JSON.stringify(results, null, 2));
210
+ }
211
+
212
+ /**
213
+ * The TF-IDF search index is stale if it is missing, has a different document
214
+ * count than the live index, or is missing any indexed memory id. Catches the
215
+ * empty-index and add/remove/rename drift cases (in-place same-id body edits
216
+ * are not detected by count alone — acceptable until a version/mtime check).
217
+ */
218
+ /**
219
+ * Rebuild the search index from all memories.
220
+ */
221
+ function handleReindex(brainDir) {
222
+ let index;
223
+ try {
224
+ index = readIndex();
225
+ } catch (err) {
226
+ console.error(JSON.stringify({
227
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
228
+ }));
229
+ process.exit(1);
230
+ }
231
+ if (!index) {
232
+ console.error(JSON.stringify({ error: 'No index.json found.' }));
233
+ process.exit(1);
234
+ }
235
+
236
+ const searchIndex = rebuildIndex(brainDir, index);
237
+ writeSearchIndex(brainDir, searchIndex);
238
+
239
+ console.log(JSON.stringify({
240
+ reindexed: true,
241
+ documents: searchIndex.doc_count,
242
+ terms: Object.keys(searchIndex.df).length,
243
+ }));
244
+ }
245
+
246
+ /**
247
+ * Build a query from context when no explicit query is given.
248
+ * Uses project name and topics as search terms.
249
+ */
250
+ function buildContextQuery(args) {
251
+ const parts = [];
252
+ if (args.project) parts.push(args.project);
253
+ if (args.topics) parts.push(args.topics);
254
+ if (args.task) parts.push(args.task);
255
+
256
+ // If still empty, use a broad query
257
+ return parts.length > 0 ? parts.join(' ') : '*';
258
+ }
259
+
260
+ /**
261
+ * Parse CLI arguments.
262
+ */
263
+ function parseArgs(argv) {
264
+ const args = {
265
+ query: null,
266
+ project: null,
267
+ task: null,
268
+ topics: null,
269
+ top: 10,
270
+ context: false,
271
+ reindex: false,
272
+ asOf: null,
273
+ asKnownOf: null,
274
+ };
275
+
276
+ const positional = [];
277
+
278
+ for (let i = 0; i < argv.length; i++) {
279
+ switch (argv[i]) {
280
+ case '--project':
281
+ args.project = argv[++i];
282
+ break;
283
+ case '--task':
284
+ args.task = argv[++i];
285
+ break;
286
+ case '--topics':
287
+ args.topics = argv[++i];
288
+ break;
289
+ case '--top':
290
+ args.top = parseInt(argv[++i], 10);
291
+ break;
292
+ case '--context':
293
+ args.context = true;
294
+ break;
295
+ case '--reindex':
296
+ args.reindex = true;
297
+ break;
298
+ case '--as-of':
299
+ args.asOf = argv[++i];
300
+ break;
301
+ case '--as-known-of':
302
+ args.asKnownOf = argv[++i];
303
+ break;
304
+ default:
305
+ if (!argv[i].startsWith('--')) {
306
+ positional.push(argv[i]);
307
+ }
308
+ break;
309
+ }
310
+ }
311
+
312
+ if (positional.length > 0) {
313
+ args.query = positional.join(' ');
314
+ }
315
+
316
+ return args;
317
+ }
318
+
319
+ main();
@@ -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 };