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(boot): run pending data migrations on every server start (#268)

[._.]/ Adam Eivyd7b80c2ea9c0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b8fcaeb0ff..8d2f690e52 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,4 +10,5 @@
## Fixed
- **Volume cover-concept generation no longer 500s on upgraded installs.** The per-season "generate volume cover concepts" LLM step was shipped with its prompt template but missing from `stage-config.json`, so existing installs hit `Stage pipeline-volume-cover-concepts not found`. Added the config entry and a migration that seeds both the template and the config on next launch — fresh installs were already fine.
+- **Pending data migrations now apply automatically on every server start.** Previously only `update.sh` ran `scripts/run-migrations.js`, so a plain pull-and-restart (or `pm2 restart` after manual git pull) left shipped migrations un-applied — new prompt stages, settings renames, and seed data sat in the queue until the user explicitly ran update or `npm run migrations`. The server now invokes the migration runner during boot, before the AI toolkit loads `stage-config.json`, and continues on failure with an error log instead of refusing to start.
- **Pipeline prose stage now honors the per-series provider/model override.** "Draft prose" was dropping the series LLM override and falling back to the default provider — fixed; the override (e.g. Codex on a series-by-series basis) is now respected on the prose stage the same way it already was on idea, comic script, and teleplay.
diff --git a/scripts/run-migrations.js b/scripts/run-migrations.js
index 3634d4cf30..21fa3d1b50 100644
--- a/scripts/run-migrations.js
+++ b/scripts/run-migrations.js
@@ -1,19 +1,26 @@
#!/usr/bin/env node
-import { readdir, readFile, writeFile, mkdir } from 'fs/promises';
-import { join, dirname } from 'path';
+import { readdir, readFile, writeFile, mkdir, rename } from 'fs/promises';
+import { join, dirname, resolve } from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
-const rootDir = join(__dirname, '..');
-const migrationsDir = join(__dirname, 'migrations');
-const appliedFile = join(rootDir, 'data', 'migrations.applied.json');
+const DEFAULT_ROOT_DIR = join(__dirname, '..');
+const DEFAULT_MIGRATIONS_DIR = join(__dirname, 'migrations');
+
+export async function runMigrations({
+ rootDir = DEFAULT_ROOT_DIR,
+ migrationsDir = DEFAULT_MIGRATIONS_DIR,
+} = {}) {
+ const appliedFile = join(rootDir, 'data', 'migrations.applied.json');
-async function run() {
// Ensure data/ exists so we can persist applied state (migrationsDir
// ships in the repo and always exists).
await mkdir(dirname(appliedFile), { recursive: true });
- // Load applied migrations list (default to [] on missing/unreadable file, throw on corrupted JSON)
+ // Load applied migrations list. Default to [] on missing/unreadable file.
+ // If 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.
let applied = [];
const raw = await readFile(appliedFile, 'utf-8').catch(err => {
if (err.code !== 'ENOENT') {
@@ -23,13 +30,20 @@ async function run() {
});
if (raw !== null) {
let parsed;
+ let corruptReason = null;
try { parsed = JSON.parse(raw); } catch (err) {
- throw new Error(`Corrupted migrations file ${appliedFile} — fix or delete it manually: ${err.message}`);
+ corruptReason = `invalid JSON: ${err.message}`;
+ }
+ if (corruptReason === null && !Array.isArray(parsed)) {
+ corruptReason = `expected array, got ${typeof parsed}`;
}
- if (!Array.isArray(parsed)) {
- throw new Error(`Corrupted migrations file ${appliedFile} — expected array, got ${typeof parsed}`);
+ if (corruptReason !== null) {
+ const aside = `${appliedFile}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
+ await rename(appliedFile, aside);
+ console.warn(`⚠️ Corrupt migrations file ${appliedFile} (${corruptReason}); renamed to ${aside} and rebuilding from scratch`);
+ } else {
+ applied = parsed;
}
- applied = parsed;
}
// Scan for migration files (*.js, sorted by filename). Test files live
@@ -61,9 +75,20 @@ async function run() {
} else {
console.log(`✅ ${ran} migration(s) applied`);
}
+ return ran;
}
-run().catch(err => {
- console.error(`❌ Migration failed: ${err.message}`);
- process.exit(1);
-});
+// Only run as CLI when invoked directly (not when imported as a module).
+// `pathToFileURL()` requires an absolute path, so we `resolve()` argv[1]
+// first (it may be relative when launched as `node scripts/run-migrations.js`).
+// URL-vs-URL comparison normalizes slashes / drive-letter casing on Windows.
+// Kept synchronous so importing the module doesn't make it an async module
+// or trigger filesystem I/O at evaluation time.
+const invokedAsScript = process.argv[1]
+ && import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
+if (invokedAsScript) {
+ runMigrations().catch(err => {
+ console.error(`❌ Migration failed: ${err?.stack ?? err}`);
+ process.exit(1);
+ });
+}
diff --git a/scripts/run-migrations.test.js b/scripts/run-migrations.test.js
new file mode 100644
index 0000000000..afde20fef2
--- /dev/null
+++ b/scripts/run-migrations.test.js
@@ -0,0 +1,96 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, readdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import { runMigrations } from './run-migrations.js';
+
+describe('runMigrations corrupt applied-list recovery', () => {
+ let rootDir;
+ let dataDir;
+ let migrationsDir;
+ let appliedFile;
+ let warnSpy;
+ let logSpy;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'run-migrations-'));
+ dataDir = join(rootDir, 'data');
+ migrationsDir = join(rootDir, 'migrations');
+ mkdirSync(dataDir, { recursive: true });
+ mkdirSync(migrationsDir, { recursive: true });
+ appliedFile = join(dataDir, 'migrations.applied.json');
+
+ // Fixture migration that simply touches a marker file — idempotent if it
+ // checks existsSync before writing.
+ writeFileSync(join(migrationsDir, '001-fixture.js'), `
+import { writeFileSync } from 'fs';
+import { join } from 'path';
+export default {
+ async up({ rootDir }) {
+ writeFileSync(join(rootDir, 'data', 'fixture-marker.txt'), 'ran');
+ }
+};
+`);
+
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ warnSpy.mockRestore();
+ logSpy.mockRestore();
+ });
+
+ const corruptSiblings = () =>
+ readdirSync(dataDir).filter((f) => f.startsWith('migrations.applied.json.corrupt-'));
+
+ it('renames truncated JSON aside and rebuilds from scratch', async () => {
+ writeFileSync(appliedFile, '[\n "001-fixture.js",\n "002-'); // truncated mid-write
+
+ await runMigrations({ rootDir, migrationsDir });
+
+ expect(existsSync(appliedFile)).toBe(true);
+ const newContent = JSON.parse(readFileSync(appliedFile, 'utf-8'));
+ expect(newContent).toEqual(['001-fixture.js']);
+
+ const aside = corruptSiblings();
+ expect(aside).toHaveLength(1);
+ expect(readFileSync(join(dataDir, aside[0]), 'utf-8')).toContain('001-fixture.js');
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('Corrupt migrations file'));
+ expect(existsSync(join(dataDir, 'fixture-marker.txt'))).toBe(true);
+ });
+
+ it('renames non-array JSON aside and rebuilds', async () => {
+ writeFileSync(appliedFile, '{"hijacked": true}');
+
+ await runMigrations({ rootDir, migrationsDir });
+
+ expect(corruptSiblings()).toHaveLength(1);
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('expected array'));
+ expect(JSON.parse(readFileSync(appliedFile, 'utf-8'))).toEqual(['001-fixture.js']);
+ });
+
+ it('leaves a valid applied list untouched', async () => {
+ writeFileSync(appliedFile, JSON.stringify(['001-fixture.js'], null, 2) + '\n');
+
+ const ran = await runMigrations({ rootDir, migrationsDir });
+
+ expect(ran).toBe(0);
+ expect(corruptSiblings()).toHaveLength(0);
+ expect(warnSpy).not.toHaveBeenCalled();
+ expect(existsSync(join(dataDir, 'fixture-marker.txt'))).toBe(false);
+ });
+
+ it('runs cleanly when the applied file is missing entirely', async () => {
+ expect(existsSync(appliedFile)).toBe(false);
+
+ const ran = await runMigrations({ rootDir, migrationsDir });
+
+ expect(ran).toBe(1);
+ expect(JSON.parse(readFileSync(appliedFile, 'utf-8'))).toEqual(['001-fixture.js']);
+ expect(corruptSiblings()).toHaveLength(0);
+ expect(warnSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/index.js b/server/index.js
index 4033fcf64f..4ff826a1d8 100644
--- a/server/index.js
+++ b/server/index.js
@@ -132,6 +132,7 @@ import { recoverStuckAutoRuns } from './services/pipeline/autoRunner.js';
import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';
import { initDrillCache } from './services/meatspacePostDrillCache.js';
import { createAIToolkit } from './lib/aiToolkit/index.js';
+import { runMigrations } from '../scripts/run-migrations.js';
import { createPortOSProviderRoutes } from './routes/providers.js';
import { createPortOSRunsRoutes } from './routes/runs.js';
import { createPortOSPromptsRoutes } from './routes/prompts.js';
@@ -169,6 +170,18 @@ initSocket(io);
const DATA_DIR = PATHS.data;
const DATA_SAMPLE_DIR = join(__dirname, '..', 'data.sample');
+// Apply pending data migrations BEFORE the AI toolkit reads stage-config.json
+// and providers.json. Without this, a plain pull-and-restart (no update.sh)
+// leaves new prompt stages and other shipped data changes unregistered —
+// existing installs hit "Stage X not found" until the user manually runs
+// `npm run migrations` or `npm run update`. Idempotent and cheap when the
+// applied-list is already current.
+await runMigrations({ rootDir: join(__dirname, '..') }).catch(err => {
+ // Log the full stack (or stringified err for non-Error throws) so failures
+ // during boot are diagnosable without rerunning under a debugger.
+ console.error(`❌ Migration run failed at startup: ${err?.stack ?? err}`);
+});
+
// Lifecycle hooks shared between AI Toolkit and PortOS runner shim
const aiToolkitHooks = {
onRunCreated: (metadata) => {
diff --git a/server/vitest.config.js b/server/vitest.config.js
index e98050e0a3..fe567cf37d 100644
--- a/server/vitest.config.js
+++ b/server/vitest.config.js
@@ -13,7 +13,7 @@ export default defineConfig({
include: [
'**/*.test.js',
'../client/src/**/*.test.js',
- '../scripts/migrations/**/*.test.js',
+ '../scripts/**/*.test.js',
],
coverage: {
provider: 'v8',