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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: auto-run world → universe data rename on server boot
Adam Eivy5cba9615a585
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 879a498baa..38a8d507ed 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -5,5 +5,6 @@## Changed## Fixed+- Auto-run the world → universe data rename on server boot. The conversion previously shipped as a manual CLI script (`server/scripts/migrateWorldToUniverse.js`) that nobody knew to invoke, so installs upgrading from the World Builder era kept stale `data/world-builder.json` files and never saw their worlds appear as universes. The new migration `031-world-to-universe-data-rename.js` does the file rename, top-level key rename (`worlds`→`universes`), `worldId`→`universeId` rewrite in `pipeline-series.json`, `worldRun`→`universeRun` rewrite in `media-jobs.json`, and also relinks any `"World: <name>"` render collections in `media-collections.json` to their universe by canonical-name match.## Removeddiff --git a/scripts/migrations/031-world-to-universe-data-rename.js b/scripts/migrations/031-world-to-universe-data-rename.jsnew file mode 100644index 0000000000..d297aa613c--- /dev/null+++ b/scripts/migrations/031-world-to-universe-data-rename.js@@ -0,0 +1,188 @@+/**+ * Rename legacy "World" → "Universe" data shapes on disk.+ *+ * Background:+ * PortOS originally shipped a "World Builder" feature whose data lived in+ * `data/world-builder.json` with a top-level `worlds: []` key. The feature+ * was renamed to "Universe Builder" — `data/universe-builder.json` with+ * `universes: []`, plus `worldId` → `universeId` on series and `worldRun`+ * → `universeRun` on media jobs.+ *+ * The conversion shipped as a manual CLI script+ * (`server/scripts/migrateWorldToUniverse.js`) that users had to invoke+ * after upgrading. Anyone who upgraded without reading release notes was+ * left with un-migrated data — their old worlds never appeared as+ * universes in the new UI. This auto-running migration closes that gap.+ *+ * Steps (each idempotent — a re-run after partial completion is safe):+ * 1. Rename `data/world-builder.json` → `data/universe-builder.json`.+ * 2. In that file, rename top-level `worlds` key → `universes`.+ * 3. In `pipeline-series.json`, rename every `worldId` field → `universeId`.+ * 4. In `media-jobs.json`, rename every `worldRun` field → `universeRun`.+ * 5. In `media-collections.json`, rename legacy `"World: <name>"` render+ * buckets to `"Universe: <name>"` AND stamp `universeId` when the name+ * uniquely matches one of the migrated universes. Mirrors the logic in+ * migration 021 (link orphan universe collections) but adapted for the+ * old "World:" prefix — without this, the legacy buckets stay+ * unlinked-and-mis-prefixed, and the next render mints a fresh+ * "Universe: <name>" bucket, stranding the old renders.+ *+ * Edge cases:+ * - If both `world-builder.json` and `universe-builder.json` exist+ * (interrupted migration, hand-rename), the rename step skips with a+ * warning. Downstream steps still run — they read the universe file.+ * - Migration 001 already runs first by sort order; it collapses+ * date-suffixed `"World: <name> — YYYY-MM-DD"` buckets into one bucket+ * per base name, so by the time step 5 fires the names are clean.+ * - Universes with no rendered collection just have step 5 no-op for them.+ */++import { readFile, writeFile, rename, stat } from 'fs/promises';+import { join } from 'path';++const COLLECTION_NAME_MAX = 80;+const LEGACY_PREFIX = 'World: ';+const NEW_PREFIX = 'Universe: ';++const fileExists = (path) => stat(path).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+});++const readText = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ return raw;+};++const readJson = async (path) => {+ const raw = await readText(path);+ if (raw == null) return null;+ return JSON.parse(raw);+};++const writeJson = (path, value) =>+ writeFile(path, JSON.stringify(value, null, 2) + '\n');++// Mirrors `universeCollectionNameFor` in server/services/mediaCollections.js+// — duplicated inline so this one-shot migration's contract is frozen+// against future runtime changes to the naming convention.+const canonicalCollectionName = (universeName) =>+ `${NEW_PREFIX}${typeof universeName === 'string' ? universeName : ''}`.slice(0, COLLECTION_NAME_MAX);++// Legacy form — same shape but with the old prefix. Used to match collections+// minted before the rename so we can adopt them by name.+const legacyCollectionName = (universeName) =>+ `${LEGACY_PREFIX}${typeof universeName === 'string' ? universeName : ''}`.slice(0, COLLECTION_NAME_MAX);++const norm = (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');++async function renameWorldBuilderFile(dataDir) {+ const oldPath = join(dataDir, 'world-builder.json');+ const newPath = join(dataDir, 'universe-builder.json');+ const [hasOld, hasNew] = await Promise.all([fileExists(oldPath), fileExists(newPath)]);+ if (hasOld && hasNew) {+ console.warn(`⚠️ migration 031: both world-builder.json and universe-builder.json exist — leaving files alone (resolve manually)`);+ return false;+ }+ if (!hasOld) return false;+ await rename(oldPath, newPath);+ console.log(`🌍→🌐 migration 031: renamed world-builder.json → universe-builder.json`);+ return true;+}++async function renameTopLevelKey(dataDir) {+ const path = join(dataDir, 'universe-builder.json');+ const doc = await readJson(path);+ if (!doc || typeof doc !== 'object') return false;+ if (Array.isArray(doc.universes)) return false; // already migrated+ if (!Array.isArray(doc.worlds)) return false; // nothing to do+ const { worlds, ...rest } = doc;+ await writeJson(path, { universes: worlds, ...rest });+ console.log(`🌐 migration 031: renamed top-level "worlds" → "universes" (${worlds.length} entries)`);+ return true;+}++// Text-rewrite a single JSON key without re-stringifying the whole file —+// preserves the user's formatting and keeps the diff minimal. Only matches+// the `"<fromKey>":` token so substrings inside string values can't collide.+async function renameJsonField(path, fromKey, toKey, label) {+ const raw = await readText(path);+ if (raw == null) return 0;+ const pattern = new RegExp(`"${fromKey}"\\s*:`, 'g');+ const count = (raw.match(pattern) || []).length;+ if (count === 0) return 0;+ const next = raw.replace(pattern, `"${toKey}":`);+ await writeFile(path, next);+ console.log(`🔄 migration 031: renamed ${count} "${fromKey}" → "${toKey}" key(s) in ${label}`);+ return count;+}++// Step 5 — rename "World: <name>" → "Universe: <name>" collections AND+// stamp universeId where the name uniquely identifies one universe.+async function relinkLegacyWorldCollections(dataDir) {+ const collectionsPath = join(dataDir, 'media-collections.json');+ const universesPath = join(dataDir, 'universe-builder.json');++ const [collectionsDoc, universesDoc] = await Promise.all([+ readJson(collectionsPath),+ readJson(universesPath),+ ]);+ if (!collectionsDoc || !Array.isArray(collectionsDoc.collections)) return;+ if (!universesDoc || !Array.isArray(universesDoc.universes)) return;++ // Index universes by the legacy collection-name they would have produced,+ // so we match the prefix the old renderer wrote. Truncate the same way+ // the runtime does so long names still match through the same path.+ // Value is a list — multi-match means ambiguous, skip.+ const universesByLegacyName = new Map();+ for (const u of universesDoc.universes) {+ const key = norm(legacyCollectionName(u?.name));+ if (!key || key === norm(LEGACY_PREFIX)) continue; // skip empty/whitespace names+ const bucket = universesByLegacyName.get(key) || [];+ bucket.push(u);+ universesByLegacyName.set(key, bucket);+ }++ let renamed = 0;+ let ambiguous = 0;+ const now = new Date().toISOString();+ for (const c of collectionsDoc.collections) {+ if (!c || typeof c.name !== 'string') continue;+ if (c.universeId) continue; // already linked, don't touch+ if (!c.name.startsWith(LEGACY_PREFIX)) continue;+ const matches = universesByLegacyName.get(norm(c.name));+ if (!matches || matches.length === 0) continue;+ if (matches.length > 1) {+ ambiguous += 1;+ console.warn(`⚠️ migration 031: collection "${c.name}" matches ${matches.length} universes — skipping (ambiguous link).`);+ continue;+ }+ const universe = matches[0];+ c.name = canonicalCollectionName(universe.name);+ c.universeId = universe.id;+ c.updatedAt = now;+ renamed += 1;+ }++ if (renamed > 0) {+ await writeJson(collectionsPath, collectionsDoc);+ console.log(`🔗 migration 031: relinked ${renamed} legacy "World: <name>" collection(s) → "Universe: <name>" with universeId stamp`);+ }+ if (ambiguous > 0) {+ console.log(`ℹ️ migration 031: ${ambiguous} legacy collection(s) skipped due to multiple same-named universes.`);+ }+}++export default {+ async up({ rootDir }) {+ const dataDir = join(rootDir, 'data');+ await renameWorldBuilderFile(dataDir);+ await renameTopLevelKey(dataDir);+ await renameJsonField(join(dataDir, 'pipeline-series.json'), 'worldId', 'universeId', 'pipeline-series.json');+ await renameJsonField(join(dataDir, 'media-jobs.json'), 'worldRun', 'universeRun', 'media-jobs.json');+ await relinkLegacyWorldCollections(dataDir);+ },+};diff --git a/scripts/migrations/031-world-to-universe-data-rename.test.js b/scripts/migrations/031-world-to-universe-data-rename.test.jsnew file mode 100644index 0000000000..49a254c071--- /dev/null+++ b/scripts/migrations/031-world-to-universe-data-rename.test.js@@ -0,0 +1,178 @@+/**+ * Test for migration 031 — rename legacy "World" → "Universe" data shapes+ * on disk. Picked up by server/vitest.config.js's+ * `../scripts/migrations/**\/*.test.js` glob.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './031-world-to-universe-data-rename.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 031 — world → universe data rename', () => {+ let rootDir;+ let dataDir;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-031-'));+ dataDir = join(rootDir, 'data');+ mkdirSync(dataDir, { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('renames world-builder.json → universe-builder.json and the top-level key', async () => {+ writeJson(join(dataDir, 'world-builder.json'), {+ worlds: [{ id: 'u-1', name: 'Echoes of the Choir' }],+ runs: [],+ });++ await migration.up({ rootDir });++ expect(existsSync(join(dataDir, 'world-builder.json'))).toBe(false);+ expect(existsSync(join(dataDir, 'universe-builder.json'))).toBe(true);+ const after = readJson(join(dataDir, 'universe-builder.json'));+ expect(after.universes).toEqual([{ id: 'u-1', name: 'Echoes of the Choir' }]);+ expect(after.worlds).toBeUndefined();+ expect(after.runs).toEqual([]);+ });++ it('renames worldId → universeId in pipeline-series.json', async () => {+ writeJson(join(dataDir, 'pipeline-series.json'), {+ series: [+ { id: 's-1', worldId: 'u-1', title: 'Test' },+ { id: 's-2', worldId: 'u-2', title: 'Other' },+ ],+ });++ await migration.up({ rootDir });++ const after = readJson(join(dataDir, 'pipeline-series.json'));+ expect(after.series[0].universeId).toBe('u-1');+ expect(after.series[0].worldId).toBeUndefined();+ expect(after.series[1].universeId).toBe('u-2');+ });++ it('renames worldRun → universeRun in media-jobs.json', async () => {+ writeJson(join(dataDir, 'media-jobs.json'), {+ jobs: [+ { id: 'j-1', params: { worldRun: 'r-1' } },+ ],+ });++ await migration.up({ rootDir });++ const after = readJson(join(dataDir, 'media-jobs.json'));+ expect(after.jobs[0].params.universeRun).toBe('r-1');+ expect(after.jobs[0].params.worldRun).toBeUndefined();+ });++ it('relinks legacy "World: <name>" collections to migrated universes', async () => {+ writeJson(join(dataDir, 'world-builder.json'), {+ worlds: [+ { id: 'u-choir', name: 'Echoes of the Choir' },+ { id: 'u-scav', name: 'Scavenger Time' },+ ],+ });+ writeJson(join(dataDir, 'media-collections.json'), {+ collections: [+ { id: 'c-1', name: 'World: Echoes of the Choir', items: [] },+ { id: 'c-2', name: 'World: Scavenger Time', items: [] },+ { id: 'c-3', name: 'My Personal Notes', items: [] }, // untouched+ ],+ });++ await migration.up({ rootDir });++ const after = readJson(join(dataDir, 'media-collections.json'));+ const byId = Object.fromEntries(after.collections.map((c) => [c.id, c]));+ expect(byId['c-1'].name).toBe('Universe: Echoes of the Choir');+ expect(byId['c-1'].universeId).toBe('u-choir');+ expect(byId['c-1'].updatedAt).toBeTruthy();+ expect(byId['c-2'].name).toBe('Universe: Scavenger Time');+ expect(byId['c-2'].universeId).toBe('u-scav');+ expect(byId['c-3'].name).toBe('My Personal Notes');+ expect(byId['c-3'].universeId).toBeUndefined();+ });++ it('skips ambiguous legacy collections that match multiple universes by name', async () => {+ writeJson(join(dataDir, 'world-builder.json'), {+ worlds: [+ { id: 'u-a', name: 'Duplicate' },+ { id: 'u-b', name: 'Duplicate' },+ ],+ });+ writeJson(join(dataDir, 'media-collections.json'), {+ collections: [+ { id: 'c-dup', name: 'World: Duplicate', items: [] },+ ],+ });++ await migration.up({ rootDir });++ const after = readJson(join(dataDir, 'media-collections.json'));+ expect(after.collections[0].name).toBe('World: Duplicate'); // unchanged+ expect(after.collections[0].universeId).toBeUndefined();+ });++ it('does not touch already-linked collections', async () => {+ writeJson(join(dataDir, 'world-builder.json'), {+ worlds: [{ id: 'u-1', name: 'Already Linked' }],+ });+ writeJson(join(dataDir, 'media-collections.json'), {+ collections: [+ { id: 'c-existing', name: 'Universe: Already Linked', universeId: 'u-1', items: [] },+ ],+ });++ const before = readJson(join(dataDir, 'media-collections.json'));+ await migration.up({ rootDir });+ const after = readJson(join(dataDir, 'media-collections.json'));+ expect(after.collections[0]).toEqual(before.collections[0]);+ });++ it('is a no-op when already migrated (idempotent re-run)', async () => {+ writeJson(join(dataDir, 'universe-builder.json'), {+ universes: [{ id: 'u-1', name: 'Already Migrated' }],+ });+ writeJson(join(dataDir, 'pipeline-series.json'), {+ series: [{ id: 's-1', universeId: 'u-1' }],+ });++ const beforeUniverse = readJson(join(dataDir, 'universe-builder.json'));+ const beforeSeries = readJson(join(dataDir, 'pipeline-series.json'));++ await migration.up({ rootDir });++ expect(readJson(join(dataDir, 'universe-builder.json'))).toEqual(beforeUniverse);+ expect(readJson(join(dataDir, 'pipeline-series.json'))).toEqual(beforeSeries);+ });++ it('leaves files alone when both legacy and new files exist (manual cleanup case)', async () => {+ writeJson(join(dataDir, 'world-builder.json'), {+ worlds: [{ id: 'u-old', name: 'Old' }],+ });+ writeJson(join(dataDir, 'universe-builder.json'), {+ universes: [{ id: 'u-new', name: 'New' }],+ });++ await migration.up({ rootDir });++ // Both files must still exist with original contents — the migration+ // refuses to clobber when there's an ambiguous starting state.+ expect(readJson(join(dataDir, 'world-builder.json')).worlds[0].name).toBe('Old');+ expect(readJson(join(dataDir, 'universe-builder.json')).universes[0].name).toBe('New');+ });++ it('handles missing files gracefully (fresh install)', async () => {+ // No files at all — every step is a no-op, must not throw.+ await expect(migration.up({ rootDir })).resolves.not.toThrow();+ expect(existsSync(join(dataDir, 'universe-builder.json'))).toBe(false);+ });+});