Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: convert pre-split Brain and media-collection stores when restoring an older backup (#12626)

[._.]/ Adam Eivy9b724ace75da
diff --git a/client/src/components/BackupWidget.jsx b/client/src/components/BackupWidget.jsx
index 93d09ae1c2..ebfd7f22c1 100644
--- a/client/src/components/BackupWidget.jsx
+++ b/client/src/components/BackupWidget.jsx
@@ -62,6 +62,8 @@ const snapshotIdentity = (snapshot) =>
snapshot.selectionKey || `${snapshot.source || 'current'}/${snapshot.id}`;
const snapshotSourceLabel = (snapshot) =>
snapshot.sourceLabel || snapshot.source || 'Current machine';
+const legacyStoreNames = (stores, status) =>
+ stores.filter(store => store.status === status).map(store => store.store).join(', ');
// ---------------------------------------------------------------------------
// RestorePanel
@@ -133,7 +135,9 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
if (result) {
// Execution re-verifies the snapshot; report its status after the preview closes.
const suffix = result.verification?.status === 'unverified' ? ' (unverified legacy snapshot)' : '';
- toast.success(`File restore complete — ${result.changedFiles?.length ?? 0} file(s) restored${suffix}`);
+ const parked = (result.restoredLegacyStores ?? []).filter(store => store.parkedAs).map(store => store.parkedAs);
+ const conversion = parked.length > 0 ? `. Converted older-format data; the replaced stores were kept as ${parked.join(', ')}` : '';
+ toast.success(`File restore complete — ${result.changedFiles?.length ?? 0} file(s) restored${suffix}${conversion}`);
onClose();
}
}, [acceptedPreview, onClose, onRestoreStateChange, previewMatchesCurrentRequest, restoring, snapshot]);
@@ -216,6 +220,19 @@ function RestorePanel({ snapshot, onClose, restoring, onRestoreStateChange }) {
</span>
</p>
)}
+ {preview.restoredLegacyStores?.length > 0 && (
+ <p className="mb-2 flex items-start gap-1.5 rounded border border-port-warning/40 bg-port-warning/10 p-2 text-xs text-port-warning" role="alert">
+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />
+ <span className="min-w-0 break-words">
+ {legacyStoreNames(preview.restoredLegacyStores, 'pending') && (
+ <>This snapshot keeps {legacyStoreNames(preview.restoredLegacyStores, 'pending')} in an older single-file format. Restoring converts it to the current format and moves this install&apos;s copy aside to <code>&lt;store&gt;.pre-restore-&lt;time&gt;</code> instead of merging the two. </>
+ )}
+ {legacyStoreNames(preview.restoredLegacyStores, 'unreadable') && (
+ <>The snapshot copy of {legacyStoreNames(preview.restoredLegacyStores, 'unreadable')} is unreadable, so it is restored as-is without conversion and its records stay hidden until the file is repaired.</>
+ )}
+ </span>
+ </p>
+ )}
<p className="text-xs text-gray-500 mb-1">
{preview.changedFiles?.length ?? 0} file(s) would change:
</p>
diff --git a/client/src/components/BackupWidget.test.jsx b/client/src/components/BackupWidget.test.jsx
index 9d1ec400fb..2f770dd251 100644
--- a/client/src/components/BackupWidget.test.jsx
+++ b/client/src/components/BackupWidget.test.jsx
@@ -287,6 +287,28 @@ describe('BackupWidget snapshots', () => {
expect(screen.getByRole('button', { name: 'Restore 1 file(s)' })).toBeEnabled();
});
+ it('announces a pre-split store conversion and names where the replaced store was kept', async () => {
+ mockRestoreBackup
+ .mockResolvedValueOnce({
+ dryRun: true,
+ changedFiles: ['brain/people.json'],
+ restoredLegacyStores: [{ store: 'brain/people', legacyFile: 'brain/people.json', status: 'pending', parkedAs: null }],
+ })
+ .mockResolvedValueOnce({
+ changedFiles: ['brain/people.json'],
+ restoredLegacyStores: [{ store: 'brain/people', legacyFile: 'brain/people.json', status: 'converted', parkedAs: 'brain/people.pre-restore-example' }],
+ });
+ renderWidget();
+ await openRestorePanel();
+ fireEvent.click(screen.getByRole('button', { name: 'Preview changes' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent(/keeps brain\/people in an older single-file format.*pre-restore/);
+ fireEvent.click(screen.getByRole('button', { name: 'Restore 1 file(s)' }));
+ await waitFor(() => expect(mockToast.success).toHaveBeenCalledWith(
+ 'File restore complete — 1 file(s) restored. Converted older-format data; the replaced stores were kept as brain/people.pre-restore-example',
+ ));
+ });
+
it('shows no migration warning for a gap that is empty or unknown', async () => {
mockRestoreBackup
.mockResolvedValueOnce({ changedFiles: ['cos/quota-burn.json'], ledgerGap: { count: 0, names: [] } })
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 00a00c3e0f..dd24a12eb9 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -513,7 +513,7 @@ File restore copies what the snapshot holds and leaves live files the snapshot l
Keep the original backup intact. Copy it into a disposable offline install running the compatible historical version, upgrade that isolated install through the file-to-database transition, and verify the imported records and linked files there. Make a current-format file and PostgreSQL backup from the converted install, then use the normal verified restore workflow. Do not convert against the live database or delete its markers. Current file-primary siblings (such as manuscript reviews, draft Markdown and media assets) and parked `.imported` recovery evidence remain eligible for file restore. Selecting one of those siblings is allowed even if another part of the snapshot contains legacy metadata.
-A full restore also installs the snapshot's `migrations.applied.json`, so the next start re-runs every file migration the snapshot predates. A folder restore (`subdirFilter`) keeps the live ledger, so restored files can come back in a shape older than migrations no runner will revisit. Its preview and result therefore carry `ledgerGap`: `{ count, names }` listing the migrations the live ledger records and the snapshot's lacks, or `null` when either ledger is missing or unreadable. A full restore omits the field. The widget warns on a non-empty gap and recommends a full restore, but does not refuse: a folder no migration touched restores correctly. The quota-burn plan is converted on the spot: a restore covering `cos/quota-burn.json` (full, `cos`, or that file) runs any legacy `jobType` steps through the same conversion as migration 359 (`reconcileRestoredQuotaBurnPlan`), reusing each step's deterministic `job-burn-<family>-<step>` custom job, so a repeated restore creates no duplicates.
+A full restore also installs the snapshot's `migrations.applied.json`, so the next start re-runs every file migration the snapshot predates. That re-run only upgrades restored files for migrations gated on their input. The store-split migrations (059 for media collections, 200 for the Brain stores) gate on their output, a type index already at schema v1, and file restore leaves the live index in place, so their re-run is a no-op over a restored monolith. Restore therefore converts those stores itself (#12626): when the scope covers a store (full restore, `brain`, `brain/<type>.json`, `media-collections` or `media-collections.json`) and the snapshot carries its monolith (`brain/<type>.json`, `media-collections.json`) without `<store>/index.json`, a successful transfer moves the live `<store>/` directory to `<store>.pre-restore-<timestamp>/` (and a live `.bak-200`/`.bak-059` backup beside it), runs the frozen split migration against the install, and invalidates the Brain caches. The restored records, tombstones included, then load immediately, for folder restores too. A snapshot that has the split layout plus a stray monolith (setup-data re-seeds those after an upgrade) is current and is not converted. A monolith the split would refuse (unparseable, or a malformed records container) is restored as-is and never parks the live store. Preview and result list these stores in `restoredLegacyStores` (`{ store, legacyFile, status, parkedAs }`, with `status` `pending` in a preview and `converted` or `unreadable` after execution); the widget warns before restore and names the parked directory afterwards. A folder restore (`subdirFilter`) keeps the live ledger, so restored files can come back in a shape older than migrations no runner will revisit. Its preview and result therefore carry `ledgerGap`: `{ count, names }` listing the migrations the live ledger records and the snapshot's lacks, or `null` when either ledger is missing or unreadable. A full restore omits the field. The widget warns on a non-empty gap and recommends a full restore, but does not refuse: a folder no migration touched restores correctly. The quota-burn plan is converted on the spot: a restore covering `cos/quota-burn.json` (full, `cos`, or that file) runs any legacy `jobType` steps through the same conversion as migration 359 (`reconcileRestoredQuotaBurnPlan`), reusing each step's deterministic `job-burn-<family>-<step>` custom job, so a repeated restore creates no duplicates.
**Every nonzero rsync exit fails a restore, including 24.** A backup tolerates exit 24 ("some source files vanished") because it reads the live data tree, where a file deleted mid-scan is normal. A restore reads a snapshot that must not change under it, so a vanished source file means live data may now mix restored and older files: preview and execution both reject it. An execution failure is reported as a partial restore — the error says some files may already have been overwritten because file restore is not transactional — and caches (settings, Brain, media index) are reconciled before the error is returned, exactly as for any other failed transfer.
diff --git a/server/services/backup.js b/server/services/backup.js
index 950ecfa237..a2f4e6b126 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -33,6 +33,7 @@ import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
import { isSafeSnapshotSource, isSafeSubdirFilter, anchorUserExcludes } from '../lib/sharedSchemas.js';
import { reloadSettings, withLiveSettingsRestore } from './settings.js';
import { invalidateAllCaches as invalidateBrainCaches } from './brainStorage.js';
+import { convertRestoredLegacySplitStores, describeLegacySplitStores, snapshotLegacySplitStores } from './backupLegacyStores.js';
import { noteSystemActivity } from './systemActivityNotify.js';
// Module-level state
@@ -1750,6 +1751,13 @@ async function restoreHeldSnapshot({ snapshotDir, currentSource }, snapshotId, {
// whatever it lacks; only a folder restore can leave restored files behind
// migrations the live ledger already records.
const ledgerGap = subdirFilter ? await migrationLedgerGap(srcDir) : undefined;
+ // Split migrations gate on their output, so neither ledger re-runs them over
+ // a restored monolith; restore converts those stores itself (#12626).
+ const legacyStores = await snapshotLegacySplitStores(srcDir, subdirFilter);
+ const restoreNotes = (restoredLegacyStores) => ({
+ ...(ledgerGap !== undefined && { ledgerGap }),
+ ...(restoredLegacyStores.length > 0 && { restoredLegacyStores }),
+ });
// Restore must compare destination bytes even when size and mtime match.
// Rsync's default quick-check would otherwise report a successful no-op for
@@ -1802,15 +1810,22 @@ async function restoreHeldSnapshot({ snapshotDir, currentSource }, snapshotId, {
// A preview holds no owner, fences no identity and reconciles no cache.
if (dryRun) {
const changedFiles = await transferFiles();
- return { dryRun, snapshotId, subdirFilter, changedFiles, verification, ...(ledgerGap !== undefined && { ledgerGap }) };
+ return { dryRun, snapshotId, subdirFilter, changedFiles, verification, ...restoreNotes(describeLegacySplitStores(legacyStores)) };
}
const scope = subdirFilter;
+ let restoredLegacyStores = [];
+ // Conversion parks live stores, so it runs only after a successful transfer,
+ // and before reconciliation so the Brain caches drop the parked records.
const changedFiles = await withLiveFileRestoreOwners(scope, srcDir, () => transferAndReconcileLiveFiles({
subdirFilter,
- transfer: () => transferWithIdentityFence({ scope, srcDir, transferFiles }),
+ transfer: async () => {
+ const changed = await transferWithIdentityFence({ scope, srcDir, transferFiles });
+ restoredLegacyStores = await convertRestoredLegacySplitStores(legacyStores);
+ return changed;
+ },
}));
- return { dryRun, snapshotId, subdirFilter, changedFiles, verification, ...(ledgerGap !== undefined && { ledgerGap }) };
+ return { dryRun, snapshotId, subdirFilter, changedFiles, verification, ...restoreNotes(restoredLegacyStores) };
}
const MIGRATION_LEDGER_FILE = 'migrations.applied.json';
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 1c7d5ea49b..a5402760d6 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -24,16 +24,21 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
-import { createReadStream, existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
+import { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { basename, dirname, join as joinPath } from 'path';
import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
// runBackup persists state to PATHS.data/backup/state.json. Re-root PATHS at
// a temp tree so the suite can never write into the live install's data dir.
+// PATHS.data is <install>/data, as in production: a restore runs frozen file
+// migrations, which take the install root and join `data/` themselves.
var TEST_DATA_ROOT;
function testDataRoot() {
- if (!TEST_DATA_ROOT) TEST_DATA_ROOT = mkdtempSync(joinPath(tmpdir(), 'portos-backup-data-'));
+ if (!TEST_DATA_ROOT) {
+ TEST_DATA_ROOT = joinPath(mkdtempSync(joinPath(tmpdir(), 'portos-backup-install-')), 'data');
+ mkdirSync(TEST_DATA_ROOT);
+ }
return TEST_DATA_ROOT;
}
vi.mock('../lib/fileUtils.js', async (importOriginal) => {
@@ -42,7 +47,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
});
afterAll(() => {
- if (TEST_DATA_ROOT) rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ if (TEST_DATA_ROOT) rmSync(dirname(TEST_DATA_ROOT), { recursive: true, force: true });
});
@@ -2405,6 +2410,87 @@ describe('restoreSnapshot manifest verification', () => {
expect(withLiveCosRestore).toHaveBeenCalledWith(expect.any(Function), { snapshotLegacyConfig: expected });
});
+ describe('snapshot from before a store split (#12626)', () => {
+ const legacyPeople = JSON.stringify({ records: {
+ 'p-1': { name: 'Example Person', updatedAt: '2026-01-01T00:00:00.000Z' },
+ 'p-2': { _deleted: true, updatedAt: '2026-01-02T00:00:00.000Z', deletedAt: '2026-01-02T00:00:00.000Z' },
+ } });
+ const live = (...parts) => joinPath(PATHS.data, ...parts);
+ const readLive = async (...parts) => JSON.parse(await realFs.readFile(live(...parts), 'utf8'));
+
+ beforeEach(async () => {
+ // An upgraded install: split layout at v1 with a record of its own.
+ await realFs.mkdir(live('brain', 'people', 'live-1'), { recursive: true });
+ await realFs.writeFile(live('brain', 'people', 'index.json'), JSON.stringify({ schemaVersion: 1, type: 'people', config: {} }));
+ await realFs.writeFile(live('brain', 'people', 'live-1', 'index.json'), JSON.stringify({ name: 'Live Person' }));
+ invalidateBrainCaches.mockClear();
+ });
+
+ afterEach(async () => {
+ await realFs.rm(live('brain'), { recursive: true, force: true });
+ });
+
+ async function seedSnapshot(files) {
+ const manifest = {};
+ for (const [path, body] of Object.entries(files)) manifest[path] = await writeSnapshotFile(path, body);
+ await writeManifest(manifest);
+ }
+
+ it.each([undefined, 'brain', 'brain/people.json'])('converts a restored legacy Brain store and parks the live one (scope %s)', async (subdirFilter) => {
+ await seedSnapshot({ 'brain/people.json': legacyPeople });
+
+ const preview = await finishRestore({ dryRun: true, subdirFilter });
+ expect(preview.restoredLegacyStores).toEqual([{ store: 'brain/people', legacyFile: 'brain/people.json', status: 'pending', parkedAs: null }]);
+ expect(await readLive('brain', 'people', 'live-1', 'index.json')).toEqual({ name: 'Live Person' });
+
+ // rsync is faked, so stand in for its transfer of the snapshot monolith.
+ await realFs.writeFile(live('brain', 'people.json'), legacyPeople);
+ spawn.mockReset();
+ const result = await finishRestore({ dryRun: false, subdirFilter });
+
+ const [converted] = result.restoredLegacyStores;
+ expect(converted).toMatchObject({ store: 'brain/people', status: 'converted', parkedAs: expect.stringMatching(/^brain\/people\.pre-restore-/) });
+ expect(await readLive('brain', 'people', 'p-1', 'index.json')).toMatchObject({ name: 'Example Person' });
+ expect(await readLive('brain', 'people', 'p-2', 'index.json')).toMatchObject({ _deleted: true });
+ expect(existsSync(live('brain', 'people', 'live-1'))).toBe(false);
+ expect(await readLive(converted.parkedAs, 'live-1', 'index.json')).toEqual({ name: 'Live Person' });
+ expect(existsSync(live('brain', 'people.json.bak-200'))).toBe(true);
+ expect(invalidateBrainCaches).toHaveBeenCalled();
+ });
+
+ it('treats a split snapshot with a stray re-seeded monolith as current', async () => {
+ await seedSnapshot({
+ 'brain/people.json': legacyPeople,
+ 'brain/people/index.json': JSON.stringify({ schemaVersion: 1, type: 'people', config: {} }),
+ });
+ await realFs.writeFile(live('brain', 'people.json'), legacyPeople);
+
+ const result = await finishRestore({ dryRun: false });
+ expect(result).not.toHaveProperty('restoredLegacyStores');
+ expect(await readLive('brain', 'people', 'live-1', 'index.json')).toEqual({ name: 'Live Person' });
+ expect(existsSync(live('brain', 'people', 'p-1'))).toBe(false);
+ });
+
+ it('leaves Brain alone when the restore scope excludes it', async () => {
+ await seedSnapshot({ 'brain/people.json': legacyPeople, 'cos/example.json': '{}' });
+
+ const result = await finishRestore({ dryRun: false, subdirFilter: 'cos' });
+ expect(result).not.toHaveProperty('restoredLegacyStores');
+ expect(await readLive('brain', 'people', 'live-1', 'index.json')).toEqual({ name: 'Live Person' });
+ await realFs.rm(live('cos', 'example.json'), { force: true });
+ });
+
+ it('never parks the live store for a monolith the split would refuse', async () => {
+ const malformed = JSON.stringify({ records: [{ id: 'p-1' }] });
+ await seedSnapshot({ 'brain/people.json': malformed });
+ await realFs.writeFile(live('brain', 'people.json'), malformed);
+
+ const result = await finishRestore({ dryRun: false });
+ expect(result.restoredLegacyStores).toEqual([{ store: 'brain/people', legacyFile: 'brain/people.json', status: 'unreadable', parkedAs: null }]);
+ expect(await readLive('brain', 'people', 'live-1', 'index.json')).toEqual({ name: 'Live Person' });
+ });
+ });
+
describe('folder restore of an older snapshot (#12355)', () => {
const liveLedgerPath = () => joinPath(PATHS.data, 'migrations.applied.json');
const liveQuotaBurnPath = () => joinPath(PATHS.cos, 'quota-burn.json');
diff --git a/server/services/backupLegacyStores.js b/server/services/backupLegacyStores.js
new file mode 100644
index 0000000000..55f0bcd45c
--- /dev/null
+++ b/server/services/backupLegacyStores.js
@@ -0,0 +1,126 @@
+/**
+ * Restore-time conversion of stores a snapshot carries in a layout older than a
+ * split migration (#12626).
+ *
+ * Migrations 059 and 200 split monolithic stores into per-record directories
+ * and gate on their OUTPUT: a type index already at v1 makes them a no-op. A
+ * restore copies a pre-split snapshot's monolith back without removing the live
+ * per-record directory (file restore is additive), so the boot re-run finds the
+ * live index, skips, and the restored records are never read. Folder restores
+ * keep the live ledger and never re-run the migration at all.
+ *
+ * So after a successful transfer the live directory is parked as
+ * `<typeDir>.pre-restore-<timestamp>` and the frozen migration runs against the
+ * install immediately, splitting the restored monolith exactly as an upgrade
+ * would have. The migrations are invoked, never re-implemented, so a restore
+ * converts with the same semantics the install crossed when it upgraded.
+ */
+import { rename, stat } from 'fs/promises';
+import { basename, dirname, join } from 'path';
+import { PATHS, readJSONFileStrict } from '../lib/fileUtils.js';
+
+// Frozen with the migrations they invoke: migration 200's type list as of 200.
+const BRAIN_SPLIT_TYPES = [
+ 'people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets',
+ 'journals', 'inbox', 'songs',
+];
+
+const loadBrainSplit = () => import('../../scripts/migrations/200-split-brain-stores-to-per-record.js');
+const loadMediaCollectionsSplit = () => import('../../scripts/migrations/059-split-media-collections.js');
+
+const LEGACY_SPLIT_STORES = Object.freeze([
+ ...BRAIN_SPLIT_TYPES.map(type => ({
+ store: `brain/${type}`,
+ scopes: ['brain', `brain/${type}.json`],
+ legacyFile: `brain/${type}.json`,
+ backupSuffix: '.bak-200',
+ loadMigration: loadBrainSplit,
+ // Migration 200 throws on a records container that is present but not a map.
+ readable: doc => doc.records == null || (typeof doc.records === 'object' && !Array.isArray(doc.records)),
+ })),
+ {
+ store: 'media-collections',
+ scopes: ['media-collections', 'media-collections.json'],
+ legacyFile: 'media-collections.json',
+ backupSuffix: '.bak-059',
+ loadMigration: loadMediaCollectionsSplit,
+ readable: () => true,
+ },
+]);
+
+const exists = path => stat(path).then(
+ () => true,
+ error => { if (error.code === 'ENOENT') return false; throw error; },
+);
+
+/**
+ * The split stores a restore of `scope` installs in their pre-split layout: the
+ * snapshot carries the monolith but no `<typeDir>/index.json`. A snapshot with
+ * both carries a stray monolith setup-data re-seeded after the split, which is
+ * not legacy. An unreadable monolith is reported but never converted, so its
+ * live store is not parked for a split that would throw.
+ */
+export async function snapshotLegacySplitStores(srcDir, scope) {
+ const found = [];
+ for (const entry of LEGACY_SPLIT_STORES) {
+ if (scope && !entry.scopes.includes(scope)) continue;
+ if (!await exists(join(srcDir, entry.legacyFile))) continue;
+ if (await exists(join(srcDir, entry.store, 'index.json'))) continue;
+ const { ok, value } = await readJSONFileStrict(join(srcDir, entry.legacyFile), null, { logError: false });
+ const readable = ok && value !== null && typeof value === 'object' && !Array.isArray(value) && entry.readable(value);
+ found.push({ ...entry, readable });
+ }
+ return found;
+}
+
+/** The result-facing projection of `snapshotLegacySplitStores` for a preview. */
+export const describeLegacySplitStores = stores => stores.map(({ store, legacyFile, readable }) => ({
+ store, legacyFile, status: readable ? 'pending' : 'unreadable', parkedAs: null,
+}));
+
+/**
+ * Park each convertible store's live directory (and a live migration backup the
+ * split's own rename would overwrite), then run the frozen split migrations.
+ * Call only after the transfer succeeded, inside the live-restore owners.
+ */
+export async function convertRestoredLegacySplitStores(stores) {
+ if (stores.length === 0) return [];
+ // Migrations take the install root and join `data/` themselves.
+ if (basename(PATHS.data) !== 'data') {
+ throw new Error(`Cannot convert restored legacy stores: data directory ${PATHS.data} is not <install>/data`);
+ }
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
+ const results = [];
+ for (const entry of stores) {
+ if (!entry.readable) {
+ console.warn(`⚠️ Restore left ${entry.legacyFile} in its pre-split layout: the snapshot copy is unreadable`);
+ results.push({ store: entry.store, legacyFile: entry.legacyFile, status: 'unreadable', parkedAs: null });
+ continue;
+ }
+ const liveDir = join(PATHS.data, entry.store);
+ const parkedAs = `${entry.store}.pre-restore-${stamp}`;
+ const parked = await rename(liveDir, join(PATHS.data, parkedAs)).then(
+ () => true,
+ error => { if (error.code === 'ENOENT') return false; throw error; },
+ );
+ const liveBackup = join(PATHS.data, `${entry.legacyFile}${entry.backupSuffix}`);
+ if (await exists(liveBackup)) await rename(liveBackup, `${liveBackup}.pre-restore-${stamp}`);
+ results.push({ store: entry.store, legacyFile: entry.legacyFile, status: 'converted', parkedAs: parked ? parkedAs : null });
+ }
+
+ // One run per migration: 200 splits every Brain type, and a type whose live
+ // index was not parked is a gate-1 no-op.
+ const loaders = [...new Set(stores.filter(entry => entry.readable).map(entry => entry.loadMigration))];
+ const rootDir = dirname(PATHS.data);
+ for (const load of loaders) {
+ const { default: migration } = await load();
+ await migration.up({ rootDir }).catch((error) => {
+ const parked = results.filter(result => result.parkedAs).map(result => result.parkedAs);
+ throw new Error(`Converting restored legacy stores failed: ${error.message}${parked.length ? `. Previous stores are parked as ${parked.join(', ')}` : ''}`, { cause: error });
+ });
+ }
+ for (const result of results.filter(result => result.status === 'converted')) {
+ console.log(`📦 Restore converted ${result.legacyFile} to per-record files${result.parkedAs ? `; previous store parked as ${result.parkedAs}` : ''}`);
+ }
+ return results;
+}