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
refactor: fold the CD/musicVideo/sprites backend dispatchers into pgFileFacade (#2899)
[._.]/ Adam Eivy84b3db029a6f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6c4db76c5a..b25aeba5e5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -73,3 +73,4 @@- **[issue-2837] Break the agent-lifecycle circular-dependency cluster** — `finalizeAgent`/`releaseAgentLane` (plus the success-criteria + output-hook helpers) move to `server/services/agentFinalization.js`, the summary extractors to `agentSummaryExtraction.js`, runner recovery to `agentRunnerSync.js`, and the runner output batchers to `agentRunnerOutputBatchers.js`. With those leaves in place the two static cycles (`agentLifecycle` ↔ `agentCliSpawning`, `agentLifecycle` ↔ `agentTuiSpawning`) are gone, and three `await import()` cycle-dodges — `handleOrphanedTask`, the spawner's init-time lifecycle/management lookups, and `flushRunnerOutputBatcher` — become plain static imports. `agentLifecycle.js` still re-exports every moved symbol, so no import path changes for callers. New `agentImportCycles.test.js` re-derives the static import graph and fails if a cycle is reintroduced.- **[issue-2844] Drop the `@dnd-kit/utilities` dependency** — the package was pulled in only for `CSS.Transform.toString()` at three drag-and-drop sites (influence chips, CoS sortable tasks, video timeline blocks). A ~10-line owned helper, `dndTransformToCss` in `client/src/lib/dndTransform.js`, replaces it with byte-identical output (rounded `translate3d` + verbatim `scaleX`/`scaleY`, `undefined` for a null transform), and the direct dependency is removed from `client/package.json` and its lockfile. It remains in the tree only as a transitive peer of `@dnd-kit/core`/`sortable`, which stay.- **[issue-2846] Add a client `sleep(ms)` helper and rebuild `useLocalStorageBool` on `safeStorage`** — `client/src/utils/sleep.js` mirrors the server helper and replaces the three duplicated inline delays (`lazyWithReload`'s retry backoff, `staleChunkReload`'s purge race timeout, `voiceClient`'s decoder-tick wait). `useLocalStorageBool`/`useLocalStoragePersisted` now delegate their four hand-rolled `try/catch` storage helpers to `client/src/lib/safeStorage.js`, which gains a `safeWriteJsonStorage` that guards `JSON.stringify` alongside `setItem`. The JSON read keeps a private sentinel so a stored `null` still runs the caller's `parse` migration instead of collapsing into "missing".+- **[issue-2899] Fold the Creative Director / Music Video / Sprites `selectBackend()` dispatchers into `pgFileFacade`** — Creative Director, Music Video, and Sprites each memoized their own copy of the same file-vs-Postgres selector (already drifted: differing error text, differing test-mode predicate). A new `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` in `server/lib/pgFileFacade.js` wraps the existing `createPgFileFacade`/`resolvePgBackend` backbone for stores whose backends are whole modules rather than built objects, so the escape-hatch posture, the health-check → `ensureSchema` → one-time-migration bring-up, and the selection memoization live in one place. Public store surfaces are unchanged (`getProjectsBackendName()` still reports `'file'`/`'postgres'`), each store keeps its own requirement message, and Sprites keeps its stronger `isTestRunner()` test-mode signal via the new `isTestMode` hook — no gating semantics were weakened. The selector also exposes a `reset()` test seam matching the `_reset<X>Backend()` exports on the artists/tracks/albums/authors stores, which still hand-roll the same dispatcher and are tracked separately.diff --git a/server/lib/README.md b/server/lib/README.mdindex 6946ad0659..c45e37226d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -135,7 +135,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. || `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. || `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |-| `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. |+| `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → `{ selectBackend, getBackendName }` where the name is `'file'`/`'postgres'`; `isTestMode` lets a store use the stronger `isTestRunner()` signal (Sprites). || `multipart.js` | Streaming multipart/form-data parser. || `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. || `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |diff --git a/server/lib/pgFileFacade.js b/server/lib/pgFileFacade.jsindex 15a3f5742a..934a623c46 100644--- a/server/lib/pgFileFacade.js+++ b/server/lib/pgFileFacade.js@@ -13,6 +13,11 @@* What stays in each store: its own `makeFile` / `makePg` backend factories* (the file layouts differ genuinely — collectionStore vs settings.json vs a* bespoke on-disk JSON format) and its public facade surface.+ *+ * A second family of stores (Creative Director, Music Video, Sprites) dispatches+ * to whole backend MODULES rather than built objects, and hand-rolled the same+ * selector a third time (#2899). `createRecordStoreBackendSelector` below wraps+ * this backbone for that shape.*/import { checkHealth, ensureSchema } from './db.js';@@ -58,15 +63,18 @@ export async function resolvePgBackend({ requirement, migrate, loadDb, makePg })* @param {object} opts* @param {() => object|Promise<object>} opts.makeFile Build the file backend.* @param {() => Promise<object>} opts.makePg Build the PG backend.+ * @param {() => boolean} [opts.isFile] Escape-hatch predicate (default `isFileBackend`).+ * Overridden only by stores that use a stronger test-mode signal (see+ * `createRecordStoreBackendSelector`'s `isTestMode`).* @returns {{ getBackend: () => Promise<object>, getBackendName: () => (string|null), reset: () => void }}*/-export function createPgFileFacade({ makeFile, makePg }) {+export function createPgFileFacade({ makeFile, makePg, isFile = isFileBackend }) {let backend = null;let selecting = null;const getBackend = () => {if (backend) return Promise.resolve(backend);if (!selecting) {- selecting = Promise.resolve(isFileBackend() ? makeFile() : makePg())+ selecting = Promise.resolve(isFile() ? makeFile() : makePg()).then((b) => { backend = b; return b; }).finally(() => { selecting = null; });}@@ -78,3 +86,85 @@ export function createPgFileFacade({ makeFile, makePg }) {reset: () => { backend = null; selecting = null; },};}++/**+ * Memoized backend selector for stores whose backends are whole MODULES+ * (`import('./projectsFile.js')` vs `import('./projectsDB.js')`) rather than+ * objects built from `db.js` — Creative Director, Music Video, Sprites (#2899).+ * Each had hand-rolled the identical dispatcher, and they had already drifted+ * (differing error text, differing test-mode predicate).+ *+ * Same posture as `createPgFileFacade` (do NOT weaken it): the dev/test escape+ * hatch selects the file backend with NO database contact at all; otherwise+ * `resolvePgBackend` health-checks, runs the idempotent `ensureSchema()` (a store+ * may be called before the boot DB gate, e.g. CD's boot recovery scan), runs the+ * optional one-time migration, then loads the PG module.+ *+ * Test-mode detection stays per-store (`isTestMode`) because the stores+ * genuinely differ today: Sprites keys on `isTestRunner()` (`NODE_ENV==='test'`+ * OR `VITEST` — the stronger signal), CD/Music Video on `NODE_ENV==='test'` only+ * via the shared `isFileBackend()`. Unifying on `isTestRunner()` would be a+ * strengthening, but it changes what their existing backend-selection suites+ * observe (vitest always sets `VITEST`), so semantics are preserved exactly here+ * and the unification is left as a separate decision.+ *+ * @param {object} opts+ * @param {string} [opts.label] Store name used in the default unreachable-DB error.+ * @param {() => Promise<object>} opts.loadFileBackend Loader for the file backend module.+ * @param {() => Promise<object>} opts.loadDbBackend Loader for the PostgreSQL backend module.+ * @param {string} [opts.requireDbMessage] Override for the unreachable-DB error message.+ * @param {() => boolean} [opts.isTestMode] Test-mode predicate; when omitted the shared+ * `isFileBackend()` (MEMORY_BACKEND=file OR NODE_ENV=test) is used as-is.+ * @param {() => Promise<void>} [opts.onDbReady] One-time migration run after `ensureSchema()`+ * and before the DB backend import (CD's legacy JSON → table import).+ * @returns {{ selectBackend: () => Promise<object>, getBackendName: () => ('file'|'postgres'|null) }}+ */+export function createRecordStoreBackendSelector({+ label,+ loadFileBackend,+ loadDbBackend,+ requireDbMessage,+ isTestMode,+ onDbReady,+} = {}) {+ if (typeof loadFileBackend !== 'function' || typeof loadDbBackend !== 'function') {+ throw new Error('createRecordStoreBackendSelector requires loadFileBackend + loadDbBackend loader functions');+ }++ const requirement = requireDbMessage+ || `${label || 'This store'} requires PostgreSQL — run \`npm run setup:db\` (dev/test only: set MEMORY_BACKEND=file in .env)`;++ let backendName = null;+ const facade = createPgFileFacade({+ isFile: isTestMode+ ? () => process.env.MEMORY_BACKEND === 'file' || isTestMode()+ : isFileBackend,+ makeFile: async () => {+ const mod = await loadFileBackend();+ backendName = 'file';+ return mod;+ },+ makePg: async () => {+ const mod = await resolvePgBackend({+ requirement,+ migrate: onDbReady,+ loadDb: loadDbBackend,+ makePg: (m) => m,+ });+ backendName = 'postgres';+ return mod;+ },+ });++ return {+ selectBackend: facade.getBackend,+ /** Name of the active backend, or null before first selection (diagnostics/tests). */+ getBackendName: () => backendName,+ /**+ * Test seam — drop the memoized selection so a suite can re-select. Mirrors+ * the `_reset<X>Backend()` exports the artists/tracks/albums/authors stores+ * carry, so folding those in later needs no new surface here.+ */+ reset: () => { facade.reset(); backendName = null; },+ };+}diff --git a/server/lib/pgFileFacade.test.js b/server/lib/pgFileFacade.test.jsindex 282136e880..d86139bde7 100644--- a/server/lib/pgFileFacade.test.js+++ b/server/lib/pgFileFacade.test.js@@ -7,7 +7,7 @@ const checkHealth = vi.fn();const ensureSchema = vi.fn(async () => {});vi.mock('./db.js', () => ({ checkHealth: (...a) => checkHealth(...a), ensureSchema: (...a) => ensureSchema(...a) }));-const { isFileBackend, resolvePgBackend, createPgFileFacade } = await import('./pgFileFacade.js');+const { isFileBackend, resolvePgBackend, createPgFileFacade, createRecordStoreBackendSelector } = await import('./pgFileFacade.js');const tick = () => new Promise((r) => setImmediate(r));@@ -124,3 +124,134 @@ describe('resolvePgBackend', () => {expect(backend.name).toBe('postgres');});});++describe('createRecordStoreBackendSelector', () => {+ const orig = { MEMORY_BACKEND: process.env.MEMORY_BACKEND, NODE_ENV: process.env.NODE_ENV };+ beforeEach(() => { checkHealth.mockReset(); ensureSchema.mockClear(); });+ afterEach(() => {+ process.env.NODE_ENV = orig.NODE_ENV;+ if (orig.MEMORY_BACKEND === undefined) delete process.env.MEMORY_BACKEND;+ else process.env.MEMORY_BACKEND = orig.MEMORY_BACKEND;+ });++ const loaders = () => ({+ loadFileBackend: vi.fn(async () => ({ listRecords: async () => ['file'] })),+ loadDbBackend: vi.fn(async () => ({ listRecords: async () => ['db'] })),+ });++ it('selects the file backend under NODE_ENV=test without touching the DB', async () => {+ process.env.NODE_ENV = 'test';+ delete process.env.MEMORY_BACKEND;+ const { loadFileBackend, loadDbBackend } = loaders();+ const { selectBackend, getBackendName } = createRecordStoreBackendSelector({ label: 'Demo', loadFileBackend, loadDbBackend });+ expect(getBackendName()).toBe(null);+ expect(await (await selectBackend()).listRecords()).toEqual(['file']);+ expect(getBackendName()).toBe('file');+ expect(checkHealth).not.toHaveBeenCalled();+ expect(loadDbBackend).not.toHaveBeenCalled();+ });++ it('selects the file backend under MEMORY_BACKEND=file outside test mode', async () => {+ process.env.NODE_ENV = 'production';+ process.env.MEMORY_BACKEND = 'file';+ const { loadFileBackend, loadDbBackend } = loaders();+ const { selectBackend, getBackendName } = createRecordStoreBackendSelector({ label: 'Demo', loadFileBackend, loadDbBackend });+ await selectBackend();+ expect(getBackendName()).toBe('file');+ expect(checkHealth).not.toHaveBeenCalled();+ });++ it('honors a custom isTestMode predicate (the isTestRunner posture) and keeps the file escape hatch', async () => {+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ const { loadFileBackend, loadDbBackend } = loaders();+ const { selectBackend, getBackendName } = createRecordStoreBackendSelector({+ label: 'Demo', loadFileBackend, loadDbBackend, isTestMode: () => true,+ });+ await selectBackend();+ expect(getBackendName()).toBe('file');+ expect(checkHealth).not.toHaveBeenCalled();+ });++ it('still honors MEMORY_BACKEND=file when a custom isTestMode says "not a test"', async () => {+ process.env.NODE_ENV = 'production';+ process.env.MEMORY_BACKEND = 'file';+ const { loadFileBackend, loadDbBackend } = loaders();+ const { selectBackend, getBackendName } = createRecordStoreBackendSelector({+ label: 'Demo', loadFileBackend, loadDbBackend, isTestMode: () => false,+ });+ await selectBackend();+ expect(getBackendName()).toBe('file');+ expect(checkHealth).not.toHaveBeenCalled();+ });++ it('brings Postgres up (ensureSchema → onDbReady → import) and memoizes the selection', async () => {+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ checkHealth.mockResolvedValue({ connected: true });+ const order = [];+ ensureSchema.mockImplementation(async () => { order.push('ensureSchema'); });+ const onDbReady = vi.fn(async () => { order.push('onDbReady'); });+ const loadFileBackend = vi.fn();+ const loadDbBackend = vi.fn(async () => { order.push('loadDb'); return { listRecords: async () => ['db'] }; });++ const { selectBackend, getBackendName } = createRecordStoreBackendSelector({ label: 'Demo', loadFileBackend, loadDbBackend, onDbReady });+ expect(await (await selectBackend()).listRecords()).toEqual(['db']);+ await selectBackend();++ expect(order).toEqual(['ensureSchema', 'onDbReady', 'loadDb']);+ expect(getBackendName()).toBe('postgres');+ expect(loadFileBackend).not.toHaveBeenCalled();+ expect(checkHealth).toHaveBeenCalledTimes(1);+ });++ it('throws the store-specific requirement message when Postgres is unreachable', async () => {+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ checkHealth.mockResolvedValue({ connected: false });+ const { loadFileBackend, loadDbBackend } = loaders();+ const { selectBackend, getBackendName } = createRecordStoreBackendSelector({+ label: 'Demo', loadFileBackend, loadDbBackend, requireDbMessage: 'Demo requires PostgreSQL — custom',+ });+ await expect(selectBackend()).rejects.toThrow('Demo requires PostgreSQL — custom');+ expect(ensureSchema).not.toHaveBeenCalled();+ expect(getBackendName()).toBe(null);+ });++ it('falls back to a labeled default requirement message', async () => {+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ checkHealth.mockResolvedValue({ connected: false });+ const { loadFileBackend, loadDbBackend } = loaders();+ const { selectBackend } = createRecordStoreBackendSelector({ label: 'Demo', loadFileBackend, loadDbBackend });+ await expect(selectBackend()).rejects.toThrow(/^Demo requires PostgreSQL/);+ });++ it('retries selection after a failed Postgres bring-up instead of caching the failure', async () => {+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ checkHealth.mockResolvedValueOnce({ connected: false }).mockResolvedValueOnce({ connected: true });+ const { loadFileBackend, loadDbBackend } = loaders();+ const { selectBackend, getBackendName } = createRecordStoreBackendSelector({ label: 'Demo', loadFileBackend, loadDbBackend });+ await expect(selectBackend()).rejects.toThrow(/requires PostgreSQL/);+ expect(await (await selectBackend()).listRecords()).toEqual(['db']);+ expect(getBackendName()).toBe('postgres');+ });++ it('reset() drops the memoized selection and the reported name', async () => {+ process.env.NODE_ENV = 'test';+ delete process.env.MEMORY_BACKEND;+ const { loadFileBackend, loadDbBackend } = loaders();+ const { selectBackend, getBackendName, reset } = createRecordStoreBackendSelector({ label: 'Demo', loadFileBackend, loadDbBackend });+ await selectBackend();+ expect(getBackendName()).toBe('file');+ reset();+ expect(getBackendName()).toBe(null);+ await selectBackend();+ expect(loadFileBackend).toHaveBeenCalledTimes(2);+ });++ it('fails fast when the loaders are missing', () => {+ expect(() => createRecordStoreBackendSelector({ label: 'Demo' })).toThrow(/loadFileBackend/);+ });+});diff --git a/server/services/creativeDirector/local.js b/server/services/creativeDirector/local.jsindex 978e80b7b0..7906f00803 100644--- a/server/services/creativeDirector/local.js+++ b/server/services/creativeDirector/local.js@@ -22,7 +22,7 @@* that imported it from here historically.*/-import { checkHealth, ensureSchema } from '../../lib/db.js';+import { createRecordStoreBackendSelector } from '../../lib/pgFileFacade.js';import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';import { resolveIngredientsByIds, linkIngredientsToCreativeDirector } from '../catalogDB.js';import { buildCastFromIngredients } from './catalogSeed.js';@@ -30,43 +30,28 @@ import { enqueueFirstPassSceneFrames } from './firstPassGen.js';export { trimRuns, startingImageFilename } from './projectsLogic.js';-let backend = null;-let backendName = null;--async function selectBackend() {- if (backend) return backend;-- const envBackend = process.env.MEMORY_BACKEND;-- // Explicit file escape hatch, or test mode (no DB) → file backend.- if (envBackend === 'file' || process.env.NODE_ENV === 'test') {- backend = await import('./projectsFile.js');- backendName = 'file';- return backend;- }-- // Default + explicit postgres → PostgreSQL. The boot DB gate in- // server/index.js fail-fasts when Postgres is required but missing, but the- // boot RECOVERY scan (recoverInFlightProjects) calls in here BEFORE that gate- // runs ensureSchema() — so an upgrade install may not have the- // creative_director_projects table yet at first call. Mirror memoryBackend.js- // and run ensureSchema() here ourselves (idempotent) so the backend is- // self-sufficient regardless of boot ordering.- const health = await checkHealth();- if (!health.connected) {- throw new Error('Creative Director requires PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env; the launcher maps it to MEMORY_BACKEND=file for the unsupported file backend)');- }- await ensureSchema();- const { migrateCreativeDirectorToDB } = await import('../../scripts/migrateCreativeDirectorToDB.js');- await migrateCreativeDirectorToDB();- backend = await import('./projectsDB.js');- backendName = 'postgres';- return backend;-}+// Shared dispatcher (#2899). The boot DB gate in server/index.js fail-fasts when+// Postgres is required but missing, but the boot RECOVERY scan+// (recoverInFlightProjects) calls in here BEFORE that gate runs ensureSchema() —+// so an upgrade install may not have the creative_director_projects table yet at+// first call. The selector runs ensureSchema() itself (idempotent, mirroring+// memoryBackend.js) so the backend is self-sufficient regardless of boot+// ordering, then `onDbReady` runs the one-time legacy-JSON import before the PG+// backend loads, so the first caller sees migrated projects.+const { selectBackend, getBackendName } = createRecordStoreBackendSelector({+ label: 'Creative Director',+ loadFileBackend: () => import('./projectsFile.js'),+ loadDbBackend: () => import('./projectsDB.js'),+ requireDbMessage: 'Creative Director requires PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env; the launcher maps it to MEMORY_BACKEND=file for the unsupported file backend)',+ onDbReady: async () => {+ const { migrateCreativeDirectorToDB } = await import('../../scripts/migrateCreativeDirectorToDB.js');+ await migrateCreativeDirectorToDB();+ },+});/** Name of the active backend, or null before first call (for diagnostics/tests). */export function getProjectsBackendName() {- return backendName;+ return getBackendName();}// Announce a newly-created project to the per-record peer-sync pipeline (#1564):diff --git a/server/services/musicVideo/projects.js b/server/services/musicVideo/projects.jsindex 94bc7c44b1..31e3583981 100644--- a/server/services/musicVideo/projects.js+++ b/server/services/musicVideo/projects.js@@ -21,38 +21,21 @@* sweep. The soft-delete fields were already on the record, so this was additive.*/-import { checkHealth, ensureSchema } from '../../lib/db.js';+import { createRecordStoreBackendSelector } from '../../lib/pgFileFacade.js';import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';-let backend = null;-let backendName = null;--async function selectBackend() {- if (backend) return backend;-- const envBackend = process.env.MEMORY_BACKEND;- if (envBackend === 'file' || process.env.NODE_ENV === 'test') {- backend = await import('./projectsFile.js');- backendName = 'file';- return backend;- }-- // Default + explicit postgres → PostgreSQL. ensureSchema() is idempotent and- // run here (mirroring memoryBackend.js) so the backend is self-sufficient- // regardless of boot ordering.- const health = await checkHealth();- if (!health.connected) {- throw new Error('Music Video requires PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env)');- }- await ensureSchema();- backend = await import('./projectsDB.js');- backendName = 'postgres';- return backend;-}+// Shared dispatcher (#2899). ensureSchema() runs inside the selector (mirroring+// memoryBackend.js) so the backend is self-sufficient regardless of boot ordering.+const { selectBackend, getBackendName } = createRecordStoreBackendSelector({+ label: 'Music Video',+ loadFileBackend: () => import('./projectsFile.js'),+ loadDbBackend: () => import('./projectsDB.js'),+ requireDbMessage: 'Music Video requires PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env)',+});/** Name of the active backend, or null before first call (for diagnostics/tests). */export function getProjectsBackendName() {- return backendName;+ return getBackendName();}// Announce a newly-created project to the per-record peer-sync pipeline: emit thediff --git a/server/services/sprites/records.js b/server/services/sprites/records.jsindex 100fabcb0a..9b24582bbe 100644--- a/server/services/sprites/records.js+++ b/server/services/sprites/records.js@@ -14,33 +14,21 @@* #2895's scope); the tombstone trio on the record keeps peer-sync additive.*/-import { checkHealth, ensureSchema, isTestRunner } from '../../lib/db.js';+import { isTestRunner } from '../../lib/db.js';import { ServerError } from '../../lib/errorHandler.js';+import { createRecordStoreBackendSelector } from '../../lib/pgFileFacade.js';import { listSpriteAssets } from './paths.js';import { deriveSpriteId, isValidSpriteId } from './recordsLogic.js';-let backend = null;--async function selectBackend() {- if (backend) return backend;-- // isTestRunner (NODE_ENV==='test' OR VITEST) is the repo's supported test- // detection — a wrapper that drops NODE_ENV must still select the file- // backend instead of hitting the real DB's test gate.- const envBackend = process.env.MEMORY_BACKEND;- if (envBackend === 'file' || isTestRunner()) {- backend = await import('./recordsFile.js');- return backend;- }-- const health = await checkHealth();- if (!health.connected) {- throw new Error('Sprites requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file in .env)');- }- await ensureSchema();- backend = await import('./recordsDB.js');- return backend;-}+// Shared dispatcher (#2899). isTestRunner (NODE_ENV==='test' OR VITEST) is the+// repo's supported test detection — a wrapper that drops NODE_ENV must still+// select the file backend instead of hitting the real DB's test gate.+const { selectBackend } = createRecordStoreBackendSelector({+ label: 'Sprites',+ loadFileBackend: () => import('./recordsFile.js'),+ loadDbBackend: () => import('./recordsDB.js'),+ isTestMode: isTestRunner,+});export async function listRecords(options = {}) {return (await selectBackend()).listRecords(options);