brain-memory 0.1.0-beta.9 → 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.
Files changed (81) hide show
  1. package/CHANGELOG.md +555 -0
  2. package/README.md +385 -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 +163 -0
  29. package/bin/import.js +132 -0
  30. package/bin/install.js +63 -31
  31. package/bin/memorize.js +637 -0
  32. package/bin/pin.js +44 -0
  33. package/bin/recall.js +287 -0
  34. package/bin/reinforce.js +191 -0
  35. package/bin/restore.js +122 -0
  36. package/bin/session-start.js +337 -0
  37. package/bin/skill.js +67 -0
  38. package/bin/unpin.js +38 -0
  39. package/bin/verify.js +154 -0
  40. package/commands/brain/forget.md +243 -13
  41. package/commands/brain/import.md +125 -0
  42. package/commands/brain/memorize.md +95 -137
  43. package/commands/brain/pin.md +79 -0
  44. package/commands/brain/remember.md +53 -103
  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 +57 -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 +201 -0
  55. package/prompts/claude.md +107 -40
  56. package/prompts/copilot.md +203 -0
  57. package/prompts/kilo.md +202 -0
  58. package/prompts/openai.md +112 -45
  59. package/prompts/opencode.md +200 -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 +81 -0
  73. package/src/scorer.js +69 -12
  74. package/src/skills.js +208 -0
  75. package/src/tfidf.js +520 -0
  76. package/commands/brain/consolidate.md +0 -153
  77. package/commands/brain/explore.md +0 -79
  78. package/commands/brain/init.md +0 -149
  79. package/commands/brain/review.md +0 -130
  80. package/commands/brain/sunshine.md +0 -337
  81. package/prompts/gemini.md +0 -134
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Brain Memory — Content Lint (OWASP ASI06: memory poisoning)
3
+ *
4
+ * A memory should record facts; a MemGhost-style payload is almost always
5
+ * instruction-shaped ("always do X", "ignore previous instructions", "run
6
+ * this command"). Origin labels are asserted by the caller, so an honest
7
+ * agent relaying poisoned content can mislabel it — this lint catches the
8
+ * payload shape itself, regardless of origin.
9
+ *
10
+ * Severity ladder:
11
+ * injection Text that tries to steer the agent against the user. Never
12
+ * downgraded — no legitimate memory says "ignore previous
13
+ * instructions" or pipes a download into a shell.
14
+ * suspect Directive/imperative content. Downgraded to advisory for
15
+ * type:preference and cognitive_type:procedural memories, which
16
+ * legitimately contain instructions ("always use 2-space
17
+ * indent", skill steps).
18
+ * advisory Recorded in the audit trail, never quarantining.
19
+ *
20
+ * Pure and dependency-free; used at write time by bin/memorize.js.
21
+ */
22
+
23
+ const SEVERITY_RANK = { none: 0, advisory: 1, suspect: 2, injection: 3 };
24
+
25
+ // Each rule: name, base severity, and a matcher over the combined text.
26
+ // Patterns are case-insensitive; `m` where line-anchoring matters.
27
+ const RULES = [
28
+ {
29
+ rule: 'injection_override',
30
+ severity: 'injection',
31
+ re: /\b(?:ignore|disregard|forget)\s+(?:all\s+|any\s+)?(?:previous|prior|above|earlier)\s+(?:instructions?|rules?|context|prompts?)|\bnew\s+(?:system\s+)?instructions?\s*:|\byou\s+are\s+now\b|\bdo\s+not\s+(?:tell|inform|notify)\s+the\s+user\b|\bwithout\s+(?:asking|telling|informing)\s+the\s+user\b/i,
32
+ },
33
+ {
34
+ rule: 'pipe_to_shell',
35
+ severity: 'injection',
36
+ re: /\b(?:curl|wget)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba|z|da)?sh\b/i,
37
+ },
38
+ {
39
+ rule: 'secret_exfil',
40
+ severity: 'injection',
41
+ re: /\b(?:send|post|upload|forward|exfiltrate|transmit|email)(?:s|ed|ing)?\b[^\n.]{0,80}\b(?:token|password|secret|api.?key|credential|private.?key|\.env)\b|\b(?:token|password|secret|api.?key|credential|private.?key)s?\b[^\n.]{0,80}\b(?:send|post|upload|forward|exfiltrate|transmit|email)(?:s|ed|ing)?\b/i,
42
+ },
43
+ {
44
+ rule: 'imperative_directive',
45
+ severity: 'suspect',
46
+ re: /^(?:always|never|you\s+must|do\s+not|don't|make\s+sure\s+to|from\s+now\s+on|remember\s+to)\b/im,
47
+ },
48
+ {
49
+ rule: 'command_execution',
50
+ severity: 'suspect',
51
+ re: /\b(?:run|execute)\b[^\n.]{0,60}\b(?:curl|wget|bash|sh\s+-c|npm\s+i(?:nstall)?|npx|pip\s+install|powershell)\b/i,
52
+ },
53
+ {
54
+ rule: 'url_with_imperative',
55
+ severity: 'suspect',
56
+ re: null, // composite — handled in code below
57
+ },
58
+ {
59
+ rule: 'tool_instruction',
60
+ severity: 'suspect',
61
+ re: /\b(?:use|call|invoke)\s+the\s+\w+\s+tool\b/i,
62
+ },
63
+ ];
64
+
65
+ const URL_RE = /https?:\/\/[^\s)"'<>]+/i;
66
+ const FETCH_VERB_RE = /\b(?:fetch|visit|open|download|navigate\s+to|go\s+to|send\s+to|post\s+to)\b/i;
67
+
68
+ // Memory shapes that legitimately contain instructions.
69
+ function isInstructionalShape(mem) {
70
+ return mem.type === 'preference' || mem.cognitive_type === 'procedural';
71
+ }
72
+
73
+ /** First ~60 chars of the matched region, for the audit trail. */
74
+ function excerptAround(text, match) {
75
+ if (!match) return '';
76
+ const idx = text.toLowerCase().indexOf(match.toLowerCase());
77
+ const start = Math.max(0, idx);
78
+ return text.slice(start, start + 60).replace(/\s+/g, ' ').trim();
79
+ }
80
+
81
+ /**
82
+ * Lint a memory's title + content for instruction-shaped payloads.
83
+ *
84
+ * @param {Object} mem - { title, content, type, cognitive_type }
85
+ * @returns {{ flags: Array<{rule, severity, excerpt}>, severity: string }}
86
+ * `severity` is the highest flag severity ('none' when clean).
87
+ */
88
+ function lintMemoryContent(mem) {
89
+ const text = `${mem.title || ''}\n${mem.content || ''}`;
90
+ const downgrade = isInstructionalShape(mem);
91
+ const flags = [];
92
+
93
+ for (const r of RULES) {
94
+ let matched = null;
95
+ if (r.rule === 'url_with_imperative') {
96
+ if (URL_RE.test(text) && FETCH_VERB_RE.test(text)) {
97
+ matched = (text.match(URL_RE) || [''])[0];
98
+ }
99
+ } else {
100
+ const m = text.match(r.re);
101
+ if (m) matched = m[0];
102
+ }
103
+ if (!matched) continue;
104
+
105
+ // Injection rules are never downgraded; suspect rules become advisory for
106
+ // instruction-shaped memory types.
107
+ const severity = r.severity === 'suspect' && downgrade ? 'advisory' : r.severity;
108
+ flags.push({ rule: r.rule, severity, excerpt: excerptAround(text, matched) });
109
+ }
110
+
111
+ const severity = flags.reduce(
112
+ (top, f) => (SEVERITY_RANK[f.severity] > SEVERITY_RANK[top] ? f.severity : top),
113
+ 'none'
114
+ );
115
+ return { flags, severity };
116
+ }
117
+
118
+ module.exports = { lintMemoryContent, RULES, SEVERITY_RANK };
@@ -25,7 +25,7 @@ const EXCLUDED = new Set(['.sync', '.DS_Store']);
25
25
  */
26
26
  function exportBrain(brainDir, outputPath, passphrase) {
27
27
  if (!fs.existsSync(brainDir)) {
28
- throw new Error('~/.brain/ directory not found. Run /brain:init first.');
28
+ throw new Error('~/.brain/ directory not found. Reinstall with `npx brain-memory`, or run /brain:sync to create it.');
29
29
  }
30
30
 
31
31
  const files = {};
@@ -58,6 +58,10 @@ function collectFiles(dir, brainDir, files) {
58
58
  if (EXCLUDED.has(topLevel)) continue;
59
59
 
60
60
  const fullPath = path.join(dir, entry.name);
61
+ // Symlinks are skipped entirely: following one would copy whatever it
62
+ // points at (potentially outside ~/.brain, e.g. ~/.ssh keys) into an
63
+ // export that may be transferred or synced.
64
+ if (entry.isSymbolicLink()) continue;
61
65
  if (entry.isDirectory()) {
62
66
  collectFiles(fullPath, brainDir, files);
63
67
  } else {
@@ -68,6 +72,23 @@ function collectFiles(dir, brainDir, files) {
68
72
  }
69
73
  }
70
74
 
75
+ /**
76
+ * Reject export entries whose path would land outside ~/.brain/ — absolute
77
+ * paths or any `..` segment. A hostile .brain-export must fail loudly, not
78
+ * write ~/.ssh/authorized_keys.
79
+ *
80
+ * @param {string} relPath - Forward-slash relative path from the export file
81
+ * @returns {string} The OS-native relative path
82
+ * @throws {Error} on traversal
83
+ */
84
+ function safeNativePath(relPath) {
85
+ const segments = relPath.split('/');
86
+ if (relPath.startsWith('/') || /^[a-zA-Z]:/.test(relPath) || segments.includes('..') || segments.includes('')) {
87
+ throw new Error(`Invalid path in export file (traversal): ${relPath}`);
88
+ }
89
+ return segments.join(path.sep);
90
+ }
91
+
71
92
  /**
72
93
  * Import memories from a .brain-export file into ~/.brain/.
73
94
  *
@@ -105,7 +126,7 @@ function importBrain(inputPath, brainDir, passphrase, options = {}) {
105
126
  }
106
127
  }
107
128
 
108
- if (!payload || !payload.files || typeof payload.files !== 'object') {
129
+ if (!payload || !payload.files || typeof payload.files !== 'object' || Array.isArray(payload.files)) {
109
130
  throw new Error('Invalid export format: missing files object.');
110
131
  }
111
132
 
@@ -115,8 +136,8 @@ function importBrain(inputPath, brainDir, passphrase, options = {}) {
115
136
  let skipped = 0;
116
137
 
117
138
  for (const [relPath, content] of Object.entries(payload.files)) {
118
- // Convert forward-slash paths to OS-native
119
- const nativePath = relPath.split('/').join(path.sep);
139
+ // Convert forward-slash paths to OS-native, refusing traversal
140
+ const nativePath = safeNativePath(relPath);
120
141
  const destPath = path.join(brainDir, nativePath);
121
142
 
122
143
  if (mode === 'merge' && fs.existsSync(destPath)) {
@@ -151,9 +172,24 @@ function previewImport(inputPath, brainDir, passphrase) {
151
172
  let payload;
152
173
 
153
174
  if (passphrase) {
154
- payload = JSON.parse(decrypt(raw, passphrase));
175
+ try {
176
+ payload = JSON.parse(decrypt(raw, passphrase));
177
+ } catch (err) {
178
+ if (err.message.includes('Unsupported state') || err.message.includes('unable to authenticate') || err.message.includes('Invalid encrypted data')) {
179
+ throw new Error('Decryption failed — wrong passphrase or corrupted file.');
180
+ }
181
+ throw err;
182
+ }
155
183
  } else {
156
- payload = JSON.parse(raw.toString('utf8'));
184
+ try {
185
+ payload = JSON.parse(raw.toString('utf8'));
186
+ } catch {
187
+ throw new Error('Invalid export file. If the file is encrypted, provide a passphrase.');
188
+ }
189
+ }
190
+
191
+ if (!payload || !payload.files || typeof payload.files !== 'object' || Array.isArray(payload.files)) {
192
+ throw new Error('Invalid export format: missing files object.');
157
193
  }
158
194
 
159
195
  const files = Object.keys(payload.files);
@@ -161,7 +197,9 @@ function previewImport(inputPath, brainDir, passphrase) {
161
197
  const existingFiles = [];
162
198
 
163
199
  for (const relPath of files) {
164
- const nativePath = relPath.split('/').join(path.sep);
200
+ // Same traversal guard as importBrain — the preview is what the agent
201
+ // shows the user, so a hostile export must fail here too, not look benign.
202
+ const nativePath = safeNativePath(relPath);
165
203
  const destPath = path.join(brainDir, nativePath);
166
204
  if (fs.existsSync(destPath)) {
167
205
  existingFiles.push(relPath);
package/src/git-sync.js CHANGED
@@ -17,8 +17,10 @@ const SYNC_DIR = '.sync';
17
17
  const REPO_DIR = 'repo';
18
18
  const CONFIG_FILE = 'config.json';
19
19
 
20
- // Files/dirs inside ~/.brain/ that should NOT be synced
21
- const EXCLUDED = new Set(['.sync', '.DS_Store']);
20
+ // Files/dirs inside ~/.brain/ that should NOT be synced. `.cloud` holds Brain
21
+ // Cloud OAuth tokens and pre-restore backups — credentials must never be
22
+ // committed to a git remote.
23
+ const EXCLUDED = new Set(['.sync', '.cloud', '.DS_Store']);
22
24
 
23
25
  /**
24
26
  * Check whether `git` is available on PATH.
@@ -148,6 +150,10 @@ function copyDir(srcDir, destDir, brainDir, passphrase) {
148
150
  const srcPath = path.join(srcDir, entry.name);
149
151
  const destPath = path.join(destDir, entry.name);
150
152
 
153
+ // Symlinks are skipped: for a symlink entry isDirectory() is false, so the
154
+ // else-branch would readFileSync THROUGH the link — copying whatever it
155
+ // points at (e.g. ~/.ssh keys) into the sync repo and pushing it.
156
+ if (entry.isSymbolicLink()) continue;
151
157
  if (entry.isDirectory()) {
152
158
  fs.mkdirSync(destPath, { recursive: true });
153
159
  copyDir(srcPath, destPath, brainDir, passphrase);
@@ -185,10 +191,17 @@ function copyRepoDir(srcDir, destDir, repoDir, passphrase) {
185
191
  const srcPath = path.join(srcDir, entry.name);
186
192
  const destPath = path.join(destDir, entry.name);
187
193
 
194
+ // A symlink in the repo (a remote can commit one) is never materialized
195
+ // into ~/.brain, and an existing symlink at the destination is removed
196
+ // rather than written through.
197
+ if (entry.isSymbolicLink()) continue;
188
198
  if (entry.isDirectory()) {
189
199
  fs.mkdirSync(destPath, { recursive: true });
190
200
  copyRepoDir(srcPath, destPath, repoDir, passphrase);
191
201
  } else {
202
+ try {
203
+ if (fs.lstatSync(destPath).isSymbolicLink()) fs.rmSync(destPath, { force: true });
204
+ } catch (_) { /* destination doesn't exist */ }
192
205
  const content = fs.readFileSync(srcPath);
193
206
  if (passphrase) {
194
207
  fs.writeFileSync(destPath, decrypt(content, passphrase));
@@ -323,20 +336,51 @@ function pull(brainDir, passphrase) {
323
336
  if (config.remote) configureRemote(brainDir, config.remote);
324
337
  }
325
338
 
326
- // Pull
339
+ // Try fast-forward pull first
340
+ let pulled = false;
341
+ let hasConflicts = false;
342
+ let conflictFiles = [];
343
+
327
344
  try {
328
345
  git(repoDir, ['pull', 'origin', 'main', '--ff-only'], { timeout: 30000 });
346
+ pulled = true;
329
347
  } catch (err) {
330
- // Could be first pull (nothing to pull), or merge conflict
331
- if (err.message && err.message.includes('Not possible to fast-forward')) {
332
- return { pulled: false, message: 'Merge conflict detected. Push your local changes first, or manually resolve in ~/.brain/.sync/repo/' };
333
- }
334
- // First clone — try to set up tracking
348
+ // Fast-forward failed — try fetch + merge
335
349
  try {
336
350
  git(repoDir, ['fetch', 'origin'], { timeout: 15000 });
337
- git(repoDir, ['merge', 'origin/main', '--ff-only']);
338
351
  } catch {
339
- return { pulled: false, message: 'Remote has no commits yet or is unreachable.' };
352
+ return { pulled: false, hasConflicts: false, message: 'Remote is unreachable.' };
353
+ }
354
+
355
+ try {
356
+ git(repoDir, ['merge', 'origin/main']);
357
+ pulled = true;
358
+ } catch {
359
+ // Check for unmerged paths
360
+ try {
361
+ const status = git(repoDir, ['status', '--porcelain']);
362
+ conflictFiles = status
363
+ .split('\n')
364
+ .filter((line) => line.startsWith('U') || line.startsWith('AA') || line.startsWith('DD'))
365
+ .map((line) => line.slice(3));
366
+ hasConflicts = conflictFiles.length > 0;
367
+ } catch { /* ignore status errors */ }
368
+
369
+ // Abort the failed merge to leave repo clean
370
+ try {
371
+ git(repoDir, ['merge', '--abort']);
372
+ } catch { /* ignore if nothing to abort */ }
373
+
374
+ if (hasConflicts) {
375
+ return {
376
+ pulled: false,
377
+ hasConflicts: true,
378
+ conflictFiles,
379
+ message: `Merge conflict in ${conflictFiles.length} file(s). Push your local changes first or manually resolve.`,
380
+ };
381
+ }
382
+
383
+ return { pulled: false, hasConflicts: false, message: 'Remote has no commits yet or merge failed.' };
340
384
  }
341
385
  }
342
386
 
@@ -347,7 +391,120 @@ function pull(brainDir, passphrase) {
347
391
  config.lastPull = new Date().toISOString();
348
392
  writeConfig(configPath, config);
349
393
 
350
- return { pulled: true, message: `Pulled successfully at ${config.lastPull}` };
394
+ return { pulled: true, hasConflicts: false, message: `Pulled successfully at ${config.lastPull}` };
395
+ }
396
+
397
+ /**
398
+ * List restore points — the commits in the sync repo's history, newest first.
399
+ *
400
+ * A restore point exists for every push (and every pre-restore safety
401
+ * snapshot), so granularity follows how often the brain is pushed.
402
+ *
403
+ * @param {string} brainDir - Absolute path to ~/.brain/
404
+ * @param {number} [limit=20] - Maximum entries to return
405
+ * @returns {Array<{ commit: string, date: string, message: string }>}
406
+ */
407
+ function listRestorePoints(brainDir, limit = 20) {
408
+ const { repoDir, configPath } = resolvePaths(brainDir);
409
+ const config = readConfig(configPath);
410
+ if (!config) throw new Error('Sync not configured. Run /brain:sync setup first.');
411
+ if (!fs.existsSync(path.join(repoDir, '.git'))) return [];
412
+
413
+ let out;
414
+ try {
415
+ out = git(repoDir, ['log', '--pretty=format:%H%x09%cI%x09%s', '-n', String(limit)]);
416
+ } catch {
417
+ return []; // repo initialized but no commits yet
418
+ }
419
+ if (!out) return [];
420
+ return out.split('\n').map((line) => {
421
+ const [commit, date, ...subject] = line.split('\t');
422
+ return { commit, date, message: subject.join('\t') };
423
+ });
424
+ }
425
+
426
+ /**
427
+ * Remove everything inside ~/.brain/ except the excluded infrastructure
428
+ * entries (.sync/), so a restore can't leave orphaned post-snapshot files
429
+ * behind. Only called after the current state is committed to sync history.
430
+ */
431
+ function clearBrainDir(brainDir) {
432
+ for (const entry of fs.readdirSync(brainDir)) {
433
+ if (EXCLUDED.has(entry)) continue;
434
+ fs.rmSync(path.join(brainDir, entry), { recursive: true, force: true });
435
+ }
436
+ }
437
+
438
+ /**
439
+ * Restore ~/.brain/ to a previous restore point.
440
+ *
441
+ * History only moves forward: the current brain state is first committed as a
442
+ * pre-restore safety snapshot (when it differs from HEAD), then the target
443
+ * tree is materialized as a NEW commit on main — so the restore itself is
444
+ * always undoable via another restore.
445
+ *
446
+ * @param {string} brainDir - Absolute path to ~/.brain/
447
+ * @param {string} ref - Commit hash (or any git ref) to restore to
448
+ * @param {string} [passphrase] - Encryption passphrase (if configured)
449
+ * @returns {{ restored_to: string, safety_commit: string|null, restore_commit: string }}
450
+ */
451
+ function restoreTo(brainDir, ref, passphrase) {
452
+ const { repoDir, configPath } = resolvePaths(brainDir);
453
+ const config = readConfig(configPath);
454
+ if (!config) throw new Error('Sync not configured. Run /brain:sync setup first.');
455
+
456
+ const pass = config.encrypt ? passphrase : null;
457
+ if (config.encrypt && !passphrase) {
458
+ throw new Error('Encryption is enabled but no passphrase provided.');
459
+ }
460
+ if (!fs.existsSync(path.join(repoDir, '.git'))) {
461
+ throw new Error('No sync history yet — push at least once before restoring.');
462
+ }
463
+
464
+ // Validate the ref up front (also resolves short hashes / dates via git).
465
+ let target;
466
+ try {
467
+ target = git(repoDir, ['rev-parse', '--verify', `${ref}^{commit}`]);
468
+ } catch {
469
+ throw new Error(`Unknown restore point "${ref}". Use --list to see available points.`);
470
+ }
471
+
472
+ // Safety snapshot: commit the CURRENT brain state before touching anything,
473
+ // so even unsynced work survives the restore in history.
474
+ copyBrainToRepo(brainDir, repoDir, pass);
475
+ git(repoDir, ['add', '-A']);
476
+ let safetyCommit = null;
477
+ if (git(repoDir, ['status', '--porcelain'])) {
478
+ git(repoDir, ['commit', '-m', `pre-restore snapshot ${new Date().toISOString()}`]);
479
+ safetyCommit = git(repoDir, ['rev-parse', 'HEAD']);
480
+ }
481
+
482
+ // Materialize the target tree in the worktree and commit it forward.
483
+ // Wipe first so files absent in the target don't survive, then let
484
+ // `git add -A` stage those deletions alongside the checked-out content.
485
+ for (const entry of fs.readdirSync(repoDir)) {
486
+ if (entry === '.git') continue;
487
+ fs.rmSync(path.join(repoDir, entry), { recursive: true, force: true });
488
+ }
489
+ git(repoDir, ['checkout', target, '--', '.']);
490
+ git(repoDir, ['add', '-A']);
491
+ if (git(repoDir, ['status', '--porcelain'])) {
492
+ git(repoDir, ['commit', '-m', `restore to ${target.slice(0, 12)}`]);
493
+ }
494
+ const restoreCommit = git(repoDir, ['rev-parse', 'HEAD']);
495
+
496
+ // Only now mutate the live brain — the snapshot above makes this recoverable.
497
+ // audit.log is deliberately carried across the swap: the append-only trail
498
+ // must record history *through* a restore, not be rolled back by one.
499
+ const auditPath = path.join(brainDir, 'audit.log');
500
+ let auditTrail = null;
501
+ try { auditTrail = fs.readFileSync(auditPath); } catch { auditTrail = null; }
502
+
503
+ clearBrainDir(brainDir);
504
+ copyRepoToBrain(repoDir, brainDir, pass);
505
+ if (auditTrail !== null) fs.writeFileSync(auditPath, auditTrail, { mode: 0o600 });
506
+
507
+ return { restored_to: target, safety_commit: safetyCommit, restore_commit: restoreCommit };
351
508
  }
352
509
 
353
510
  /**
@@ -404,6 +561,8 @@ module.exports = {
404
561
  getStatus,
405
562
  push,
406
563
  pull,
564
+ listRestorePoints,
565
+ restoreTo,
407
566
  getSyncConfig,
408
567
  writeSyncConfig,
409
568
  // Internal — exported for testing