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
Migrate Story Builder sessions to PostgreSQL (#1016)
Adam Eivy8abc38de33e9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3339cf5456..626e39102f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,7 @@- **Songs: the practice tools now lead the View tab** — the sheet music, metronome, and vocal recorder are grouped at the top of a song's performance view (just under the meta line and round-stack toggle), instead of the recorder sitting at the very bottom below the lyrics and references. So when you open a song to play it, you read the chart, set the tempo, and record against it without scrolling — the lyrics and reference videos follow underneath.- **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.- **Pipeline series & issues now store in PostgreSQL** — your comic/TV series and their issues (the 8-stage production pipeline state: idea, prose, comic script, teleplay, comic pages, storyboards, episode video, audio) moved out of the per-record `data/pipeline-series/{id}/index.json` and `data/pipeline-issues/{id}/index.json` files into dedicated `pipeline_series` and `pipeline_issues` tables, one row per record. The hot relationships are promoted to indexed columns — `pipeline_issues (series_id, number)` directly serves the issue-renumber pass (the most common cross-record pipeline query), and `pipeline_series (universe_id)` serves the universe delete-guard and "series in this universe" lists. Existing installs are migrated automatically and losslessly on first boot. Each issue's full stage map (including its `lastRunId` transcript pointers) stays in the row's `data` payload, and the "Finish the draft" manuscript-review sibling document stays a file alongside the series — only the series/issue records themselves moved. Nothing changes in how you create, edit, delete, renumber, run, or sync the pipeline: the 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 the pipeline cleanly with a peer still on the old file storage). This is the second implementation slice (#1015) of the Create relational-schema migration designed in #999, building on the Universes slice (#1014). The pipeline still persists to the per-record file store under the `MEMORY_BACKEND=file` dev/test escape hatch.+- **Story Builder sessions now store in PostgreSQL** — the guided Story Builder's session records (the per-step lock/integrity state, the cross-machine staleness baseline, your current step, and the saved provider/model picker choice) moved out of the per-record `data/story-builder/{id}/index.json` files into a dedicated `story_builder_sessions` table, one row per session. The two links every session carries — its universe and its series — are promoted to indexed columns, and the OPT-IN cross-machine resume flag (`sync`) is promoted too so the federation snapshot loop can find the sync-enabled sessions without deserializing every session's body. Existing installs are migrated automatically and losslessly on first boot — the legacy `data/story-builder/` directory is renamed aside (`data/story-builder.imported`) as a one-release recovery source. Nothing changes in how you create, run, lock, reconcile, or sync sessions: the Story Builder UI and the opt-in cross-machine resume wire format are unchanged (no schema-version bump — the sync payload is storage-independent, so a machine on this version syncs sessions cleanly with a peer still on the old file storage). This is the third implementation slice (#1016) of the Create relational-schema migration designed in #999, building on the Universes (#1014) and Pipeline (#1015) slices. Sessions 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/server/index.js b/server/index.jsindex 6b43fb6275..9ba1ebf06d 100644--- a/server/index.js+++ b/server/index.js@@ -858,6 +858,12 @@ ensureSelf()// Series first (issues soft-ref it for universe resolution / lists).await seriesStore().listIds();await issueStore().listIds();+ // Story Builder sessions PG warm (#1016): same contract — touch the store+ // so it selects Postgres and runs its one-time file→DB import+ // (migrateStoryBuilderToDB) BEFORE httpServer.listen, so the first+ // request/sync sees migrated sessions. Universe + series warmed first+ // (sessions soft-ref both for the staleness recompute / linked-record view).+ await storyBuilderStore().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 runsdiff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 4dfad31096..e1f9f6b87f 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -261,6 +261,20 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {expect(sqlIdx.size).toBeGreaterThan(0);});+ // Story Builder sessions (#1016) — same drift risk; its own table + indexes.+ it('story_builder_sessions has the same columns and indexes in both files', () => {+ const sqlBody = extractCreateTable(INIT_SQL, 'story_builder_sessions');+ const jsBody = extractCreateTable(DB_JS, 'story_builder_sessions');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE story_builder_sessions').toBeTruthy();+ expect(jsBody, 'db.js missing CREATE TABLE story_builder_sessions').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());+ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_stb_');+ const jsIdx = extractIndexNames(DB_JS, 'idx_stb_');+ 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) anddiff --git a/server/lib/db.js b/server/lib/db.jsindex 3053811c34..6ee7163935 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -689,6 +689,32 @@ async function ensureSchemaImpl() {`CREATE INDEX IF NOT EXISTS idx_issues_series ON pipeline_issues (series_id, number) WHERE deleted = FALSE`,`CREATE INDEX IF NOT EXISTS idx_issues_season ON pipeline_issues (season_id) WHERE season_id IS NOT NULL`,`CREATE INDEX IF NOT EXISTS idx_issues_updated ON pipeline_issues (updated_at)`,++ // Story Builder sessions (issue #1016). One row per session; the conductor+ // bookkeeping (`steps` lock/integrity map, `syncedHashes` baseline,+ // `currentStep`, `llm` picker choice) stays entirely in `data` JSONB. The two+ // FKs `universe_id` / `series_id` are promoted for "sessions linked to this+ // record" lookups. `sync` is promoted because Story Builder is the one store+ // whose federation is OPT-IN — the snapshot loop filters WHERE sync = TRUE to+ // decide what to even consider pushing, so promoting it avoids deserializing+ // every session's `data` per snapshot tick. `ephemeral` + the LWW/tombstone+ // trio mirror the body. NO sync_sequence (sessions ride the existing dataSync+ // snapshot/LWW model, not the per-record push pipeline). Mirrors init-db.sql.+ `CREATE TABLE IF NOT EXISTS story_builder_sessions (+ id TEXT PRIMARY KEY,+ universe_id TEXT,+ series_id TEXT,+ sync BOOLEAN DEFAULT FALSE,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ ephemeral BOOLEAN DEFAULT FALSE,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ+ )`,+ `CREATE INDEX IF NOT EXISTS idx_stb_universe ON story_builder_sessions (universe_id)`,+ `CREATE INDEX IF NOT EXISTS idx_stb_series ON story_builder_sessions (series_id)`,+ `CREATE INDEX IF NOT EXISTS idx_stb_updated ON story_builder_sessions (updated_at)`,];for (const sql of catalogDDL) {await pool.query(sql);diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex c666bd713a..c182f6798f 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -735,3 +735,30 @@ CREATE TABLE IF NOT EXISTS pipeline_issues (CREATE INDEX IF NOT EXISTS idx_issues_series ON pipeline_issues (series_id, number) WHERE deleted = FALSE;CREATE INDEX IF NOT EXISTS idx_issues_season ON pipeline_issues (season_id) WHERE season_id IS NOT NULL;CREATE INDEX IF NOT EXISTS idx_issues_updated ON pipeline_issues (updated_at);++-- Story Builder sessions (issue #1016). One row per session; the conductor+-- bookkeeping (`steps` lock/integrity map, `syncedHashes` baseline,+-- `currentStep`, `llm` picker choice) stays entirely in `data` JSONB. The two+-- FKs `universe_id` / `series_id` are promoted for "sessions linked to this+-- record" lookups. `sync` is promoted because Story Builder is the one store+-- whose federation is OPT-IN — the snapshot loop filters WHERE sync = TRUE to+-- decide what to even consider pushing, so promoting it avoids deserializing+-- every session's `data` per snapshot tick. `ephemeral` + the LWW/tombstone+-- trio mirror the body. NO sync_sequence (sessions ride the existing dataSync+-- snapshot/LWW model, not the per-record push pipeline).+-- Mirrors the story_builder_sessions block in db.js ensureSchema().+CREATE TABLE IF NOT EXISTS story_builder_sessions (+ id TEXT PRIMARY KEY,+ universe_id TEXT,+ series_id TEXT,+ sync BOOLEAN DEFAULT FALSE,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ ephemeral BOOLEAN DEFAULT FALSE,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ+);+CREATE INDEX IF NOT EXISTS idx_stb_universe ON story_builder_sessions (universe_id);+CREATE INDEX IF NOT EXISTS idx_stb_series ON story_builder_sessions (series_id);+CREATE INDEX IF NOT EXISTS idx_stb_updated ON story_builder_sessions (updated_at);diff --git a/server/scripts/migrateStoryBuilderToDB.js b/server/scripts/migrateStoryBuilderToDB.jsnew file mode 100644index 0000000000..ffafb82194--- /dev/null+++ b/server/scripts/migrateStoryBuilderToDB.js@@ -0,0 +1,102 @@+/**+ * One-time importer: data/story-builder/{id}/index.json (collectionStore) →+ * PostgreSQL (`story_builder_sessions`), for Phase 3 Create / issue #1016.+ *+ * Sessions used to live one-record-per-dir. As of #1016 they live one-row-per-+ * session in Postgres. On the first PG-backed access (from+ * services/storyBuilderStore/store.js, BEFORE the boot warm reads any session),+ * this importer copies each legacy record into `story_builder_sessions`. Session+ * dirs hold ONLY index.json (no file-primary siblings), so — like the universe+ * and pipeline-issues importers — the whole legacy dir is renamed aside after+ * all rows land.+ *+ * Idempotency / safety (mirrors migrateIssuesToDB):+ * - Marker-gated in data/story-builder.migrated.json so the walk runs once.+ * - INSERT … ON CONFLICT (id) DO NOTHING — never clobbers an existing row.+ * - LOSSLESS: each record copied verbatim into `data`.+ * - The legacy dir is RENAMED to data/story-builder.imported (not deleted)+ * so it remains a recovery source for ≥1 release. Renamed ONLY after all+ * rows land AND only then is the marker written — a crash mid-import leaves+ * the dir → next boot retries (ON CONFLICT DO NOTHING makes the retry safe).+ */++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 = 'story-builder';+const IMPORTED_DIRNAME = 'story-builder.imported';+const MARKER_FILENAME = 'story-builder.migrated.json';+const RECORD_RE = /^stb-[A-Za-z0-9-]+$/;++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 session record → `story_builder_sessions` row. Verbatim into+// `data`; the typed mirror columns are bind-sanitized so a hand-edited/legacy+// value 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 result = await query(+ `INSERT INTO story_builder_sessions (id, universe_id, series_id, sync, data, ephemeral, created_at, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10)+ ON CONFLICT (id) DO NOTHING`,+ [+ record.id,+ typeof record.universeId === 'string' && record.universeId ? record.universeId : null,+ typeof record.seriesId === 'string' && record.seriesId ? record.seriesId : null,+ record.sync === true,+ JSON.stringify(record),+ record.ephemeral === true,+ createdAt,+ mirrorTimestamp(record.updatedAt, createdAt),+ record.deleted === true,+ mirrorTimestamp(record.deletedAt, null),+ ],+ );+ return result.rowCount > 0;+}++export async function migrateStoryBuilderToDB() {+ 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): no-op WITHOUT stamping the marker (keeps the+ // recovery escape hatch open — see migrateIssuesToDB).+ if (!dirStat || !dirStat.isDirectory()) {+ return { ok: true, reason: 'fresh-install', imported: 0 };+ }++ const entries = await readdir(legacyDir).catch(() => []);+ let imported = 0;+ let skipped = 0;+ for (const name of entries) {+ if (!RECORD_RE.test(name)) continue; // skip index.json, hidden, non-record dirs+ 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;+ }++ try {+ await rename(legacyDir, join(PATHS.data, IMPORTED_DIRNAME));+ } catch (err) {+ console.warn(`⚠️ story-builder→DB import: imported ${imported} session(s) but renaming ${LEGACY_DIRNAME} aside failed (${err.message}) — leaving dir, will retry marker next boot`);+ return { ok: true, reason: 'imported-rename-failed', imported, skipped };+ }+ await writeMarker({ migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });+ console.log(`📖 story-builder→DB import: imported ${imported} session(s) (${skipped} skipped); data/${LEGACY_DIRNAME} renamed to ${IMPORTED_DIRNAME}`);+ return { ok: true, reason: 'imported', imported, skipped };+}diff --git a/server/scripts/migrateStoryBuilderToDB.test.js b/server/scripts/migrateStoryBuilderToDB.test.jsnew file mode 100644index 0000000000..f1a6274359--- /dev/null+++ b/server/scripts/migrateStoryBuilderToDB.test.js@@ -0,0 +1,128 @@+/**+ * Tests for the legacy data/story-builder/{id}/index.json → Postgres importer+ * (#1016). Session dirs hold only index.json (no siblings), so the whole legacy+ * dir is renamed aside after rows land — like the pipeline-issues importer. Disk+ * + PG are mocked.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++let files = {};+let dirEntries = null;+let recordsByDir = {};+let renameShouldFail = false;+let renamed = [];++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { data: '/fake/data' },+ readJSONFile: vi.fn(async (path) => 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 () => (dirEntries === null ? [] : dirEntries)),+ stat: vi.fn(async (path) => {+ if (path === '/fake/data/story-builder') {+ 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 table;+const query = vi.fn(async (sql, params) => {+ if (/INSERT INTO story_builder_sessions/.test(sql)) {+ const id = params[0];+ if (table.has(id)) return { rowCount: 0, rows: [] };+ table.set(id, { id, universeId: params[1], seriesId: params[2], sync: params[3], data: JSON.parse(params[4]) });+ return { rowCount: 1, rows: [] };+ }+ return { rowCount: 0, rows: [] };+});+vi.mock('../lib/db.js', () => ({ query: (...a) => query(...a) }));++const MARKER = '/fake/data/story-builder.migrated.json';+const rec = (id, extra = {}) => ({ id, title: id, intakeMode: 'seed', createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z', ...extra });++async function importer() {+ const { migrateStoryBuilderToDB } = await import('./migrateStoryBuilderToDB.js');+ return migrateStoryBuilderToDB();+}++beforeEach(() => {+ files = {};+ dirEntries = null;+ recordsByDir = {};+ renameShouldFail = false;+ renamed = [];+ table = new Map();+ query.mockClear();+});++describe('migrateStoryBuilderToDB', () => {+ it('fresh install (no legacy dir): no-op WITHOUT a marker', async () => {+ const result = await importer();+ expect(result).toMatchObject({ ok: true, reason: 'fresh-install', imported: 0 });+ expect(MARKER in files).toBe(false);+ });++ it('marker already present: no-op', async () => {+ files[MARKER] = JSON.stringify({ reason: 'imported' });+ dirEntries = ['stb-1'];+ recordsByDir['/fake/data/story-builder/stb-1/index.json'] = rec('stb-1');+ const result = await importer();+ expect(result).toMatchObject({ reason: 'already-applied' });+ expect(table.size).toBe(0);+ });++ it('imports records verbatim, renames the dir aside, stamps marker', async () => {+ dirEntries = ['stb-1', 'stb-2', 'index.json', '.DS_Store'];+ recordsByDir['/fake/data/story-builder/stb-1/index.json'] = rec('stb-1', { universeId: 'u-1', seriesId: 'ser-1', steps: { idea: { locked: true } } });+ recordsByDir['/fake/data/story-builder/stb-2/index.json'] = rec('stb-2');+ const result = await importer();+ expect(result).toMatchObject({ ok: true, reason: 'imported', imported: 2 });+ expect(table.get('stb-1').data.steps.idea.locked).toBe(true); // verbatim+ expect(table.get('stb-1').universeId).toBe('u-1'); // mirror column+ expect(table.get('stb-1').seriesId).toBe('ser-1'); // mirror column+ expect(renamed).toEqual([['/fake/data/story-builder', '/fake/data/story-builder.imported']]);+ expect(MARKER in files).toBe(true);+ });++ it('promotes the OPT-IN sync flag into the mirror column', async () => {+ dirEntries = ['stb-on', 'stb-off'];+ recordsByDir['/fake/data/story-builder/stb-on/index.json'] = rec('stb-on', { sync: true });+ recordsByDir['/fake/data/story-builder/stb-off/index.json'] = rec('stb-off', { sync: false });+ await importer();+ expect(table.get('stb-on').sync).toBe(true);+ expect(table.get('stb-off').sync).toBe(false);+ });++ it('skips an unreadable record', async () => {+ dirEntries = ['stb-1', 'stb-bad'];+ recordsByDir['/fake/data/story-builder/stb-1/index.json'] = rec('stb-1');+ recordsByDir['/fake/data/story-builder/stb-bad/index.json'] = null;+ const result = await importer();+ expect(result.imported).toBe(1);+ expect(table.has('stb-1')).toBe(true);+ expect(table.has('stb-bad')).toBe(false);+ });++ it('rename failure leaves the marker UNwritten so next boot retries', async () => {+ dirEntries = ['stb-1'];+ recordsByDir['/fake/data/story-builder/stb-1/index.json'] = rec('stb-1');+ renameShouldFail = true;+ const result = await importer();+ expect(result).toMatchObject({ ok: true, reason: 'imported-rename-failed', imported: 1 });+ expect(MARKER in files).toBe(false);+ expect(table.has('stb-1')).toBe(true);+ });+});diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex 19e2714d9c..38e31475f3 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -26,6 +26,7 @@ import { mergeSeriesFromSync, listSeries } from './pipeline/series.js';import { mergeIssuesFromSync, listIssues } from './pipeline/issues.js';import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './mediaCollections.js';import { listSyncableSessionsForWire, mergeStorySessionsFromSync } from './storyBuilder.js';+import { getStoryBuilderMutationEpoch } from './storyBuilderStore/store.js';import { sanitizeStateForWire } from '../lib/syncWire.js';// --- Category Definitions ---@@ -82,11 +83,20 @@ const MEDIA_COLLECTIONS_DIR = join(PATHS.data, 'media-collections');// CHECKSUM_PATHS below.const PEER_SUBSCRIPTIONS_FILE = join(PATHS.data, 'sharing', 'peer_subscriptions.json');const VIDEO_HISTORY_FILE = join(PATHS.data, 'video-history.json');-// Story Builder sessions live in per-record `data/story-builder/<id>/index.json`-// (collectionStore layout) with a type-level `data/story-builder/index.json`.-// Only `sync: true` sessions ride this category (#730); the fingerprint walker-// descends into the dir so a session edit invalidates the snapshot checksum.+// Story Builder sessions used to live in per-record `data/story-builder/<id>/+// index.json`; #1016 moved the RECORDS into PostgreSQL (`story_builder_sessions`).+// Only `sync: true` sessions ride this category (#730). Same federation-+// invisibility problem as universes (#1014): a PG-backed session edit no longer+// touches this directory, so the dir fingerprint alone would go stale and peers+// would stop receiving session edits. The store exports a monotonic mutation+// epoch (bumped on every session record write/delete) folded into this path's+// fingerprint via STORY_BUILDER_EPOCH_KEY below. Under the file backend the dir+// still changes too (harmless double-signal).const STORY_BUILDER_DIR = join(PATHS.data, 'story-builder');+// Sentinel fingerprint-map key (not a real path — readFingerprintMap special-+// cases it) carrying the Story Builder mutation epoch into the storyBuilder+// checksum cache.+const STORY_BUILDER_EPOCH_KEY = '__storyBuilderEpoch';const MEATSPACE_FILES = {'daily-log.json': { arrayKey: 'entries', idField: 'date' },@@ -778,12 +788,14 @@ const CHECKSUM_PATHS = {// 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],- // storyBuilder invalidates on its own per-record dir. The snapshot includes- // ONLY sync-enabled sessions, but the fingerprint walker is content-agnostic- // (any session file edit re-checksums) — over-invalidation is harmless: the- // snapshot getter filters back to sync:true and the checksum is unchanged- // when no synced session moved, so the orchestrator still skips the transfer.- storyBuilder: [STORY_BUILDER_DIR],+ // STORY_BUILDER_EPOCH_KEY folds in the store's mutation epoch so a PG-backed+ // session edit (which doesn't touch STORY_BUILDER_DIR) still invalidates the+ // cache — see STORY_BUILDER_DIR's note. The snapshot includes ONLY+ // sync-enabled sessions, but the epoch/dir signal is content-agnostic (any+ // session write re-checksums) — over-invalidation is harmless: the snapshot+ // getter filters back to sync:true and the checksum is unchanged when no+ // synced session moved, so the orchestrator still skips the transfer.+ storyBuilder: [STORY_BUILDER_DIR, STORY_BUILDER_EPOCH_KEY],};const CATEGORIES = {@@ -898,6 +910,7 @@ async function readFingerprintMap(paths) {// though no file moved. fingerprintsEqual compares these like any value.if (p === UNIVERSE_EPOCH_KEY) { out[p] = `epoch:${getUniverseMutationEpoch()}`; return; }if (p === PIPELINE_EPOCH_KEY) { out[p] = `epoch:${getPipelineMutationEpoch()}`; return; }+ if (p === STORY_BUILDER_EPOCH_KEY) { out[p] = `epoch:${getStoryBuilderMutationEpoch()}`; return; }const s = await stat(p).catch(() => null);if (!s) { out[p] = null; return; }if (s.isDirectory()) {diff --git a/server/services/dataSync.storyBuilderEpoch.test.js b/server/services/dataSync.storyBuilderEpoch.test.jsnew file mode 100644index 0000000000..a2f2394134--- /dev/null+++ b/server/services/dataSync.storyBuilderEpoch.test.js@@ -0,0 +1,68 @@+/**+ * dataSync Story Builder mutation-epoch fingerprint (#1016).+ *+ * When Story Builder sessions move to PostgreSQL, a session edit no longer+ * touches data/story-builder/, so the directory file-fingerprint that gates+ * dataSync's storyBuilder snapshot cache goes stale — peers would silently stop+ * receiving session edits. The fix folds the store's monotonic mutation epoch+ * into the storyBuilder checksum fingerprint.+ *+ * This test isolates that mechanism: listSyncableSessionsForWire is mocked so the+ * snapshot CONTENT can change with NO file change, and getStoryBuilderMutationEpoch+ * is mocked so we control the epoch. It proves (a) a content change WITHOUT an+ * epoch bump is masked by the cache, 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-stb-epoch-' });++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++let sessionsContent = [];+let epoch = 0;++vi.mock('./storyBuilder.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ listSyncableSessionsForWire: vi.fn(async () => sessionsContent),+ mergeStorySessionsFromSync: vi.fn(async () => ({ applied: false, count: 0 })),+ };+});+vi.mock('./storyBuilderStore/store.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, getStoryBuilderMutationEpoch: vi.fn(() => epoch) };+});++const dataSync = await import('./dataSync.js');++afterAll(cleanup);++beforeEach(() => {+ sessionsContent = [{ id: 'stb-1', title: 'A', sync: true, updatedAt: '2026-05-17T10:00:00Z' }];+ epoch = 0;+});++describe('dataSync — Story Builder 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('storyBuilder');+ sessionsContent = [{ id: 'stb-1', title: 'CHANGED', sync: true, updatedAt: '2026-05-17T11:00:00Z' }];+ const after = await dataSync.getChecksum('storyBuilder');+ 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('storyBuilder');+ sessionsContent = [{ id: 'stb-1', title: 'CHANGED', sync: true, updatedAt: '2026-05-17T11:00:00Z' }];+ epoch += 1; // the store bumps this on every record write/delete+ const after = await dataSync.getChecksum('storyBuilder');+ expect(after.checksum).not.toBe(before.checksum);+ expect(after.checksum).toBe((await dataSync.getSnapshot('storyBuilder')).checksum);+ });+});diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.jsindex a2b8da1bf6..8b1054bbab 100644--- a/server/services/storyBuilder.js+++ b/server/services/storyBuilder.js@@ -30,13 +30,13 @@* The tombstone/origin/ephemeral fields are carried only for on-disk shape* parity (and forward-compat with the eventual sync wire integration).*- * Persisted to data/story-builder/{id}/index.json.+ * Storage: one row per session in PostgreSQL (`story_builder_sessions`) as of+ * #1016 (legacy on-disk shape was data/story-builder/{id}/index.json). The+ * storyBuilderStore facade is a drop-in for the collectionStore surface this+ * service calls, so only the `store()` factory below changed.*/-import { join } from 'path';import { randomUUID } from 'crypto';-import { PATHS } from '../lib/fileUtils.js';-import { createCollectionStore } from '../lib/collectionStore.js';import { isStr, trimTo, pickPromptFields, BIBLE_KIND } from '../lib/storyBible.js';import { sanitizeOrigin } from '../lib/sharingOrigin.js';import { sanitizeSoftDeleteFields } from '../lib/syncWire.js';@@ -45,6 +45,7 @@ import {STEP_IDS, STEP_STATUSES, isValidStepId,} from '../lib/storyBuilderSteps.js';import { hashUpstream, computeStaleSteps, computeSyncDrift } from '../lib/storyBuilderIntegrity.js';+import { getStoryBuilderStore } from './storyBuilderStore/store.js';import { createUniverse, deleteUniverse, getUniverse, updateUniverse } from './universeBuilder.js';import { expandWorldTemplate } from './universeBuilderExpand.js';import { refineWorldPrompts } from './universeBuilderRefine.js';@@ -58,20 +59,11 @@ import {ERR_VALIDATION as ARC_ERR_VALIDATION,} from './pipeline/arcPlanner.js';-const TYPE_SCHEMA_VERSION = 1;--let _store = null;-const store = () => {- if (_store && _store.dir === join(PATHS.data, 'story-builder')) return _store;- _store = createCollectionStore({- dir: join(PATHS.data, 'story-builder'),- type: 'storyBuilder',- schemaVersion: TYPE_SCHEMA_VERSION,- sanitizeRecord: sanitizeSession,- idPattern: /^stb-[A-Za-z0-9-]+$/,- });- return _store;-};+// Storage backend dispatcher (#1016): the facade is a drop-in for the+// collectionStore surface this service used to call directly, so every method+// below keeps calling `store().loadAll()`, `store().queueRecordWrite(...)`, etc.+// unchanged — only the backend (PostgreSQL vs the file escape hatch) moved.+const store = () => getStoryBuilderStore(sanitizeSession);export const storyBuilderStore = () => store();export const ERR_NOT_FOUND = 'STORY_BUILDER_NOT_FOUND';diff --git a/server/services/storyBuilderStore/db.js b/server/services/storyBuilderStore/db.jsnew file mode 100644index 0000000000..856e29f781--- /dev/null+++ b/server/services/storyBuilderStore/db.js@@ -0,0 +1,80 @@+/**+ * Story Builder sessions — PostgreSQL leaf I/O (#1016).+ *+ * One row per session in `story_builder_sessions`: the full sanitized record+ * (the `steps` lock/integrity map, `syncedHashes` baseline, `currentStep`,+ * `llm` picker choice, `origin`, tombstone fields) in `data` JSONB, with+ * universe_id / series_id / sync / ephemeral / updated_at / deleted / deleted_at+ * mirrored into columns for the queries the service + federation actually run+ * (sessions-for-a-record lookups, the OPT-IN sync snapshot filter, LWW+ * staleness, tombstone GC).+ *+ * 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+ * `sanitizeSession` on read, so reads here return `data` verbatim (the columns+ * are a queryable mirror, never read back).+ */++import { query } from '../../lib/db.js';+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';++/** Raw on-disk-equivalent record (the `data` JSONB), or null. No sanitize. */+export async function readRaw(id) {+ const { rows } = await query(`SELECT data FROM story_builder_sessions WHERE id = $1`, [id]);+ return rows[0]?.data ?? null;+}++/** Every session id (live, ephemeral, AND tombstones) — the service filters. */+export async function listIds() {+ const { rows } = await query(`SELECT id FROM story_builder_sessions`);+ return rows.map((r) => r.id);+}++/** Every record's raw `data` JSONB in one query (live/ephemeral/tombstones). */+export async function listRaw() {+ const { rows } = await query(`SELECT data FROM story_builder_sessions`);+ 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/peer-sourced 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);+ await query(+ `INSERT INTO story_builder_sessions (id, universe_id, series_id, sync, data, ephemeral, created_at, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10)+ ON CONFLICT (id) DO UPDATE SET+ universe_id = EXCLUDED.universe_id,+ series_id = EXCLUDED.series_id,+ sync = EXCLUDED.sync,+ data = EXCLUDED.data,+ ephemeral = EXCLUDED.ephemeral,+ updated_at = EXCLUDED.updated_at,+ deleted = EXCLUDED.deleted,+ deleted_at = EXCLUDED.deleted_at`,+ [+ id,+ typeof record?.universeId === 'string' && record.universeId ? record.universeId : null,+ typeof record?.seriesId === 'string' && record.seriesId ? record.seriesId : null,+ record?.sync === true,+ JSON.stringify(record),+ 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 story_builder_sessions WHERE id = $1`, [id]);+}diff --git a/server/services/storyBuilderStore/db.test.js b/server/services/storyBuilderStore/db.test.jsnew file mode 100644index 0000000000..d85e111aec--- /dev/null+++ b/server/services/storyBuilderStore/db.test.js@@ -0,0 +1,103 @@+/**+ * Postgres-backed round-trip for the Story Builder sessions DB adapter (#1016).+ * SKIPS cleanly when no DB is reachable. Snapshots + restores the table.+ */++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 = 'story_builder_sessions') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'story_builder_sessions table not present';+ }+}++if (!dbReady) console.log(`⏭️ storyBuilderStore/db.test.js skipped: ${skipReason}`);++const S = (id, extra = {}) => ({+ id, title: id, intakeMode: 'seed', universeId: 'u-1', seriesId: 'ser-1',+ currentStep: 'idea', steps: {}, llm: { provider: null, model: null }, sync: false,+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-02T00:00:00.000Z',+ deleted: false, deletedAt: null, ...extra,+});++describe.skipIf(!dbReady)('Story Builder sessions DB adapter round-trip', () => {+ let db;+ let snap = [];+ beforeAll(async () => {+ db = await import('./db.js');+ snap = (await query(`SELECT * FROM story_builder_sessions`)).rows;+ });++ beforeEach(async () => { await query(`DELETE FROM story_builder_sessions`); });++ afterAll(async () => {+ await query(`DELETE FROM story_builder_sessions`).catch(() => {});+ for (const r of snap) {+ await query(+ `INSERT INTO story_builder_sessions (id, universe_id, series_id, sync, data, ephemeral, created_at, updated_at, deleted, deleted_at)+ VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7,$8,$9,$10) ON CONFLICT (id) DO NOTHING`,+ [r.id, r.universe_id, r.series_id, r.sync, JSON.stringify(r.data), r.ephemeral, r.created_at, r.updated_at, r.deleted, r.deleted_at],+ ).catch(() => {});+ }+ await close();+ });++ it('writes a record and reads it back verbatim (steps + syncedHashes preserved)', async () => {+ const rec = S('stb-1', {+ sync: true,+ steps: { idea: { status: 'locked', locked: true, lockedAt: '2026-01-02T00:00:00.000Z', upstreamHash: 'h' } },+ syncedHashes: { idea: 'a'.repeat(64) },+ });+ await db.writeRaw('stb-1', rec);+ expect(await db.readRaw('stb-1')).toEqual(rec);+ });++ it('upsert updates the record and the mirror columns (universe/series/sync)', async () => {+ await db.writeRaw('stb-1', S('stb-1', { universeId: 'u-1', sync: false }));+ await db.writeRaw('stb-1', S('stb-1', { universeId: 'u-2', seriesId: 'ser-2', sync: true, updatedAt: '2026-03-03T00:00:00.000Z' }));+ const col = (await query(`SELECT universe_id, series_id, sync, updated_at FROM story_builder_sessions WHERE id = 'stb-1'`)).rows[0];+ expect(col.universe_id).toBe('u-2');+ expect(col.series_id).toBe('ser-2');+ expect(col.sync).toBe(true);+ expect(new Date(col.updated_at).toISOString()).toBe('2026-03-03T00:00:00.000Z');+ });++ it('the OPT-IN sync filter serves only sync-enabled sessions', async () => {+ await db.writeRaw('stb-on', S('stb-on', { sync: true }));+ await db.writeRaw('stb-off', S('stb-off', { sync: false }));+ const synced = (await query(`SELECT id FROM story_builder_sessions WHERE sync = TRUE ORDER BY id`)).rows;+ expect(synced.map((r) => r.id)).toEqual(['stb-on']);+ });++ it('listIds returns live, tombstoned, and ephemeral ids alike', async () => {+ await db.writeRaw('stb-live', S('stb-live'));+ await db.writeRaw('stb-dead', S('stb-dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));+ await db.writeRaw('stb-ghost', S('stb-ghost', { ephemeral: true }));+ expect((await db.listIds()).sort()).toEqual(['stb-dead', 'stb-ghost', 'stb-live']);+ });++ it('tolerates a malformed timestamp without throwing', async () => {+ await db.writeRaw('stb-bad', S('stb-bad', { updatedAt: 'not-a-date', createdAt: 'nope' }));+ const col = (await query(`SELECT created_at, updated_at FROM story_builder_sessions WHERE id = 'stb-bad'`)).rows[0];+ expect(col.created_at).toBeInstanceOf(Date);+ expect(col.updated_at).toBeInstanceOf(Date);+ });++ it('deleteRaw removes the row (idempotent)', async () => {+ await db.writeRaw('stb-1', S('stb-1'));+ await db.deleteRaw('stb-1');+ expect(await db.readRaw('stb-1')).toBeNull();+ await db.deleteRaw('stb-1');+ });+});diff --git a/server/services/storyBuilderStore/store.js b/server/services/storyBuilderStore/store.jsnew file mode 100644index 0000000000..72be1d55e7--- /dev/null+++ b/server/services/storyBuilderStore/store.js@@ -0,0 +1,227 @@+/**+ * Story Builder sessions — storage backend dispatcher (#1016).+ *+ * Sessions used to live one-record-per-dir under+ * data/story-builder/{id}/index.json (collectionStore). As of #1016 they live+ * one-row-per-session in PostgreSQL (`story_builder_sessions`). This facade is a+ * DROP-IN for the `createCollectionStore` surface storyBuilder.js already calls+ * (loadAll / loadOne / queueRecordWrite / saveOne / saveOneNow / verifySchemaVersion),+ * so the service keeps its public API and only its `store()` factory changes. It+ * owns the in-process serialization (per-id write queue) + the sanitizer, and+ * delegates 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 storyBuilder snapshot by fingerprinting the data/story-builder+ * directory. A PG-backed session edit no longer touches that directory, so the+ * module-level MUTATION EPOCH below is bumped on every record write/delete;+ * dataSync folds it into the storyBuilder fingerprint, keeping the storage swap+ * invisible to peers. Sessions hold ONLY index.json (no file-primary siblings),+ * so — unlike the series store — there is no on-disk `recordDir` to preserve.+ *+ * The first PG-backed call runs a one-time, marker-gated import of the legacy+ * data/story-builder file store into the table (migrateStoryBuilderToDB).+ */++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/story-builder/index.json — preserved so an install on the file escape+// hatch still passes the boot verifier. (PG has no type-index file.)+const TYPE_SCHEMA_VERSION = 1;+const ID_PATTERN = /^stb-[A-Za-z0-9-]+$/;++function isFileBackend() {+ return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';+}++function assertValidId(id) {+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) {+ throw new Error(`storyBuilderStore: invalid record id "${id}" — must match ${ID_PATTERN}`);+ }+}++// --- 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.+let mutationEpoch = 0;+/** Current Story Builder mutation epoch — folded into dataSync's fingerprint. */+export function getStoryBuilderMutationEpoch() {+ return mutationEpoch;+}++// --- File backend (escape hatch / tests): wraps collectionStore ---+function makeFileBackend(dir, sanitizeRecord) {+ const cs = createCollectionStore({+ dir,+ type: 'storyBuilder',+ schemaVersion: TYPE_SCHEMA_VERSION,+ sanitizeRecord,+ idPattern: ID_PATTERN,+ });+ return {+ name: 'file',+ readRaw: (id) => cs.loadOneRaw(id),+ readOne: (id) => cs.loadOne(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),+ verify: () => cs.verifySchemaVersion(),+ };+}++// --- PostgreSQL backend: pure leaf I/O from ./db.js ---+function makePgBackend(db, sanitizeRecord) {+ return {+ name: 'postgres',+ readRaw: db.readRaw,+ readOne: async (id) => {+ const raw = await db.readRaw(id);+ return raw ? sanitizeRecord(raw) : null;+ },+ listIds: db.listIds,+ listRaw: db.listRaw,+ writeRaw: db.writeRaw,+ deleteRaw: db.deleteRaw,+ verify: async () => ({ ok: true, type: 'storyBuilder', onDisk: null, expected: null,+ message: 'collection "storyBuilder" @ postgres (#1016)' }),+ };+}++async function pgBackend(sanitizeRecord) {+ const health = await checkHealth();+ if (!health.connected) {+ throw new Error('Story Builder requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)');+ }+ await ensureSchema();+ const { migrateStoryBuilderToDB } = await import('../../scripts/migrateStoryBuilderToDB.js');+ await migrateStoryBuilderToDB();+ const db = await import('./db.js');+ return makePgBackend(db, sanitizeRecord);+}++// --- Facade: collectionStore-compatible, queues + epoch + sanitize ---+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, sanitizer)) : pgBackend(sanitizer))+ .then((b) => { backend = b; return b; })+ .finally(() => { selecting = null; });+ }+ return selecting;+ };++ // Per-id write queue — mirrors collectionStore.queueRecordWrite.+ const recordTails = new Map();+ function queueRecordWrite(id, fn) {+ assertValidId(id);+ 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;+ }++ const loadOne = async (id) => {+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) return null;+ return (await getBackend()).readOne(id);+ };++ const saveOneNow = async (id, record) => {+ assertValidId(id);+ const out = await (await getBackend()).writeRaw(id, record);+ mutationEpoch += 1;+ return out ?? record;+ };++ const deleteOneNow = async (id) => {+ assertValidId(id);+ await (await getBackend()).deleteRaw(id);+ mutationEpoch += 1;+ };++ return {+ dir,+ type: 'storyBuilder',+ _setSanitizer: (fn) => { if (typeof fn === 'function') sanitizer = fn; },+ getBackendName: () => backend?.name ?? null,++ // Reads (sanitized, matching collectionStore.loadOne/loadAll)+ listIds: async () => (await getBackend()).listIds(),+ loadOne,+ loadOneRaw: async (id) => {+ if (typeof id !== 'string' || !ID_PATTERN.test(id)) return null;+ return (await getBackend()).readRaw(id);+ },+ loadAll: async () => {+ const raw = await (await getBackend()).listRaw();+ return raw.map((r) => sanitizer(r)).filter((r) => r != null);+ },++ // Writes+ queueRecordWrite,+ saveOneNow,+ saveOne: (id, record) => queueRecordWrite(id, () => saveOneNow(id, record)),+ deleteOneNow,+ deleteOne: (id) => queueRecordWrite(id, () => deleteOneNow(id)),++ // Boot-time verifier. Under PG return ok WITHOUT forcing backend selection+ // (the early boot verifier runs before the dbReady gate; the authoritative+ // warm in index.js selects the backend at the right time).+ verifySchemaVersion: async () => {+ if (!isFileBackend()) {+ return { ok: true, type: 'storyBuilder', onDisk: null, expected: null,+ message: 'collection "storyBuilder" @ postgres (#1016)' };+ }+ return (await getBackend()).verify();+ },+ };+}++let _facade = null;+let _facadeDir = null;++/**+ * Get the Story Builder store facade. Pass the record sanitizer+ * (sanitizeSession) so loadOne/loadAll return sanitized records without store.js+ * importing the service (which would close a cycle). Synchronous — backend+ * selection is deferred into each method.+ */+export function getStoryBuilderStore(sanitizeRecord) {+ const dir = join(PATHS.data, 'story-builder');+ 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 _resetStoryBuilderStore() {+ _facade = null;+ _facadeDir = null;+}diff --git a/server/services/storyBuilderStore/store.test.js b/server/services/storyBuilderStore/store.test.jsnew file mode 100644index 0000000000..c90154ba9a--- /dev/null+++ b/server/services/storyBuilderStore/store.test.js@@ -0,0 +1,102 @@+/**+ * Story Builder store facade — file-backend dispatcher behavior (#1016).+ *+ * NODE_ENV=test selects the file backend (collectionStore over a real tmpdir),+ * so this exercises the facade WITHOUT a database: the collectionStore-compatible+ * read/write/delete surface storyBuilder.js uses, and the module-level mutation+ * epoch that record writes/deletes bump (and reads do not) — the signal dataSync+ * folds into its fingerprint so the storage swap stays invisible to federation.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'stb-store-test-'));++vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };+});++const { getStoryBuilderStore, _resetStoryBuilderStore, getStoryBuilderMutationEpoch } = await import('./store.js');++const passthroughSanitize = (r) => (r ? { ...r, _sanitized: true } : r);++describe('Story Builder store facade — file backend', () => {+ beforeEach(() => {+ rmSync(join(TEST_DATA_ROOT, 'story-builder'), { recursive: true, force: true });+ _resetStoryBuilderStore();+ });+ afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));++ it('selects the file backend under NODE_ENV=test', async () => {+ const s = getStoryBuilderStore(passthroughSanitize);+ await s.listIds();+ expect(s.getBackendName()).toBe('file');+ });++ it('saveOneNow persists, loadOneRaw returns verbatim, loadOne sanitizes', async () => {+ const s = getStoryBuilderStore(passthroughSanitize);+ await s.saveOneNow('stb-1', { id: 'stb-1', title: 'Salt Run' });+ expect(await s.loadOneRaw('stb-1')).toEqual({ id: 'stb-1', title: 'Salt Run' });+ expect(await s.loadOne('stb-1')).toEqual({ id: 'stb-1', title: 'Salt Run', _sanitized: true });+ expect(await s.listIds()).toEqual(['stb-1']);+ });++ it('loadAll returns every record sanitized', async () => {+ const s = getStoryBuilderStore(passthroughSanitize);+ await s.saveOneNow('stb-1', { id: 'stb-1', title: 'A' });+ await s.saveOneNow('stb-2', { id: 'stb-2', title: 'B' });+ const all = await s.loadAll();+ expect(all.map((r) => r.id).sort()).toEqual(['stb-1', 'stb-2']);+ expect(all.every((r) => r._sanitized)).toBe(true);+ });++ it('deleteOneNow removes the record', async () => {+ const s = getStoryBuilderStore(passthroughSanitize);+ await s.saveOneNow('stb-1', { id: 'stb-1', title: 'X' });+ await s.deleteOneNow('stb-1');+ expect(await s.loadOneRaw('stb-1')).toBeNull();+ expect(await s.listIds()).toEqual([]);+ });++ it('record writes AND deletes bump the mutation epoch; reads do not', async () => {+ const s = getStoryBuilderStore(passthroughSanitize);+ const e0 = getStoryBuilderMutationEpoch();+ await s.saveOneNow('stb-1', { id: 'stb-1', title: 'X' });+ const e1 = getStoryBuilderMutationEpoch();+ expect(e1).toBeGreaterThan(e0);+ await s.loadOne('stb-1');+ await s.listIds();+ expect(getStoryBuilderMutationEpoch()).toBe(e1); // reads don't bump+ await s.deleteOneNow('stb-1');+ expect(getStoryBuilderMutationEpoch()).toBeGreaterThan(e1);+ });++ it('queueRecordWrite serializes same-id RMW and rejects bad ids', async () => {+ const s = getStoryBuilderStore(passthroughSanitize);+ expect(() => s.queueRecordWrite('bad-id', async () => 'never')).toThrow(/invalid record id/);+ const order = [];+ await Promise.all([+ s.queueRecordWrite('stb-x', async () => { order.push('a-start'); await Promise.resolve(); order.push('a-end'); }),+ s.queueRecordWrite('stb-x', async () => { order.push('b'); }),+ ]);+ expect(order).toEqual(['a-start', 'a-end', 'b']);+ });++ it('saveOneNow / deleteOneNow reject ids outside the stb- allowlist (backend parity)', async () => {+ const s = getStoryBuilderStore(passthroughSanitize);+ await expect(s.saveOneNow('ser-1', { id: 'ser-1', title: 'X' })).rejects.toThrow(/invalid record id/);+ await expect(s.deleteOneNow('nope')).rejects.toThrow(/invalid record id/);+ });++ it('verifySchemaVersion reports the file collection version', async () => {+ const s = getStoryBuilderStore(passthroughSanitize);+ await s.saveOneNow('stb-1', { id: 'stb-1', title: 'X' });+ const status = await s.verifySchemaVersion();+ expect(status.ok).toBe(true);+ expect(status.type).toBe('storyBuilder');+ });+});