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: preserve migration ledger state across failures (#8711)

[._.]/ Adam Eivyd548fe6511b7
diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js
index 7498b4303a..634fe2a339 100644
--- a/scripts/run-migrations.js
+++ b/scripts/run-migrations.js
@@ -1,9 +1,10 @@
#!/usr/bin/env node
-import { readdir, readFile, writeFile, mkdir, rename } from 'fs/promises';
+import { readdir, readFile, mkdir, rename } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
import { resolveInstallRoot, isWorktreeRoot } from '../server/lib/dataRoot.js';
import { isDirectlyInvoked } from './lib/directInvocation.js';
+import { writeJsonAtomic } from './migrations/_lib.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
// Prefer an explicit PORTOS_DATA_ROOT env var over the executing-file location
@@ -33,20 +34,19 @@ async function scanMigrationFiles(migrationsDir) {
}
/**
- * Read the applied-migrations list. Default to [] on missing/unreadable file.
+ * Read the applied-migrations list. A missing file defaults to [].
*
* When `repair` is true and the file is corrupt (mid-write truncation, bad
- * JSON, wrong shape), rename it aside and rebuild from scratch — migrations are
- * idempotent, so re-running is safe, and this prevents one bad write from
- * bricking every subsequent boot. When `repair` is false (read-only callers
- * like listPendingMigrations), a corrupt file is treated as `[]` WITHOUT
- * mutating anything on disk.
+ * JSON, wrong shape), rename it aside and rebuild the ledger from scratch so
+ * corruption does not brick future boots. Non-ENOENT read errors
+ * propagate in repair mode: treating an unreadable ledger as empty could rerun
+ * migrations against live data. When `repair` is false (read-only callers like
+ * listPendingMigrations), read errors and corrupt content are treated as `[]`
+ * WITHOUT mutating anything on disk.
*/
async function readAppliedList(appliedFile, { repair = false } = {}) {
const raw = await readFile(appliedFile, 'utf-8').catch(err => {
- if (err.code !== 'ENOENT' && repair) {
- console.warn(`⚠️ Could not read ${appliedFile}: ${err.message}, defaulting to []`);
- }
+ if (err.code !== 'ENOENT' && repair) throw err;
return null;
});
if (raw === null) return [];
@@ -143,7 +143,7 @@ export async function runMigrations({
applied.push(file);
disarmed++;
}
- if (disarmed > 0) await writeFile(appliedFile, JSON.stringify(applied, null, 2) + '\n');
+ if (disarmed > 0) await writeJsonAtomic(appliedFile, applied);
}
let ran = 0;
@@ -159,7 +159,7 @@ export async function runMigrations({
console.log(`🔄 Running migration: ${file}`);
await migration.up({ rootDir, migrationsDir });
applied.push(file);
- await writeFile(appliedFile, JSON.stringify(applied, null, 2) + '\n');
+ await writeJsonAtomic(appliedFile, applied);
ran++;
console.log(`✅ Migration applied: ${file}`);
}
diff --git a/scripts/run-migrations.test.js b/scripts/run-migrations.test.js
index cad83d64f4..0d309fd33e 100644
--- a/scripts/run-migrations.test.js
+++ b/scripts/run-migrations.test.js
@@ -1,11 +1,28 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, readdirSync, existsSync } from 'fs';
+import * as fsPromises from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { runMigrations, listPendingMigrations } from './run-migrations.js';
-describe('runMigrations corrupt applied-list recovery', () => {
+const fsMocks = vi.hoisted(() => ({ readFailures: new Map(), realRename: null }));
+
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ fsMocks.realRename = actual.rename;
+ return {
+ ...actual,
+ readFile: vi.fn(async (path, ...args) => {
+ const failure = fsMocks.readFailures.get(String(path));
+ if (failure) throw failure;
+ return actual.readFile(path, ...args);
+ }),
+ rename: vi.fn((...args) => actual.rename(...args)),
+ };
+});
+
+describe('runMigrations applied-list handling', () => {
let rootDir;
let dataDir;
let migrationsDir;
@@ -39,6 +56,8 @@ export default {
afterEach(() => {
rmSync(rootDir, { recursive: true, force: true });
+ fsMocks.readFailures.clear();
+ vi.mocked(fsPromises.rename).mockImplementation((...args) => fsMocks.realRename(...args));
warnSpy.mockRestore();
logSpy.mockRestore();
});
@@ -94,6 +113,65 @@ export default {
expect(warnSpy).not.toHaveBeenCalled();
});
+ it('rejects unreadable ledgers without running migrations or changing their bytes', async () => {
+ const original = '["001-fixture.js"]\n';
+ writeFileSync(appliedFile, original);
+ fsMocks.readFailures.set(appliedFile, Object.assign(new Error('permission denied'), { code: 'EACCES' }));
+
+ await expect(runMigrations({ rootDir, migrationsDir })).rejects.toMatchObject({ code: 'EACCES' });
+
+ expect(readFileSync(appliedFile, 'utf-8')).toBe(original);
+ expect(existsSync(join(dataDir, 'fixture-marker.txt'))).toBe(false);
+ });
+
+ it('keeps listPendingMigrations tolerant of an unreadable ledger', async () => {
+ const original = '["001-fixture.js"]\n';
+ writeFileSync(appliedFile, original);
+ fsMocks.readFailures.set(appliedFile, Object.assign(new Error('permission denied'), { code: 'EACCES' }));
+
+ await expect(listPendingMigrations({ rootDir, migrationsDir })).resolves.toEqual(['001-fixture.js']);
+
+ expect(readFileSync(appliedFile, 'utf-8')).toBe(original);
+ expect(corruptSiblings()).toHaveLength(0);
+ });
+
+ it('writes both the purge-disarm and migration ledger through temp-file renames', async () => {
+ writeFileSync(appliedFile, '[]\n');
+ writeFileSync(join(migrationsDir, '002-purge.js'), `
+export default {
+ purge: true,
+ async up() { throw new Error('disarmed purge migration must not run'); }
+};
+`);
+
+ const renameMock = vi.mocked(fsPromises.rename);
+ const observations = [];
+ renameMock.mockImplementation(async (source, destination) => {
+ if (destination === appliedFile) {
+ observations.push({
+ source,
+ targetBefore: readFileSync(destination, 'utf-8'),
+ tempContents: readFileSync(source, 'utf-8'),
+ });
+ }
+ return fsMocks.realRename(source, destination);
+ });
+
+ const ran = await runMigrations({ rootDir, migrationsDir });
+
+ expect(ran).toBe(1);
+ expect(observations).toHaveLength(2);
+ for (const observation of observations) {
+ expect(observation.source).toBe(`${appliedFile}.tmp-${process.pid}`);
+ expect(Array.isArray(JSON.parse(observation.targetBefore))).toBe(true);
+ expect(Array.isArray(JSON.parse(observation.tempContents))).toBe(true);
+ }
+ expect(JSON.parse(observations[0].tempContents)).toEqual(['002-purge.js']);
+ expect(JSON.parse(observations[1].tempContents)).toEqual(['002-purge.js', '001-fixture.js']);
+ expect(existsSync(`${appliedFile}.tmp-${process.pid}`)).toBe(false);
+ expect(JSON.parse(readFileSync(appliedFile, 'utf-8'))).toEqual(['002-purge.js', '001-fixture.js']);
+ });
+
it('skips `_`-prefixed shared-helper files (never imports them as migrations)', async () => {
// _lib.js / _testHelpers.js are imported by migration files + tests but
// they don't export `up()` — if the runner tried to load them it would