brain-memory 0.1.0-beta.34 → 0.1.0-beta.36
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 +74 -0
- package/README.md +29 -0
- package/bin/brain.js +13 -0
- package/bin/import.js +132 -0
- package/bin/memorize.js +5 -28
- package/bin/recall.js +6 -0
- package/bin/restore.js +130 -0
- package/bin/session-start.js +4 -0
- package/commands/brain/import.md +125 -0
- package/commands/brain/remember.md +2 -2
- package/package.json +2 -2
- package/prompts/antigravity.md +4 -1
- package/prompts/claude.md +4 -1
- package/prompts/copilot.md +4 -1
- package/prompts/kilo.md +4 -1
- package/prompts/openai.md +4 -1
- package/prompts/opencode.md +4 -1
- package/src/cloud-sync.js +94 -0
- package/src/git-sync.js +115 -0
- package/src/harvest.js +562 -0
- package/src/provenance.js +79 -0
- package/src/receipt.js +10 -2
- package/src/scorer.js +13 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brain-memory",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.36",
|
|
4
4
|
"description": "A brain-inspired hierarchical memory system for AI coding agents. Deep nested file structure that mimics human memory with time-decay and strength-based recall.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude-code",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"url": "git+https://github.com/omelas-tech/brain.git"
|
|
45
45
|
},
|
|
46
46
|
"scripts": {
|
|
47
|
-
"test": "node --test test/index-manager.test.js test/scorer.test.js test/tfidf.test.js test/receipt.test.js test/recall.test.js test/recall-cli.test.js test/forget.test.js test/functional.test.js test/erasure.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/cloud-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js test/session-start.test.js test/memorize.test.js test/pinning.test.js test/skills.test.js test/contradiction.test.js",
|
|
47
|
+
"test": "node --test test/index-manager.test.js test/scorer.test.js test/tfidf.test.js test/receipt.test.js test/recall.test.js test/recall-cli.test.js test/forget.test.js test/functional.test.js test/erasure.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/restore.test.js test/trust-recall.test.js test/cloud-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js test/session-start.test.js test/memorize.test.js test/pinning.test.js test/skills.test.js test/contradiction.test.js test/harvest.test.js",
|
|
48
48
|
"test:integrations": "npm run test:integrations:openclaw && npm run test:integrations:copilot && npm run test:integrations:kilo && npm run test:integrations:hermes",
|
|
49
49
|
"test:integrations:openclaw": "node --test integrations/openclaw/test/*.test.mjs",
|
|
50
50
|
"test:integrations:copilot": "node --test integrations/copilot/test/*.test.mjs",
|
package/prompts/antigravity.md
CHANGED
|
@@ -58,6 +58,9 @@ Core:
|
|
|
58
58
|
- `/brain-pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
|
|
59
59
|
- `/brain-forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
|
|
60
60
|
|
|
61
|
+
Cold start:
|
|
62
|
+
- `/brain-import [--project P] [--since 30d]` — Seed a new brain from transcripts your agents already wrote
|
|
63
|
+
|
|
61
64
|
Sync & skills:
|
|
62
65
|
- `/brain-sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
|
|
63
66
|
- `/brain-skills [list|show|add|use|remove|export]` — Manage procedural skills
|
|
@@ -172,7 +175,7 @@ The recall engine ensures **identical scoring across all agents** — Claude, Ge
|
|
|
172
175
|
|
|
173
176
|
## Recall Receipts
|
|
174
177
|
|
|
175
|
-
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
|
|
178
|
+
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer. Low-trust memories (origin `tool-output` or `external`) carry a trailing `⚠ <origin>` marker in their receipt — keep it when copying; it is the visible warning that the fact came from outside the user/agent dialogue.
|
|
176
179
|
|
|
177
180
|
- When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
|
|
178
181
|
- Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
|
package/prompts/claude.md
CHANGED
|
@@ -57,6 +57,9 @@ The everyday loop is **ambient** — `remember` and `memorize` run automatically
|
|
|
57
57
|
- `/brain:pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
|
|
58
58
|
- `/brain:forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
|
|
59
59
|
|
|
60
|
+
**Cold start**
|
|
61
|
+
- `/brain:import [--project P] [--since 30d]` — Seed a new brain from transcripts your agents already wrote
|
|
62
|
+
|
|
60
63
|
**Sync & skills**
|
|
61
64
|
- `/brain:sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
|
|
62
65
|
- `/brain:skills [list|show|add|use|remove|export]` — Manage procedural skills
|
|
@@ -171,7 +174,7 @@ The recall engine ensures **identical scoring across all agents** — Claude, Ge
|
|
|
171
174
|
|
|
172
175
|
## Recall Receipts
|
|
173
176
|
|
|
174
|
-
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
|
|
177
|
+
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer. Low-trust memories (origin `tool-output` or `external`) carry a trailing `⚠ <origin>` marker in their receipt — keep it when copying; it is the visible warning that the fact came from outside the user/agent dialogue.
|
|
175
178
|
|
|
176
179
|
- When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
|
|
177
180
|
- Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
|
package/prompts/copilot.md
CHANGED
|
@@ -60,6 +60,9 @@ Core:
|
|
|
60
60
|
- `/brain-pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
|
|
61
61
|
- `/brain-forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
|
|
62
62
|
|
|
63
|
+
Cold start:
|
|
64
|
+
- `/brain-import [--project P] [--since 30d]` — Seed a new brain from transcripts your agents already wrote
|
|
65
|
+
|
|
63
66
|
Sync & skills:
|
|
64
67
|
- `/brain-sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
|
|
65
68
|
- `/brain-skills [list|show|add|use|remove|export]` — Manage procedural skills
|
|
@@ -174,7 +177,7 @@ The recall engine ensures **identical scoring across all agents** — Claude, Co
|
|
|
174
177
|
|
|
175
178
|
## Recall Receipts
|
|
176
179
|
|
|
177
|
-
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
|
|
180
|
+
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer. Low-trust memories (origin `tool-output` or `external`) carry a trailing `⚠ <origin>` marker in their receipt — keep it when copying; it is the visible warning that the fact came from outside the user/agent dialogue.
|
|
178
181
|
|
|
179
182
|
- When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
|
|
180
183
|
- Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
|
package/prompts/kilo.md
CHANGED
|
@@ -59,6 +59,9 @@ The everyday loop is **ambient** — `remember` and `memorize` run automatically
|
|
|
59
59
|
- `/brain:pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
|
|
60
60
|
- `/brain:forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
|
|
61
61
|
|
|
62
|
+
**Cold start**
|
|
63
|
+
- `/brain:import [--project P] [--since 30d]` — Seed a new brain from transcripts your agents already wrote
|
|
64
|
+
|
|
62
65
|
**Sync & skills**
|
|
63
66
|
- `/brain:sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
|
|
64
67
|
- `/brain:skills [list|show|add|use|remove|export]` — Manage procedural skills
|
|
@@ -173,7 +176,7 @@ The recall engine ensures **identical scoring across all agents** — Claude, Ge
|
|
|
173
176
|
|
|
174
177
|
## Recall Receipts
|
|
175
178
|
|
|
176
|
-
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
|
|
179
|
+
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer. Low-trust memories (origin `tool-output` or `external`) carry a trailing `⚠ <origin>` marker in their receipt — keep it when copying; it is the visible warning that the fact came from outside the user/agent dialogue.
|
|
177
180
|
|
|
178
181
|
- When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
|
|
179
182
|
- Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
|
package/prompts/openai.md
CHANGED
|
@@ -58,6 +58,9 @@ Core:
|
|
|
58
58
|
- `/brain-pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
|
|
59
59
|
- `/brain-forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
|
|
60
60
|
|
|
61
|
+
Cold start:
|
|
62
|
+
- `/brain-import [--project P] [--since 30d]` — Seed a new brain from transcripts your agents already wrote
|
|
63
|
+
|
|
61
64
|
Sync & skills:
|
|
62
65
|
- `/brain-sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
|
|
63
66
|
- `/brain-skills [list|show|add|use|remove|export]` — Manage procedural skills
|
|
@@ -172,7 +175,7 @@ The recall engine ensures **identical scoring across all agents** — Claude, Ge
|
|
|
172
175
|
|
|
173
176
|
## Recall Receipts
|
|
174
177
|
|
|
175
|
-
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
|
|
178
|
+
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer. Low-trust memories (origin `tool-output` or `external`) carry a trailing `⚠ <origin>` marker in their receipt — keep it when copying; it is the visible warning that the fact came from outside the user/agent dialogue.
|
|
176
179
|
|
|
177
180
|
- When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
|
|
178
181
|
- Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
|
package/prompts/opencode.md
CHANGED
|
@@ -57,6 +57,9 @@ The everyday loop is **ambient** — `remember` and `memorize` run automatically
|
|
|
57
57
|
- `/brain:pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
|
|
58
58
|
- `/brain:forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
|
|
59
59
|
|
|
60
|
+
**Cold start**
|
|
61
|
+
- `/brain:import [--project P] [--since 30d]` — Seed a new brain from transcripts your agents already wrote
|
|
62
|
+
|
|
60
63
|
**Sync & skills**
|
|
61
64
|
- `/brain:sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
|
|
62
65
|
- `/brain:skills [list|show|add|use|remove|export]` — Manage procedural skills
|
|
@@ -171,7 +174,7 @@ The recall engine ensures **identical scoring across all agents** — Claude, Ge
|
|
|
171
174
|
|
|
172
175
|
## Recall Receipts
|
|
173
176
|
|
|
174
|
-
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer.
|
|
177
|
+
Every memory returned by `brain recall` and by the session-start payload (each `context_recall` and `pinned` entry) carries a pre-minted `receipt` field: `◉ memory: "<title>" (<type>, <age>)`. Receipts make memory visibly fire — the user sees exactly which memory shaped an answer. Low-trust memories (origin `tool-output` or `external`) carry a trailing `⚠ <origin>` marker in their receipt — keep it when copying; it is the visible warning that the fact came from outside the user/agent dialogue.
|
|
175
178
|
|
|
176
179
|
- When recalled or pinned memories **materially shaped your answer**, end the response with their `receipt` lines, copied **verbatim** — max 3 lines, at the very end.
|
|
177
180
|
- Only receipt what actually influenced the output. Pinned memories get a receipt only when they were decisive for this specific answer — they are always present, and receipting them every turn is spam.
|
package/src/cloud-sync.js
CHANGED
|
@@ -456,6 +456,98 @@ async function pull(brainDir) {
|
|
|
456
456
|
}
|
|
457
457
|
}
|
|
458
458
|
|
|
459
|
+
// ---------------------------------------------------------------------------
|
|
460
|
+
// Versions / Restore
|
|
461
|
+
// ---------------------------------------------------------------------------
|
|
462
|
+
|
|
463
|
+
// Local entries a cloud restore must never touch: sync/auth infrastructure and
|
|
464
|
+
// _archived/, which is deliberately excluded from cloud pushes (see
|
|
465
|
+
// TAR_EXCLUDES) and so does not exist in the snapshot being restored.
|
|
466
|
+
const RESTORE_PRESERVE = new Set(['.sync', '.cloud', '.DS_Store', '_archived']);
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* List cloud restore points — pre-overwrite snapshots Brain Cloud takes
|
|
470
|
+
* automatically before every push commit. Newest first.
|
|
471
|
+
*
|
|
472
|
+
* @param {string} brainDir
|
|
473
|
+
* @returns {Promise<Array<{version: string, date: string}>>}
|
|
474
|
+
*/
|
|
475
|
+
async function listVersions(brainDir) {
|
|
476
|
+
const config = readConfig(brainDir);
|
|
477
|
+
if (!config) throw new Error('Not logged in. Run cloud login first.');
|
|
478
|
+
if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
|
|
479
|
+
|
|
480
|
+
const token = await getValidToken(brainDir);
|
|
481
|
+
const res = await jsonRequest(
|
|
482
|
+
`${config.api_url}/api/brains/${config.brain_id}/versions`,
|
|
483
|
+
'GET', null, token
|
|
484
|
+
);
|
|
485
|
+
if (res.status !== 200) {
|
|
486
|
+
throw new Error(`Failed to list versions (${res.status}): ${res.data.error || ''}`);
|
|
487
|
+
}
|
|
488
|
+
return res.data.versions || [];
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Restore ~/.brain/ from a cloud version snapshot.
|
|
493
|
+
*
|
|
494
|
+
* Before touching anything, the current brain is packed into a local backup
|
|
495
|
+
* under .cloud/ (kept for the last 5 restores) so the restore is undoable even
|
|
496
|
+
* without the git sync path. audit.log is carried forward across the swap —
|
|
497
|
+
* the append-only trail records history through a restore, never rolls back.
|
|
498
|
+
* The cloud's live brain is NOT modified; push when satisfied with the result.
|
|
499
|
+
*
|
|
500
|
+
* @param {string} brainDir
|
|
501
|
+
* @param {string} version - Snapshot name from listVersions()
|
|
502
|
+
* @returns {Promise<{restored_version: string, size_bytes: number, backup: string}>}
|
|
503
|
+
*/
|
|
504
|
+
async function restoreVersion(brainDir, version) {
|
|
505
|
+
const config = readConfig(brainDir);
|
|
506
|
+
if (!config) throw new Error('Not logged in. Run cloud login first.');
|
|
507
|
+
if (!config.brain_id) throw new Error('No brain linked. Run cloud login again.');
|
|
508
|
+
if (!version) throw new Error('No version given. List them with versions first.');
|
|
509
|
+
|
|
510
|
+
const token = await getValidToken(brainDir);
|
|
511
|
+
const url = `${config.api_url}/api/brains/${config.brain_id}/sync?version=${encodeURIComponent(version)}`;
|
|
512
|
+
const tmpFile = path.join(os.tmpdir(), `brain-restore-${Date.now()}.tar.gz`);
|
|
513
|
+
|
|
514
|
+
try {
|
|
515
|
+
await downloadFile(url, tmpFile, token);
|
|
516
|
+
const size = fs.statSync(tmpFile).size;
|
|
517
|
+
|
|
518
|
+
// Local safety backup of the CURRENT state (the download above already
|
|
519
|
+
// succeeded, so a failure past this point can always be rolled forward).
|
|
520
|
+
const { cloudDir } = resolvePaths(brainDir);
|
|
521
|
+
fs.mkdirSync(cloudDir, { recursive: true });
|
|
522
|
+
const backupName = `pre-restore-${new Date().toISOString().replace(/[:.]/g, '')}.tar.gz`;
|
|
523
|
+
const backupPath = path.join(cloudDir, backupName);
|
|
524
|
+
const packed = packBrain(brainDir);
|
|
525
|
+
fs.copyFileSync(packed, backupPath);
|
|
526
|
+
try { fs.unlinkSync(packed); } catch { /* ignore */ }
|
|
527
|
+
const backups = fs.readdirSync(cloudDir).filter((n) => n.startsWith('pre-restore-')).sort();
|
|
528
|
+
while (backups.length > 5) fs.rmSync(path.join(cloudDir, backups.shift()), { force: true });
|
|
529
|
+
|
|
530
|
+
// Carry the append-only audit trail across the swap.
|
|
531
|
+
const auditPath = path.join(brainDir, 'audit.log');
|
|
532
|
+
let auditTrail = null;
|
|
533
|
+
try { auditTrail = fs.readFileSync(auditPath); } catch { auditTrail = null; }
|
|
534
|
+
|
|
535
|
+
for (const entry of fs.readdirSync(brainDir)) {
|
|
536
|
+
if (RESTORE_PRESERVE.has(entry)) continue;
|
|
537
|
+
fs.rmSync(path.join(brainDir, entry), { recursive: true, force: true });
|
|
538
|
+
}
|
|
539
|
+
unpackBrain(tmpFile, brainDir);
|
|
540
|
+
if (auditTrail !== null) fs.writeFileSync(auditPath, auditTrail, { mode: 0o600 });
|
|
541
|
+
|
|
542
|
+
config.last_pull = new Date().toISOString();
|
|
543
|
+
writeConfig(brainDir, config);
|
|
544
|
+
|
|
545
|
+
return { restored_version: version, size_bytes: size, backup: backupPath };
|
|
546
|
+
} finally {
|
|
547
|
+
try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
459
551
|
// ---------------------------------------------------------------------------
|
|
460
552
|
// Status
|
|
461
553
|
// ---------------------------------------------------------------------------
|
|
@@ -520,6 +612,8 @@ module.exports = {
|
|
|
520
612
|
logout,
|
|
521
613
|
push,
|
|
522
614
|
pull,
|
|
615
|
+
listVersions,
|
|
616
|
+
restoreVersion,
|
|
523
617
|
status,
|
|
524
618
|
readConfig,
|
|
525
619
|
writeConfig,
|
package/src/git-sync.js
CHANGED
|
@@ -381,6 +381,119 @@ function pull(brainDir, passphrase) {
|
|
|
381
381
|
return { pulled: true, hasConflicts: false, message: `Pulled successfully at ${config.lastPull}` };
|
|
382
382
|
}
|
|
383
383
|
|
|
384
|
+
/**
|
|
385
|
+
* List restore points — the commits in the sync repo's history, newest first.
|
|
386
|
+
*
|
|
387
|
+
* A restore point exists for every push (and every pre-restore safety
|
|
388
|
+
* snapshot), so granularity follows how often the brain is pushed.
|
|
389
|
+
*
|
|
390
|
+
* @param {string} brainDir - Absolute path to ~/.brain/
|
|
391
|
+
* @param {number} [limit=20] - Maximum entries to return
|
|
392
|
+
* @returns {Array<{ commit: string, date: string, message: string }>}
|
|
393
|
+
*/
|
|
394
|
+
function listRestorePoints(brainDir, limit = 20) {
|
|
395
|
+
const { repoDir, configPath } = resolvePaths(brainDir);
|
|
396
|
+
const config = readConfig(configPath);
|
|
397
|
+
if (!config) throw new Error('Sync not configured. Run /brain:sync setup first.');
|
|
398
|
+
if (!fs.existsSync(path.join(repoDir, '.git'))) return [];
|
|
399
|
+
|
|
400
|
+
let out;
|
|
401
|
+
try {
|
|
402
|
+
out = git(repoDir, ['log', '--pretty=format:%H%x09%cI%x09%s', '-n', String(limit)]);
|
|
403
|
+
} catch {
|
|
404
|
+
return []; // repo initialized but no commits yet
|
|
405
|
+
}
|
|
406
|
+
if (!out) return [];
|
|
407
|
+
return out.split('\n').map((line) => {
|
|
408
|
+
const [commit, date, ...subject] = line.split('\t');
|
|
409
|
+
return { commit, date, message: subject.join('\t') };
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Remove everything inside ~/.brain/ except the excluded infrastructure
|
|
415
|
+
* entries (.sync/), so a restore can't leave orphaned post-snapshot files
|
|
416
|
+
* behind. Only called after the current state is committed to sync history.
|
|
417
|
+
*/
|
|
418
|
+
function clearBrainDir(brainDir) {
|
|
419
|
+
for (const entry of fs.readdirSync(brainDir)) {
|
|
420
|
+
if (EXCLUDED.has(entry)) continue;
|
|
421
|
+
fs.rmSync(path.join(brainDir, entry), { recursive: true, force: true });
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Restore ~/.brain/ to a previous restore point.
|
|
427
|
+
*
|
|
428
|
+
* History only moves forward: the current brain state is first committed as a
|
|
429
|
+
* pre-restore safety snapshot (when it differs from HEAD), then the target
|
|
430
|
+
* tree is materialized as a NEW commit on main — so the restore itself is
|
|
431
|
+
* always undoable via another restore.
|
|
432
|
+
*
|
|
433
|
+
* @param {string} brainDir - Absolute path to ~/.brain/
|
|
434
|
+
* @param {string} ref - Commit hash (or any git ref) to restore to
|
|
435
|
+
* @param {string} [passphrase] - Encryption passphrase (if configured)
|
|
436
|
+
* @returns {{ restored_to: string, safety_commit: string|null, restore_commit: string }}
|
|
437
|
+
*/
|
|
438
|
+
function restoreTo(brainDir, ref, passphrase) {
|
|
439
|
+
const { repoDir, configPath } = resolvePaths(brainDir);
|
|
440
|
+
const config = readConfig(configPath);
|
|
441
|
+
if (!config) throw new Error('Sync not configured. Run /brain:sync setup first.');
|
|
442
|
+
|
|
443
|
+
const pass = config.encrypt ? passphrase : null;
|
|
444
|
+
if (config.encrypt && !passphrase) {
|
|
445
|
+
throw new Error('Encryption is enabled but no passphrase provided.');
|
|
446
|
+
}
|
|
447
|
+
if (!fs.existsSync(path.join(repoDir, '.git'))) {
|
|
448
|
+
throw new Error('No sync history yet — push at least once before restoring.');
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// Validate the ref up front (also resolves short hashes / dates via git).
|
|
452
|
+
let target;
|
|
453
|
+
try {
|
|
454
|
+
target = git(repoDir, ['rev-parse', '--verify', `${ref}^{commit}`]);
|
|
455
|
+
} catch {
|
|
456
|
+
throw new Error(`Unknown restore point "${ref}". Use --list to see available points.`);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// Safety snapshot: commit the CURRENT brain state before touching anything,
|
|
460
|
+
// so even unsynced work survives the restore in history.
|
|
461
|
+
copyBrainToRepo(brainDir, repoDir, pass);
|
|
462
|
+
git(repoDir, ['add', '-A']);
|
|
463
|
+
let safetyCommit = null;
|
|
464
|
+
if (git(repoDir, ['status', '--porcelain'])) {
|
|
465
|
+
git(repoDir, ['commit', '-m', `pre-restore snapshot ${new Date().toISOString()}`]);
|
|
466
|
+
safetyCommit = git(repoDir, ['rev-parse', 'HEAD']);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// Materialize the target tree in the worktree and commit it forward.
|
|
470
|
+
// Wipe first so files absent in the target don't survive, then let
|
|
471
|
+
// `git add -A` stage those deletions alongside the checked-out content.
|
|
472
|
+
for (const entry of fs.readdirSync(repoDir)) {
|
|
473
|
+
if (entry === '.git') continue;
|
|
474
|
+
fs.rmSync(path.join(repoDir, entry), { recursive: true, force: true });
|
|
475
|
+
}
|
|
476
|
+
git(repoDir, ['checkout', target, '--', '.']);
|
|
477
|
+
git(repoDir, ['add', '-A']);
|
|
478
|
+
if (git(repoDir, ['status', '--porcelain'])) {
|
|
479
|
+
git(repoDir, ['commit', '-m', `restore to ${target.slice(0, 12)}`]);
|
|
480
|
+
}
|
|
481
|
+
const restoreCommit = git(repoDir, ['rev-parse', 'HEAD']);
|
|
482
|
+
|
|
483
|
+
// Only now mutate the live brain — the snapshot above makes this recoverable.
|
|
484
|
+
// audit.log is deliberately carried across the swap: the append-only trail
|
|
485
|
+
// must record history *through* a restore, not be rolled back by one.
|
|
486
|
+
const auditPath = path.join(brainDir, 'audit.log');
|
|
487
|
+
let auditTrail = null;
|
|
488
|
+
try { auditTrail = fs.readFileSync(auditPath); } catch { auditTrail = null; }
|
|
489
|
+
|
|
490
|
+
clearBrainDir(brainDir);
|
|
491
|
+
copyRepoToBrain(repoDir, brainDir, pass);
|
|
492
|
+
if (auditTrail !== null) fs.writeFileSync(auditPath, auditTrail, { mode: 0o600 });
|
|
493
|
+
|
|
494
|
+
return { restored_to: target, safety_commit: safetyCommit, restore_commit: restoreCommit };
|
|
495
|
+
}
|
|
496
|
+
|
|
384
497
|
/**
|
|
385
498
|
* Read sync config from ~/.brain/.sync/config.json.
|
|
386
499
|
*
|
|
@@ -435,6 +548,8 @@ module.exports = {
|
|
|
435
548
|
getStatus,
|
|
436
549
|
push,
|
|
437
550
|
pull,
|
|
551
|
+
listRestorePoints,
|
|
552
|
+
restoreTo,
|
|
438
553
|
getSyncConfig,
|
|
439
554
|
writeSyncConfig,
|
|
440
555
|
// Internal — exported for testing
|