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
feat(catalog): move user-defined types to PostgreSQL (#1001)
Adam Eivy45f51ef55035
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 4ead807106..f02b9e8bf3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -15,6 +15,7 @@## Changed+- **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).- **Creative Director state now lives in PostgreSQL** — Creative Director projects (treatment, scenes, and run history) moved out of the single monolithic `data/creative-director-projects.json` file into a `creative_director_projects` table, one row per project. The orchestrator rewrote that whole file ≈10 times per scene render, so a long session turned every project list/read into an O(N²) reserialize; per-project rows remove that contention, and concurrent writes to the same project (render-progress + agent-run updates) are now serialized with a row lock so they can't lose each other's updates. Existing installs are migrated automatically and losslessly on first boot — the legacy file is kept (renamed `…json.imported`) as a recovery source. Behavior is unchanged; this is a storage move (Phase 3 of the Postgres-first plan, #997). The file backend remains reachable under the `MEMORY_BACKEND=file` dev/test escape hatch.- **PostgreSQL is now a required dependency** — file-based JSON storage is no longer offered as a normal setup choice. `npm run setup:db` presents only Docker and Native PostgreSQL hosting modes (and auto-selects native when a healthy local PostgreSQL is already reachable). On boot, PortOS now verifies the database is reachable with the required schema and refuses to start with an actionable message if it isn't — instead of silently falling back to file-backed memory and serving a half-broken install (the creative catalog has no file-backed equivalent). `MEMORY_BACKEND=file` survives only as an explicit, unsupported development/test escape hatch. New docs: [`docs/STORAGE.md`](../docs/STORAGE.md) (the storage-classification contract — `db-primary` / `file-primary` / `asset-file-db-indexed` / `ephemeral-file` — plus a "new data store?" review checklist) and [`docs/BACKUP.md`](../docs/BACKUP.md) (backup/restore now that the Postgres dump is required system state).diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 65716e6435..ab94a1e8ea 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -32,8 +32,9 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges (the strongest argument for Postgres as the catalog graph store).- `memories` / `memory_links` — long-term memory + pgvector similarity.- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.+- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.-**Postgres-First target.** Universes, pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. Catalog user-defined types should also move from `settings.json` into catalog DB tables. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997.)+**Postgres-First target.** Universes, pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001.)---diff --git a/server/index.js b/server/index.jsindex 9a99733224..ebf36c0e8a 100644--- a/server/index.js+++ b/server/index.js@@ -143,8 +143,9 @@ import { startBackupScheduler } from './services/backupScheduler.js';import { startCitySnapshotScheduler } from './services/citySnapshotScheduler.js';import * as telegram from './services/telegram.js';import * as telegramBridge from './services/telegramBridge.js';-import { getSettings as getInitSettings, settingsEvents } from './services/settings.js';+import { getSettings as getInitSettings } from './services/settings.js';import { setUserCatalogTypes } from './lib/catalogTypes.js';+import { readUserTypes as readUserTypeSlice } from './services/catalogUserTypes/store.js';import { startUpdateScheduler, recordUpdateResult, clearStaleUpdateInProgress, getCurrentVersion } from './services/updateChecker.js';import { restoreLoops } from './services/loops.js';import { startBrainScheduler } from './services/brainScheduler.js';@@ -555,18 +556,18 @@ startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot sched// Periodically GC orphan zero-issue/zero-canon importer shells left by an// abandoned analyze (issue #727).startOrphanShellGc();-// Warm the catalog user-type registry from settings before any catalog request-// can land, so user-defined types validate + mint ids immediately on boot.-// Refresh on every settings write (the Settings → Catalog tab persists through-// updateSettings, which emits this event) so the in-process registry tracks-// edits without a restart.-getInitSettings()- .then(s => setUserCatalogTypes(s.catalogUserTypes || []))+// Warm the catalog user-type registry from the user-type store (Postgres as of+// #1001; the settings.json slice under the escape hatch) before any catalog+// request can land, so user-defined types validate + mint ids immediately on+// boot. The store's PG backend self-runs ensureSchema + the one-time settings→DB+// import, so this is safe even though it fires before the boot DB gate. No+// settings:updated listener anymore: the registry's only writers are the+// `/api/catalog/types` routes and the sync merge, both of which call+// setUserCatalogTypes(next) directly — a settings save no longer touches types,+// and a listener reading the now-absent settings key would wipe the registry.+readUserTypeSlice()+ .then(list => setUserCatalogTypes(Array.isArray(list) ? list : [])).catch(err => console.error(`❌ Catalog user-type warm failed: ${err.message}`));-settingsEvents.on('settings:updated', (s) => {- try { setUserCatalogTypes(s?.catalogUserTypes || []); }- catch (err) { console.error(`❌ Catalog user-type refresh failed: ${err.message}`); }-});// Initialize Telegram (manual bot or MCP bridge based on settings)getInitSettings().then(s => {if (s.telegram?.method === 'mcp-bridge') {@@ -843,6 +844,14 @@ ensureSelf()// queryable index over them. Idempotent, safe to run every boot.const { initMediaAssetIndex } = await import('./services/mediaAssetIndex/index.js');await initMediaAssetIndex();+ // Authoritative catalog user-type warm (#1001): with the DB confirmed ++ // schema ensured, load the registry from the catalog_user_types store+ // (running the one-time settings→DB import on first access). This runs+ // BEFORE httpServer.listen, so a normal install always serves with the+ // registry warm even if the early fire-and-forget warm above raced a cold+ // DB. Idempotent with that early warm (same setUserCatalogTypes result).+ const warmTypes = await readUserTypeSlice();+ setUserCatalogTypes(Array.isArray(warmTypes) ? warmTypes : []);} catch (err) {console.error(`🪄 catalog migrations failed at boot: ${err.message}`);}diff --git a/server/lib/catalogTypes.js b/server/lib/catalogTypes.jsindex f2486dca35..d9f8a92ebd 100644--- a/server/lib/catalogTypes.js+++ b/server/lib/catalogTypes.js@@ -216,8 +216,9 @@ export function getCatalogType(id) {}// --- User-defined types (runtime layer) -----------------------------------// User types are defined in `data/settings.json` (`catalogUserTypes: []`) and-// merged into the active registry at boot/runtime via `setUserCatalogTypes`.+// User types are persisted in PostgreSQL (`catalog_user_types`, #1001 — they+// lived in `data/settings.json` `catalogUserTypes: []` before that) and merged+// into the active registry at boot/runtime via `setUserCatalogTypes`.// They are NOT in the static REGISTRY/CATALOG_TYPES export — that stays the six// built-ins so the parity + DDL-literal tests keep asserting against a stable// list. Active-type callers (validation refine, id minting, type-validity@@ -296,13 +297,14 @@ export function normalizeUserType(raw, taken = new Set()) {let activeUserTypes = [];/**- * Replace the active user-type set from a settings `catalogUserTypes` array.- * Called at boot (after settings load) and on every settings-update event so- * the in-process registry tracks the persisted definitions without a restart.- * Skips entries that fail to normalize, collide with a system id, duplicate an- * earlier user id, or carry a `deletedAt` tombstone (a soft-deleted type is- * retained in the persisted slice so the deletion federates, but it must not- * appear in the active registry).+ * Replace the active user-type set from a user-type slice (the array the+ * catalogUserTypes store returns; `catalog_user_types` rows / the settings slice+ * under the escape hatch). Called at boot (after the store warm) and by every+ * route/sync write so the in-process registry tracks the persisted definitions+ * without a restart. Skips entries that fail to normalize, collide with a+ * system id, duplicate an earlier user id, or carry a `deletedAt` tombstone (a+ * soft-deleted type is retained in the persisted slice so the deletion+ * federates, but it must not appear in the active registry).*/export function setUserCatalogTypes(list = []) {const taken = new Set();diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex cc5fe29fe8..7901050db9 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -79,9 +79,11 @@ export const SCRAP_SOURCE_KINDS = Object.freeze(['voice-memo', // POST /catalog/ingest/voice — recorded memo, Whisper-transcribed]);-// --- User-defined catalog types (settings.json `catalogUserTypes`) --------// A user type is a settings-persisted, federated definition that merges into-// the active type registry at boot/runtime as a `system:false` entry. The+// --- User-defined catalog types (PostgreSQL `catalog_user_types`, #1001) --+// A user type is a DB-persisted (formerly settings.json), federated definition+// that merges into the active type registry at boot/runtime as a `system:false`+// entry. The schemas below still validate the slice/entry SHAPE — which is+// storage-independent — at the route + sync boundaries. The// shape is intentionally minimal: an id (the stored `type` discriminator), a// label, a primary content key, and a flat list of typed fields the generic// editor renders. There is NO per-type React file — the renderer is generic.@@ -112,10 +114,12 @@ export const catalogUserTypeSchema = z.object({deletedAt: z.string().datetime().nullable().optional(),}).strict();-// The whole `catalogUserTypes` settings slice: ≤64 user types, unique ids, and-// no id colliding with a built-in system type. (Prefix-collision is resolved-// deterministically at merge time in `normalizeUserType`, so it's not gated-// here — two user types with prefix-deriving-to-the-same base just get `name2`.)+// The whole user-type slice: ≤64 user types, unique ids, and no id colliding+// with a built-in system type. (Prefix-collision is resolved deterministically+// at merge time in `normalizeUserType`, so it's not gated here — two user types+// with prefix-deriving-to-the-same base just get `name2`.) The name retains the+// `Settings` suffix for back-compat with the many importers; the slice now lives+// in `catalog_user_types`, not settings.json.export const catalogUserTypesSettingsSchema = z.array(catalogUserTypeSchema).max(64).refine((list) => new Set(list.map((t) => t.id)).size === list.length, {message: 'duplicate catalog user-type id',@@ -512,7 +516,8 @@ export const catalogSyncMediaSchema = z.object({}).passthrough();// User-defined type DEFINITIONS on the wire (catalog v8). LWW-merged on the-// receiver into its own `settings.json` `catalogUserTypes` slice. Loose-shaped+// receiver into its own user-type store (`catalog_user_types` as of #1001; the+// `settings.json` `catalogUserTypes` slice before that). Loose-shaped// (passthrough, no field-kind enum) so a forked peer's extra field shape still// stores — the active-registry merge re-normalizes on apply, and a malformed// entry is dropped there rather than 400-ing the whole envelope. `updatedAt`diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 2927a6a403..a8fafb3029 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -189,6 +189,19 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {expect(sqlIdx.size).toBeGreaterThan(0);});+ // Catalog user-defined types (#1001) — non-`catalog_`-prefixed table name in+ // BOTH DDL sources (the parity `CATALOG_TABLES` loop matches by literal table+ // name, and this one isn't in that list), so it gets its own column assertion.+ // It declares no secondary index, so nothing to compare there.+ it('catalog_user_types has the same columns in both files', () => {+ const sqlBody = extractCreateTable(INIT_SQL, 'catalog_user_types');+ const jsBody = extractCreateTable(DB_JS, 'catalog_user_types');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE catalog_user_types').toBeTruthy();+ expect(jsBody, 'db.js missing CREATE TABLE catalog_user_types').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());+ });+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 27cdb3c8b6..ab15e3cc79 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -566,6 +566,26 @@ async function ensureSchemaImpl() {// created_at DESC is the gallery/history sort order; kind narrows// images-vs-videos. A composite (kind, created_at DESC) serves both.`CREATE INDEX IF NOT EXISTS idx_media_assets_kind_created ON media_assets (kind, created_at DESC)`,++ // Catalog user-defined types (Phase 4 lead-in, issue #1001). One row per+ // user-defined ingredient type — the registry that defines catalog row+ // semantics, moved out of data/settings.json (`catalogUserTypes`) so type+ // evolution versions/syncs alongside the catalog data it governs. `id` is+ // the type discriminator (the `type` column on catalog_ingredients + the+ // `cat-<prefix>-<uuid>` mint seed); the full definition lives in `data`+ // JSONB. updated_at / deleted_at mirror the federation LWW clock + tombstone+ // (a soft-deleted type is KEPT as a tombstone row so the deletion federates+ // — setUserCatalogTypes filters tombstones out of the active registry).+ // ≤64 rows, read whole on every warm/sync, so no secondary index (an unused+ // index is just write amplification). Mirrors the catalog_user_types block+ // in init-db.sql.+ `CREATE TABLE IF NOT EXISTS catalog_user_types (+ id TEXT PRIMARY KEY,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW()+ )`,];for (const sql of catalogDDL) {await pool.query(sql);diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex c0cded86aa..770e013598 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -137,16 +137,19 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// ≤v6 receiver doesn't understand child scrap rows, so a v7 sender pushing to// it is sender-ahead and gets a 412. A v7 receiver still accepts ≤v6 senders// (their scraps carry no chunk fields → chunkIndex 0 / parentScrapId null).- // v8 = user-defined ingredient types. The definitions live in settings.json- // (`catalogUserTypes`), merge into the active type registry at boot/runtime,- // and ride a new additive `catalogTypes: [...]` block in the catalog sync- // envelope (LWW-merged into the receiver's own settings slice). Same gating- // rationale as v4–v7: a ≤v7 receiver doesn't understand the `catalogTypes`- // block, so a v8 sender pushing to it is sender-ahead and gets a 412- // (otherwise the older peer would silently drop every user-type definition,- // then reject every ingredient row carrying one of those unknown types). A v8- // receiver still accepts ≤v7 senders (sender-behind); their envelopes carry no- // `catalogTypes` block and the receiver applies the other kinds as before.+ // v8 = user-defined ingredient types. The definitions are persisted in the+ // catalogUserTypes store (`catalog_user_types` as of #1001; settings.json+ // `catalogUserTypes` before that — the move did NOT bump this version because+ // the wire shape is storage-independent), merge into the active type registry+ // at boot/runtime, and ride a new additive `catalogTypes: [...]` block in the+ // catalog sync envelope (LWW-merged into the receiver's own user-type store).+ // Same gating rationale as v4–v7: a ≤v7 receiver doesn't understand the+ // `catalogTypes` block, so a v8 sender pushing to it is sender-ahead and gets+ // a 412 (otherwise the older peer would silently drop every user-type+ // definition, then reject every ingredient row carrying one of those unknown+ // types). A v8 receiver still accepts ≤v7 senders (sender-behind); their+ // envelopes carry no `catalogTypes` block and the receiver applies the other+ // kinds as before.catalog: 8,// v1 = cross-machine resumable Story Builder sessions (#730). Sessions are// local-only by default and excluded from sync; only `sync: true` sessionsdiff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex c99dd6a60c..fed1da4897 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -37,7 +37,7 @@ import {REF_KINDS,} from '../lib/catalogValidation.js';import { getActiveCatalogTypes, setUserCatalogTypes } from '../lib/catalogTypes.js';-import { getSettings, updateSettings } from '../services/settings.js';+import { readUserTypes as readUserTypeSlice, writeUserTypes } from '../services/catalogUserTypes/store.js';import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalogBulkParsers.js';import { resolveImageInputPath } from '../lib/fileUtils.js';import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';@@ -723,17 +723,18 @@ router.post('/migration/rerun', asyncHandler(async (req, res) => {}));// --- User-defined ingredient types ---------------------------------------// User types live in settings.json (`catalogUserTypes`) and merge into the-// active type registry. These routes are the CRUD surface the Settings →-// Catalog tab drives. Every mutating route persists through the settings-// service AND calls `setUserCatalogTypes` so the in-process registry refreshes-// without a restart. The GET returns the FULL active registry (system + user)-// normalized for the client merge, with each entry's `system` flag.+// User types live in PostgreSQL (`catalog_user_types`, #1001 — formerly the+// settings.json `catalogUserTypes` slice) and merge into the active type+// registry. These routes are the CRUD surface the Settings → Catalog tab+// drives. Every mutating route persists through the catalogUserTypes store AND+// calls `setUserCatalogTypes` so the in-process registry refreshes without a+// restart. The GET returns the FULL active registry (system + user) normalized+// for the client merge, with each entry's `system` flag.// Read the persisted user-type slice as a plain array (tolerates absent/junk).const readUserTypes = async () => {- const settings = await getSettings();- return Array.isArray(settings.catalogUserTypes) ? settings.catalogUserTypes : [];+ const list = await readUserTypeSlice();+ return Array.isArray(list) ? list : [];};router.get('/types', asyncHandler(async (req, res) => {@@ -769,7 +770,7 @@ router.post('/types', asyncHandler(async (req, res) => {// Validate the whole slice (unique-id + system-collision refinements) before// persisting — a system-id collision (e.g. "character") is rejected here.validateRequest(catalogUserTypesSettingsSchema, next);- await updateSettings({ catalogUserTypes: next });+ await writeUserTypes(next);setUserCatalogTypes(next);console.log(`🧩 Catalog: added user type "${body.id}"`);res.status(201).json({ types: getActiveCatalogTypes() });@@ -786,7 +787,7 @@ router.patch('/types/:id', asyncHandler(async (req, res) => {const next = [...current];next[idx] = stampUserType(merged);validateRequest(catalogUserTypesSettingsSchema, next);- await updateSettings({ catalogUserTypes: next });+ await writeUserTypes(next);setUserCatalogTypes(next);console.log(`🧩 Catalog: updated user type "${req.params.id}"`);res.json({ types: getActiveCatalogTypes() });@@ -822,7 +823,7 @@ router.delete('/types/:id', asyncHandler(async (req, res) => {i === idx ? { ...t, deletedAt, updatedAt: deletedAt } : t));validateRequest(catalogUserTypesSettingsSchema, next);- await updateSettings({ catalogUserTypes: next });+ await writeUserTypes(next);setUserCatalogTypes(next);console.log(`🧩 Catalog: deleted user type "${req.params.id}"${force ? ' (forced)' : ''}`);res.json({ types: getActiveCatalogTypes() });diff --git a/server/routes/settings.js b/server/routes/settings.jsindex 1b019889ae..f0942663da 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -10,7 +10,6 @@ import {} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, validateRequest } from '../lib/validation.js';-import { catalogUserTypesSettingsSchema } from '../lib/catalogValidation.js';const router = Router();@@ -97,21 +96,19 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.citySnapshots !== undefined) {validateRequest(citySnapshotConfigSchema.partial(), req.body.citySnapshots);}- // User-defined catalog types — validate the whole slice (unique-id +- // system-collision refinements) when the key is present, mirroring the- // backup/embeddings slice guards above. The catalog `/types` routes are the- // primary write path, but a direct PUT /api/settings must enforce the same- // contract so a malformed slice can't reach disk and break the registry.- if (req.body?.catalogUserTypes !== undefined) {- validateRequest(catalogUserTypesSettingsSchema, req.body.catalogUserTypes);- }+ // User-defined catalog types moved out of settings.json into PostgreSQL+ // (`catalog_user_types`, #1001). The `/api/catalog/types` routes are the only+ // write path; a `catalogUserTypes` key in a PUT /api/settings body (legacy+ // client, restore bundle) is stripped below alongside `secrets` so it can't+ // write a dead, unread slice back into settings.json (which the boot import+ // would then re-import and rename aside on the next restart, churning state).// Strip `secrets` from the incoming PUT body so an authenticated session// (or stolen cookie) can't disable the auth gate or clobber other secrets// by sending `{ "secrets": { ... } }` directly to /api/settings — that// would bypass the current-password proof the /api/auth/password routes// require. Secrets are write-only through their dedicated routes// (/api/auth/password, /api/github/secrets, etc.).- const { secrets: _ignoredSecrets, ...settingsPatch } = req.body || {};+ const { secrets: _ignoredSecrets, catalogUserTypes: _ignoredTypes, ...settingsPatch } = req.body || {};const merged = await updateSettings(settingsPatch);// The queue caches codex.parallelLimit in-process; sync it from the// merged value so a save takes effect without a restart and withoutdiff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex c8752aae6f..f19eabcb3c 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -615,3 +615,22 @@ CREATE TABLE IF NOT EXISTS media_assets (-- created_at DESC is the gallery/history sort order; kind narrows-- images-vs-videos. A composite (kind, created_at DESC) serves both.CREATE INDEX IF NOT EXISTS idx_media_assets_kind_created ON media_assets (kind, created_at DESC);++-- Catalog user-defined types (Phase 4 lead-in, issue #1001). One row per+-- user-defined ingredient type — the registry that defines catalog row+-- semantics, moved out of data/settings.json (`catalogUserTypes`) so type+-- evolution versions/syncs alongside the catalog data it governs. `id` is the+-- type discriminator (the `type` column on catalog_ingredients + the+-- `cat-<prefix>-<uuid>` mint seed); the full definition lives in `data` JSONB.+-- updated_at / deleted_at mirror the federation LWW clock + tombstone (a+-- soft-deleted type is KEPT as a tombstone row so the deletion federates —+-- setUserCatalogTypes filters tombstones out of the active registry). ≤64 rows,+-- read whole on every warm/sync, so no secondary index. Mirrors the+-- catalog_user_types block in db.js ensureSchema().+CREATE TABLE IF NOT EXISTS catalog_user_types (+ id TEXT PRIMARY KEY,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ DEFAULT NOW()+);diff --git a/server/scripts/migrateCatalogUserTypesToDB.js b/server/scripts/migrateCatalogUserTypesToDB.jsnew file mode 100644index 0000000000..4a12534f72--- /dev/null+++ b/server/scripts/migrateCatalogUserTypesToDB.js@@ -0,0 +1,95 @@+/**+ * One-time importer: data/settings.json `catalogUserTypes` → PostgreSQL+ * (catalog_user_types), for Phase 4 lead-in / issue #1001.+ *+ * User-defined ingredient types used to live in the settings blob. As of #1001+ * they live one-row-per-type in Postgres. On the first PG-backed access (from+ * services/catalogUserTypes/store.js, BEFORE the boot registry warm reads any+ * type), this importer copies each legacy type into the table.+ *+ * Idempotency / safety:+ * - The MARKER is the absence of the legacy `catalogUserTypes` key in+ * settings.json. Reading settings is already cheap + done at boot, so no+ * separate marker file is needed (unlike the CD import, whose legacy state+ * was a standalone file). A fresh install (no key) no-ops immediately.+ * - INSERT … ON CONFLICT (id) DO NOTHING — a type already in the table (a+ * partial prior run that crashed before the key was renamed) is never+ * clobbered. The DB row is authoritative once it exists.+ * - The legacy slice is RENAMED in place to `catalogUserTypes_imported` (not+ * deleted) so it survives as a read-only recovery source for at least one+ * release (Phase 5 note) — mirroring the CD import's `.imported` file+ * rename. No live consumer reads the renamed key, so it can't drift or+ * resurrect stale types via the settings:updated registry refresh.+ * - The rename happens AFTER all rows land, so a crash mid-import leaves the+ * live key in place → next boot retries (ON CONFLICT DO NOTHING makes the+ * retry safe). The key is renamed ONLY if every insert succeeded.+ *+ * NOT marker-gated via data/migrations.applied.json: that list is the+ * prompt-replace runner under scripts/migrations/ and runs before the DB gate.+ * This import must run only when Postgres is the confirmed-healthy backend, so+ * it's gated on the settings-key presence and invoked from the backend selector+ * (mirrors migrateCreativeDirectorToDB).+ */++import { query } from '../lib/db.js';+import { mirrorTimestamp } from '../lib/pgTimestamp.js';+import { getSettings, updateSettingsWith } from '../services/settings.js';++const LEGACY_KEY = 'catalogUserTypes';+const IMPORTED_KEY = 'catalogUserTypes_imported';++// Remove the live legacy key, parking its value under the recovery key — but+// NEVER overwrite an existing recovery copy. The original (pre-migration) slice+// is the one worth keeping for a release; a later re-introduced legacy key (a+// restore bundle / hand-edit landing after the migration already ran) is just+// dropped, not promoted over the original recovery copy it would otherwise+// clobber. The DB rows are authoritative regardless.+const renameLegacyAside = (cur) => {+ const { [LEGACY_KEY]: old, ...rest } = cur;+ if (rest[IMPORTED_KEY] !== undefined) return rest; // keep the original recovery copy+ return { ...rest, [IMPORTED_KEY]: old };+};++export async function migrateCatalogUserTypesToDB() {+ const settings = await getSettings();+ const legacy = settings[LEGACY_KEY];++ // No legacy key → already imported on a prior boot, or a fresh install.+ if (legacy === undefined) return { ok: true, reason: 'already-applied', imported: 0 };++ if (!Array.isArray(legacy)) {+ // A hand-edited non-array shouldn't block boot. Rename it aside so the+ // garbage can't keep feeding the registry, but import nothing.+ console.warn(`⚠️ catalog-user-types→DB import: settings.${LEGACY_KEY} is not an array — renaming aside, imported 0`);+ await updateSettingsWith(renameLegacyAside);+ return { ok: false, reason: 'not-an-array', imported: 0 };+ }++ let imported = 0;+ let skipped = 0;+ for (const type of legacy) {+ if (!type || typeof type !== 'object' || typeof type.id !== 'string' || !type.id) {+ skipped += 1;+ continue;+ }+ // Import verbatim — the full definition goes into `data`. The typed mirror+ // columns are bind-sanitized so a hand-edited timestamp can't make the+ // INSERT throw and abort the whole import (which runs during backend init).+ const result = await query(+ `INSERT INTO catalog_user_types (id, data, updated_at, deleted_at)+ VALUES ($1, $2::jsonb, COALESCE($3::timestamptz, NOW()), $4)+ ON CONFLICT (id) DO NOTHING`,+ [type.id, JSON.stringify(type), mirrorTimestamp(type.updatedAt, null), mirrorTimestamp(type.deletedAt, null)],+ );+ if (result.rowCount > 0) imported += 1;+ else skipped += 1;+ }++ // Rename the legacy key aside AFTER all rows land (so a crash mid-import+ // leaves the live key in place → next boot retries the idempotent import).+ // Preserves the original recovery copy if one already exists (see helper).+ await updateSettingsWith(renameLegacyAside);++ console.log(`🧩 catalog-user-types→DB import: imported ${imported} type(s) into catalog_user_types (${skipped} skipped); settings.${LEGACY_KEY} renamed to ${IMPORTED_KEY}`);+ return { ok: true, reason: 'imported', imported, skipped };+}diff --git a/server/scripts/migrateCatalogUserTypesToDB.test.js b/server/scripts/migrateCatalogUserTypesToDB.test.jsnew file mode 100644index 0000000000..963c5f3b2e--- /dev/null+++ b/server/scripts/migrateCatalogUserTypesToDB.test.js@@ -0,0 +1,105 @@+/**+ * Unit tests for the settings.catalogUserTypes → catalog_user_types importer+ * (#1001). Pure — the DB `query` and the settings service are mocked, so the+ * suite asserts the import semantics (verbatim copy, ON CONFLICT idempotency,+ * key rename-aside, crash-before-rename retry) without Postgres or disk.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++let store = {};+const inserted = [];+let insertRowCount = 1;++vi.mock('../services/settings.js', () => ({+ getSettings: vi.fn(async () => ({ ...store })),+ updateSettingsWith: vi.fn(async (mutate) => { store = await mutate({ ...store }); return store; }),+}));+vi.mock('../lib/db.js', () => ({+ query: vi.fn(async (_sql, params) => {+ inserted.push(params);+ return { rowCount: insertRowCount };+ }),+}));++const { migrateCatalogUserTypesToDB } = await import('./migrateCatalogUserTypesToDB.js');++beforeEach(() => {+ store = {};+ inserted.length = 0;+ insertRowCount = 1;+});++describe('migrateCatalogUserTypesToDB', () => {+ it('no-ops on a fresh install (no legacy key)', async () => {+ const res = await migrateCatalogUserTypesToDB();+ expect(res).toMatchObject({ ok: true, reason: 'already-applied', imported: 0 });+ expect(inserted).toHaveLength(0);+ expect(store.catalogUserTypes_imported).toBeUndefined();+ });++ it('imports each legacy type verbatim and renames the key aside', async () => {+ store = { catalogUserTypes: [+ { id: 'faction', label: 'Faction', updatedAt: '2026-01-01T00:00:00.000Z' },+ { id: 'guild', label: 'Guild' },+ ] };+ const res = await migrateCatalogUserTypesToDB();+ expect(res).toMatchObject({ ok: true, reason: 'imported', imported: 2 });+ expect(inserted).toHaveLength(2);+ // First param of each INSERT is the id, second is the verbatim JSON.+ expect(inserted.map((p) => p[0])).toEqual(['faction', 'guild']);+ expect(JSON.parse(inserted[0][1])).toMatchObject({ id: 'faction', label: 'Faction' });+ // Live key gone, recovery key holds the original slice.+ expect(store.catalogUserTypes).toBeUndefined();+ expect(store.catalogUserTypes_imported).toHaveLength(2);+ });++ it('is idempotent on re-run: the renamed key means a second call no-ops', async () => {+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction' }] };+ await migrateCatalogUserTypesToDB();+ inserted.length = 0;+ const res = await migrateCatalogUserTypesToDB();+ expect(res.reason).toBe('already-applied');+ expect(inserted).toHaveLength(0);+ });++ it('skips structurally-invalid entries but still imports the good ones', async () => {+ store = { catalogUserTypes: [{ id: 'ok', label: 'OK' }, { label: 'no id' }, null, { id: '' }] };+ const res = await migrateCatalogUserTypesToDB();+ expect(res.imported).toBe(1);+ expect(res.skipped).toBe(3);+ expect(inserted.map((p) => p[0])).toEqual(['ok']);+ });++ it('counts an ON CONFLICT no-op (rowCount 0) as skipped, not imported', async () => {+ insertRowCount = 0; // row already in the table+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction' }] };+ const res = await migrateCatalogUserTypesToDB();+ expect(res.imported).toBe(0);+ expect(res.skipped).toBe(1);+ // Still renames the key aside — the rows are present in the table.+ expect(store.catalogUserTypes_imported).toHaveLength(1);+ });++ it('does NOT clobber an existing recovery copy when a legacy key is re-introduced', async () => {+ // Migration already ran once: original recovery copy parked.+ store = { catalogUserTypes_imported: [{ id: 'original', label: 'Original' }] };+ // A restore bundle / hand-edit re-introduces the live key post-migration.+ store.catalogUserTypes = [{ id: 'reintroduced', label: 'Reintroduced' }];+ const res = await migrateCatalogUserTypesToDB();+ expect(res.reason).toBe('imported');+ // Live key dropped, but the ORIGINAL recovery copy is preserved (not+ // overwritten by the reintroduced slice).+ expect(store.catalogUserTypes).toBeUndefined();+ expect(store.catalogUserTypes_imported).toEqual([{ id: 'original', label: 'Original' }]);+ });++ it('renames aside a non-array legacy value without importing', async () => {+ store = { catalogUserTypes: { hand: 'edited' } };+ const res = await migrateCatalogUserTypesToDB();+ expect(res).toMatchObject({ ok: false, reason: 'not-an-array', imported: 0 });+ expect(inserted).toHaveLength(0);+ expect(store.catalogUserTypes).toBeUndefined();+ expect(store.catalogUserTypes_imported).toEqual({ hand: 'edited' });+ });+});diff --git a/server/services/catalogSync.js b/server/services/catalogSync.jsindex cc8cd876ff..1c62b5f6e7 100644--- a/server/services/catalogSync.js+++ b/server/services/catalogSync.js@@ -49,7 +49,7 @@ import {import { compareSchemaVersions, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';import { friendlifyUniverseTags, LEGACY_UNIVERSE_MARKER_TAG } from '../lib/catalogUniverseTags.js';import { canonicalTagKey, setUserCatalogTypes, INGREDIENT_TYPE_IDS } from '../lib/catalogTypes.js';-import { getSettings, updateSettings } from './settings.js';+import { readUserTypes as readUserTypeSlice, writeUserTypes } from './catalogUserTypes/store.js';const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs', 'relations', 'tags', 'media'];@@ -97,11 +97,14 @@ export async function getChangesSince(since = '0', limit = 100) {// receiver can spot `savedCursor > tableMax` and rewind. One cheap MAX query.const tableMaxSequences = await getMaxSequences();- // User-defined type definitions ride EVERY envelope (settings-sourced, not- // sequence-tracked — there are at most 64 and they're small). The receiver- // LWW-merges them into its own settings slice. Absent → empty array.- const settings = await getSettings();- const catalogTypes = Array.isArray(settings.catalogUserTypes) ? settings.catalogUserTypes : [];+ // User-defined type definitions ride EVERY envelope (not sequence-tracked —+ // there are at most 64 and they're small). The receiver LWW-merges them into+ // its own user-type store. Absent → empty array. (The wire shape is storage-+ // independent: #1001 moved the local store from settings.json to Postgres+ // without changing this `catalogTypes` block, so peers interoperate across+ // the migration with no schema-version bump.)+ const catalogTypesRaw = await readUserTypeSlice();+ const catalogTypes = Array.isArray(catalogTypesRaw) ? catalogTypesRaw : [];return {catalogTypes,@@ -322,8 +325,8 @@ export async function applyRemoteChanges(envelope = {}) {* skipped, failed }`.*/export async function applyUserTypesFromPeer(incoming = []) {- const settings = await getSettings();- const local = Array.isArray(settings.catalogUserTypes) ? settings.catalogUserTypes : [];+ const localRaw = await readUserTypeSlice();+ const local = Array.isArray(localRaw) ? localRaw : [];const byId = new Map(local.map((t) => [t.id, t]));let applied = 0;let skipped = 0;@@ -353,7 +356,7 @@ export async function applyUserTypesFromPeer(incoming = []) {}if (applied > 0) {const next = [...byId.values()];- await updateSettings({ catalogUserTypes: next });+ await writeUserTypes(next);setUserCatalogTypes(next);console.log(`🧩 Catalog sync: merged ${applied} user type(s) from peer`);}diff --git a/server/services/catalogUserTypes/db.js b/server/services/catalogUserTypes/db.jsnew file mode 100644index 0000000000..85063bc118--- /dev/null+++ b/server/services/catalogUserTypes/db.js@@ -0,0 +1,75 @@+/**+ * Catalog user-defined types — PostgreSQL backend (#1001).+ *+ * One row per type in `catalog_user_types`: `id` PK, the full definition in+ * `data` JSONB, and updated_at / deleted_at mirrored into columns (the+ * federation LWW clock + tombstone). Reads return `data` verbatim so callers+ * (the CRUD routes, the sync merge, `setUserCatalogTypes`) see the exact same+ * `{ id, label, primaryContentKey, fields, updatedAt?, deletedAt? }` shape the+ * settings slice gave — the columns are a queryable mirror, never read back.+ *+ * Concurrency: single-user install, but the early boot warm, a sync pull, and a+ * route write can still overlap. `writeUserTypes` is whole-slice authoritative,+ * so it runs in one transaction (upsert everything in the list + delete any row+ * whose id left the list) — a partial apply can't leave the table half-updated.+ */++import { query, withTransaction } from '../../lib/db.js';+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';++function rowToType(row) {+ // `data` already holds id/label/primaryContentKey/fields/updatedAt/deletedAt;+ // return it verbatim so the shape matches the settings backend exactly.+ return row.data;+}++/**+ * Full user-type slice (live + tombstones), verbatim. Ordered created_at ASC+ * then id so the active registry's user-type display order is stable across+ * reads (the settings slice was insertion-ordered; created_at preserves that).+ */+export async function readUserTypes() {+ const { rows } = await query(+ `SELECT data FROM catalog_user_types ORDER BY created_at ASC, id ASC`,+ );+ return rows.map(rowToType);+}++/**+ * Persist the whole user-type slice as the authoritative end state: upsert+ * every entry in `list`, then delete any DB row whose id is no longer present.+ * A null/non-array clears the table (matches the settings backend writing `[]`).+ * `deleted_at` is the tombstone column — a deleted-but-retained entry (with a+ * `deletedAt` in its data) stays a row so the deletion keeps federating.+ */+export async function writeUserTypes(list) {+ const types = Array.isArray(list) ? list.filter((t) => t && typeof t.id === 'string' && t.id) : [];+ await withTransaction(async (client) => {+ const exec = client.query.bind(client);+ const keepIds = [];+ for (const t of types) {+ keepIds.push(t.id);+ // The typed mirror columns are bind-sanitized so a hand-edited/legacy+ // record with a malformed timestamp can't make the INSERT throw and abort+ // the whole slice write (which runs during boot warm). `data` is verbatim.+ const updatedAt = mirrorTimestamp(t.updatedAt, null);+ const deletedAt = mirrorTimestamp(t.deletedAt, null);+ await exec(+ `INSERT INTO catalog_user_types (id, data, updated_at, deleted_at)+ VALUES ($1, $2::jsonb, COALESCE($3::timestamptz, NOW()), $4)+ ON CONFLICT (id) DO UPDATE SET+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at,+ deleted_at = EXCLUDED.deleted_at`,+ [t.id, JSON.stringify(t), updatedAt, deletedAt],+ );+ }+ // Prune rows that left the desired slice. With keepIds empty the whole+ // table clears; otherwise delete everything NOT in the list.+ if (keepIds.length === 0) {+ await exec(`DELETE FROM catalog_user_types`);+ } else {+ await exec(`DELETE FROM catalog_user_types WHERE id <> ALL($1::text[])`, [keepIds]);+ }+ });+}diff --git a/server/services/catalogUserTypes/db.test.js b/server/services/catalogUserTypes/db.test.jsnew file mode 100644index 0000000000..0fe314ce50--- /dev/null+++ b/server/services/catalogUserTypes/db.test.js@@ -0,0 +1,104 @@+/**+ * Postgres-backed round-trip for the catalog user-type store (#1001).+ *+ * Like projectsDB.test.js / mediaAssetIndex/db.test.js, this needs a live+ * PostgreSQL with the schema applied. If no DB is reachable (CI, fresh+ * checkout) it SKIPS cleanly rather than failing red. When a DB IS reachable it+ * exercises the whole-slice writeUserTypes contract: upsert-everything ++ * prune-departed, tombstone retention, and verbatim readback. It snapshots and+ * restores the table so a developer's real user types survive the run.+ */++import { describe, it, expect, afterAll, beforeAll, beforeEach } from 'vitest';+import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else {+ await ensureSchema().catch(() => {});+ const probe = await query(+ `SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = 'catalog_user_types') AS ok`,+ ).catch(() => ({ rows: [{ ok: false }] }));+ if (probe.rows?.[0]?.ok) dbReady = true;+ else skipReason = 'catalog_user_types table not present';+ }+}++if (!dbReady) console.log(`⏭️ catalogUserTypes/db.test.js skipped: ${skipReason}`);++const T = (id, extra = {}) => ({ id, label: id, primaryContentKey: 'description', fields: [], ...extra });++describe.skipIf(!dbReady)('catalog user-type DB round-trip', () => {+ let db;+ let snapshot = [];+ beforeAll(async () => {+ db = await import('./db.js');+ const res = await query(`SELECT id, data, updated_at, deleted_at, created_at FROM catalog_user_types`);+ snapshot = res.rows;+ });++ beforeEach(async () => {+ await query(`DELETE FROM catalog_user_types`);+ });++ afterAll(async () => {+ await query(`DELETE FROM catalog_user_types`).catch(() => {});+ for (const r of snapshot) {+ await query(+ `INSERT INTO catalog_user_types (id, data, updated_at, deleted_at, created_at)+ VALUES ($1, $2::jsonb, $3, $4, $5) ON CONFLICT (id) DO NOTHING`,+ [r.id, JSON.stringify(r.data), r.updated_at, r.deleted_at, r.created_at],+ ).catch(() => {});+ }+ await close();+ });++ it('writes the whole slice and reads it back verbatim', async () => {+ const slice = [T('faction', { updatedAt: '2026-01-01T00:00:00.000Z' }), T('guild')];+ await db.writeUserTypes(slice);+ const back = await db.readUserTypes();+ expect(back.map((t) => t.id).sort()).toEqual(['faction', 'guild']);+ expect(back.find((t) => t.id === 'faction')).toMatchObject({ label: 'faction', updatedAt: '2026-01-01T00:00:00.000Z' });+ });++ it('prunes a row whose id left the slice (whole-slice is authoritative)', async () => {+ await db.writeUserTypes([T('a'), T('b'), T('c')]);+ await db.writeUserTypes([T('a'), T('c')]); // b departed+ const ids = (await db.readUserTypes()).map((t) => t.id).sort();+ expect(ids).toEqual(['a', 'c']);+ });++ it('clears the table when given an empty slice (or null)', async () => {+ await db.writeUserTypes([T('a')]);+ await db.writeUserTypes([]);+ expect(await db.readUserTypes()).toHaveLength(0);+ await db.writeUserTypes([T('a')]);+ await db.writeUserTypes(null);+ expect(await db.readUserTypes()).toHaveLength(0);+ });++ it('retains a tombstone row (deletedAt set) so the deletion can keep federating', async () => {+ await db.writeUserTypes([T('faction', { deletedAt: '2026-06-01T00:00:00.000Z', updatedAt: '2026-06-01T00:00:00.000Z' })]);+ const back = await db.readUserTypes();+ expect(back).toHaveLength(1);+ expect(back[0].deletedAt).toBe('2026-06-01T00:00:00.000Z');+ // The tombstone column mirrors the data tombstone for queryability.+ const { rows } = await query(`SELECT deleted_at FROM catalog_user_types WHERE id = 'faction'`);+ expect(rows[0].deleted_at).not.toBeNull();+ });++ it('tolerates a malformed updatedAt without throwing (bind-safe mirror columns)', async () => {+ await expect(db.writeUserTypes([T('faction', { updatedAt: 'not-a-date' })])).resolves.not.toThrow();+ const { rows } = await query(`SELECT updated_at FROM catalog_user_types WHERE id = 'faction'`);+ expect(rows[0].updated_at).not.toBeNull(); // fell back to NOW()+ });++ it('skips an entry with no usable id', async () => {+ await db.writeUserTypes([T('ok'), { label: 'no id' }, { id: '' }, null]);+ expect((await db.readUserTypes()).map((t) => t.id)).toEqual(['ok']);+ });+});diff --git a/server/services/catalogUserTypes/store.js b/server/services/catalogUserTypes/store.jsnew file mode 100644index 0000000000..71719e6fde--- /dev/null+++ b/server/services/catalogUserTypes/store.js@@ -0,0 +1,107 @@+/**+ * Catalog user-defined types — storage backend dispatcher (#1001).+ *+ * User-defined ingredient types used to live in data/settings.json under the+ * `catalogUserTypes` array. As of Phase 4 lead-in (#1001) they live one-row-+ * per-type in PostgreSQL (`catalog_user_types`) so type evolution versions and+ * syncs alongside the catalog data it governs, instead of riding the unrelated+ * settings blob. This module is a thin dispatcher — mirroring CD's local.js and+ * memoryBackend.js — so the two consumers (the `/api/catalog/types` CRUD routes+ * and the catalog federation sync) read/write the slice through ONE contract+ * regardless of backend.+ *+ * The contract is intentionally the same whole-slice shape the settings store+ * had: `readUserTypes()` returns the full array (live entries AND tombstones,+ * verbatim — `setUserCatalogTypes` filters tombstones out of the active+ * registry), and `writeUserTypes(list)` persists the whole array authoritatively+ * (the list IS the desired end state — upsert everything in it, drop any DB row+ * whose id left the list). With ≤64 types that's a couple of round-trips.+ *+ * Backend selection (same posture as the memory + CD backends):+ * - PostgreSQL (db.js) for normal installs.+ * - File (settings.json via the settings service) only under+ * MEMORY_BACKEND=file (escape hatch) or NODE_ENV=test — both UNSUPPORTED for+ * production. Tests boot without a DB, so they keep exercising the settings+ * slice exactly as before, and the existing route/sync suites pass unchanged.+ *+ * The first PG-backed call runs a one-time, marker-gated import of any legacy+ * settings.catalogUserTypes slice into the table (migrateCatalogUserTypesToDB),+ * 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';+}++// settings.json-backed implementation (escape hatch / tests). Byte-identical to+// the behavior the catalog routes + sync had inline before #1001, so nothing+// observable changes when no Postgres is present.+async function fileBackend() {+ const { getSettings, updateSettings } = await import('../settings.js');+ return {+ name: 'file',+ readUserTypes: async () => {+ const settings = await getSettings();+ return Array.isArray(settings.catalogUserTypes) ? settings.catalogUserTypes : [];+ },+ writeUserTypes: async (list) => {+ await updateSettings({ catalogUserTypes: Array.isArray(list) ? list : [] });+ },+ };+}++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;+}++/** Active backend name, or null before first call (diagnostics/tests). */+export function getCatalogUserTypesBackendName() {+ return backend?.name ?? null;+}++/** Reset cached backend selection — test seam only. */+export function _resetCatalogUserTypesBackend() {+ backend = null;+ selecting = null;+}++/** Full user-type slice (live + tombstones), verbatim. */+export async function readUserTypes() {+ return (await selectBackend()).readUserTypes();+}++/** Persist the whole user-type slice as the authoritative end state. */+export async function writeUserTypes(list) {+ return (await selectBackend()).writeUserTypes(list);+}diff --git a/server/services/catalogUserTypes/store.test.js b/server/services/catalogUserTypes/store.test.jsnew file mode 100644index 0000000000..8e7d7e09e0--- /dev/null+++ b/server/services/catalogUserTypes/store.test.js@@ -0,0 +1,54 @@+/**+ * Backend-dispatcher tests for the catalog user-type store (#1001).+ *+ * Under NODE_ENV=test the store selects the FILE backend (settings.json via the+ * settings service), so this suite asserts the dispatcher routes read/write to+ * the settings slice exactly as the routes/sync did inline before #1001 — the+ * back-compat guarantee that keeps the existing test suites green. settings is+ * mocked, so no disk/Postgres is touched.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++let store = {};+vi.mock('../settings.js', () => ({+ getSettings: vi.fn(async () => ({ ...store })),+ updateSettings: vi.fn(async (patch) => { store = { ...store, ...patch }; return { ...store }; }),+}));++const { readUserTypes, writeUserTypes, getCatalogUserTypesBackendName, _resetCatalogUserTypesBackend } =+ await import('./store.js');++beforeEach(() => {+ store = {};+ _resetCatalogUserTypesBackend();+});++describe('catalog user-type store — file backend (test/escape-hatch)', () => {+ it('selects the file backend under NODE_ENV=test', async () => {+ await readUserTypes();+ expect(getCatalogUserTypesBackendName()).toBe('file');+ });++ it('reads the catalogUserTypes slice from settings (absent → [])', async () => {+ expect(await readUserTypes()).toEqual([]);+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction' }] };+ expect(await readUserTypes()).toEqual([{ id: 'faction', label: 'Faction' }]);+ });++ it('tolerates a non-array slice (junk → [])', async () => {+ store = { catalogUserTypes: { not: 'an array' } };+ expect(await readUserTypes()).toEqual([]);+ });++ it('writes the whole slice back into settings.catalogUserTypes', async () => {+ await writeUserTypes([{ id: 'a' }, { id: 'b' }]);+ expect(store.catalogUserTypes).toEqual([{ id: 'a' }, { id: 'b' }]);+ });++ it('a null/non-array write persists an empty slice', async () => {+ store = { catalogUserTypes: [{ id: 'a' }] };+ await writeUserTypes(null);+ expect(store.catalogUserTypes).toEqual([]);+ });+});