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(universe): move Universe Builder to PostgreSQL (#1014)

Adam Eivy7b5eb493d737
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index aa37deeda4..e5e49021c7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -16,6 +16,7 @@
## Changed
+- **Universe Builder now stores universes in PostgreSQL** — your universes (canon bibles, categories, composite sheets, locks, influences, and the per-universe render-run history) moved out of the per-record `data/universes/{id}/index.json` files into dedicated `universes` and `universe_runs` tables, one row per universe. Existing installs are migrated automatically and losslessly on first boot — the legacy `data/universes/` directory is renamed aside (`data/universes.imported`) as a one-release recovery source. Nothing changes in how you create, edit, delete, render, or sync universes: the Universe Builder UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs universes cleanly with a peer still on the old file storage). This is the first implementation slice (#1014) of the Create relational-schema migration designed in #999. Universes still persist to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.
- **Create relational schema design (Postgres-first plan, #999)** — a design doc ([`docs/plans/2026-06-07-create-relational-schema-design.md`](../docs/plans/2026-06-07-create-relational-schema-design.md)) now specifies the PostgreSQL data model for the remaining file-backed Create domains: universes, pipeline series/issues, Story Builder sessions, and Writers Room metadata, plus how `catalog_ingredient_refs` will resolve to DB-native targets. It's design-only (no behavior change): one row per record with the record body in a `data` JSONB column and only queryable fields promoted to columns (mirroring the Creative Director #997 and catalog-user-types #1001 swaps), zero hard FKs (so a federated ref can still arrive before its target), Writers Room draft `.md` bodies staying file-backed with only their metadata indexed, and — crucially — no change to the existing snapshot/push federation model, so each store's file→DB move stays invisible to peers with no schema-version bump. Five implementation slices are tracked as #1014–#1018.
- **Catalog user-defined types now live in PostgreSQL** — the user-defined ingredient types you create in Settings → Catalog (the registry that defines what fields a custom catalog type has) moved out of the `data/settings.json` blob into a dedicated `catalog_user_types` table, one row per type, so type definitions version and federate alongside the catalog data they govern instead of riding the unrelated settings file. Existing installs are migrated automatically and losslessly on first boot — the legacy `catalogUserTypes` slice is renamed aside (`catalogUserTypes_imported`) as a one-release recovery source. Nothing changes in how you create, edit, delete, or sync types: the `/api/catalog/types` UI and the cross-machine federation wire format are unchanged (no schema-version bump — the sync payload is storage-independent), so a machine on this version syncs types cleanly with a peer still on the old one. This is the Phase 4 lead-in of the Postgres-first plan (#1001), unblocking typed catalog references. Types still persist to the settings slice under the `MEMORY_BACKEND=file` dev/test escape hatch.
- **Generated images & videos now have a PostgreSQL index** — every generated image and video is mirrored into a new `media_assets` table (one row per asset), so media metadata — prompt, model, dimensions, lineage, timestamps — becomes queryable from the database instead of only by scanning `data/images/*` sidecars and `data/video-history.json`. The bytes and those files stay exactly where they are and remain authoritative; the table is a *derived* index, rebuilt from disk on boot (and pruned of any asset whose file has been removed) and kept current as new media finishes rendering. Nothing about the gallery, history, or generation flows changes for you — this is the foundation (Phase 3.2 of the Postgres-first plan, #1000) that later lets media collections and catalog attachments resolve through one queryable asset index. The index is simply not maintained under the `MEMORY_BACKEND=file` dev/test escape hatch (media still serves from disk).
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index f325d8a990..0a1908b47c 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -33,8 +33,9 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `memories` / `memory_links` — long-term memory + pgvector similarity.
- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.
- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.
+- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.
-**Postgres-First target.** Universes, pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. The schema for the Create domains is designed in [`docs/plans/2026-06-07-create-relational-schema-design.md`](./plans/2026-06-07-create-relational-schema-design.md) (#999), with implementation tracked as #1014–#1018. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001.)
+**Postgres-First target.** Pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. The schema for the Create domains is designed in [`docs/plans/2026-06-07-create-relational-schema-design.md`](./plans/2026-06-07-create-relational-schema-design.md) (#999), with implementation tracked as #1014–#1018. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001; **universes moved in Phase 3 Create slice 1 / #1014** — see the `universes` entry above. Pipeline series/issues #1015, Story Builder #1016, Writers Room #1017, and the catalog ref resolver #1018 are the remaining slices.)
---
diff --git a/server/index.js b/server/index.js
index ebf36c0e8a..f83526225d 100644
--- a/server/index.js
+++ b/server/index.js
@@ -844,6 +844,13 @@ ensureSelf()
// queryable index over them. Idempotent, safe to run every boot.
const { initMediaAssetIndex } = await import('./services/mediaAssetIndex/index.js');
await initMediaAssetIndex();
+ // Universe Builder PG warm (#1014): with the DB confirmed + schema ensured,
+ // touch the universe store so it selects the Postgres backend and runs the
+ // one-time data/universes file→DB import (migrateUniversesToDB) BEFORE
+ // httpServer.listen — so the first request/sync sees migrated records, not
+ // a half-applied import racing a request. listIds() is the cheapest call
+ // that forces backend selection. Idempotent (marker-gated import).
+ await universeStore().listIds();
// Authoritative catalog user-type warm (#1001): with the DB confirmed +
// schema ensured, load the registry from the catalog_user_types store
// (running the one-time settings→DB import on first access). This runs
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.js
index a8fafb3029..c1c2450357 100644
--- a/server/lib/db.catalogDdlParity.test.js
+++ b/server/lib/db.catalogDdlParity.test.js
@@ -202,6 +202,36 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {
.toEqual([...new Set(extractColumnNames(jsBody))].sort());
});
+ // Universe Builder records (#1014) — non-`catalog_`-prefixed table in BOTH
+ // DDL sources, with non-`idx_catalog_`-prefixed indexes, so it gets its own
+ // column + index parity assertion.
+ it('universes has the same columns and indexes in both files', () => {
+ const sqlBody = extractCreateTable(INIT_SQL, 'universes');
+ const jsBody = extractCreateTable(DB_JS, 'universes');
+ expect(sqlBody, 'init-db.sql missing CREATE TABLE universes').toBeTruthy();
+ expect(jsBody, 'db.js missing CREATE TABLE universes').toBeTruthy();
+ expect([...new Set(extractColumnNames(sqlBody))].sort())
+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());
+ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_universes_');
+ const jsIdx = extractIndexNames(DB_JS, 'idx_universes_');
+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
+ expect(sqlIdx.size).toBeGreaterThan(0);
+ });
+
+ // Universe render-history log (#1014) — same drift risk; its own table + index.
+ it('universe_runs has the same columns and index in both files', () => {
+ const sqlBody = extractCreateTable(INIT_SQL, 'universe_runs');
+ const jsBody = extractCreateTable(DB_JS, 'universe_runs');
+ expect(sqlBody, 'init-db.sql missing CREATE TABLE universe_runs').toBeTruthy();
+ expect(jsBody, 'db.js missing CREATE TABLE universe_runs').toBeTruthy();
+ expect([...new Set(extractColumnNames(sqlBody))].sort())
+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());
+ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_universe_runs_');
+ const jsIdx = extractIndexNames(DB_JS, 'idx_universe_runs_');
+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());
+ expect(sqlIdx.size).toBeGreaterThan(0);
+ });
+
it('search_tsv payload field set matches', () => {
// Both files re-declare the GENERATED ALWAYS expression character-for-
// character today. If one side adds a payload key (e.g. voiceNotes) and
diff --git a/server/lib/db.js b/server/lib/db.js
index ab15e3cc79..0e771321cc 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -586,6 +586,53 @@ async function ensureSchemaImpl() {
deleted_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW()
)`,
+
+ // Universe Builder records (Phase 3 Create migration, issue #1014). One row
+ // per universe, the full sanitized record (canon bibles, categories,
+ // compositeSheets, locks, influences) in `data` JSONB, moved out of
+ // data/universes/{id}/index.json (collectionStore). Only the fields the
+ // service/federation query, join, or sort on are mirrored into columns:
+ // `name` (rename-cascade + delete-guard + list sort), `schema_version` (the
+ // RECORD-shape version sanitizeTemplate stamps — a column so a future
+ // migration can find unmigrated rows without parsing JSONB), `ephemeral`
+ // (the snapshot loop filters local-only records), and the LWW/tombstone
+ // trio (updated_at/deleted/deleted_at). NO sync_sequence: universes
+ // federate via the EXISTING dataSync snapshot/push model (LWW on the body's
+ // updatedAt), NOT catalog-style pull cursors — the storage swap is invisible
+ // to peers (no schema-version bump). The mirror columns are populated FROM
+ // the record body (mirrorTimestamp), not a DB trigger. Mirrors the universes
+ // block in init-db.sql.
+ `CREATE TABLE IF NOT EXISTS universes (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ schema_version INTEGER NOT NULL DEFAULT 4,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+ )`,
+ // Partial index on the live set — the common list/scan path is "non-deleted
+ // universes". updated_at supports LWW-staleness scans.
+ `CREATE INDEX IF NOT EXISTS idx_universes_live ON universes (deleted) WHERE deleted = FALSE`,
+ `CREATE INDEX IF NOT EXISTS idx_universes_updated ON universes (updated_at)`,
+
+ // Universe render-history log (issue #1014). The type-level `config.runs[]`
+ // array collectionStore kept in data/universes/index.json (capped 200,
+ // NEVER federated — per-peer local) becomes its own table. `universe_id` is
+ // a soft ref (no FK): the cascade-clean on universe delete is handled in the
+ // service exactly as the file backend did, and a soft ref keeps the table
+ // independent of universe-row insert ordering during the one-time import.
+ // `data` holds jobIds[]/promptCount/collectionId. Mirrors init-db.sql.
+ `CREATE TABLE IF NOT EXISTS universe_runs (
+ id TEXT PRIMARY KEY,
+ universe_id TEXT NOT NULL,
+ collection_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_universe_runs_universe ON universe_runs (universe_id, created_at DESC)`,
];
for (const sql of catalogDDL) {
await pool.query(sql);
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index f19eabcb3c..2ec141fd5c 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -634,3 +634,49 @@ CREATE TABLE IF NOT EXISTS catalog_user_types (
deleted_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW()
);
+
+-- Universe Builder records (Phase 3 Create migration, issue #1014). One row per
+-- universe, the full sanitized record (canon bibles, categories, compositeSheets,
+-- locks, influences) in `data` JSONB, moved out of data/universes/{id}/index.json
+-- (collectionStore). Only the fields the service/federation query, join, or sort
+-- on are mirrored into columns: `name` (rename-cascade + delete-guard + list
+-- sort), `schema_version` (the RECORD-shape version sanitizeTemplate stamps — a
+-- column so a future migration can find unmigrated rows without parsing JSONB),
+-- `ephemeral` (the snapshot loop filters local-only records), and the
+-- LWW/tombstone trio (updated_at/deleted/deleted_at). NO sync_sequence: universes
+-- federate via the EXISTING dataSync snapshot/push model (LWW on the body's
+-- updatedAt), NOT catalog-style pull cursors — the storage swap is invisible to
+-- peers (no schema-version bump). The mirror columns are populated FROM the
+-- record body, not a DB trigger. Mirrors the universes block in db.js
+-- ensureSchema().
+CREATE TABLE IF NOT EXISTS universes (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ schema_version INTEGER NOT NULL DEFAULT 4,
+ ephemeral BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ deleted BOOLEAN DEFAULT FALSE,
+ deleted_at TIMESTAMPTZ
+);
+-- Partial index on the live set — the common list/scan path is "non-deleted
+-- universes". updated_at supports LWW-staleness scans.
+CREATE INDEX IF NOT EXISTS idx_universes_live ON universes (deleted) WHERE deleted = FALSE;
+CREATE INDEX IF NOT EXISTS idx_universes_updated ON universes (updated_at);
+
+-- Universe render-history log (issue #1014). The type-level `config.runs[]` array
+-- collectionStore kept in data/universes/index.json (capped 200, NEVER federated
+-- — per-peer local) becomes its own table. `universe_id` is a soft ref (no FK):
+-- the cascade-clean on universe delete is handled in the service exactly as the
+-- file backend did, and a soft ref keeps the table independent of universe-row
+-- insert ordering during the one-time import. `data` holds
+-- jobIds[]/promptCount/collectionId. Mirrors db.js ensureSchema().
+CREATE TABLE IF NOT EXISTS universe_runs (
+ id TEXT PRIMARY KEY,
+ universe_id TEXT NOT NULL,
+ collection_id TEXT,
+ data JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+);
+CREATE INDEX IF NOT EXISTS idx_universe_runs_universe ON universe_runs (universe_id, created_at DESC);
diff --git a/server/scripts/migrateUniversesToDB.js b/server/scripts/migrateUniversesToDB.js
new file mode 100644
index 0000000000..c087449166
--- /dev/null
+++ b/server/scripts/migrateUniversesToDB.js
@@ -0,0 +1,139 @@
+/**
+ * One-time importer: data/universes/{id}/index.json (collectionStore) →
+ * PostgreSQL (`universes` + `universe_runs`), for Phase 3 Create / issue #1014.
+ *
+ * Universes used to live one-record-per-dir with a type-level index.json holding
+ * the cross-record `config.runs[]` log. As of #1014 they live one-row-per-
+ * universe in Postgres. On the first PG-backed access (from
+ * services/universeBuilder/store.js, BEFORE the boot warm reads any universe),
+ * this importer copies each legacy record into `universes` and each run into
+ * `universe_runs`.
+ *
+ * Idempotency / safety (mirrors migrateCreativeDirectorToDB):
+ * - Marker-gated in data/universes.migrated.json so the walk runs once.
+ * - INSERT … ON CONFLICT (id) DO NOTHING — a row already in the table (a
+ * partial prior run, or a record created after the import began) is never
+ * clobbered. The DB row is authoritative once it exists.
+ * - LOSSLESS: each record is copied verbatim into `data` (the live store's
+ * sanitizer runs on read; trimming the runs cap is the live store's job).
+ * - The legacy directory is RENAMED to data/universes.imported (not deleted)
+ * so it remains a recovery source for at least one release, and a re-run
+ * can't re-import stale rows over fresher DB state. Renamed ONLY after all
+ * rows land AND the marker is written — a crash mid-import leaves the dir in
+ * place → next boot retries (ON CONFLICT DO NOTHING makes the retry safe).
+ *
+ * NOT marker-gated via data/migrations.applied.json: that list is the
+ * prompt-replace runner under scripts/migrations/ and runs before the DB gate.
+ * This import must run only when Postgres is the confirmed-healthy backend, so
+ * it's gated on its own marker and invoked from the backend selector.
+ */
+
+import { readFile, writeFile, rename, readdir, stat } from 'fs/promises';
+import { join } from 'path';
+import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { query } from '../lib/db.js';
+import { mirrorTimestamp } from '../lib/pgTimestamp.js';
+
+const LEGACY_DIRNAME = 'universes';
+const IMPORTED_DIRNAME = 'universes.imported';
+const MARKER_FILENAME = 'universes.migrated.json';
+
+async function markerExists() {
+ const raw = await readFile(join(PATHS.data, MARKER_FILENAME), 'utf-8').catch(() => null);
+ return raw != null;
+}
+
+async function writeMarker(payload) {
+ await writeFile(join(PATHS.data, MARKER_FILENAME), JSON.stringify(payload, null, 2) + '\n', 'utf-8');
+}
+
+// One legacy universe record → `universes` row. Verbatim into `data`; the typed
+// mirror columns are bind-sanitized so a hand-edited/legacy timestamp or missing
+// field can't make the INSERT throw and abort the whole import.
+async function importRecord(record) {
+ if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return false;
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(record.createdAt, now);
+ const schemaVersion = Number.isInteger(record.schemaVersion) ? record.schemaVersion : 4;
+ const result = await query(
+ `INSERT INTO universes (id, name, data, schema_version, ephemeral, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7, $8, $9)
+ ON CONFLICT (id) DO NOTHING`,
+ [
+ record.id,
+ typeof record.name === 'string' ? record.name : '',
+ JSON.stringify(record),
+ schemaVersion,
+ record.ephemeral === true,
+ createdAt,
+ mirrorTimestamp(record.updatedAt, createdAt),
+ record.deleted === true,
+ mirrorTimestamp(record.deletedAt, null),
+ ],
+ );
+ return result.rowCount > 0;
+}
+
+async function importRun(run) {
+ if (!run || typeof run !== 'object' || typeof run.id !== 'string' || typeof run.universeId !== 'string') return false;
+ const result = await query(
+ `INSERT INTO universe_runs (id, universe_id, collection_id, data, created_at)
+ VALUES ($1, $2, $3, $4::jsonb, $5)
+ ON CONFLICT (id) DO NOTHING`,
+ [
+ run.id,
+ run.universeId,
+ typeof run.collectionId === 'string' ? run.collectionId : null,
+ JSON.stringify(run),
+ mirrorTimestamp(run.createdAt, new Date().toISOString()),
+ ],
+ );
+ return result.rowCount > 0;
+}
+
+export async function migrateUniversesToDB() {
+ if (await markerExists()) return { ok: true, reason: 'already-applied', imported: 0 };
+
+ const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
+ const dirStat = await stat(legacyDir).catch(() => null);
+
+ // Fresh install (no legacy dir): stamp the marker so we don't re-probe every
+ // boot, and return.
+ if (!dirStat || !dirStat.isDirectory()) {
+ await writeMarker({ migratedAt: new Date().toISOString(), imported: 0, runs: 0, reason: 'fresh-install' });
+ return { ok: true, reason: 'fresh-install', imported: 0, runs: 0 };
+ }
+
+ const entries = await readdir(legacyDir).catch(() => []);
+ let imported = 0;
+ let skipped = 0;
+ for (const name of entries) {
+ if (name === 'index.json' || name.startsWith('.')) continue;
+ const record = await readJSONFile(join(legacyDir, name, 'index.json'), null, { allowArray: false, logError: false });
+ if (!record) { skipped += 1; continue; }
+ if (await importRecord(record)) imported += 1;
+ else skipped += 1;
+ }
+
+ // Runs from the type-level index.json `config.runs[]`.
+ let runs = 0;
+ const typeIndex = await readJSONFile(join(legacyDir, 'index.json'), null, { allowArray: false, logError: false });
+ const legacyRuns = Array.isArray(typeIndex?.config?.runs) ? typeIndex.config.runs : [];
+ for (const run of legacyRuns) {
+ if (await importRun(run)) runs += 1;
+ }
+
+ // Rename the legacy dir aside AFTER all rows land, then stamp the marker only
+ // if the rename succeeded (so a rollback / MEMORY_BACKEND=file boot can't read
+ // a stale dir while the marker claims migration is done). If the rename fails,
+ // leave the dir + no marker → next boot retries the idempotent import.
+ try {
+ await rename(legacyDir, join(PATHS.data, IMPORTED_DIRNAME));
+ } catch (err) {
+ console.warn(`⚠️ universes→DB import: imported ${imported} record(s)/${runs} run(s) but renaming ${LEGACY_DIRNAME} aside failed (${err.message}) — leaving dir, will retry marker next boot`);
+ return { ok: true, reason: 'imported-rename-failed', imported, runs };
+ }
+ await writeMarker({ migratedAt: new Date().toISOString(), imported, runs, skipped, reason: 'imported' });
+ console.log(`🌍 universes→DB import: imported ${imported} universe(s) + ${runs} run(s) (${skipped} skipped); data/${LEGACY_DIRNAME} renamed to ${IMPORTED_DIRNAME}`);
+ return { ok: true, reason: 'imported', imported, runs, skipped };
+}
diff --git a/server/scripts/migrateUniversesToDB.test.js b/server/scripts/migrateUniversesToDB.test.js
new file mode 100644
index 0000000000..07f3040159
--- /dev/null
+++ b/server/scripts/migrateUniversesToDB.test.js
@@ -0,0 +1,150 @@
+/**
+ * Tests for the legacy data/universes/{id}/index.json → Postgres importer (#1014).
+ *
+ * The legacy dir walk (readdir/stat), per-record JSON reads (readJSONFile),
+ * marker I/O (readFile/writeFile), and the dir rename are mocked to in-memory
+ * state; `db.query` is a fake honoring ON CONFLICT DO NOTHING. No disk, no PG.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// In-memory marker/legacy state.
+let files = {}; // path → string (markers)
+let dirEntries = null; // readdir(legacyDir) result, or null = ENOENT
+let recordsByDir = {}; // `${legacyDir}/${id}/index.json` → record object
+let typeIndex = null; // legacyDir/index.json content
+let renameShouldFail = false;
+let renamed = [];
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: '/fake/data' },
+ readJSONFile: vi.fn(async (path) => {
+ if (path === '/fake/data/universes/index.json') return typeIndex;
+ return recordsByDir[path] ?? null;
+ }),
+}));
+
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async (path) => {
+ if (!(path in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
+ return files[path];
+ }),
+ writeFile: vi.fn(async (path, content) => { files[path] = content; }),
+ rename: vi.fn(async (from, to) => {
+ if (renameShouldFail) throw new Error('EACCES');
+ renamed.push([from, to]);
+ }),
+ readdir: vi.fn(async () => {
+ if (dirEntries === null) return [];
+ return dirEntries;
+ }),
+ stat: vi.fn(async (path) => {
+ if (path === '/fake/data/universes') {
+ if (dirEntries === null) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
+ return { isDirectory: () => true };
+ }
+ const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e;
+ }),
+}));
+
+let uTable;
+let rTable;
+const query = vi.fn(async (sql, params) => {
+ if (/INSERT INTO universes/.test(sql)) {
+ const id = params[0];
+ if (uTable.has(id)) return { rowCount: 0, rows: [] };
+ uTable.set(id, { id, name: params[1], data: JSON.parse(params[2]) });
+ return { rowCount: 1, rows: [] };
+ }
+ if (/INSERT INTO universe_runs/.test(sql)) {
+ const id = params[0];
+ if (rTable.has(id)) return { rowCount: 0, rows: [] };
+ rTable.set(id, { id, universeId: params[1] });
+ return { rowCount: 1, rows: [] };
+ }
+ return { rowCount: 0, rows: [] };
+});
+vi.mock('../lib/db.js', () => ({ query: (...a) => query(...a) }));
+
+const MARKER = '/fake/data/universes.migrated.json';
+const rec = (id, extra = {}) => ({ id, name: id, schemaVersion: 4, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z', ...extra });
+
+async function importer() {
+ const { migrateUniversesToDB } = await import('./migrateUniversesToDB.js');
+ return migrateUniversesToDB();
+}
+
+beforeEach(() => {
+ files = {};
+ dirEntries = null;
+ recordsByDir = {};
+ typeIndex = null;
+ renameShouldFail = false;
+ renamed = [];
+ uTable = new Map();
+ rTable = new Map();
+ query.mockClear();
+});
+
+describe('migrateUniversesToDB', () => {
+ it('fresh install (no legacy dir): stamps marker, imports nothing', async () => {
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'fresh-install', imported: 0 });
+ expect(MARKER in files).toBe(true);
+ expect(uTable.size).toBe(0);
+ });
+
+ it('marker already present: no-op (does not re-walk)', async () => {
+ files[MARKER] = JSON.stringify({ reason: 'imported' });
+ dirEntries = ['u-1'];
+ recordsByDir['/fake/data/universes/u-1/index.json'] = rec('u-1');
+ const result = await importer();
+ expect(result).toMatchObject({ reason: 'already-applied' });
+ expect(uTable.size).toBe(0); // never touched the table
+ });
+
+ it('imports records + runs verbatim, then renames the dir aside and stamps marker', async () => {
+ dirEntries = ['u-1', 'u-2', 'index.json', '.DS_Store'];
+ recordsByDir['/fake/data/universes/u-1/index.json'] = rec('u-1', { logline: 'a' });
+ recordsByDir['/fake/data/universes/u-2/index.json'] = rec('u-2');
+ typeIndex = { config: { runs: [
+ { id: 'r-1', universeId: 'u-1', jobIds: [], promptCount: 3, createdAt: '2026-01-03T00:00:00.000Z' },
+ ] } };
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'imported', imported: 2, runs: 1 });
+ expect(uTable.get('u-1').data.logline).toBe('a'); // verbatim
+ expect(rTable.has('r-1')).toBe(true);
+ expect(renamed).toEqual([['/fake/data/universes', '/fake/data/universes.imported']]);
+ expect(MARKER in files).toBe(true);
+ });
+
+ it('is idempotent: a re-run over the same rows imports 0 (ON CONFLICT DO NOTHING)', async () => {
+ dirEntries = ['u-1'];
+ recordsByDir['/fake/data/universes/u-1/index.json'] = rec('u-1');
+ uTable.set('u-1', { id: 'u-1' }); // already in the table from a prior partial run
+ const result = await importer();
+ expect(result.imported).toBe(0);
+ expect(renamed.length).toBe(1); // still renames aside + stamps marker
+ expect(MARKER in files).toBe(true);
+ });
+
+ it('skips a record whose index.json is missing/unparseable', async () => {
+ dirEntries = ['u-1', 'u-bad'];
+ recordsByDir['/fake/data/universes/u-1/index.json'] = rec('u-1');
+ recordsByDir['/fake/data/universes/u-bad/index.json'] = null; // readJSONFile → null
+ const result = await importer();
+ expect(result.imported).toBe(1);
+ expect(uTable.has('u-1')).toBe(true);
+ expect(uTable.has('u-bad')).toBe(false);
+ });
+
+ it('rename failure leaves the marker UNwritten so next boot retries', async () => {
+ dirEntries = ['u-1'];
+ recordsByDir['/fake/data/universes/u-1/index.json'] = rec('u-1');
+ renameShouldFail = true;
+ const result = await importer();
+ expect(result).toMatchObject({ ok: true, reason: 'imported-rename-failed', imported: 1 });
+ expect(MARKER in files).toBe(false); // no marker → retry next boot
+ expect(uTable.has('u-1')).toBe(true); // rows already landed; retry is safe (ON CONFLICT)
+ });
+});
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 7aab74b2e9..1c8765ec2d 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -20,6 +20,7 @@ import {
formatVersionGap,
} from '../lib/schemaVersions.js';
import { mergeUniversesFromSync, listUniverses } from './universeBuilder.js';
+import { getUniverseMutationEpoch } from './universeBuilder/store.js';
import { mergeSeriesFromSync, listSeries } from './pipeline/series.js';
import { mergeIssuesFromSync, listIssues } from './pipeline/issues.js';
import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './mediaCollections.js';
@@ -38,11 +39,21 @@ const MEATSPACE_DIR = PATHS.meatspace;
const PIPELINE_SERIES_DIR = join(PATHS.data, 'pipeline-series');
const PIPELINE_ISSUES_DIR = join(PATHS.data, 'pipeline-issues');
// Universes used to live in a single `universe-builder.json`; migration 034
-// splits them into `data/universes/<id>/index.json` with a type-level
-// `data/universes/index.json`. Sync uses the directory for both reading
-// (listUniverses, below) and for fingerprint-based checksum caching — the
-// fingerprint walker descends into the dir so per-record edits invalidate.
+// split them into `data/universes/<id>/index.json`, and #1014 moved them again
+// into PostgreSQL (`universes` + `universe_runs`). Sync reads them through the
+// service (listUniverses, below). For the fingerprint-based checksum cache, a
+// PG-backed edit no longer touches this directory, so the dir fingerprint alone
+// would go stale and peers would silently stop receiving universe edits. The
+// universe store exports a monotonic mutation epoch (bumped on every record
+// write/delete) that we fold into this path's fingerprint via
+// UNIVERSE_EPOCH_KEY below — so the checksum cache invalidates on a DB edit just
+// as it did on a file edit, keeping the storage swap invisible to federation.
+// Under the file backend the dir still changes too (harmless double-signal).
const UNIVERSE_BUILDER_DIR = join(PATHS.data, 'universes');
+// Sentinel fingerprint-map key (not a real path — readFingerprintMap special-
+// cases it) carrying the universe mutation epoch into the universe +
+// mediaCollections checksum caches.
+const UNIVERSE_EPOCH_KEY = '__universeEpoch';
// Migration 059 split the monolithic media-collections.json into per-record
// `data/media-collections/<id>/index.json`. The fingerprint walker descends
// into the dir so per-record edits invalidate the snapshot checksum cache.
@@ -733,14 +744,18 @@ const CHECKSUM_PATHS = {
// subscribe/unsubscribe invalidates the per-peer snapshot checksum cache —
// the exclude-set is derived from subscriptions, so the scoped snapshot's
// content (and checksum) can change even when no record file moved.
- universe: [UNIVERSE_BUILDER_DIR, PEER_SUBSCRIPTIONS_FILE],
+ // UNIVERSE_EPOCH_KEY folds in the store's mutation epoch so a PG-backed
+ // universe edit (which doesn't touch UNIVERSE_BUILDER_DIR) still invalidates
+ // the cache — see UNIVERSE_BUILDER_DIR's note. PEER_SUBSCRIPTIONS_FILE so a
+ // subscribe/unsubscribe re-checksums the per-peer scoped snapshot.
+ universe: [UNIVERSE_BUILDER_DIR, UNIVERSE_EPOCH_KEY, PEER_SUBSCRIPTIONS_FILE],
pipeline: [PIPELINE_SERIES_DIR, PIPELINE_ISSUES_DIR, PEER_SUBSCRIPTIONS_FILE],
// mediaCollections invalidates on its own record dir AND on the parent
// record files — `getMediaCollectionsSnapshot` filters collections whose
// linked universe/series is ephemeral, so a "mark ephemeral" PATCH on a
// universe must re-checksum the collections snapshot even though no
// media-collections record file moved. Same goes for un-ephemeral.
- mediaCollections: [MEDIA_COLLECTIONS_DIR, UNIVERSE_BUILDER_DIR, PIPELINE_SERIES_DIR, PEER_SUBSCRIPTIONS_FILE],
+ mediaCollections: [MEDIA_COLLECTIONS_DIR, UNIVERSE_BUILDER_DIR, UNIVERSE_EPOCH_KEY, PIPELINE_SERIES_DIR, PEER_SUBSCRIPTIONS_FILE],
// videoHistory is a flat history file with no parent-record dependency —
// its checksum invalidates only when video-history.json itself moves.
videoHistory: [VIDEO_HISTORY_FILE],
@@ -859,6 +874,10 @@ async function fingerprintDirTwoLevels(dirPath) {
async function readFingerprintMap(paths) {
const out = {};
await Promise.all(paths.map(async (p) => {
+ // Sentinel: carry the universe store's mutation epoch (a number) instead of
+ // a file stat, so a PG-backed universe edit invalidates the cache even
+ // though no file moved. fingerprintsEqual compares these like any value.
+ if (p === UNIVERSE_EPOCH_KEY) { out[p] = `epoch:${getUniverseMutationEpoch()}`; return; }
const s = await stat(p).catch(() => null);
if (!s) { out[p] = null; return; }
if (s.isDirectory()) {
diff --git a/server/services/dataSync.universeEpoch.test.js b/server/services/dataSync.universeEpoch.test.js
new file mode 100644
index 0000000000..d27541f83a
--- /dev/null
+++ b/server/services/dataSync.universeEpoch.test.js
@@ -0,0 +1,104 @@
+/**
+ * dataSync universe mutation-epoch fingerprint (#1014).
+ *
+ * When universes move to PostgreSQL, a universe edit no longer touches
+ * data/universes/, so the directory file-fingerprint that gates dataSync's
+ * snapshot cache goes stale — peers would silently stop receiving universe
+ * edits. The fix folds the universe store's monotonic mutation epoch into the
+ * universe + mediaCollections checksum fingerprints.
+ *
+ * This test isolates that mechanism: `listUniverses` is mocked so the snapshot
+ * CONTENT can change with NO file/directory change, and `getUniverseMutationEpoch`
+ * is mocked so we control the epoch. It proves (a) a content change WITHOUT an
+ * epoch bump is masked by the cache (the bug the fix exists to prevent, shown
+ * here as the cache correctly holding when the epoch is the only honest signal),
+ * and (b) bumping the epoch invalidates the cache and surfaces the new content.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
+
+const { makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-datasync-epoch-' });
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makeProxy(actual);
+});
+
+// Controllable universe content + epoch. The data dir is a fresh empty tmpdir
+// (no universes/ subdir), so its fingerprint is constant across the test — the
+// ONLY varying input to the universe fingerprint is the mocked epoch.
+let universeContent = [];
+let epoch = 0;
+
+// Partial mock — keep every real export (storyBuilder + others import shared
+// constants from this module at load time) and override only listUniverses.
+vi.mock('./universeBuilder.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ listUniverses: vi.fn(async () => universeContent),
+ mergeUniversesFromSync: vi.fn(async () => ({ applied: false, count: 0 })),
+ };
+});
+vi.mock('./universeBuilder/store.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, getUniverseMutationEpoch: vi.fn(() => epoch) };
+});
+
+// mediaCollections snapshot filters collections by their linked universe's
+// ephemeral state, so a universe edit must re-checksum it. Mock listCollections
+// so we can change what the snapshot would contain without touching any file.
+let collectionContent = [];
+vi.mock('./mediaCollections.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ listCollections: vi.fn(async () => collectionContent),
+ mergeMediaCollectionsFromSync: vi.fn(async () => ({ applied: false, count: 0 })),
+ };
+});
+
+const dataSync = await import('./dataSync.js');
+
+afterAll(cleanup);
+
+beforeEach(() => {
+ universeContent = [{ id: 'u1', name: 'A', createdAt: '2026-05-17T09:00:00Z', updatedAt: '2026-05-17T10:00:00Z' }];
+ collectionContent = [];
+ epoch = 0;
+});
+
+describe('dataSync — universe mutation-epoch fingerprint', () => {
+ it('a content change WITHOUT an epoch bump or file change is masked by the cache', async () => {
+ const before = await dataSync.getChecksum('universe');
+ // Simulate a PG-backed edit that does NOT bump the epoch and does NOT touch
+ // the directory. The cache fingerprint is unchanged → stale checksum served.
+ // (This is exactly why the epoch MUST be bumped on every store write.)
+ universeContent = [{ id: 'u1', name: 'CHANGED', updatedAt: '2026-05-17T11:00:00Z' }];
+ const after = await dataSync.getChecksum('universe');
+ expect(after.checksum).toBe(before.checksum); // masked — fingerprint identical
+ });
+
+ it('bumping the epoch invalidates the cache and surfaces the new content', async () => {
+ const before = await dataSync.getChecksum('universe');
+ universeContent = [{ id: 'u1', name: 'CHANGED', updatedAt: '2026-05-17T11:00:00Z' }];
+ epoch += 1; // the store bumps this on every record write/delete
+ const after = await dataSync.getChecksum('universe');
+ expect(after.checksum).not.toBe(before.checksum);
+ expect(after.checksum).toBe((await dataSync.getSnapshot('universe')).checksum);
+ });
+
+ it('the mediaCollections fingerprint folds in the universe epoch (re-filters on universe change)', async () => {
+ // A collection linked to u1. getMediaCollectionsSnapshot drops collections
+ // whose linked universe is ephemeral — so when u1 flips ephemeral (a PG edit
+ // that bumps the epoch but touches no file), the mediaCollections snapshot
+ // must change. Without the epoch in its fingerprint, the cache would mask it.
+ collectionContent = [{ id: 'c1', name: 'Universe: A', universeId: 'u1', items: [], updatedAt: '2026-05-17T10:00:00Z' }];
+ const before = await dataSync.getChecksum('mediaCollections');
+ universeContent = [{ id: 'u1', name: 'A', ephemeral: true, updatedAt: '2026-05-17T11:00:00Z' }];
+ epoch += 1;
+ const after = await dataSync.getChecksum('mediaCollections');
+ expect(after.checksum).not.toBe(before.checksum);
+ });
+});
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 3480bc7148..533fc3c4ee 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -27,8 +27,8 @@
import { join, basename } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, atomicWrite, ensureDir, resolveImageRef } from '../lib/fileUtils.js';
-import { createCollectionStore } from '../lib/collectionStore.js';
+import { PATHS, ensureDir, resolveImageRef } from '../lib/fileUtils.js';
+import { getUniverseStore } from './universeBuilder/store.js';
import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';
import { flattenCanonDescriptorFragments, richCanonDescriptorFragments } from '../lib/canonPrompt.js';
import {
@@ -64,36 +64,23 @@ import { listSeries } from './pipeline/series.js';
// characters[]. See "Categories vs canon — decision" in PLAN.md.
export const CURRENT_SCHEMA_VERSION = 4;
-// TYPE-level (storage layout) schema version stamped on `data/universes/index.json`.
-// v5 — universes split out of monolithic `data/universe-builder.json` into
-// per-record `data/universes/{id}/index.json`. Cross-record `runs[]`
-// moves into `index.json`'s `config.runs`. See migration 034.
-const TYPE_SCHEMA_VERSION = 5;
-
-// Lazy store factory so test harnesses that swap PATHS.data per-test
-// (mkdtempSync + Proxy mock) still see the right temp root — the store
-// captures PATHS.data once at first call, then stays warm.
-let _store = null;
-const store = () => {
- if (_store && _store.dir === join(PATHS.data, 'universes')) return _store;
- _store = createCollectionStore({
- dir: join(PATHS.data, 'universes'),
- type: 'universes',
- schemaVersion: TYPE_SCHEMA_VERSION,
- sanitizeRecord: sanitizeTemplate,
- // Permissive — defense-in-depth against stray non-id entries from
- // readdir, not an authoritative validator. The 8–80 / dash-only rule
- // lives on UNIVERSE_ID_RE inside insertUniverseWithId, which is where
- // user-supplied ids actually arrive.
- idPattern: /^[A-Za-z0-9_-]{1,128}$/,
- });
- return _store;
-};
+// Universe storage facade (#1014). PostgreSQL-backed (`universes` +
+// `universe_runs`) on normal installs; the per-record file store
+// (collectionStore) only under MEMORY_BACKEND=file / NODE_ENV=test. The facade
+// is SYNCHRONOUS — it owns the per-id write queue + the mutation epoch + applies
+// `sanitizeTemplate` on read — and defers backend selection into each method, so
+// this service keeps calling `store()` exactly as it did the collectionStore.
+// Methods used here: loadOne / loadOneRaw / listIds / queueRecordWrite /
+// writeRecord(id, rec) / deleteRecord(id) / loadRuns / appendRun /
+// removeRunsForUniverses. `writeRecord`/`deleteRecord` replace the inline
+// ensureDir+atomicWrite(recordPath) / rm(recordDir) the file layout used, and
+// bump the mutation epoch so dataSync re-sends the universe snapshot to peers
+// (the storage swap stays invisible to federation — see the schema-design doc).
+const store = () => getUniverseStore(sanitizeTemplate);
/**
- * Exported for the boot-time verifier in `server/index.js`. Lazy because the
- * universe-builder module loads BEFORE PATHS.data resolves in some test
- * harnesses; calling this getter at boot time picks up the right root.
+ * Exported for the boot-time verifier in `server/index.js`. The facade getter
+ * is cheap + memoized; calling it at boot picks up the right PATHS.data root.
*/
export const universeStore = () => store();
@@ -834,21 +821,18 @@ let canonBackfillLogged = false;
async function readState() {
await ensureDir(PATHS.data);
const s = store();
- // Load raw records in parallel (no sanitizer) so we can detect schema-
- // version drift before the in-memory sanitization step. We deliberately
- // do NOT use store.loadAll() here — that runs sanitizeRecord, losing the
+ // Load raw records (no sanitizer) so we can detect schema-version drift
+ // before the in-memory sanitization step. listRaw() is one bulk read (a
+ // single SELECT on PG; parallel file reads on the escape hatch) — we
+ // deliberately sanitize HERE rather than via a loadAll() that would lose the
// pre-sanitized schemaVersion needed for the backfill log.
- const ids = await s.listIds();
- const rawRecords = await Promise.all(ids.map((id) => s.loadOneRaw(id)));
+ const rawRecords = await s.listRaw();
const rawById = new Map();
for (const r of rawRecords) {
if (r && typeof r.id === 'string') rawById.set(r.id, r);
}
const universes = rawRecords.map((r) => sanitizeTemplate(r)).filter(Boolean);
- const typeIndex = await s.loadTypeIndex();
- const runs = Array.isArray(typeIndex.config?.runs)
- ? typeIndex.config.runs.map(sanitizeRun).filter(Boolean)
- : [];
+ const runs = (await s.loadRuns()).map(sanitizeRun).filter(Boolean);
// The in-memory result is always at CURRENT_SCHEMA_VERSION (sanitizeTemplate
// re-stamps it on every read). Don't persist the migration here — that
// write would race against any concurrent per-record mutator and could
@@ -953,10 +937,9 @@ export async function createUniverse(input = {}) {
// Importer-orphan marker (issue #727) — see sanitizeTemplate.
importDraft: input.importDraft === true,
});
- // Write through the store — we're inside the per-id queue so use
- // atomicWrite directly to avoid re-queueing on the same id.
- await ensureDir(store().recordDir(next.id));
- await atomicWrite(store().recordPath(next.id), next);
+ // Persist through the facade (backend-agnostic). We're inside the per-id
+ // queue, and writeRecord does NOT re-queue, so this can't deadlock.
+ await store().writeRecord(next.id, next);
return next;
});
// Fire-and-forget auto-subscribe to every peer with universe-sync enabled.
@@ -1006,8 +989,7 @@ export async function insertUniverseWithId(input = {}) {
if (wasResurrection) {
console.warn(`♻️ insertUniverseWithId: overwriting tombstone for ${input.id}`);
}
- await ensureDir(s.recordDir(next.id));
- await atomicWrite(s.recordPath(next.id), next);
+ await s.writeRecord(next.id, next);
return { next, wasResurrection };
});
// Mirror createUniverse's federation side-effects on tombstone-overwrite:
@@ -1274,8 +1256,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
if (Array.isArray(mergedRecord.characters)) {
mergedRecord.characters = pruneStaleReferenceSheets(mergedRecord.characters);
}
- await ensureDir(s.recordDir(id));
- await atomicWrite(s.recordPath(id), mergedRecord);
+ await s.writeRecord(id, mergedRecord);
// Project the freshly-persisted canon arrays back into their catalog rows
// SYNCHRONOUSLY (inside the queue) so the authoritative catalog_ingredients
// row can never lag the embedded cache on the same request. Best-effort:
@@ -1400,29 +1381,13 @@ export async function deleteUniverse(id) {
if (cur.deleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
const now = new Date().toISOString();
const tombstone = { ...cur, deleted: true, deletedAt: now, updatedAt: now };
- await ensureDir(s.recordDir(id));
- await atomicWrite(s.recordPath(id), tombstone);
+ await s.writeRecord(id, tombstone);
});
// Drop runs referencing the deleted universe — they're useless without it.
- // CRITICAL: the load + filter + write MUST run inside queueTypeIndexWrite as a
- // single critical section. An earlier version did the load OUTSIDE the queue
- // and then saveTypeIndex inside it — saveTypeIndex's shallow merge then
- // wholesale-replaced `config.runs` with the stale filtered snapshot,
- // silently dropping any recordRun that landed between the outer load and
- // the queued write. Stay inside the queue and use atomicWrite directly
- // (saveTypeIndex would self-re-queue and deadlock).
- await s.queueTypeIndexWrite(async () => {
- const typeIndex = await s.loadTypeIndex();
- const filteredRuns = (typeIndex.config?.runs || []).filter((r) => r.universeId !== id);
- const next = {
- schemaVersion: typeIndex.schemaVersion,
- type: typeIndex.type,
- config: { ...(typeIndex.config || {}), runs: filteredRuns },
- updatedAt: new Date().toISOString(),
- };
- await ensureDir(s.dir);
- await atomicWrite(s.typeIndexPath(), next);
- });
+ // The facade's removeRunsForUniverses serializes the runs read→filter→write on
+ // its own run-tail, so a concurrent recordRun can't lose its newly-appended
+ // run to a stale filtered snapshot.
+ await s.removeRunsForUniverses([id]);
// Release the rename-lock on any linked media collections — without this,
// the orphan collection's `universeId` stays stamped and the lock in
// updateCollection blocks renames forever even though the universe is gone.
@@ -1511,8 +1476,7 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:
// do NOT cascade orphan-cleanup. A tombstone for a record we never
// had has nothing to clean up; firing `emitRecordDeleted` would
// spuriously tear down share-bucket subscriptions.
- await ensureDir(s.recordDir(sanitized.id));
- await atomicWrite(s.recordPath(sanitized.id), sanitized);
+ await s.writeRecord(sanitized.id, sanitized);
// No local counterpart to lose — nothing to journal, but seed the base
// hash so a FUTURE divergence on this record is detected.
await setSyncBaseHash('universe', sanitized.id, contentHashForRecord('universe', sanitized));
@@ -1544,8 +1508,7 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:
// advances the base hash (clean or conflict) so the next snapshot
// cycle doesn't re-journal the same divergence. Never throws.
await maybeJournalBeforeOverwrite({ kind: 'universe', id: sanitized.id, local, remote: sanitized, source });
- await ensureDir(s.recordDir(sanitized.id));
- await atomicWrite(s.recordPath(sanitized.id), sanitized);
+ await s.writeRecord(sanitized.id, sanitized);
if (sanitized.deleted && !local.deleted) transitionedToDeleted.push(sanitized.id);
changed += 1;
}
@@ -1555,25 +1518,12 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:
// Persist the batched base-hash updates accumulated above in one write.
await flushBaseHashes();
if (changed === 0) return { applied: false, count: 0 };
- // Drop runs for any record that just transitioned to deleted — matches
- // the local-delete contract that ditches now-orphan runs. Same critical-
- // section requirement as deleteUniverse: load + filter + write all stay
- // inside queueTypeIndexWrite so a concurrent recordRun doesn't get its
- // newly-appended run overwritten by a stale filtered snapshot.
+ // Drop runs for any record that just transitioned to deleted — matches the
+ // local-delete contract that ditches now-orphan runs. The facade serializes
+ // the runs read→filter→write on its run-tail so a concurrent recordRun can't
+ // lose its newly-appended run to a stale filtered snapshot.
if (transitionedToDeleted.length) {
- const tombstoned = new Set(transitionedToDeleted);
- await s.queueTypeIndexWrite(async () => {
- const typeIndex = await s.loadTypeIndex();
- const filtered = (typeIndex.config?.runs || []).filter((r) => !tombstoned.has(r.universeId));
- const next = {
- schemaVersion: typeIndex.schemaVersion,
- type: typeIndex.type,
- config: { ...(typeIndex.config || {}), runs: filtered },
- updatedAt: new Date().toISOString(),
- };
- await ensureDir(s.dir);
- await atomicWrite(s.typeIndexPath(), next);
- });
+ await s.removeRunsForUniverses(transitionedToDeleted);
}
const result = { applied: true, count: changed };
// Fire cascades after the queue releases (mirrors deleteUniverse ordering)
@@ -1596,11 +1546,13 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:
export async function pruneTombstonedUniverses(beforeMs) {
if (!Number.isFinite(beforeMs)) return { pruned: 0 };
const s = store();
- const ids = await s.listIds();
- const records = await Promise.all(ids.map((id) => s.loadOne(id)));
+ // Bulk raw read for the out-of-queue candidate scan — we only need
+ // id/deleted/deletedAt, so skip the per-record sanitize. The authoritative
+ // re-check inside each per-id queue below still uses loadOne (sanitized).
+ const records = await s.listRaw();
const candidates = [];
for (const u of records) {
- if (!u?.deleted) continue;
+ if (!u?.deleted || !isStr(u.id)) continue;
const t = Date.parse(u.deletedAt || '');
if (!Number.isFinite(t)) continue;
if (t < beforeMs) candidates.push(u.id);
@@ -1618,8 +1570,7 @@ export async function pruneTombstonedUniverses(beforeMs) {
if (!fresh?.deleted) return false; // un-deleted between snapshot and queue
const t = Date.parse(fresh.deletedAt || '');
if (!Number.isFinite(t) || t >= beforeMs) return false;
- const { rm } = await import('fs/promises');
- await rm(s.recordDir(id), { recursive: true, force: true });
+ await s.deleteRecord(id);
await deleteSyncBaseHash('universe', id);
return true;
})
@@ -1635,37 +1586,15 @@ export async function pruneTombstonedUniverses(beforeMs) {
export async function recordRun(run) {
const sanitized = sanitizeRun(run);
if (!sanitized) throw makeErr('Invalid run payload', ERR_VALIDATION);
- const s = store();
- // Type-index queue serializes the runs[] read→append→write so concurrent
- // recordRun + delete-cascade can't clobber each other's runs.
- return s.queueTypeIndexWrite(async () => {
- const typeIndex = await s.loadTypeIndex();
- const runs = Array.isArray(typeIndex.config?.runs) ? [...typeIndex.config.runs] : [];
- runs.push(sanitized);
- // Keep last 200 runs to bound state growth.
- const capped = runs.length > 200 ? runs.slice(-200) : runs;
- // saveTypeIndex also queues, but we're already on the type-index queue —
- // write the file directly with atomicWrite to avoid a re-entrant queue.
- const next = {
- schemaVersion: typeIndex.schemaVersion,
- type: typeIndex.type,
- config: { ...(typeIndex.config || {}), runs: capped },
- updatedAt: new Date().toISOString(),
- };
- await ensureDir(s.dir);
- await atomicWrite(s.typeIndexPath(), next);
- return sanitized;
- });
+ // The facade serializes the runs append→cap on its own run-tail (and caps at
+ // 200), so concurrent recordRun + delete-cascade can't clobber each other.
+ await store().appendRun(sanitized);
+ return sanitized;
}
export async function listRuns(universeId = null) {
- const s = store();
- const typeIndex = await s.loadTypeIndex();
- const runs = Array.isArray(typeIndex.config?.runs)
- ? typeIndex.config.runs.map(sanitizeRun).filter(Boolean)
- : [];
- const filtered = universeId ? runs.filter((r) => r.universeId === universeId) : runs;
- return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
+ const runs = (await store().loadRuns(universeId)).map(sanitizeRun).filter(Boolean);
+ return [...runs].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
}
// Append a rendered gallery filename to the imageRefs[] of the entry the job
diff --git a/server/services/universeBuilder/db.js b/server/services/universeBuilder/db.js
new file mode 100644
index 0000000000..5b8b03109e
--- /dev/null
+++ b/server/services/universeBuilder/db.js
@@ -0,0 +1,139 @@
+/**
+ * Universe Builder — PostgreSQL leaf I/O (#1014).
+ *
+ * One row per universe in `universes`: the full sanitized record (canon bibles,
+ * categories, compositeSheets, locks, influences) in `data` JSONB, with
+ * name / schema_version / ephemeral / updated_at / deleted / deleted_at mirrored
+ * into columns for the queries the service + federation actually run (rename
+ * cascade, delete-guard, list sort, snapshot ephemeral-filter, LWW staleness).
+ * Render-history runs live one-row-per-run in `universe_runs` (local-only,
+ * capped at 200, never federated).
+ *
+ * This module is PURE leaf I/O — no in-process serialization, no sanitizing.
+ * The store facade (store.js) owns the per-id write queue + the mutation epoch
+ * and applies `sanitizeTemplate` on read, so reads here return `data` verbatim
+ * (the columns are a queryable mirror, never read back). The facade serializes
+ * the run RMWs, so the run ops here are single atomic statements/transactions.
+ */
+
+import { query, withTransaction } from '../../lib/db.js';
+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';
+
+// Keep the runs[] log bounded to the most-recent 200 — matches the file
+// backend's cap (universeBuilder.recordRun) so behavior is identical.
+const RUN_CAP = 200;
+
+// --- Universe records ---
+
+/** Raw on-disk-equivalent record (the `data` JSONB), or null. No sanitize. */
+export async function readRaw(id) {
+ const { rows } = await query(`SELECT data FROM universes WHERE id = $1`, [id]);
+ return rows[0]?.data ?? null;
+}
+
+/** Every universe id (live, ephemeral, AND tombstones) — the service filters. */
+export async function listIds() {
+ const { rows } = await query(`SELECT id FROM universes`);
+ return rows.map((r) => r.id);
+}
+
+/**
+ * Every record's raw `data` JSONB in one query (live/ephemeral/tombstones).
+ * The bulk read behind listUniverses — one SELECT instead of N per-id reads.
+ */
+export async function listRaw() {
+ const { rows } = await query(`SELECT data FROM universes`);
+ return rows.map((r) => r.data);
+}
+
+/**
+ * Upsert one record. `data` is written verbatim (lossless); the typed mirror
+ * columns are bind-sanitized so a hand-edited/legacy record with a malformed
+ * timestamp or missing field can't make the write throw (which, during the boot
+ * warm/import, would block the whole backend). `created_at` is preserved on
+ * conflict — only the first INSERT sets it.
+ */
+export async function writeRaw(id, record) {
+ const now = new Date().toISOString();
+ const createdAt = mirrorTimestamp(record?.createdAt, now);
+ const schemaVersion = Number.isInteger(record?.schemaVersion) ? record.schemaVersion : 4;
+ await query(
+ `INSERT INTO universes (id, name, data, schema_version, ephemeral, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7, $8, $9)
+ ON CONFLICT (id) DO UPDATE SET
+ name = EXCLUDED.name,
+ data = EXCLUDED.data,
+ schema_version = EXCLUDED.schema_version,
+ ephemeral = EXCLUDED.ephemeral,
+ updated_at = EXCLUDED.updated_at,
+ deleted = EXCLUDED.deleted,
+ deleted_at = EXCLUDED.deleted_at`,
+ [
+ id,
+ typeof record?.name === 'string' ? record.name : '',
+ JSON.stringify(record),
+ schemaVersion,
+ record?.ephemeral === true,
+ createdAt,
+ mirrorTimestamp(record?.updatedAt, createdAt),
+ record?.deleted === true,
+ mirrorTimestamp(record?.deletedAt, null),
+ ],
+ );
+ return record;
+}
+
+/** Hard-delete a record (tombstone GC). Idempotent — missing row is a no-op. */
+export async function deleteRaw(id) {
+ await query(`DELETE FROM universes WHERE id = $1`, [id]);
+}
+
+// --- Render-history runs (local-only) ---
+
+/** Runs (newest first), optionally scoped to one universe. Returns `data` verbatim. */
+export async function loadRuns(universeId = null) {
+ const { rows } = universeId
+ ? await query(
+ `SELECT data FROM universe_runs WHERE universe_id = $1 ORDER BY created_at DESC, id DESC`,
+ [universeId],
+ )
+ : await query(`SELECT data FROM universe_runs ORDER BY created_at DESC, id DESC`);
+ return rows.map((r) => r.data);
+}
+
+/**
+ * Append one run + trim the global log back to the most-recent RUN_CAP. Runs
+ * in a transaction so a concurrent read never sees the over-cap intermediate.
+ */
+export async function appendRun(run) {
+ await withTransaction(async (client) => {
+ const exec = client.query.bind(client);
+ await exec(
+ `INSERT INTO universe_runs (id, universe_id, collection_id, data, created_at)
+ VALUES ($1, $2, $3, $4::jsonb, $5)
+ ON CONFLICT (id) DO NOTHING`,
+ [
+ run.id,
+ run.universeId,
+ typeof run.collectionId === 'string' ? run.collectionId : null,
+ JSON.stringify(run),
+ mirrorTimestamp(run.createdAt, new Date().toISOString()),
+ ],
+ );
+ // Trim to the newest RUN_CAP across ALL universes (matches the file
+ // backend's whole-array cap, not a per-universe cap).
+ await exec(
+ `DELETE FROM universe_runs WHERE id IN (
+ SELECT id FROM universe_runs ORDER BY created_at DESC, id DESC OFFSET $1
+ )`,
+ [RUN_CAP],
+ );
+ });
+}
+
+/** Drop every run referencing any of `universeIds` (cascade on universe delete). */
+export async function removeRunsForUniverses(universeIds) {
+ const ids = Array.isArray(universeIds) ? universeIds.filter((x) => typeof x === 'string' && x) : [];
+ if (ids.length === 0) return;
+ await query(`DELETE FROM universe_runs WHERE universe_id = ANY($1::text[])`, [ids]);
+}
diff --git a/server/services/universeBuilder/db.test.js b/server/services/universeBuilder/db.test.js
new file mode 100644
index 0000000000..c596930de3
--- /dev/null
+++ b/server/services/universeBuilder/db.test.js
@@ -0,0 +1,138 @@
+/**
+ * Postgres-backed round-trip for the Universe Builder DB adapter (#1014).
+ *
+ * Like catalogUserTypes/db.test.js, this needs a live PostgreSQL with the schema
+ * applied. If no DB is reachable (CI, fresh checkout) it SKIPS cleanly rather
+ * than failing red. When a DB IS reachable it exercises the leaf I/O: verbatim
+ * record readback, listIds across live/tombstone/ephemeral, malformed-timestamp
+ * tolerance, the runs cap + cascade-remove, and hard delete. It snapshots and
+ * restores both tables so a developer's real universes survive the run.
+ */
+
+import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';
+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const probe = await query(
+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'universes') AS ok`,
+ ).catch(() => ({ rows: [{ ok: false }] }));
+ if (probe.rows?.[0]?.ok) dbReady = true;
+ else skipReason = 'universes table not present';
+ }
+}
+
+if (!dbReady) console.log(`⏭️ universeBuilder/db.test.js skipped: ${skipReason}`);
+
+const U = (id, extra = {}) => ({
+ id, name: id, schemaVersion: 4,
+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z',
+ deleted: false, deletedAt: null, ...extra,
+});
+
+describe.skipIf(!dbReady)('universeBuilder DB adapter round-trip', () => {
+ let db;
+ let uSnap = [];
+ let rSnap = [];
+ beforeAll(async () => {
+ db = await import('./db.js');
+ uSnap = (await query(`SELECT * FROM universes`)).rows;
+ rSnap = (await query(`SELECT * FROM universe_runs`)).rows;
+ });
+
+ beforeEach(async () => {
+ await query(`DELETE FROM universe_runs`);
+ await query(`DELETE FROM universes`);
+ });
+
+ afterAll(async () => {
+ await query(`DELETE FROM universe_runs`).catch(() => {});
+ await query(`DELETE FROM universes`).catch(() => {});
+ for (const r of uSnap) {
+ await query(
+ `INSERT INTO universes (id, name, data, schema_version, ephemeral, created_at, updated_at, deleted, deleted_at)
+ VALUES ($1,$2,$3::jsonb,$4,$5,$6,$7,$8,$9) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.name, JSON.stringify(r.data), r.schema_version, r.ephemeral, r.created_at, r.updated_at, r.deleted, r.deleted_at],
+ ).catch(() => {});
+ }
+ for (const r of rSnap) {
+ await query(
+ `INSERT INTO universe_runs (id, universe_id, collection_id, data, created_at)
+ VALUES ($1,$2,$3,$4::jsonb,$5) ON CONFLICT (id) DO NOTHING`,
+ [r.id, r.universe_id, r.collection_id, JSON.stringify(r.data), r.created_at],
+ ).catch(() => {});
+ }
+ await close();
+ });
+
+ it('writes a record and reads it back verbatim', async () => {
+ const rec = U('u-1', { logline: 'a city', characters: [{ id: 'c1', name: 'Ada' }] });
+ await db.writeRaw('u-1', rec);
+ const back = await db.readRaw('u-1');
+ expect(back).toEqual(rec);
+ });
+
+ it('upsert updates the record and the mirror columns', async () => {
+ await db.writeRaw('u-1', U('u-1', { name: 'First' }));
+ await db.writeRaw('u-1', U('u-1', { name: 'Renamed', updatedAt: '2026-03-03T00:00:00.000Z' }));
+ const back = await db.readRaw('u-1');
+ expect(back.name).toBe('Renamed');
+ const col = (await query(`SELECT name, updated_at FROM universes WHERE id = 'u-1'`)).rows[0];
+ expect(col.name).toBe('Renamed');
+ expect(new Date(col.updated_at).toISOString()).toBe('2026-03-03T00:00:00.000Z');
+ });
+
+ it('listIds returns live, tombstoned, and ephemeral ids alike', async () => {
+ await db.writeRaw('live', U('live'));
+ await db.writeRaw('dead', U('dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));
+ await db.writeRaw('ghost', U('ghost', { ephemeral: true }));
+ const ids = (await db.listIds()).sort();
+ expect(ids).toEqual(['dead', 'ghost', 'live']);
+ });
+
+ it('listRaw returns every record body verbatim in one query', async () => {
+ await db.writeRaw('u-1', U('u-1', { logline: 'x' }));
+ await db.writeRaw('u-2', U('u-2'));
+ const all = await db.listRaw();
+ expect(all.map((r) => r.id).sort()).toEqual(['u-1', 'u-2']);
+ expect(all.find((r) => r.id === 'u-1').logline).toBe('x');
+ });
+
+ it('tolerates a malformed timestamp without throwing (falls back)', async () => {
+ await db.writeRaw('u-bad', U('u-bad', { updatedAt: 'not-a-date', createdAt: 'nope' }));
+ const back = await db.readRaw('u-bad');
+ expect(back.id).toBe('u-bad'); // data stored verbatim
+ const col = (await query(`SELECT created_at, updated_at FROM universes WHERE id = 'u-bad'`)).rows[0];
+ expect(col.created_at).toBeInstanceOf(Date); // fell back to NOW(), not null/throw
+ expect(col.updated_at).toBeInstanceOf(Date);
+ });
+
+ it('deleteRaw removes the row (idempotent)', async () => {
+ await db.writeRaw('u-1', U('u-1'));
+ await db.deleteRaw('u-1');
+ expect(await db.readRaw('u-1')).toBeNull();
+ await db.deleteRaw('u-1'); // no throw on missing
+ });
+
+ it('appendRun stores runs and caps the global log at 200', async () => {
+ for (let i = 0; i < 205; i += 1) {
+ await db.appendRun({ id: `run-${String(i).padStart(3, '0')}`, universeId: 'u-1', jobIds: [], promptCount: i, createdAt: `2026-01-01T00:00:${String(i % 60).padStart(2, '0')}.${String(i).padStart(3, '0')}Z` });
+ }
+ const count = (await query(`SELECT COUNT(*)::int AS n FROM universe_runs`)).rows[0].n;
+ expect(count).toBe(200);
+ });
+
+ it('removeRunsForUniverses drops only the named universes runs', async () => {
+ await db.appendRun({ id: 'r-a', universeId: 'u-A', jobIds: [], promptCount: 1, createdAt: '2026-01-01T00:00:00.000Z' });
+ await db.appendRun({ id: 'r-b', universeId: 'u-B', jobIds: [], promptCount: 1, createdAt: '2026-01-01T00:00:01.000Z' });
+ await db.removeRunsForUniverses(['u-A']);
+ const remaining = await db.loadRuns();
+ expect(remaining.map((r) => r.universeId)).toEqual(['u-B']);
+ });
+});
diff --git a/server/services/universeBuilder/store.js b/server/services/universeBuilder/store.js
new file mode 100644
index 0000000000..a2500cb10c
--- /dev/null
+++ b/server/services/universeBuilder/store.js
@@ -0,0 +1,257 @@
+/**
+ * Universe Builder — storage backend dispatcher (#1014).
+ *
+ * Universes used to live one-record-per-dir under data/universes/{id}/index.json
+ * (collectionStore). As of #1014 they live one-row-per-universe in PostgreSQL
+ * (`universes` + `universe_runs`). This facade keeps `store()` SYNCHRONOUS — the
+ * 2000-line service calls it everywhere and then awaits the returned methods —
+ * by owning the in-process serialization (per-id write queue + a single-tail run
+ * queue) and the sanitizer, and delegating only leaf I/O to a memoized backend:
+ *
+ * - PostgreSQL (./db.js) for normal installs.
+ * - File (collectionStore) only under MEMORY_BACKEND=file or NODE_ENV=test —
+ * both UNSUPPORTED for production. Tests boot without a DB, so they keep
+ * exercising the per-record file store exactly as before.
+ *
+ * Federation invisibility (D2 of the schema-design doc): dataSync decides WHEN to
+ * re-send the universe snapshot to peers by fingerprinting the data/universes
+ * directory (mtime:size:inode). A PG-backed universe edit no longer touches that
+ * directory, so without help the snapshot cache would never invalidate and peers
+ * would silently stop receiving universe edits. The fix is the module-level
+ * MUTATION EPOCH below: every record write/delete bumps it, dataSync folds it
+ * into the universe + mediaCollections fingerprint, and the storage swap stays
+ * invisible to the federation layer. Run writes are local-only (stripped from the
+ * wire) so they deliberately do NOT bump the sync epoch.
+ *
+ * The first PG-backed call runs a one-time, marker-gated import of the legacy
+ * data/universes file store into the tables (migrateUniversesToDB), so the boot
+ * warm — the first caller — sees migrated records.
+ */
+
+import { join } from 'path';
+import { PATHS } from '../../lib/fileUtils.js';
+import { createCollectionStore } from '../../lib/collectionStore.js';
+import { checkHealth, ensureSchema } from '../../lib/db.js';
+
+// TYPE-level (storage layout) schema version stamped on the file backend's
+// data/universes/index.json — preserved so an install on the file escape hatch
+// still passes the boot verifier. (PG has no type-index file; see verify().)
+const TYPE_SCHEMA_VERSION = 5;
+
+function isFileBackend() {
+ return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';
+}
+
+// --- Mutation epoch (the dataSync federation-invisibility fix) ---
+// Module-level so dataSync reads ONE monotonic counter regardless of how many
+// times the facade is rebuilt (test PATHS.data swaps). Bumped on every record
+// write/delete (NOT run writes — those are local-only).
+let mutationEpoch = 0;
+/** Current universe mutation epoch — folded into dataSync's fingerprint. */
+export function getUniverseMutationEpoch() {
+ return mutationEpoch;
+}
+
+// --- File backend (escape hatch / tests): wraps collectionStore ---
+// No sanitizer on the collectionStore — the facade owns sanitize uniformly so
+// loadOneRaw and loadOne share one code path. Runs writes use saveTypeIndex,
+// whose internal queue is harmless because the facade already serializes every
+// run write on its own run-tail.
+function makeFileBackend(dir) {
+ const cs = createCollectionStore({
+ dir,
+ type: 'universes',
+ schemaVersion: TYPE_SCHEMA_VERSION,
+ idPattern: /^[A-Za-z0-9_-]{1,128}$/,
+ });
+ const runsOf = (ti) => (Array.isArray(ti.config?.runs) ? ti.config.runs : []);
+ return {
+ name: 'file',
+ readRaw: (id) => cs.loadOneRaw(id),
+ listIds: () => cs.listIds(),
+ listRaw: async () => {
+ const ids = await cs.listIds();
+ const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));
+ return records.filter((r) => r != null);
+ },
+ writeRaw: (id, record) => cs.saveOneNow(id, record),
+ deleteRaw: (id) => cs.deleteOneNow(id),
+ loadRuns: async (universeId = null) => {
+ const ti = await cs.loadTypeIndex();
+ const runs = runsOf(ti);
+ return universeId ? runs.filter((r) => r?.universeId === universeId) : runs;
+ },
+ appendRun: async (run) => {
+ const ti = await cs.loadTypeIndex();
+ const runs = [...runsOf(ti), run];
+ const capped = runs.length > 200 ? runs.slice(-200) : runs;
+ await cs.saveTypeIndex({ config: { runs: capped } });
+ },
+ removeRunsForUniverses: async (universeIds) => {
+ const drop = new Set(universeIds || []);
+ const ti = await cs.loadTypeIndex();
+ const filtered = runsOf(ti).filter((r) => !drop.has(r?.universeId));
+ await cs.saveTypeIndex({ config: { runs: filtered } });
+ },
+ verify: () => cs.verifySchemaVersion(),
+ };
+}
+
+// --- PostgreSQL backend: pure leaf I/O from ./db.js ---
+function makePgBackend(db) {
+ return {
+ name: 'postgres',
+ readRaw: db.readRaw,
+ listIds: db.listIds,
+ listRaw: db.listRaw,
+ writeRaw: db.writeRaw,
+ deleteRaw: db.deleteRaw,
+ loadRuns: db.loadRuns,
+ appendRun: db.appendRun,
+ removeRunsForUniverses: db.removeRunsForUniverses,
+ // PG has no type-index file; the DDL + one-time import ARE the layout
+ // version gate. Report ok so the boot verifier stays quiet on PG installs.
+ verify: async () => ({ ok: true, type: 'universes', onDisk: null, expected: null,
+ message: 'collection "universes" @ postgres (#1014)' }),
+ };
+}
+
+async function pgBackend() {
+ // Self-sufficient like the catalog-user-types backend: the boot DB gate
+ // fail-fasts a required-but-missing DB, but the early universe warm / a sync
+ // pull can call in BEFORE that gate's ensureSchema() runs — so bring the
+ // schema up here (idempotent) and run the one-time file→DB import first.
+ const health = await checkHealth();
+ if (!health.connected) {
+ throw new Error('Universe Builder requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)');
+ }
+ await ensureSchema();
+ const { migrateUniversesToDB } = await import('../../scripts/migrateUniversesToDB.js');
+ await migrateUniversesToDB();
+ const db = await import('./db.js');
+ return makePgBackend(db);
+}
+
+// --- Facade: sync object, queues + epoch + sanitize, async backend delegation ---
+function createFacade({ dir, sanitizeRecord }) {
+ let sanitizer = typeof sanitizeRecord === 'function' ? sanitizeRecord : (r) => r;
+
+ // Memoize the backend selection PROMISE (not just the result) so two
+ // concurrent first calls — e.g. the boot warm racing a sync pull — don't both
+ // import the PG module and run the migration twice.
+ let backend = null;
+ let selecting = null;
+ const getBackend = () => {
+ if (backend) return Promise.resolve(backend);
+ if (!selecting) {
+ selecting = (isFileBackend() ? Promise.resolve(makeFileBackend(dir)) : pgBackend())
+ .then((b) => { backend = b; return b; })
+ .finally(() => { selecting = null; });
+ }
+ return selecting;
+ };
+
+ // Per-id write queue — tail-chained per id so two RMW cycles on the SAME id
+ // serialize while different ids fan out in parallel. Backend-agnostic so file
+ // and PG serialize identically. Mirrors collectionStore's queueRecordWrite.
+ const recordTails = new Map();
+ function queueRecordWrite(id, fn) {
+ const prev = recordTails.get(id) || Promise.resolve();
+ const next = prev.then(fn, fn);
+ const silenced = next.catch(() => {});
+ recordTails.set(id, silenced);
+ silenced.finally(() => { if (recordTails.get(id) === silenced) recordTails.delete(id); });
+ return next;
+ }
+
+ // Single-tail queue for run-log writes (append / cascade-remove). The runs log
+ // is shared cross-record state, so its RMW must serialize against itself.
+ let runTail = Promise.resolve();
+ function queueRunWrite(fn) {
+ const next = runTail.then(fn, fn);
+ const silenced = next.catch(() => {});
+ runTail = silenced;
+ silenced.finally(() => { if (runTail === silenced) runTail = Promise.resolve(); });
+ return next;
+ }
+
+ return {
+ dir,
+ type: 'universes',
+ _setSanitizer: (fn) => { if (typeof fn === 'function') sanitizer = fn; },
+ getBackendName: () => backend?.name ?? null,
+
+ // Reads
+ listIds: async () => (await getBackend()).listIds(),
+ listRaw: async () => (await getBackend()).listRaw(),
+ loadOneRaw: async (id) => (await getBackend()).readRaw(id),
+ loadOne: async (id) => {
+ const raw = await (await getBackend()).readRaw(id);
+ return raw ? sanitizer(raw) : null;
+ },
+
+ // Per-id write serialization (callers run their RMW inside this)
+ queueRecordWrite,
+
+ // Backend-agnostic record persistence — replaces the inline
+ // ensureDir+atomicWrite(recordPath) / rm(recordDir) the service used to do.
+ // Both bump the mutation epoch so dataSync re-sends the universe snapshot.
+ writeRecord: async (id, record) => {
+ const out = await (await getBackend()).writeRaw(id, record);
+ mutationEpoch += 1;
+ return out ?? record;
+ },
+ deleteRecord: async (id) => {
+ await (await getBackend()).deleteRaw(id);
+ mutationEpoch += 1;
+ },
+
+ // Render-history runs (local-only — no epoch bump)
+ loadRuns: async (universeId = null) => (await getBackend()).loadRuns(universeId),
+ appendRun: (run) => queueRunWrite(async () => (await getBackend()).appendRun(run)),
+ removeRunsForUniverses: (ids) =>
+ queueRunWrite(async () => (await getBackend()).removeRunsForUniverses(ids)),
+
+ // Boot-time verifier. Under the file backend it reads the on-disk type
+ // index. Under PG it returns ok WITHOUT forcing backend selection — the
+ // early boot verifier runs before the dbReady gate, and we don't want to
+ // trigger the one-time import there; the authoritative warm in the dbReady
+ // block (server/index.js) selects the backend at the right time. The env
+ // check is cheap and matches the selection predicate.
+ verifySchemaVersion: async () => {
+ if (!isFileBackend()) {
+ return { ok: true, type: 'universes', onDisk: null, expected: null,
+ message: 'collection "universes" @ postgres (#1014)' };
+ }
+ return (await getBackend()).verify();
+ },
+ };
+}
+
+// Memoized facade, keyed by data dir so test harnesses that swap PATHS.data
+// per-test (mkdtempSync + Proxy mock) still see the right root.
+let _facade = null;
+let _facadeDir = null;
+
+/**
+ * Get the universe store facade. Pass the record sanitizer (sanitizeTemplate)
+ * so `loadOne` returns a sanitized record without store.js importing the service
+ * (which would close a cycle). Synchronous — backend selection is deferred into
+ * each method.
+ */
+export function getUniverseStore(sanitizeRecord) {
+ const dir = join(PATHS.data, 'universes');
+ if (_facade && _facadeDir === dir) {
+ if (sanitizeRecord) _facade._setSanitizer(sanitizeRecord);
+ return _facade;
+ }
+ _facade = createFacade({ dir, sanitizeRecord });
+ _facadeDir = dir;
+ return _facade;
+}
+
+/** Reset the memoized facade — test seam only (does NOT reset the epoch). */
+export function _resetUniverseStore() {
+ _facade = null;
+ _facadeDir = null;
+}
diff --git a/server/services/universeBuilder/store.test.js b/server/services/universeBuilder/store.test.js
new file mode 100644
index 0000000000..a13f94cd9d
--- /dev/null
+++ b/server/services/universeBuilder/store.test.js
@@ -0,0 +1,110 @@
+/**
+ * Universe store facade — file-backend dispatcher behavior (#1014).
+ *
+ * NODE_ENV=test selects the file backend (collectionStore over a real tmpdir),
+ * so this exercises the facade WITHOUT a database: the read/write/delete surface
+ * the service uses, the local-only runs API + 200 cap, cascade-remove, and the
+ * mutation epoch that record writes bump (and runs deliberately do NOT) — the
+ * signal dataSync folds into its fingerprint so the storage swap stays invisible
+ * to federation.
+ */
+
+import { describe, it, expect, beforeEach, afterAll } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { vi } from 'vitest';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'universe-store-test-'));
+
+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+});
+
+const { getUniverseStore, _resetUniverseStore, getUniverseMutationEpoch } = await import('./store.js');
+
+// Minimal sanitizer that just passes the record through — the facade's sanitize
+// hook is the service's sanitizeTemplate in production; here we only assert the
+// hook is applied (loadOne runs it, loadOneRaw does not).
+const passthroughSanitize = (r) => (r ? { ...r, _sanitized: true } : r);
+
+describe('universe store facade — file backend', () => {
+ beforeEach(() => {
+ rmSync(join(TEST_DATA_ROOT, 'universes'), { recursive: true, force: true });
+ _resetUniverseStore();
+ });
+ afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+ it('selects the file backend under NODE_ENV=test', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ await s.listIds();
+ expect(s.getBackendName()).toBe('file');
+ });
+
+ it('writeRecord persists, loadOneRaw returns verbatim, loadOne sanitizes', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ await s.writeRecord('u-1', { id: 'u-1', name: 'Aurora' });
+ expect(await s.loadOneRaw('u-1')).toEqual({ id: 'u-1', name: 'Aurora' });
+ expect(await s.loadOne('u-1')).toEqual({ id: 'u-1', name: 'Aurora', _sanitized: true });
+ expect((await s.listIds())).toEqual(['u-1']);
+ });
+
+ it('listRaw returns every record verbatim (no sanitize) in one bulk read', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ await s.writeRecord('u-1', { id: 'u-1', name: 'A' });
+ await s.writeRecord('u-2', { id: 'u-2', name: 'B' });
+ const all = await s.listRaw();
+ expect(all.map((r) => r.id).sort()).toEqual(['u-1', 'u-2']);
+ expect(all.every((r) => !('_sanitized' in r))).toBe(true); // raw, not sanitized
+ });
+
+ it('deleteRecord removes the record', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ await s.writeRecord('u-1', { id: 'u-1', name: 'X' });
+ await s.deleteRecord('u-1');
+ expect(await s.loadOneRaw('u-1')).toBeNull();
+ expect(await s.listIds()).toEqual([]);
+ });
+
+ it('record writes AND deletes bump the mutation epoch; reads do not', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ const e0 = getUniverseMutationEpoch();
+ await s.writeRecord('u-1', { id: 'u-1', name: 'X' });
+ const e1 = getUniverseMutationEpoch();
+ expect(e1).toBeGreaterThan(e0);
+ await s.loadOne('u-1');
+ await s.listIds();
+ expect(getUniverseMutationEpoch()).toBe(e1); // reads don't bump
+ await s.deleteRecord('u-1');
+ expect(getUniverseMutationEpoch()).toBeGreaterThan(e1);
+ });
+
+ it('runs API stores/loads, caps at 200, and does NOT bump the epoch', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ const before = getUniverseMutationEpoch();
+ for (let i = 0; i < 205; i += 1) {
+ await s.appendRun({ id: `run-${i}`, universeId: 'u-1', jobIds: [], promptCount: i, createdAt: new Date(1700000000000 + i).toISOString() });
+ }
+ const all = await s.loadRuns();
+ expect(all.length).toBe(200);
+ expect(getUniverseMutationEpoch()).toBe(before); // runs are local-only
+ });
+
+ it('loadRuns scopes by universeId; removeRunsForUniverses drops only those', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ await s.appendRun({ id: 'r-a', universeId: 'u-A', jobIds: [], promptCount: 1, createdAt: '2026-01-01T00:00:00.000Z' });
+ await s.appendRun({ id: 'r-b', universeId: 'u-B', jobIds: [], promptCount: 1, createdAt: '2026-01-01T00:00:01.000Z' });
+ expect((await s.loadRuns('u-A')).map((r) => r.id)).toEqual(['r-a']);
+ await s.removeRunsForUniverses(['u-A']);
+ expect((await s.loadRuns()).map((r) => r.universeId)).toEqual(['u-B']);
+ });
+
+ it('verifySchemaVersion reports the file collection version', async () => {
+ const s = getUniverseStore(passthroughSanitize);
+ await s.writeRecord('u-1', { id: 'u-1', name: 'X' });
+ const status = await s.verifySchemaVersion();
+ expect(status.ok).toBe(true);
+ expect(status.type).toBe('universes');
+ });
+});