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

feat: data migration scripts for world→universe + series→universe canon

[._.]/ Adam Eivy4168477c82eb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9fcea7add2..859a168da3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -187,6 +187,25 @@
## Changed
+- **Data migration scripts for bringing old machines forward.** Two new
+ scripts under `server/scripts/`:
+ - `migrateWorldToUniverse.js` — renames `data/world-builder.json` →
+ `data/universe-builder.json`, the top-level `worlds[]` → `universes[]`
+ key, every `"worldId":` → `"universeId":` in `pipeline-series.json`,
+ and every `"worldRun":` → `"universeRun":` in `media-jobs.json`. Safe
+ to re-run (idempotent).
+ - `migrateAll.js` — chains world→universe naming (above) and then
+ series-canon → universe-canon in the correct order. The single
+ command other machines need to catch up to the current schema.
+
+ Run with `node server/scripts/migrateAll.js --dry-run` first to preview;
+ drop `--dry-run` to apply.
+
+ Also fixed a bug in `migrateSeriesCanon.js` where the migration was a
+ no-op because `mergeExtractedBible` mutates its first arg (pushes into
+ it) — the post-merge length comparison was always equal. Now clones the
+ universe-side array before passing.
+
- **Pipeline render paths read canon from the linked universe (Phase B).**
Comic-page, panel, storyboard, and arc-planner LLM contexts now resolve
characters/places/objects via `getSeriesCanon(series)` — preferring the
diff --git a/server/scripts/migrateAll.js b/server/scripts/migrateAll.js
new file mode 100644
index 0000000000..ffa20bec13
--- /dev/null
+++ b/server/scripts/migrateAll.js
@@ -0,0 +1,41 @@
+#!/usr/bin/env node
+// One-shot migration runner — chains every data-shape upgrade in the
+// correct order so a stale-data machine can be brought current with one
+// command:
+//
+// node server/scripts/migrateAll.js [--dry-run]
+//
+// Order matters:
+// 1. world → universe naming (files, top-level keys, field renames).
+// Must run first because (2) reads `series.universeId`, which only
+// exists after (1) renames it from `worldId`.
+// 2. series canon → universe canon (copy series.{characters,settings,
+// objects} into the linked universe via mergeExtractedBible).
+//
+// Idempotent end-to-end: re-runs no-op once the data is current.
+
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const DRY_RUN = process.argv.includes('--dry-run');
+
+async function main() {
+ console.log(`PortOS data migration ${DRY_RUN ? '(dry-run)' : ''}\n`);
+
+ // Step 1: world → universe naming. Importing for its side-effect (running
+ // main() on import) keeps the wrapper trivial. The script reads
+ // process.argv directly, so re-pass --dry-run via env.
+ console.log('━━ Step 1/2: world → universe naming ━━');
+ process.argv = [process.argv[0], join(__dirname, 'migrateWorldToUniverse.js'), ...(DRY_RUN ? ['--dry-run'] : [])];
+ await import('./migrateWorldToUniverse.js');
+
+ // Step 2: series canon → universe canon. Same pattern.
+ console.log('\n━━ Step 2/2: series canon → universe canon ━━');
+ const { migrateSeriesCanon } = await import('../services/pipeline/migrateSeriesCanon.js');
+ await migrateSeriesCanon({ dryRun: DRY_RUN });
+
+ console.log(`\n✨ All migrations complete${DRY_RUN ? ' (dry-run — re-run without --dry-run to apply)' : ''}.`);
+}
+
+main().catch((err) => { console.error('❌ Migration failed:', err); process.exit(1); });
diff --git a/server/scripts/migrateWorldToUniverse.js b/server/scripts/migrateWorldToUniverse.js
new file mode 100644
index 0000000000..74584d2c2a
--- /dev/null
+++ b/server/scripts/migrateWorldToUniverse.js
@@ -0,0 +1,129 @@
+#!/usr/bin/env node
+// Migrate a PortOS data directory from "World" naming to "Universe" naming.
+// Run this on a machine whose data files still use the old keys (worldId,
+// worldRun, top-level `worlds: []`, `data/world-builder.json` filename).
+//
+// Usage:
+// node server/scripts/migrateWorldToUniverse.js [--dry-run] [--data-dir <path>]
+//
+// Default data-dir is `./data` relative to the repo root. Idempotent — safe
+// to re-run, no-op once everything is on the new names.
+
+import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+
+const args = process.argv.slice(2);
+const DRY_RUN = args.includes('--dry-run');
+const dataDirArg = args.indexOf('--data-dir');
+const DATA_DIR = resolve(dataDirArg >= 0 ? args[dataDirArg + 1] : 'data');
+
+const log = (msg) => console.log(`${DRY_RUN ? '[dry-run] ' : ''}${msg}`);
+const warn = (msg) => console.warn(`⚠️ ${msg}`);
+
+function rewriteJson(path, transform, description) {
+ if (!existsSync(path)) {
+ log(`skip ${description}: ${path} not present`);
+ return { touched: false };
+ }
+ const raw = readFileSync(path, 'utf-8');
+ const parsed = JSON.parse(raw);
+ const next = transform(parsed);
+ if (next === null) {
+ log(`skip ${description}: already migrated`);
+ return { touched: false };
+ }
+ if (DRY_RUN) {
+ log(`would rewrite ${description} (${path})`);
+ return { touched: true };
+ }
+ writeFileSync(path, JSON.stringify(next, null, 2));
+ log(`✅ rewrote ${description}`);
+ return { touched: true };
+}
+
+function rewriteTextKey(path, fromKey, toKey, description) {
+ // For files where we want a key rename WITHOUT re-stringifying the entire
+ // JSON (preserves the user's formatting + keeps the diff minimal). Only
+ // matches the `"<fromKey>":` token so substrings inside string values can't
+ // collide.
+ if (!existsSync(path)) {
+ log(`skip ${description}: ${path} not present`);
+ return { touched: false, count: 0 };
+ }
+ const raw = readFileSync(path, 'utf-8');
+ const pattern = new RegExp(`"${fromKey}"\\s*:`, 'g');
+ const count = (raw.match(pattern) || []).length;
+ if (count === 0) {
+ log(`skip ${description}: no "${fromKey}" keys found`);
+ return { touched: false, count: 0 };
+ }
+ const next = raw.replace(pattern, `"${toKey}":`);
+ if (DRY_RUN) {
+ log(`would rename ${count} "${fromKey}" → "${toKey}" key(s) in ${description}`);
+ return { touched: true, count };
+ }
+ writeFileSync(path, next);
+ log(`✅ renamed ${count} "${fromKey}" → "${toKey}" key(s) in ${description}`);
+ return { touched: true, count };
+}
+
+function renameFileSafe(from, to, description) {
+ if (!existsSync(from)) {
+ log(`skip ${description}: ${from} not present`);
+ return { touched: false };
+ }
+ if (existsSync(to)) {
+ warn(`${description}: both ${from} and ${to} exist — leaving alone (rename manually if old file is stale)`);
+ return { touched: false };
+ }
+ if (DRY_RUN) {
+ log(`would rename ${from} → ${to}`);
+ return { touched: true };
+ }
+ renameSync(from, to);
+ log(`✅ renamed ${from} → ${to}`);
+ return { touched: true };
+}
+
+async function main() {
+ console.log(`Migrating world → universe under ${DATA_DIR}${DRY_RUN ? ' (DRY-RUN — no writes)' : ''}\n`);
+
+ // 1. Rename data/world-builder.json → data/universe-builder.json.
+ renameFileSafe(
+ join(DATA_DIR, 'world-builder.json'),
+ join(DATA_DIR, 'universe-builder.json'),
+ 'universe data file',
+ );
+
+ // 2. Inside the (now-renamed) universe file, top-level `worlds` → `universes`.
+ rewriteJson(
+ join(DATA_DIR, 'universe-builder.json'),
+ (data) => {
+ if (data.universes) return null;
+ if (!Array.isArray(data.worlds)) return null;
+ const { worlds, ...rest } = data;
+ return { universes: worlds, ...rest };
+ },
+ 'universe-builder.json top-level key',
+ );
+
+ // 3. In pipeline-series.json, rename every `series.worldId` → `series.universeId`.
+ rewriteTextKey(
+ join(DATA_DIR, 'pipeline-series.json'),
+ 'worldId',
+ 'universeId',
+ 'pipeline-series.json',
+ );
+
+ // 4. In media-jobs.json, rename every `params.worldRun` → `params.universeRun`.
+ rewriteTextKey(
+ join(DATA_DIR, 'media-jobs.json'),
+ 'worldRun',
+ 'universeRun',
+ 'media-jobs.json',
+ );
+
+ console.log(`\n✨ Migration complete${DRY_RUN ? ' (dry-run)' : ''}. ${DRY_RUN ? 'Re-run without --dry-run to apply.' : 'Restart the PortOS server to pick up the new schema.'}`);
+}
+
+main().catch((err) => { console.error('❌ Migration failed:', err); process.exit(1); });
diff --git a/server/services/pipeline/migrateSeriesCanon.js b/server/services/pipeline/migrateSeriesCanon.js
index df9c0c6204..a996c6cba0 100644
--- a/server/services/pipeline/migrateSeriesCanon.js
+++ b/server/services/pipeline/migrateSeriesCanon.js
@@ -65,9 +65,13 @@ export async function migrateSeriesCanon({ dryRun = false, log = console.log } =
for (const [field, kind] of Object.entries(KIND_BY_FIELD)) {
const incoming = Array.isArray(s[field]) ? s[field] : [];
if (incoming.length === 0) continue;
- const merged = mergeExtractedBible(universe[field] || [], incoming, kind);
- // Skip the write when merge produced no new entries (idempotency).
- if (merged.length > (universe[field] || []).length || JSON.stringify(merged) !== JSON.stringify(universe[field] || [])) {
+ // mergeExtractedBible mutates its first arg (pushes new entries into
+ // the array, then sorts in place). Snapshot the universe side BEFORE
+ // the call so the diff check below sees the pre-merge length, and
+ // pass a clone so the live universe object isn't mutated mid-loop.
+ const before = Array.isArray(universe[field]) ? universe[field] : [];
+ const merged = mergeExtractedBible([...before], incoming, kind);
+ if (merged.length > before.length || JSON.stringify(merged) !== JSON.stringify(before)) {
patch[field] = merged;
summary.perKind[field] += incoming.length;
}