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: extract shared createPgFileFacade for store backends (#2523)
Adam Eivy0666d353505a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 365456f579..e5a6836a15 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,7 @@## Changed+- **[issue-2523] Extract a shared `createPgFileFacade` backbone for the six PG/file store dispatchers.** The pipeline series/issues, story-builder, universe-builder, catalog-user-types, and writers-room stores each re-implemented the same three pieces: the `isFileBackend()` escape-hatch predicate, the promise-memoized lazy backend selection (so concurrent first calls don't run the migration twice), and the PG bring-up sequence (health-check → `ensureSchema` → one-time file→DB migration → import the leaf-I/O `db.js`). Those now live once in `server/lib/pgFileFacade.js` as `isFileBackend()`, `resolvePgBackend({ requirement, migrate?, loadDb, makePg })`, and `createPgFileFacade({ makeFile, makePg })`; the two inline write-queue copies (`createFileWriteQueue`'s id-keyed sibling `createRecordWriteQueue`) were folded into `server/lib/fileWriteQueue.js`. Each store keeps its own genuinely-different `makeFile`/`makePg` factories and public surface; behavior is preserved on both the PostgreSQL and file/test backends. New unit tests cover the shared helpers.- **[issue-2521] Validate the remaining ad-hoc route bodies with Zod `validateRequest`.** The ports (`/check`, `/allocate`), database (`switch`/`start`/`stop`/`destroy`/`export`), brain digest/review run, telegram (`method`/`config`/`test`/`forward-types`), and AI-toolkit provider (`POST`/`PUT`/`PUT active`) routes parsed `req.body` with hand-rolled `Array.isArray`/`includes` checks. Each now has a named Zod schema (PortOS schemas in `lib/validation.js`, brain schema in `brainValidation.js`, provider schemas in `aiToolkit/validation.js`) wired through `validateRequest`, so invalid bodies return a consistent `400 VALIDATION_ERROR` with per-field `context.details` instead of ad-hoc messages. Port numbers are range-checked (and `count` coercion no longer silently accepts booleans/arrays), backend/target values are enum-checked, and provider create/update reuse the canonical `providerSchema` (`.partial()` on update). As part of wiring `PUT /api/providers/active`, the toolkit providers map is now null-prototyped on load so a crafted id (`__proto__`, `constructor`, `toString`) can no longer resolve an inherited `Object.prototype` member as an existing provider and be persisted as the active one.- **[issue-2525] Extract shared `migrationMarker` helpers using `atomicWrite`.** Eleven boot-time migration/repair/reconcile scripts under `server/scripts/` each hand-rolled `markerExists`/`readMarker`/`writeMarker` on top of `readFile(...).catch(() => null)` and a non-atomic `writeFile(JSON.stringify(...))`, so a crash mid-write could leave a truncated marker a later boot misreads as "not applied." The three helpers now live once in `server/lib/migrationMarker.js` (anchored under `PATHS.data`, built on the existing `tryReadFile`/`atomicWrite`/`safeJSONParse`), are barrel- and README-cataloged, and carry their own unit test. Marker filenames, gate semantics, and payloads are unchanged; the write path is now atomic (temp file + rename).- **[issue-2522] Deep-link Tribe tabs and fix form label associations.** The Tribe page's active section (Circle / Map / Care Queue / Focus) lived in local `useState`, so a section couldn't be shared, bookmarked, or survive a reload. It now reads from a `?tab=` URL search param (default `circle` omitted for a clean `/tribe`) with a valid-tab fallback for stale/unknown values — matching the PromptManager convention. Separately, the `StylePresetPicker` style-preset `<label>` and the Loops "Interval" `<label>` had no `htmlFor`/`id` pairing; both now associate with their control via a `useId()`-generated id so click-to-focus and screen readers work.diff --git a/server/lib/README.md b/server/lib/README.mdindex 384796fec2..f67ce04c4e 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -126,10 +126,11 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. || `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |-| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |+| `fileWriteQueue.js` | Serialize read-modify-write cycles so they don't interleave. `createFileWriteQueue()` → single-tail `queue(fn)` for one shared file; `createRecordWriteQueue(assertId?)` → id-keyed `queueRecordWrite(id, fn)` where same-id cycles serialize and different-id cycles run in parallel (the queue the PG/file store facades use for `collectionStore.queueRecordWrite` parity). || `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. || `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/fileWriteQueue.js b/server/lib/fileWriteQueue.jsindex 8f5df1cd2d..4f5d4f3b27 100644--- a/server/lib/fileWriteQueue.js+++ b/server/lib/fileWriteQueue.js@@ -43,3 +43,33 @@ export function createFileWriteQueue() {return next; // callers see the real resolve/reject};}++/**+ * Per-RECORD write queue — the id-keyed sibling of `createFileWriteQueue`.+ *+ * Two read-modify-write cycles on the SAME id serialize (the later one sees the+ * earlier one's committed result); cycles on DIFFERENT ids fan out in parallel.+ * This is the queue the PG/file store facades use so their writes serialize+ * identically to `collectionStore.queueRecordWrite` on either backend. The tail+ * Map self-prunes so it stays bounded.+ *+ * @param {(id: string) => void} [assertId] Optional per-id validator, invoked+ * before queueing (throws on a bad id, exactly as the callers' inline guards+ * did — so a malformed id rejects synchronously rather than being enqueued).+ *+ * Usage:+ * const queueRecordWrite = createRecordWriteQueue(assertValidId);+ * queueRecordWrite(id, () => saveOneNow(id, record));+ */+export function createRecordWriteQueue(assertId) {+ const tails = new Map();+ return function queueRecordWrite(id, fn) {+ if (assertId) assertId(id);+ const prev = tails.get(id) || Promise.resolve();+ const next = prev.then(fn, fn); // run fn even when prev rejects+ const silenced = next.catch(() => {});+ tails.set(id, silenced);+ silenced.finally(() => { if (tails.get(id) === silenced) tails.delete(id); });+ return next; // callers see the real resolve/reject+ };+}diff --git a/server/lib/fileWriteQueue.test.js b/server/lib/fileWriteQueue.test.jsindex 5b446a354e..e00db072f8 100644--- a/server/lib/fileWriteQueue.test.js+++ b/server/lib/fileWriteQueue.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { createFileWriteQueue } from './fileWriteQueue.js';+import { createFileWriteQueue, createRecordWriteQueue } from './fileWriteQueue.js';// Defer one event-loop tick (setImmediate is a check-phase macrotask, not a// microtask) so we can interleave with another awaiter.@@ -50,3 +50,43 @@ describe('createFileWriteQueue', () => {expect(order).toEqual(['b-fast', 'a-slow']);});});++describe('createRecordWriteQueue', () => {+ it('serializes same-id cycles in submission order', async () => {+ const queue = createRecordWriteQueue();+ const order = [];+ const a = queue('x', async () => { await tick(); order.push('a'); });+ const b = queue('x', async () => { order.push('b'); });+ await Promise.all([a, b]);+ expect(order).toEqual(['a', 'b']);+ });++ it('lets different ids run concurrently', async () => {+ const queue = createRecordWriteQueue();+ const order = [];+ // id 'x' yields; id 'y' should not wait for it.+ const x = queue('x', async () => { await tick(); order.push('x-slow'); });+ const y = queue('y', async () => { order.push('y-fast'); });+ await Promise.all([x, y]);+ expect(order).toEqual(['y-fast', 'x-slow']);+ });++ it('an earlier rejection on an id does not poison later same-id waiters', async () => {+ const queue = createRecordWriteQueue();+ const order = [];+ const bad = queue('x', async () => { await tick(); order.push('bad'); throw new Error('nope'); });+ const good = queue('x', async () => { order.push('good'); return 'ok'; });+ await expect(bad).rejects.toThrow('nope');+ await expect(good).resolves.toBe('ok');+ expect(order).toEqual(['bad', 'good']);+ });++ it('invokes the optional id validator before queueing (throws synchronously)', () => {+ const queue = createRecordWriteQueue((id) => {+ if (id !== 'ok') throw new Error(`bad id ${id}`);+ });+ expect(() => queue('bad', () => {})).toThrow('bad id bad');+ // A valid id queues without throwing.+ expect(() => queue('ok', () => Promise.resolve())).not.toThrow();+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 17d82c5903..5b62b9cb48 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -121,6 +121,7 @@ export * from './schemaVersions.js';export * from './imageClean.js';export * from './imageWatermark.js';export * from './localImageFilename.js';+export * from './pgFileFacade.js';export * from './multipart.js';export * from './safetensors.js';export * from './assetHash.js';diff --git a/server/lib/pgFileFacade.js b/server/lib/pgFileFacade.jsnew file mode 100644index 0000000000..15a3f5742a--- /dev/null+++ b/server/lib/pgFileFacade.js@@ -0,0 +1,80 @@+/**+ * PG/file store-backend facade backbone.+ *+ * PortOS has six near-identical storage dispatchers (pipeline series/issues,+ * story builder, universe builder, catalog user-types, writers room) that each+ * pick between a PostgreSQL backend (normal installs) and a file/escape-hatch+ * backend (MEMORY_BACKEND=file or NODE_ENV=test — both UNSUPPORTED for+ * production). They all reimplemented the same three pieces: the env predicate+ * that chooses the backend, the promise-memoized lazy selection, and the PG+ * bring-up sequence (health check → ensureSchema → one-time migration → import+ * the leaf-I/O `db.js`). This module owns those pieces so no store copies them.+ *+ * 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.+ */++import { checkHealth, ensureSchema } from './db.js';++/**+ * True when the file/escape-hatch backend should be used instead of PostgreSQL.+ * Dev/test only — see the Storage backend policy in CLAUDE.md.+ */+export function isFileBackend() {+ return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';+}++/**+ * Bring the PostgreSQL backend up and build it. Fail-fast on a missing DB (the+ * boot gate may not have run ensureSchema yet — an early warm or a sync pull can+ * call in first), so this is self-sufficient: it health-checks, brings the+ * schema up (idempotent), runs the one-time marker-gated file→DB import, imports+ * the leaf-I/O db module, and hands it to `makePg`.+ *+ * @param {object} opts+ * @param {string} opts.requirement Error message thrown when the DB is unreachable.+ * @param {() => Promise<void>} [opts.migrate] One-time file→DB import (optional).+ * @param {() => Promise<object>} opts.loadDb Dynamic `import('./db.js')`.+ * @param {(db: object) => object} opts.makePg Build the PG backend from the db module.+ */+export async function resolvePgBackend({ requirement, migrate, loadDb, makePg }) {+ const health = await checkHealth();+ if (!health.connected) throw new Error(requirement);+ await ensureSchema();+ if (migrate) await migrate();+ const db = await loadDb();+ return makePg(db);+}++/**+ * Shared PG/file backend selector. Picks the file backend under the dev/test+ * escape hatch and the PG backend otherwise, memoizing the 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. `makeFile` may be sync or async; `makePg` is async (usually wired to+ * `resolvePgBackend`).+ *+ * @param {object} opts+ * @param {() => object|Promise<object>} opts.makeFile Build the file backend.+ * @param {() => Promise<object>} opts.makePg Build the PG backend.+ * @returns {{ getBackend: () => Promise<object>, getBackendName: () => (string|null), reset: () => void }}+ */+export function createPgFileFacade({ makeFile, makePg }) {+ let backend = null;+ let selecting = null;+ const getBackend = () => {+ if (backend) return Promise.resolve(backend);+ if (!selecting) {+ selecting = Promise.resolve(isFileBackend() ? makeFile() : makePg())+ .then((b) => { backend = b; return b; })+ .finally(() => { selecting = null; });+ }+ return selecting;+ };+ return {+ getBackend,+ getBackendName: () => backend?.name ?? null,+ reset: () => { backend = null; selecting = null; },+ };+}diff --git a/server/lib/pgFileFacade.test.js b/server/lib/pgFileFacade.test.jsnew file mode 100644index 0000000000..282136e880--- /dev/null+++ b/server/lib/pgFileFacade.test.js@@ -0,0 +1,126 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// Mock the leaf-I/O db module so resolvePgBackend's bring-up sequence is+// observable without a real Postgres. (pgFileFacade imports checkHealth /+// ensureSchema from here.)+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 tick = () => new Promise((r) => setImmediate(r));++describe('isFileBackend', () => {+ const orig = { MEMORY_BACKEND: process.env.MEMORY_BACKEND, NODE_ENV: process.env.NODE_ENV };+ afterEach(() => {+ process.env.MEMORY_BACKEND = orig.MEMORY_BACKEND;+ process.env.NODE_ENV = orig.NODE_ENV;+ });++ it('is true under NODE_ENV=test', () => {+ process.env.NODE_ENV = 'test';+ delete process.env.MEMORY_BACKEND;+ expect(isFileBackend()).toBe(true);+ });++ it('is true under MEMORY_BACKEND=file even when not test', () => {+ process.env.NODE_ENV = 'production';+ process.env.MEMORY_BACKEND = 'file';+ expect(isFileBackend()).toBe(true);+ });++ it('is false when neither escape hatch is set', () => {+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ expect(isFileBackend()).toBe(false);+ });+});++describe('createPgFileFacade', () => {+ // Runs under NODE_ENV=test → file backend selected.+ it('selects the file backend under the test escape hatch', async () => {+ const makeFile = vi.fn(() => ({ name: 'file' }));+ const makePg = vi.fn(() => ({ name: 'postgres' }));+ const facade = createPgFileFacade({ makeFile, makePg });+ expect(facade.getBackendName()).toBe(null); // before first call+ const b = await facade.getBackend();+ expect(b.name).toBe('file');+ expect(facade.getBackendName()).toBe('file');+ expect(makeFile).toHaveBeenCalledTimes(1);+ expect(makePg).not.toHaveBeenCalled();+ });++ it('memoizes the selection so concurrent first calls build the backend once', async () => {+ let calls = 0;+ const makeFile = vi.fn(async () => { calls += 1; await tick(); return { name: 'file' }; });+ const facade = createPgFileFacade({ makeFile, makePg: vi.fn() });+ const [a, b] = await Promise.all([facade.getBackend(), facade.getBackend()]);+ expect(a).toBe(b);+ expect(calls).toBe(1);+ });++ it('reset() forces a fresh selection', async () => {+ const makeFile = vi.fn(() => ({ name: 'file' }));+ const facade = createPgFileFacade({ makeFile, makePg: vi.fn() });+ await facade.getBackend();+ facade.reset();+ expect(facade.getBackendName()).toBe(null);+ await facade.getBackend();+ expect(makeFile).toHaveBeenCalledTimes(2);+ });++ it('selects the PG backend when the escape hatch is off', async () => {+ const prev = process.env.NODE_ENV;+ process.env.NODE_ENV = 'production';+ delete process.env.MEMORY_BACKEND;+ try {+ const makeFile = vi.fn();+ const makePg = vi.fn(async () => ({ name: 'postgres' }));+ const facade = createPgFileFacade({ makeFile, makePg });+ const b = await facade.getBackend();+ expect(b.name).toBe('postgres');+ expect(makeFile).not.toHaveBeenCalled();+ expect(makePg).toHaveBeenCalledTimes(1);+ } finally {+ process.env.NODE_ENV = prev;+ }+ });+});++describe('resolvePgBackend', () => {+ beforeEach(() => { checkHealth.mockReset(); ensureSchema.mockClear(); });++ it('throws the requirement message when the DB is unreachable', async () => {+ checkHealth.mockResolvedValue({ connected: false });+ await expect(resolvePgBackend({+ requirement: 'need pg',+ loadDb: async () => ({}),+ makePg: () => ({ name: 'postgres' }),+ })).rejects.toThrow('need pg');+ expect(ensureSchema).not.toHaveBeenCalled();+ });++ it('brings the schema up, runs the migration, then builds from the db module', async () => {+ checkHealth.mockResolvedValue({ connected: true });+ const order = [];+ const migrate = vi.fn(async () => { order.push('migrate'); });+ const loadDb = vi.fn(async () => { order.push('loadDb'); return { readRaw: () => {} }; });+ const makePg = vi.fn((db) => { order.push('makePg'); return { name: 'postgres', db }; });+ ensureSchema.mockImplementation(async () => { order.push('ensureSchema'); });++ const backend = await resolvePgBackend({ requirement: 'x', migrate, loadDb, makePg });+ expect(backend.name).toBe('postgres');+ expect(order).toEqual(['ensureSchema', 'migrate', 'loadDb', 'makePg']);+ });++ it('skips the migration step when none is provided', async () => {+ checkHealth.mockResolvedValue({ connected: true });+ const backend = await resolvePgBackend({+ requirement: 'x',+ loadDb: async () => ({}),+ makePg: () => ({ name: 'postgres' }),+ });+ expect(backend.name).toBe('postgres');+ });+});diff --git a/server/services/catalogUserTypes/store.js b/server/services/catalogUserTypes/store.jsindex 71719e6fde..08757a0193 100644--- a/server/services/catalogUserTypes/store.js+++ b/server/services/catalogUserTypes/store.js@@ -29,14 +29,7 @@* so the boot registry warm — the first caller — sees migrated types.*/-import { checkHealth, ensureSchema } from '../../lib/db.js';--let backend = null;-let selecting = null;--function isFileBackend() {- return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';-}+import { createPgFileFacade, resolvePgBackend } from '../../lib/pgFileFacade.js';// settings.json-backed implementation (escape hatch / tests). Byte-identical to// the behavior the catalog routes + sync had inline before #1001, so nothing@@ -55,53 +48,41 @@ async function fileBackend() {};}-async function pgBackend() {- // Self-sufficient like the CD backend: the boot DB gate fail-fasts a- // required-but-missing DB, but a sync pull or the early registry warm can call- // in BEFORE that gate's ensureSchema() runs — so bring the schema up here- // (idempotent) and run the one-time settings→DB import before first read.- const health = await checkHealth();- if (!health.connected) {- throw new Error('Catalog user types require PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env for the unsupported file backend)');- }- await ensureSchema();- const { migrateCatalogUserTypesToDB } = await import('../../scripts/migrateCatalogUserTypesToDB.js');- await migrateCatalogUserTypesToDB();- const db = await import('./db.js');- return { name: 'postgres', readUserTypes: db.readUserTypes, writeUserTypes: db.writeUserTypes };-}--// Memoize the selection PROMISE (not just the result) so two concurrent first-// calls — e.g. the early boot warm racing a sync pull — don't both import the-// PG module and run the migration twice. (The migration is marker-gated +-// ON CONFLICT idempotent anyway, but memoizing keeps it to one round-trip.)-async function selectBackend() {- if (backend) return backend;- if (!selecting) {- selecting = (isFileBackend() ? fileBackend() : pgBackend())- .then((b) => { backend = b; return b; })- .finally(() => { selecting = null; });- }- return selecting;-}+// Self-sufficient like the CD backend: the boot DB gate fail-fasts a+// required-but-missing DB, but a sync pull or the early registry warm can call+// in BEFORE that gate's ensureSchema() runs — so resolvePgBackend brings the+// schema up (idempotent) and runs the one-time settings→DB import before first+// read. Backend selection is promise-memoized so two concurrent first calls+// don't both import the PG module / run the migration twice.+const facade = createPgFileFacade({+ makeFile: () => fileBackend(),+ makePg: () => resolvePgBackend({+ requirement: 'Catalog user types require PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env for the unsupported file backend)',+ migrate: async () => {+ const { migrateCatalogUserTypesToDB } = await import('../../scripts/migrateCatalogUserTypesToDB.js');+ await migrateCatalogUserTypesToDB();+ },+ loadDb: () => import('./db.js'),+ makePg: (db) => ({ name: 'postgres', readUserTypes: db.readUserTypes, writeUserTypes: db.writeUserTypes }),+ }),+});/** Active backend name, or null before first call (diagnostics/tests). */export function getCatalogUserTypesBackendName() {- return backend?.name ?? null;+ return facade.getBackendName();}/** Reset cached backend selection — test seam only. */export function _resetCatalogUserTypesBackend() {- backend = null;- selecting = null;+ facade.reset();}/** Full user-type slice (live + tombstones), verbatim. */export async function readUserTypes() {- return (await selectBackend()).readUserTypes();+ return (await facade.getBackend()).readUserTypes();}/** Persist the whole user-type slice as the authoritative end state. */export async function writeUserTypes(list) {- return (await selectBackend()).writeUserTypes(list);+ return (await facade.getBackend()).writeUserTypes(list);}diff --git a/server/services/pipeline/issuesStore/store.js b/server/services/pipeline/issuesStore/store.jsindex 1112f28938..7a10ca0cfa 100644--- a/server/services/pipeline/issuesStore/store.js+++ b/server/services/pipeline/issuesStore/store.js@@ -26,16 +26,13 @@import { join } from 'path';import { PATHS } from '../../../lib/fileUtils.js';import { createCollectionStore } from '../../../lib/collectionStore.js';-import { checkHealth, ensureSchema } from '../../../lib/db.js';+import { createPgFileFacade, resolvePgBackend, isFileBackend } from '../../../lib/pgFileFacade.js';+import { createFileWriteQueue } from '../../../lib/fileWriteQueue.js';import { bumpPipelineMutationEpoch } from '../syncEpoch.js';const TYPE_SCHEMA_VERSION = 1;const ID_PATTERN = /^iss-[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(`pipelineIssuesStore: invalid record id "${id}" — must match ${ID_PATTERN}`);@@ -89,45 +86,29 @@ function makePgBackend(db, sanitizeRecord) {};}-async function pgBackend(sanitizeRecord) {- const health = await checkHealth();- if (!health.connected) {- throw new Error('Pipeline issues require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)');- }- await ensureSchema();- const { migrateIssuesToDB } = await import('../../../scripts/migrateIssuesToDB.js');- await migrateIssuesToDB();- const db = await import('./db.js');- return makePgBackend(db, sanitizeRecord);-}+const pgBackend = (sanitizeRecord) => resolvePgBackend({+ requirement: 'Pipeline issues require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',+ migrate: async () => {+ const { migrateIssuesToDB } = await import('../../../scripts/migrateIssuesToDB.js');+ await migrateIssuesToDB();+ },+ loadDb: () => import('./db.js'),+ makePg: (db) => makePgBackend(db, sanitizeRecord),+});function createFacade({ dir, sanitizeRecord }) {const sanitizer = typeof sanitizeRecord === 'function' ? sanitizeRecord : (r) => r;- 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;- };+ const { getBackend, getBackendName } = createPgFileFacade({+ makeFile: () => makeFileBackend(dir, sanitizer),+ makePg: () => pgBackend(sanitizer),+ });// Single-tail type-index queue — mirrors collectionStore.queueTypeIndexWrite.// mergeIssuesFromSync / pruneTombstonedIssues load the whole issue set, mutate,// and write back; they must serialize against themselves for one consistent// merge snapshot.- let typeIndexTail = Promise.resolve();- function queueTypeIndexWrite(fn) {- const next = typeIndexTail.then(fn, fn);- const silenced = next.catch(() => {});- typeIndexTail = silenced;- silenced.finally(() => { if (typeIndexTail === silenced) typeIndexTail = Promise.resolve(); });- return next;- }+ const queueTypeIndexWrite = createFileWriteQueue();const saveOneNow = async (id, record) => {assertValidId(id);@@ -145,7 +126,7 @@ function createFacade({ dir, sanitizeRecord }) {return {dir,type: 'pipelineIssues',- getBackendName: () => backend?.name ?? null,+ getBackendName,listIds: async () => (await getBackend()).listIds(),loadOne: async (id) => {diff --git a/server/services/pipeline/seriesStore/store.js b/server/services/pipeline/seriesStore/store.jsindex 866627f370..8b5379f2fb 100644--- a/server/services/pipeline/seriesStore/store.js+++ b/server/services/pipeline/seriesStore/store.js@@ -37,7 +37,8 @@import { join } from 'path';import { PATHS } from '../../../lib/fileUtils.js';import { createCollectionStore } from '../../../lib/collectionStore.js';-import { checkHealth, ensureSchema } from '../../../lib/db.js';+import { createPgFileFacade, resolvePgBackend, isFileBackend } from '../../../lib/pgFileFacade.js';+import { createRecordWriteQueue } from '../../../lib/fileWriteQueue.js';import { bumpPipelineMutationEpoch } from '../syncEpoch.js';// TYPE-level (storage layout) schema version stamped on the file backend's@@ -46,10 +47,6 @@ import { bumpPipelineMutationEpoch } from '../syncEpoch.js';const TYPE_SCHEMA_VERSION = 1;const ID_PATTERN = /^ser-[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(`pipelineSeriesStore: invalid record id "${id}" — must match ${ID_PATTERN}`);@@ -99,45 +96,27 @@ function makePgBackend(db, sanitizeRecord) {};}-async function pgBackend(sanitizeRecord) {- const health = await checkHealth();- if (!health.connected) {- throw new Error('Pipeline series require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)');- }- await ensureSchema();- const { migrateSeriesToDB } = await import('../../../scripts/migrateSeriesToDB.js');- await migrateSeriesToDB();- const db = await import('./db.js');- return makePgBackend(db, sanitizeRecord);-}+const pgBackend = (sanitizeRecord) => resolvePgBackend({+ requirement: 'Pipeline series require PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',+ migrate: async () => {+ const { migrateSeriesToDB } = await import('../../../scripts/migrateSeriesToDB.js');+ await migrateSeriesToDB();+ },+ loadDb: () => import('./db.js'),+ makePg: (db) => makePgBackend(db, sanitizeRecord),+});// --- Facade: collectionStore-compatible, queues + epoch + sanitize ---function createFacade({ dir, sanitizeRecord }) {const sanitizer = typeof sanitizeRecord === 'function' ? sanitizeRecord : (r) => r;- 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;- };+ const { getBackend, getBackendName } = createPgFileFacade({+ makeFile: () => makeFileBackend(dir, sanitizer),+ makePg: () => pgBackend(sanitizer),+ });// 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 queueRecordWrite = createRecordWriteQueue(assertValidId);const loadOne = async (id) => {if (typeof id !== 'string' || !ID_PATTERN.test(id)) return null;@@ -163,7 +142,7 @@ function createFacade({ dir, sanitizeRecord }) {// recordDir ALWAYS resolves to the on-disk path — the manuscript-review.json// sibling is file-primary and lives there regardless of the record backend.recordDir: (id) => join(dir, id),- getBackendName: () => backend?.name ?? null,+ getBackendName,// Reads (sanitized, matching collectionStore.loadOne/loadAll)listIds: async () => (await getBackend()).listIds(),diff --git a/server/services/storyBuilderStore/store.js b/server/services/storyBuilderStore/store.jsindex 839ae25e0a..6424ab456b 100644--- a/server/services/storyBuilderStore/store.js+++ b/server/services/storyBuilderStore/store.js@@ -30,7 +30,8 @@import { join } from 'path';import { PATHS } from '../../lib/fileUtils.js';import { createCollectionStore } from '../../lib/collectionStore.js';-import { checkHealth, ensureSchema } from '../../lib/db.js';+import { createPgFileFacade, resolvePgBackend, isFileBackend } from '../../lib/pgFileFacade.js';+import { createRecordWriteQueue } from '../../lib/fileWriteQueue.js';import { bumpChangeToken, getChangeToken } from '../changeToken.js';// TYPE-level (storage layout) schema version stamped on the file backend's@@ -39,10 +40,6 @@ import { bumpChangeToken, getChangeToken } from '../changeToken.js';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}`);@@ -102,48 +99,30 @@ function makePgBackend(db, sanitizeRecord) {};}-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);-}+const pgBackend = (sanitizeRecord) => resolvePgBackend({+ requirement: 'Story Builder requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',+ migrate: async () => {+ const { migrateStoryBuilderToDB } = await import('../../scripts/migrateStoryBuilderToDB.js');+ await migrateStoryBuilderToDB();+ },+ loadDb: () => import('./db.js'),+ makePg: (db) => 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;- };+ // Backend selection is memoized (promise, not just 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. `sanitizer` is read at selection time.+ const { getBackend, getBackendName } = createPgFileFacade({+ makeFile: () => makeFileBackend(dir, sanitizer),+ makePg: () => pgBackend(sanitizer),+ });// 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 queueRecordWrite = createRecordWriteQueue(assertValidId);const loadOne = async (id) => {if (typeof id !== 'string' || !ID_PATTERN.test(id)) return null;@@ -167,7 +146,7 @@ function createFacade({ dir, sanitizeRecord }) {dir,type: 'storyBuilder',_setSanitizer: (fn) => { if (typeof fn === 'function') sanitizer = fn; },- getBackendName: () => backend?.name ?? null,+ getBackendName,// Reads (sanitized, matching collectionStore.loadOne/loadAll)listIds: async () => (await getBackend()).listIds(),diff --git a/server/services/universeBuilder/store.js b/server/services/universeBuilder/store.jsindex 3d7cf44373..e2ea3a15e1 100644--- a/server/services/universeBuilder/store.js+++ b/server/services/universeBuilder/store.js@@ -31,7 +31,8 @@import { join } from 'path';import { PATHS } from '../../lib/fileUtils.js';import { createCollectionStore } from '../../lib/collectionStore.js';-import { checkHealth, ensureSchema } from '../../lib/db.js';+import { createPgFileFacade, resolvePgBackend, isFileBackend } from '../../lib/pgFileFacade.js';+import { createFileWriteQueue, createRecordWriteQueue } from '../../lib/fileWriteQueue.js';import { bumpChangeToken, getChangeToken } from '../changeToken.js';// TYPE-level (storage layout) schema version stamped on the file backend's@@ -39,10 +40,6 @@ import { bumpChangeToken, getChangeToken } from '../changeToken.js';// 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';-}-// Record-id allowlist — IDENTICAL to the collectionStore idPattern the file// backend enforced. The facade must reject the same ids on the PG path so the// two backends accept the same records: a malformed synced/imported id (e.g.@@ -142,71 +139,46 @@ function makePgBackend(db) {};}-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);-}+// 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 resolvePgBackend+// brings the schema up (idempotent) and runs the one-time file→DB import first.+const pgBackend = () => resolvePgBackend({+ requirement: 'Universe Builder requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',+ migrate: async () => {+ const { migrateUniversesToDB } = await import('../../scripts/migrateUniversesToDB.js');+ await migrateUniversesToDB();+ },+ loadDb: () => import('./db.js'),+ makePg: (db) => 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;- };+ // Backend selection is memoized (promise, not just 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.+ const { getBackend, getBackendName } = createPgFileFacade({+ makeFile: () => makeFileBackend(dir),+ makePg: () => pgBackend(),+ });// 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) {- assertValidId(id); // parity with collectionStore.queueRecordWrite- 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 queueRecordWrite = createRecordWriteQueue(assertValidId);// 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;- }+ const queueRunWrite = createFileWriteQueue();return {dir,type: 'universes',_setSanitizer: (fn) => { if (typeof fn === 'function') sanitizer = fn; },- getBackendName: () => backend?.name ?? null,+ getBackendName,// ReadslistIds: async () => (await getBackend()).listIds(),diff --git a/server/services/writersRoom/store.js b/server/services/writersRoom/store.jsindex d650b1e1ca..fe8af2a5c8 100644--- a/server/services/writersRoom/store.js+++ b/server/services/writersRoom/store.js@@ -30,7 +30,7 @@import { readFile, readdir } from 'fs/promises';import { atomicWrite, ensureDir, readJSONFile, safeJSONParse } from '../../lib/fileUtils.js';-import { checkHealth, ensureSchema } from '../../lib/db.js';+import { createPgFileFacade, resolvePgBackend } from '../../lib/pgFileFacade.js';import { ServerError } from '../../lib/errorHandler.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,@@ -44,10 +44,6 @@ import {WORK_ID_RE, wrRoot, wrFoldersFile, wrExercisesFile, wrWorksDir, wrManifestPath,} from './_shared.js';-function isFileBackend() {- return process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test';-}-// --- File backend (escape hatch / tests): the legacy on-disk JSON format ---// Reproduces local.js's original storage primitives verbatim so an install on// the file escape hatch (and every test that boots without a DB) behaves@@ -288,43 +284,33 @@ function makePgBackend(db) {return { name: 'postgres', ...db };}-async function pgBackend() {- const health = await checkHealth();- if (!health.connected) {- throw new Error('Writers Room requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)');- }- await ensureSchema();- const { migrateWritersRoomToDB } = await import('../../scripts/migrateWritersRoomToDB.js');- await migrateWritersRoomToDB();- const db = await import('./db.js');- return makePgBackend(db);-}+const pgBackend = () => resolvePgBackend({+ requirement: 'Writers Room requires PostgreSQL — run `npm run setup:db` (dev/test only: set MEMORY_BACKEND=file for the unsupported file backend)',+ migrate: async () => {+ const { migrateWritersRoomToDB } = await import('../../scripts/migrateWritersRoomToDB.js');+ await migrateWritersRoomToDB();+ },+ loadDb: () => import('./db.js'),+ makePg: (db) => makePgBackend(db),+});// Memoize the backend-selection PROMISE (not just the result) so two concurrent// first calls — e.g. the boot warm racing a request — don't both import the PG// module and run the migration twice.-let backend = null;-let selecting = null;+const facade = createPgFileFacade({+ makeFile: () => makeFileBackend(),+ makePg: () => pgBackend(),+});+const { getBackend } = facade;export function _resetWritersRoomStore() {- backend = null;- selecting = null;-}--function getBackend() {- if (backend) return Promise.resolve(backend);- if (!selecting) {- selecting = (isFileBackend() ? Promise.resolve(makeFileBackend()) : pgBackend())- .then((b) => { backend = b; return b; })- .finally(() => { selecting = null; });- }- return selecting;+ facade.reset();}/** The Writers Room metadata store — backend resolved lazily per call. */export function writersRoomStore() {return {- getBackendName: () => backend?.name ?? null,+ getBackendName: () => facade.getBackendName(),listFolders: async () => (await getBackend()).listFolders(),readFolder: async (id, opts) => (await getBackend()).readFolder(id, opts),listFolderIds: async (opts) => (await getBackend()).listFolderIds(opts),