Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(catalog): user-defined ingredient types, merged into the registry at runtime and federated

[._.]/ Adam Eivy9e9950a44d1d
diff --git a/server/index.js b/server/index.js
index 3bb94facbf..dc9efb7dde 100644
--- a/server/index.js
+++ b/server/index.js
@@ -137,7 +137,8 @@ import * as cos from './services/cos.js';
import { startBackupScheduler } from './services/backupScheduler.js';
import * as telegram from './services/telegram.js';
import * as telegramBridge from './services/telegramBridge.js';
-import { getSettings as getInitSettings } from './services/settings.js';
+import { getSettings as getInitSettings, settingsEvents } from './services/settings.js';
+import { setUserCatalogTypes } from './lib/catalogTypes.js';
import { startUpdateScheduler, recordUpdateResult, clearStaleUpdateInProgress, getCurrentVersion } from './services/updateChecker.js';
import { restoreLoops } from './services/loops.js';
import { startBrainScheduler } from './services/brainScheduler.js';
@@ -499,6 +500,18 @@ initBrainMemoryBridge();
initDrillCache().catch(err => console.error(`❌ POST drill cache init failed: ${err.message}`));
// Initialize backup scheduler for daily data backups
startBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));
+// 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 || []))
+ .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') {
diff --git a/server/lib/catalogTypes.js b/server/lib/catalogTypes.js
index 029b257d9c..ce36e952eb 100644
--- a/server/lib/catalogTypes.js
+++ b/server/lib/catalogTypes.js
@@ -167,21 +167,151 @@ for (const t of REGISTRY) {
}
}
-export const CATALOG_TYPES = Object.freeze(REGISTRY.map((t) => Object.freeze({ ...t })));
+// Every static entry is a SYSTEM type — tagged `system: true` so the runtime
+// merge (system + user-defined) can tell built-ins from settings-defined types
+// without comparing against the id list. The parity test + DDL-literal test
+// depend on this static export staying the six built-ins ONLY; user types live
+// purely in the runtime layer below, never spliced into REGISTRY.
+export const CATALOG_TYPES = Object.freeze(REGISTRY.map((t) => Object.freeze({ ...t, system: true })));
/** Frozen ordered list of type ids — the canonical `INGREDIENT_TYPES`. */
export const INGREDIENT_TYPE_IDS = Object.freeze(CATALOG_TYPES.map((t) => t.id));
const BY_ID = Object.freeze(Object.fromEntries(CATALOG_TYPES.map((t) => [t.id, t])));
-/** Look up a registry entry by type id. Returns `undefined` for unknown ids. */
+// Reserved system idPrefixes — a user type's minted idPrefix must never collide
+// with these (chr/plc/obj/idea/scn/cnc) or two types would share the
+// `cat-<prefix>-<uuid>` namespace. Also reserve `scrap`/`rev`/`tag` (used by
+// other catalog id mints) so a user type can't shadow them.
+const SYSTEM_ID_PREFIXES = new Set([...CATALOG_TYPES.map((t) => t.idPrefix), 'scrap', 'rev', 'tag']);
+const SYSTEM_TYPE_IDS = new Set(INGREDIENT_TYPE_IDS);
+
+/** Look up a SYSTEM registry entry by type id. Returns `undefined` for unknown ids. */
export function getCatalogType(id) {
return BY_ID[id];
}
-/** Mint the `cat-<prefix>-<uuid>` id for a type, or throw on unknown type. */
+// --- 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`.
+// 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
+// guards) go through `getActiveCatalogType`/`isActiveType` instead.
+
+/** Field kinds a user type may declare. Drives the generic editor renderer. */
+export const USER_TYPE_FIELD_KINDS = Object.freeze(['string', 'longtext', 'tags', 'ref']);
+
+// Deterministic, collision-free idPrefix for a user type. Derives a short slug
+// from the type id, then disambiguates against the reserved system prefixes (and
+// any prefixes already minted in THIS merge pass) by appending `2`, `3`, … —
+// so the minted `cat-<prefix>-<uuid>` namespace never overlaps a system type.
+function deriveUserIdPrefix(id, taken) {
+ const base = String(id || '').toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 4) || 'utyp';
+ let prefix = base;
+ let n = 1;
+ while (SYSTEM_ID_PREFIXES.has(prefix) || taken.has(prefix)) {
+ n += 1;
+ prefix = `${base}${n}`;
+ }
+ return prefix;
+}
+
+/**
+ * Map a settings entry `{ id, label, primaryContentKey, fields[] }` to the
+ * internal registry shape used by every active-type consumer. `taken` is the
+ * set of idPrefixes already minted in this merge pass (mutated here) so two
+ * user types can't collide on their derived prefix. Returns `null` for a
+ * structurally-invalid entry (missing id / label) so the merge can skip it.
+ */
+export function normalizeUserType(raw, taken = new Set()) {
+ if (!raw || typeof raw !== 'object') return null;
+ const id = typeof raw.id === 'string' ? raw.id.trim() : '';
+ const label = typeof raw.label === 'string' ? raw.label.trim() : '';
+ if (!id || !label) return null;
+ const primaryContentKey = typeof raw.primaryContentKey === 'string' && raw.primaryContentKey.trim()
+ ? raw.primaryContentKey.trim()
+ : 'description';
+ const fields = Array.isArray(raw.fields)
+ ? raw.fields.filter((f) => f && typeof f.key === 'string' && f.key.trim())
+ : [];
+ // snippet fallback chain: primary content key first, then every longtext key
+ // (richest prose), de-duplicated. Always at least the primary key.
+ const snippetFallbackKeys = [];
+ for (const k of [primaryContentKey, ...fields.filter((f) => f.kind === 'longtext').map((f) => f.key)]) {
+ if (k && !snippetFallbackKeys.includes(k)) snippetFallbackKeys.push(k);
+ }
+ const idPrefix = deriveUserIdPrefix(id, taken);
+ taken.add(idPrefix);
+ return Object.freeze({
+ id,
+ label,
+ idPrefix,
+ badgeColor: 'bg-gray-500/20 text-gray-300 border-gray-500/40',
+ primaryContentKey,
+ primaryContentLabel: fields.find((f) => f.key === primaryContentKey)?.label || 'Description',
+ snippetFallbackKeys,
+ ftsFields: [],
+ extractionShape: 'light',
+ payloadSchemaVersion: 1,
+ payloadUpgraders: {},
+ defaultTags: [],
+ system: false,
+ fields: Object.freeze(fields.map((f) => Object.freeze({
+ key: String(f.key).trim(),
+ label: typeof f.label === 'string' && f.label.trim() ? f.label.trim() : String(f.key).trim(),
+ kind: USER_TYPE_FIELD_KINDS.includes(f.kind) ? f.kind : 'string',
+ ...(Number.isInteger(f.maxLength) ? { maxLength: f.maxLength } : {}),
+ }))),
+ });
+}
+
+// Module-level mutable set of active user types (system types are static). The
+// active registry is system-first, then user types in declaration order. A user
+// type whose id collides with a system id is skipped (system always wins).
+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, or duplicate
+ * an earlier user id.
+ */
+export function setUserCatalogTypes(list = []) {
+ const taken = new Set();
+ const out = [];
+ const seen = new Set();
+ for (const raw of Array.isArray(list) ? list : []) {
+ const normalized = normalizeUserType(raw, taken);
+ if (!normalized) continue;
+ if (SYSTEM_TYPE_IDS.has(normalized.id) || seen.has(normalized.id)) continue;
+ seen.add(normalized.id);
+ out.push(normalized);
+ }
+ activeUserTypes = out;
+ return activeUserTypes;
+}
+
+/** Active (system + user) types as an ordered list — system first. */
+export function getActiveCatalogTypes() {
+ return [...CATALOG_TYPES, ...activeUserTypes];
+}
+
+/** Look up an active (system OR user) type by id. Returns `undefined` if unknown. */
+export function getActiveCatalogType(id) {
+ return BY_ID[id] || activeUserTypes.find((t) => t.id === id);
+}
+
+/** True when `id` names an active system OR user type. */
+export function isActiveType(id) {
+ return Boolean(getActiveCatalogType(id));
+}
+
+/** Mint the `cat-<prefix>-<uuid>` id for a type, or throw on unknown type.
+ * Resolves system AND active user types so a user-typed create mints a valid id. */
export function ingredientIdPrefix(id) {
- const t = BY_ID[id];
+ const t = getActiveCatalogType(id);
if (!t) throw new Error(`Unknown ingredient type: ${id}`);
return t.idPrefix;
}
@@ -201,9 +331,10 @@ export const FTS_PAYLOAD_FIELDS = Object.freeze((() => {
return out;
})());
-/** Current payload-shape version for a type (1 when the type declares none). */
+/** Current payload-shape version for a type (1 when the type declares none).
+ * Resolves system AND user types (user types are payloadSchemaVersion 1). */
export function currentPayloadSchemaVersion(id) {
- return BY_ID[id]?.payloadSchemaVersion ?? 1;
+ return getActiveCatalogType(id)?.payloadSchemaVersion ?? 1;
}
/**
@@ -213,7 +344,7 @@ export function currentPayloadSchemaVersion(id) {
* caller can mutate/merge without poisoning the registry. Unknown type → `[]`.
*/
export function defaultTagsForType(id) {
- return [...(BY_ID[id]?.defaultTags || [])];
+ return [...(getActiveCatalogType(id)?.defaultTags || [])];
}
// --- Tag taxonomy --------------------------------------------------------
diff --git a/server/lib/catalogTypes.test.js b/server/lib/catalogTypes.test.js
index 95979787a5..d8d2f2a3ad 100644
--- a/server/lib/catalogTypes.test.js
+++ b/server/lib/catalogTypes.test.js
@@ -33,9 +33,17 @@ import {
canonicalTagKey,
tagIdForKey,
defaultTagsForType,
+ USER_TYPE_FIELD_KINDS,
+ normalizeUserType,
+ setUserCatalogTypes,
+ getActiveCatalogTypes,
+ getActiveCatalogType,
+ isActiveType,
} from './catalogTypes.js';
import { INGREDIENT_TYPES } from './catalogValidation.js';
+import { afterEach } from 'vitest';
+
const HERE = dirname(fileURLToPath(import.meta.url));
const INIT_SQL = readFileSync(join(HERE, '..', 'scripts', 'init-db.sql'), 'utf8');
const DB_JS = readFileSync(join(HERE, 'db.js'), 'utf8');
@@ -250,6 +258,84 @@ describe('catalogTypes — relation kinds', () => {
});
});
+describe('catalogTypes — user-defined types (runtime layer)', () => {
+ afterEach(() => setUserCatalogTypes([]));
+
+ it('tags every static entry system:true and never splices user types into CATALOG_TYPES', () => {
+ for (const t of CATALOG_TYPES) expect(t.system).toBe(true);
+ setUserCatalogTypes([{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }]);
+ // The static export is unchanged — user types live only in the runtime layer.
+ expect(CATALOG_TYPES.map((t) => t.id)).toEqual(['character', 'place', 'object', 'idea', 'scene', 'concept']);
+ expect(CATALOG_TYPES.some((t) => t.id === 'faction')).toBe(false);
+ });
+
+ it('USER_TYPE_FIELD_KINDS are the four documented kinds', () => {
+ expect([...USER_TYPE_FIELD_KINDS]).toEqual(['string', 'longtext', 'tags', 'ref']);
+ });
+
+ it('normalizeUserType maps a settings entry to the internal registry shape', () => {
+ const t = normalizeUserType({
+ id: 'faction', label: 'Faction', primaryContentKey: 'creed',
+ fields: [
+ { key: 'creed', label: 'Creed', kind: 'longtext' },
+ { key: 'leader', label: 'Leader', kind: 'ref' },
+ { key: 'motto', label: 'Motto', kind: 'string' },
+ ],
+ });
+ expect(t.system).toBe(false);
+ expect(t.extractionShape).toBe('light');
+ expect(t.payloadSchemaVersion).toBe(1);
+ expect(t.badgeColor).toMatch(/gray/);
+ expect(t.primaryContentLabel).toBe('Creed');
+ // snippet fallback: primary content key first, then longtext keys.
+ expect(t.snippetFallbackKeys[0]).toBe('creed');
+ // idPrefix never collides with a system prefix.
+ expect(['chr', 'plc', 'obj', 'idea', 'scn', 'cnc']).not.toContain(t.idPrefix);
+ expect(t.fields.map((f) => f.key)).toEqual(['creed', 'leader', 'motto']);
+ });
+
+ it('normalizeUserType returns null for a structurally invalid entry', () => {
+ expect(normalizeUserType(null)).toBeNull();
+ expect(normalizeUserType({ label: 'no id' })).toBeNull();
+ expect(normalizeUserType({ id: 'x' })).toBeNull();
+ });
+
+ it('setUserCatalogTypes merges system+user (system first) and resolves via active getters', () => {
+ setUserCatalogTypes([{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }]);
+ const active = getActiveCatalogTypes();
+ expect(active.slice(0, 6).map((t) => t.id)).toEqual([...INGREDIENT_TYPE_IDS]);
+ expect(active[active.length - 1].id).toBe('faction');
+ expect(getActiveCatalogType('faction')?.label).toBe('Faction');
+ expect(getActiveCatalogType('character')?.system).toBe(true);
+ expect(isActiveType('faction')).toBe(true);
+ expect(isActiveType('character')).toBe(true);
+ expect(isActiveType('nope')).toBe(false);
+ });
+
+ it('a user type colliding with a system id is skipped (system wins)', () => {
+ setUserCatalogTypes([{ id: 'character', label: 'Hijack', primaryContentKey: 'x', fields: [] }]);
+ // Still the system character (system:true), not the hijack.
+ expect(getActiveCatalogType('character')?.system).toBe(true);
+ expect(getActiveCatalogType('character')?.label).toBe('Character');
+ });
+
+ it('two user types deriving the same base prefix get distinct prefixes', () => {
+ setUserCatalogTypes([
+ { id: 'fact', label: 'Fact', primaryContentKey: 'x', fields: [] },
+ { id: 'fact-sheet', label: 'Fact Sheet', primaryContentKey: 'x', fields: [] },
+ ]);
+ const types = getActiveCatalogTypes().filter((t) => !t.system);
+ const prefixes = types.map((t) => t.idPrefix);
+ expect(new Set(prefixes).size).toBe(prefixes.length);
+ });
+
+ it('ingredientIdPrefix + currentPayloadSchemaVersion resolve active user types', () => {
+ setUserCatalogTypes([{ id: 'faction', label: 'Faction', primaryContentKey: 'x', fields: [] }]);
+ expect(() => ingredientIdPrefix('faction')).not.toThrow();
+ expect(currentPayloadSchemaVersion('faction')).toBe(1);
+ });
+});
+
describe('catalogTypes — media kinds', () => {
it('exposes the documented media kinds, frozen + unique', () => {
expect(Object.isFrozen(MEDIA_KINDS)).toBe(true);
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index f5e7f0f22c..5fbd9cc117 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -12,13 +12,29 @@
import { z } from 'zod';
import { BIBLE_LIMITS } from './storyBible.js';
-import { INGREDIENT_TYPE_IDS, RELATION_KIND_IDS, MEDIA_KIND_IDS } from './catalogTypes.js';
-
-// Derived from the shared type registry (`catalogTypes.js`) — adding a type
-// there flows through to every Zod enum below automatically. Kept as a frozen
+import {
+ INGREDIENT_TYPE_IDS,
+ RELATION_KIND_IDS,
+ MEDIA_KIND_IDS,
+ USER_TYPE_FIELD_KINDS,
+ isActiveType,
+} from './catalogTypes.js';
+
+// Derived from the shared type registry (`catalogTypes.js`) — adding a SYSTEM
+// type there flows through to consumers automatically. Kept as a frozen
// re-export so existing `import { INGREDIENT_TYPES }` callers are unaffected.
+// NOTE: this is the SYSTEM list only — the local-create `type` gate below uses
+// the runtime `isActiveType` refinement so user-defined types validate too.
export const INGREDIENT_TYPES = INGREDIENT_TYPE_IDS;
+// Local ingredient `type` gate. Was a frozen `z.enum(INGREDIENT_TYPES)`; now a
+// runtime refinement against the active registry (system + user-defined types)
+// so a user-typed create/query passes. The cross-instance SYNC path stays loose
+// (`z.string().max(32)` below) — a peer ingredient may arrive before its type
+// row applies, and the version gate already covers true shape skew.
+const ingredientTypeGate = z.string().trim().min(1).max(32)
+ .refine(isActiveType, 'unknown ingredient type');
+
export const REF_KINDS = Object.freeze([
'universe',
'series',
@@ -63,6 +79,41 @@ 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
+// 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.
+const userTypeIdentifier = z.string().trim().regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/, 'must be a slug/identifier').max(64);
+const userTypeField = z.object({
+ key: userTypeIdentifier,
+ label: z.string().trim().min(1).max(80),
+ kind: z.enum(USER_TYPE_FIELD_KINDS),
+ maxLength: z.number().int().min(1).max(20_000).optional(),
+}).strict();
+
+export const catalogUserTypeSchema = z.object({
+ // The type id is also the `cat-<prefix>-<uuid>` discriminator stored in the
+ // DB — slug-only, ≤32 so it stays a tidy column value.
+ id: z.string().trim().regex(/^[a-z][a-z0-9-]*$/, 'id must be a lowercase slug').max(32),
+ label: z.string().trim().min(1).max(80),
+ primaryContentKey: userTypeIdentifier,
+ fields: z.array(userTypeField).max(40),
+}).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`.)
+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',
+ })
+ .refine((list) => list.every((t) => !INGREDIENT_TYPE_IDS.includes(t.id)), {
+ message: 'catalog user-type id collides with a built-in type',
+ });
+
export const catalogScrapCreateSchema = z.object({
title: z.string().trim().max(300).optional().nullable(),
rawText: z.string().min(1).max(2_000_000),
@@ -158,7 +209,7 @@ export const catalogVoiceIngestSchema = z.object({
}).strict();
export const catalogIngredientCreateSchema = z.object({
- type: z.enum(INGREDIENT_TYPES),
+ type: ingredientTypeGate,
name: z.string().trim().min(1).max(BIBLE_LIMITS.NAME_MAX),
payload,
tags,
@@ -195,7 +246,7 @@ export const catalogRevisionRestoreSchema = z.object({
}).strict();
export const catalogIngredientQuerySchema = z.object({
- type: z.enum(INGREDIENT_TYPES).optional(),
+ type: ingredientTypeGate.optional(),
tag: tag.optional(),
q: z.string().trim().max(500).optional(),
limit: z.coerce.number().int().min(1).max(200).optional(),
@@ -352,7 +403,10 @@ export const catalogSyncScrapSchema = z.object({
export const catalogSyncIngredientSchema = z.object({
id: z.string().min(1).max(80),
- type: z.enum(INGREDIENT_TYPES),
+ // Loose on the wire (NOT the active-type refinement): a peer ingredient may
+ // arrive before its user-type row applies, so a not-yet-known type stores
+ // harmlessly. The version gate covers true cross-instance shape skew.
+ type: z.string().max(32),
name: z.string().max(BIBLE_LIMITS.NAME_MAX),
payload: syncPayload,
tags: syncTags,
@@ -447,6 +501,20 @@ export const catalogSyncMediaSchema = z.object({
syncSequence: z.string().optional(),
}).passthrough();
+// User-defined type DEFINITIONS on the wire (catalog v8). LWW-merged on the
+// receiver into its own `settings.json` `catalogUserTypes` slice. 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`
+// drives the LWW window; absent → treated as createdAt for the comparison.
+export const catalogSyncUserTypeSchema = z.object({
+ id: z.string().min(1).max(32),
+ label: z.string().max(80),
+ primaryContentKey: z.string().max(64).optional(),
+ fields: z.array(z.unknown()).max(40).optional(),
+ updatedAt: z.string().optional(),
+}).passthrough();
+
export const catalogSyncEnvelopeSchema = z.object({
scraps: z.array(catalogSyncScrapSchema).max(5_000).optional(),
ingredients: z.array(catalogSyncIngredientSchema).max(5_000).optional(),
@@ -455,5 +523,8 @@ export const catalogSyncEnvelopeSchema = z.object({
relations: z.array(catalogSyncRelationSchema).max(20_000).optional(),
tags: z.array(catalogSyncTagSchema).max(20_000).optional(),
media: z.array(catalogSyncMediaSchema).max(20_000).optional(),
+ // Additive catalog v8 block — user-defined type definitions. Optional so a
+ // ≤v7 peer's envelope (no `catalogTypes`) still validates.
+ catalogTypes: z.array(catalogSyncUserTypeSchema).max(64).optional(),
portosMeta,
}).passthrough();
diff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.js
index b2e80fa36d..217986cced 100644
--- a/server/lib/catalogValidation.test.js
+++ b/server/lib/catalogValidation.test.js
@@ -28,7 +28,11 @@ import {
catalogPortraitSetSchema,
MEDIA_KINDS,
catalogUrlIngestSchema,
+ catalogUserTypeSchema,
+ catalogUserTypesSettingsSchema,
} from './catalogValidation.js';
+import { setUserCatalogTypes } from './catalogTypes.js';
+import { afterEach } from 'vitest';
describe('catalogValidation — ingredient types & ref kinds', () => {
it('exposes the six v1 ingredient types as a frozen list', () => {
@@ -101,6 +105,92 @@ describe('catalogValidation — catalogIngredientCreateSchema', () => {
});
});
+describe('catalogValidation — ingredient type refinement (user types)', () => {
+ afterEach(() => setUserCatalogTypes([]));
+
+ it('accepts an active user type and rejects it once removed', () => {
+ setUserCatalogTypes([{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }]);
+ expect(catalogIngredientCreateSchema.parse({ type: 'faction', name: 'Choir' }).type).toBe('faction');
+ setUserCatalogTypes([]);
+ expect(() => catalogIngredientCreateSchema.parse({ type: 'faction', name: 'Choir' })).toThrow();
+ });
+
+ it('the query schema type gate also honors active user types', () => {
+ setUserCatalogTypes([{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }]);
+ expect(catalogIngredientQuerySchema.parse({ type: 'faction' }).type).toBe('faction');
+ expect(() => catalogIngredientQuerySchema.parse({ type: 'ghost' })).toThrow();
+ });
+
+ it('the sync ingredient gate stays loose (unknown type stores harmlessly)', () => {
+ // catalogSyncIngredientSchema.type is z.string().max(32) — a not-yet-known
+ // type must NOT be rejected on the sync apply path.
+ const env = catalogSyncEnvelopeSchema.parse({
+ ingredients: [{ id: 'cat-x-1', type: 'faction', name: 'X', createdAt: 'now', updatedAt: 'now' }],
+ });
+ expect(env.ingredients[0].type).toBe('faction');
+ });
+});
+
+describe('catalogValidation — catalogUserTypeSchema', () => {
+ const valid = { id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [{ key: 'creed', label: 'Creed', kind: 'longtext' }] };
+
+ it('accepts a well-formed user type', () => {
+ expect(() => catalogUserTypeSchema.parse(valid)).not.toThrow();
+ });
+
+ it('rejects a non-slug id and an oversized id', () => {
+ expect(() => catalogUserTypeSchema.parse({ ...valid, id: 'Faction' })).toThrow();
+ expect(() => catalogUserTypeSchema.parse({ ...valid, id: 'x'.repeat(33) })).toThrow();
+ });
+
+ it('rejects an unknown field kind', () => {
+ expect(() => catalogUserTypeSchema.parse({ ...valid, fields: [{ key: 'k', label: 'K', kind: 'wysiwyg' }] })).toThrow();
+ });
+
+ it('rejects more than 40 fields', () => {
+ const fields = Array.from({ length: 41 }, (_, i) => ({ key: `f${i}`, label: `F${i}`, kind: 'string' }));
+ expect(() => catalogUserTypeSchema.parse({ ...valid, fields })).toThrow();
+ });
+
+ it('rejects unknown top-level keys (strict)', () => {
+ expect(() => catalogUserTypeSchema.parse({ ...valid, extractionShape: 'bible' })).toThrow();
+ });
+});
+
+describe('catalogValidation — catalogUserTypesSettingsSchema', () => {
+ const t = (id) => ({ id, label: id, primaryContentKey: 'x', fields: [] });
+
+ it('accepts a unique-id list', () => {
+ expect(() => catalogUserTypesSettingsSchema.parse([t('faction'), t('relic')])).not.toThrow();
+ });
+
+ it('rejects duplicate ids', () => {
+ expect(() => catalogUserTypesSettingsSchema.parse([t('faction'), t('faction')])).toThrow(/duplicate/);
+ });
+
+ it('rejects an id colliding with a built-in system type', () => {
+ expect(() => catalogUserTypesSettingsSchema.parse([t('character')])).toThrow(/built-in/);
+ });
+
+ it('rejects more than 64 types', () => {
+ const many = Array.from({ length: 65 }, (_, i) => t(`u${i}`));
+ expect(() => catalogUserTypesSettingsSchema.parse(many)).toThrow();
+ });
+});
+
+describe('catalogValidation — catalogSyncEnvelopeSchema catalogTypes block', () => {
+ it('accepts a catalogTypes block (additive v8)', () => {
+ const env = catalogSyncEnvelopeSchema.parse({
+ catalogTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [], updatedAt: 'now' }],
+ });
+ expect(env.catalogTypes[0].id).toBe('faction');
+ });
+
+ it('validates without a catalogTypes block (≤v7 peer)', () => {
+ expect(() => catalogSyncEnvelopeSchema.parse({ ingredients: [] })).not.toThrow();
+ });
+});
+
describe('catalogValidation — catalogIngredientPatchSchema', () => {
it('accepts a tag-only patch', () => {
const out = catalogIngredientPatchSchema.parse({ tags: ['noir'] });
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index e3278a34bd..e5b4455434 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -110,7 +110,17 @@ 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).
- catalog: 7,
+ // 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.
+ catalog: 8,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 8b816c1ba2..c4f8edceca 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -31,8 +31,12 @@ import {
catalogUrlIngestSchema,
catalogFileIngestSchema,
catalogVoiceIngestSchema,
+ catalogUserTypeSchema,
+ catalogUserTypesSettingsSchema,
REF_KINDS,
} from '../lib/catalogValidation.js';
+import { getActiveCatalogTypes, setUserCatalogTypes } from '../lib/catalogTypes.js';
+import { getSettings, updateSettings } from '../services/settings.js';
import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalogBulkParsers.js';
import { resolveImageInputPath } from '../lib/fileUtils.js';
import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';
@@ -705,4 +709,84 @@ router.post('/migration/rerun', asyncHandler(async (req, res) => {
res.json(result);
}));
+// --- 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.
+
+// 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 : [];
+};
+
+router.get('/types', asyncHandler(async (req, res) => {
+ // Active registry (system first, then user). Each entry already carries
+ // `system`, `label`, `primaryContentKey`, `snippetFallbackKeys`, and (for
+ // user types) the `fields` list the generic editor renders.
+ res.json({ types: getActiveCatalogTypes() });
+}));
+
+router.post('/types', asyncHandler(async (req, res) => {
+ const body = validateRequest(catalogUserTypeSchema, req.body);
+ const current = await readUserTypes();
+ if (current.some((t) => t.id === body.id)) {
+ throw new ServerError(`Catalog type "${body.id}" already exists`, { status: 409 });
+ }
+ const next = [...current, body];
+ // 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 });
+ setUserCatalogTypes(next);
+ console.log(`🧩 Catalog: added user type "${body.id}"`);
+ res.status(201).json({ types: getActiveCatalogTypes() });
+}));
+
+router.patch('/types/:id', asyncHandler(async (req, res) => {
+ // Merge the path id onto the body so a partial PATCH still validates as a
+ // full user-type (id is immutable — the path wins over any body id).
+ const merged = validateRequest(catalogUserTypeSchema, { ...req.body, id: req.params.id });
+ const current = await readUserTypes();
+ const idx = current.findIndex((t) => t.id === req.params.id);
+ if (idx === -1) throw new ServerError(`Catalog type "${req.params.id}" not found`, { status: 404 });
+ const next = [...current];
+ next[idx] = merged;
+ validateRequest(catalogUserTypesSettingsSchema, next);
+ await updateSettings({ catalogUserTypes: next });
+ setUserCatalogTypes(next);
+ console.log(`🧩 Catalog: updated user type "${req.params.id}"`);
+ res.json({ types: getActiveCatalogTypes() });
+}));
+
+router.delete('/types/:id', asyncHandler(async (req, res) => {
+ const current = await readUserTypes();
+ const idx = current.findIndex((t) => t.id === req.params.id);
+ if (idx === -1) throw new ServerError(`Catalog type "${req.params.id}" not found`, { status: 404 });
+ // Refuse to delete a type that still has ingredients of that type unless the
+ // caller explicitly forces it (`?force=true`) — otherwise those rows become
+ // orphaned (their `type` no longer resolves in the active registry, so the
+ // detail page falls back to the generic 'idea' editor and the type filter
+ // drops them). force=true deletes the definition anyway; the rows survive
+ // and just render under the fallback editor.
+ const force = req.query.force === 'true';
+ if (!force) {
+ const { items } = await catalogDB.listIngredients({ type: req.params.id, limit: 1 });
+ if (items.length > 0) {
+ throw new ServerError(
+ `Catalog type "${req.params.id}" has ingredients — pass ?force=true to delete it anyway`,
+ { status: 409, code: 'CATALOG_TYPE_IN_USE' },
+ );
+ }
+ }
+ const next = current.filter((t) => t.id !== req.params.id);
+ await updateSettings({ catalogUserTypes: next });
+ setUserCatalogTypes(next);
+ console.log(`🧩 Catalog: deleted user type "${req.params.id}"${force ? ' (forced)' : ''}`);
+ res.json({ types: getActiveCatalogTypes() });
+}));
+
export default router;
diff --git a/server/routes/catalogTypes.test.js b/server/routes/catalogTypes.test.js
new file mode 100644
index 0000000000..628a640331
--- /dev/null
+++ b/server/routes/catalogTypes.test.js
@@ -0,0 +1,141 @@
+/**
+ * Route tests for the user-defined catalog TYPE CRUD endpoints
+ * (GET/POST/PATCH/DELETE /api/catalog/types).
+ *
+ * Pure — settings + catalogDB are mocked so no Postgres or real settings.json
+ * is touched. The settings mock keeps an in-memory `catalogUserTypes` slice so
+ * create → list → delete round-trips through the same code path the live
+ * routes use, without writing to disk.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+// In-memory settings store the route's getSettings/updateSettings read/write.
+let store = {};
+vi.mock('../services/settings.js', () => ({
+ getSettings: vi.fn(async () => ({ ...store })),
+ updateSettings: vi.fn(async (patch) => { store = { ...store, ...patch }; return { ...store }; }),
+}));
+
+// listIngredients drives the delete-in-use guard. Default: no ingredients.
+let ingredientsForType = [];
+vi.mock('../services/catalogDB.js', () => ({
+ listIngredients: vi.fn(async () => ({ items: ingredientsForType, nextOffset: 0 })),
+}));
+// catalogSync is imported by the route module's `import * as catalogSync`.
+vi.mock('../services/catalogSync.js', () => ({}));
+
+const router = (await import('./catalog.js')).default;
+// Reset the in-process registry between tests via the real module.
+const { setUserCatalogTypes, getActiveCatalogType } = await import('../lib/catalogTypes.js');
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/catalog', router);
+ app.use(errorMiddleware);
+ return app;
+}
+
+beforeEach(() => {
+ store = {};
+ ingredientsForType = [];
+ setUserCatalogTypes([]);
+});
+
+describe('GET /api/catalog/types', () => {
+ it('returns the active registry (system first) including a synced user type', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }] };
+ setUserCatalogTypes(store.catalogUserTypes);
+ const res = await request(makeApp()).get('/api/catalog/types');
+ expect(res.status).toBe(200);
+ const ids = res.body.types.map((t) => t.id);
+ expect(ids.slice(0, 6)).toEqual(['character', 'place', 'object', 'idea', 'scene', 'concept']);
+ expect(ids).toContain('faction');
+ expect(res.body.types.find((t) => t.id === 'faction').system).toBe(false);
+ expect(res.body.types.find((t) => t.id === 'character').system).toBe(true);
+ });
+});
+
+describe('POST /api/catalog/types', () => {
+ it('creates a user type, persists it, and refreshes the registry', async () => {
+ const body = { id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [{ key: 'creed', label: 'Creed', kind: 'longtext' }] };
+ const res = await request(makeApp()).post('/api/catalog/types').send(body);
+ expect(res.status).toBe(201);
+ expect(res.body.types.some((t) => t.id === 'faction')).toBe(true);
+ expect(store.catalogUserTypes).toHaveLength(1);
+ // Registry refreshed in-process.
+ expect(getActiveCatalogType('faction')?.label).toBe('Faction');
+ });
+
+ it('rejects a duplicate id with 409', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }] };
+ const res = await request(makeApp())
+ .post('/api/catalog/types')
+ .send({ id: 'faction', label: 'Again', primaryContentKey: 'x', fields: [] });
+ expect(res.status).toBe(409);
+ });
+
+ it('rejects an id colliding with a built-in system type (400 via slice refinement)', async () => {
+ const res = await request(makeApp())
+ .post('/api/catalog/types')
+ .send({ id: 'character', label: 'Hijack', primaryContentKey: 'x', fields: [] });
+ expect(res.status).toBe(400);
+ });
+
+ it('400s a malformed body (non-slug id)', async () => {
+ const res = await request(makeApp())
+ .post('/api/catalog/types')
+ .send({ id: 'Faction!', label: 'X', primaryContentKey: 'x', fields: [] });
+ expect(res.status).toBe(400);
+ });
+});
+
+describe('PATCH /api/catalog/types/:id', () => {
+ it('updates an existing user type', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }] };
+ const res = await request(makeApp())
+ .patch('/api/catalog/types/faction')
+ .send({ label: 'Guild', primaryContentKey: 'creed', fields: [] });
+ expect(res.status).toBe(200);
+ expect(res.body.types.find((t) => t.id === 'faction').label).toBe('Guild');
+ expect(store.catalogUserTypes[0].label).toBe('Guild');
+ });
+
+ it('404s an unknown id', async () => {
+ const res = await request(makeApp())
+ .patch('/api/catalog/types/ghost')
+ .send({ label: 'X', primaryContentKey: 'x', fields: [] });
+ expect(res.status).toBe(404);
+ });
+});
+
+describe('DELETE /api/catalog/types/:id', () => {
+ it('deletes an unused type', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }] };
+ const res = await request(makeApp()).delete('/api/catalog/types/faction');
+ expect(res.status).toBe(200);
+ expect(store.catalogUserTypes).toHaveLength(0);
+ });
+
+ it('refuses to delete a type with ingredients (409) unless ?force=true', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }] };
+ ingredientsForType = [{ id: 'cat-fac-1' }];
+ const refused = await request(makeApp()).delete('/api/catalog/types/faction');
+ expect(refused.status).toBe(409);
+ // Slice untouched on the refused delete.
+ expect(store.catalogUserTypes).toHaveLength(1);
+ // Forced delete drops the definition anyway.
+ const forced = await request(makeApp()).delete('/api/catalog/types/faction?force=true');
+ expect(forced.status).toBe(200);
+ expect(store.catalogUserTypes).toHaveLength(0);
+ });
+
+ it('404s an unknown id', async () => {
+ const res = await request(makeApp()).delete('/api/catalog/types/ghost');
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/server/routes/settings.js b/server/routes/settings.js
index 5a55ec722e..f7c88a29de 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -8,6 +8,7 @@ import {
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, validateRequest } from '../lib/validation.js';
+import { catalogUserTypesSettingsSchema } from '../lib/catalogValidation.js';
const router = Router();
@@ -73,6 +74,14 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.embeddings !== undefined) {
validateRequest(settingsEmbeddingsSchema.partial(), req.body.embeddings);
}
+ // 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);
+ }
const merged = await updateSettings(req.body);
// The queue caches codex.parallelLimit in-process; sync it from the
// merged value so a save takes effect without a restart and without
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 4ca8d948e4..57ff5dfb71 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -12,7 +12,7 @@
import { randomUUID } from 'crypto';
import { query, withTransaction, pgvectorToArray, arrayToPgvector } from '../lib/db.js';
import {
- getCatalogType,
+ getActiveCatalogType,
ingredientIdPrefix,
currentPayloadSchemaVersion,
canonicalTagKey,
@@ -392,7 +392,7 @@ export async function deleteScrap(id, { hard = false } = {}) {
// See `POST /api/catalog/scraps/:id/commit` for the scrap-commit batch that
// needs every per-draft ingredient + source-link to commit-or-rollback together.
export async function createIngredient({ id: explicitId, type, name, payload = {}, tags = [], embedding = null, embeddingModel = null } = {}, { client, source = 'user', actor = null } = {}) {
- if (!type || !getCatalogType(type)) throw new Error(`Invalid ingredient type: ${type}`);
+ if (!type || !getActiveCatalogType(type)) throw new Error(`Invalid ingredient type: ${type}`);
if (!name || !String(name).trim()) throw new Error('name is required');
// `explicitId` is used by the backfill when a universe arrives from a peer
@@ -588,7 +588,7 @@ export async function deleteIngredient(id, { hard = false } = {}) {
* `null` if no row exists at that id (caller falls through to plain INSERT).
*/
export async function reviveDeletedIngredient(id, { type, name, payload = {}, tags = [] } = {}) {
- if (!type || !getCatalogType(type)) throw new Error(`reviveDeletedIngredient: invalid type ${type}`);
+ if (!type || !getActiveCatalogType(type)) throw new Error(`reviveDeletedIngredient: invalid type ${type}`);
if (!name || !String(name).trim()) throw new Error('reviveDeletedIngredient: name required');
// Re-stamp the payload schemaVersion on revive — the revived row is being
// rewritten with a fresh payload, so it gets this install's current marker
diff --git a/server/services/catalogDB.registry.test.js b/server/services/catalogDB.registry.test.js
index 783c701512..117a752b34 100644
--- a/server/services/catalogDB.registry.test.js
+++ b/server/services/catalogDB.registry.test.js
@@ -57,11 +57,14 @@ vi.mock('./instances.js', () => ({
}));
import { createIngredient, reviveDeletedIngredient } from './catalogDB.js';
-import { currentPayloadSchemaVersion } from '../lib/catalogTypes.js';
+import { currentPayloadSchemaVersion, setUserCatalogTypes } from '../lib/catalogTypes.js';
beforeEach(() => {
captured.sql = null;
captured.params = null;
+ // Reset the user-type registry between tests so a leftover definition can't
+ // leak across cases.
+ setUserCatalogTypes([]);
});
describe('createIngredient — payload schemaVersion stamping', () => {
@@ -105,6 +108,34 @@ describe('createIngredient — registry-derived id prefix + type guard', () => {
});
});
+describe('createIngredient — user-defined types', () => {
+ it('mints a cat-<prefix>-<uuid> id and round-trips a user-typed create', async () => {
+ setUserCatalogTypes([{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [{ key: 'creed', label: 'Creed', kind: 'longtext' }] }]);
+ const ing = await createIngredient({ type: 'faction', name: 'The Choir', payload: { creed: 'unity' } });
+ expect(ing.id).toMatch(/^cat-[a-z0-9]+-[0-9a-f-]{36}$/);
+ expect(ing.type).toBe('faction');
+ const stored = JSON.parse(captured.params[3]);
+ expect(stored.creed).toBe('unity');
+ // User types are payloadSchemaVersion 1.
+ expect(stored.schemaVersion).toBe(1);
+ });
+
+ it('throws for an unregistered user type before touching the DB', async () => {
+ // No setUserCatalogTypes call → 'faction' is not active.
+ await expect(createIngredient({ type: 'faction', name: 'x' })).rejects.toThrow(/Invalid ingredient type/);
+ expect(captured.params).toBeNull();
+ });
+
+ it('never mints a user prefix that collides with a system prefix', async () => {
+ // id 'characters' would slug to 'char' which is NOT a system prefix ('chr'),
+ // but 'cha' could; assert the minted prefix avoids all six system prefixes.
+ setUserCatalogTypes([{ id: 'chronicle', label: 'Chronicle', primaryContentKey: 'body', fields: [{ key: 'body', label: 'Body', kind: 'longtext' }] }]);
+ const ing = await createIngredient({ type: 'chronicle', name: 'Log' });
+ const prefix = ing.id.split('-')[1];
+ expect(['chr', 'plc', 'obj', 'idea', 'scn', 'cnc']).not.toContain(prefix);
+ });
+});
+
describe('reviveDeletedIngredient — registry guard + payload stamping', () => {
it('validates the type against the registry (not a stale prefix map)', async () => {
await expect(reviveDeletedIngredient('cat-x-1', { type: 'wardrobe', name: 'Cape' }))
diff --git a/server/services/catalogSync.js b/server/services/catalogSync.js
index 0f8bf65cb4..8eda3ccc80 100644
--- a/server/services/catalogSync.js
+++ b/server/services/catalogSync.js
@@ -48,7 +48,8 @@ import {
} from './catalogDB.js';
import { compareSchemaVersions, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
import { friendlifyUniverseTags, LEGACY_UNIVERSE_MARKER_TAG } from '../lib/catalogUniverseTags.js';
-import { canonicalTagKey } from '../lib/catalogTypes.js';
+import { canonicalTagKey, setUserCatalogTypes, INGREDIENT_TYPE_IDS } from '../lib/catalogTypes.js';
+import { getSettings, updateSettings } from './settings.js';
const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs', 'relations', 'tags', 'media'];
@@ -96,7 +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 : [];
+
return {
+ catalogTypes,
scraps: scraps.items,
ingredients: ingredients.items,
sources: sources.items,
@@ -147,6 +155,7 @@ export async function applyRemoteChanges(envelope = {}) {
relations: { applied: 0, failed: 0 },
tags: { inserted: 0, updated: 0, skipped: 0, failed: 0 },
media: { applied: 0, failed: 0 },
+ catalogTypes: { applied: 0, skipped: 0, failed: 0 },
errors: [],
};
@@ -285,9 +294,63 @@ export async function applyRemoteChanges(envelope = {}) {
errLabel: 'media', idFor: (m) => `${m?.ingredientId}/${m?.kind}/${m?.mediaKey}`,
});
+ // User-defined type definitions (catalog v8). LWW-merge the incoming
+ // definitions into the local settings slice: a peer's type whose `updatedAt`
+ // is newer than (or equal to, for a first-seen) the local copy wins; a type
+ // colliding with a built-in system id is skipped. The merge writes the
+ // settings slice ONCE (not per-row) and refreshes the in-process registry so
+ // the synced types resolve immediately. Wrapped so a settings write failure
+ // tallies as a single failure rather than aborting the whole apply.
+ if (Array.isArray(envelope.catalogTypes) && envelope.catalogTypes.length > 0) {
+ try {
+ stats.catalogTypes = await applyUserTypesFromPeer(envelope.catalogTypes);
+ } catch (err) {
+ stats.catalogTypes = { applied: 0, skipped: 0, failed: envelope.catalogTypes.length };
+ recordFailure('catalogTypes', null, err);
+ }
+ }
+
return stats;
}
+/**
+ * LWW-merge a peer's user-defined type definitions into the local settings
+ * `catalogUserTypes` slice. A peer type wins when its `updatedAt` is newer than
+ * the local copy's (or the local copy has none); a first-seen type is adopted.
+ * Types colliding with a built-in system id are skipped. Writes the settings
+ * slice once and refreshes the in-process registry. Returns `{ applied,
+ * skipped, failed }`.
+ */
+export async function applyUserTypesFromPeer(incoming = []) {
+ const settings = await getSettings();
+ const local = Array.isArray(settings.catalogUserTypes) ? settings.catalogUserTypes : [];
+ const byId = new Map(local.map((t) => [t.id, t]));
+ let applied = 0;
+ let skipped = 0;
+ const updatedOf = (t) => (typeof t?.updatedAt === 'string' ? t.updatedAt : '');
+ for (const peer of incoming) {
+ const id = typeof peer?.id === 'string' ? peer.id.trim() : '';
+ // Skip a malformed entry or one colliding with a built-in system id —
+ // system types always win and are never represented in this slice.
+ if (!id || INGREDIENT_TYPE_IDS.includes(id)) { skipped++; continue; }
+ const existing = byId.get(id);
+ // LWW on updatedAt: adopt when no local copy, or the peer is at-or-newer.
+ if (!existing || updatedOf(peer) >= updatedOf(existing)) {
+ byId.set(id, { ...peer, id });
+ applied++;
+ } else {
+ skipped++;
+ }
+ }
+ if (applied > 0) {
+ const next = [...byId.values()];
+ await updateSettings({ catalogUserTypes: next });
+ setUserCatalogTypes(next);
+ console.log(`🧩 Catalog sync: merged ${applied} user type(s) from peer`);
+ }
+ return { applied, skipped, failed: 0 };
+}
+
// Total rows actually applied (inserted + updated for LWW kinds, applied for
// tuple-unique kinds) across an `applyRemoteChanges` stats object. Lives here —
// not in the federation orchestrator — so the per-kind stats SHAPE has a single
@@ -299,7 +362,8 @@ export function countAppliedFromStats(stats = {}) {
(stats.sources?.applied || 0) + (stats.refs?.applied || 0) +
(stats.relations?.applied || 0) +
(stats.tags?.inserted || 0) + (stats.tags?.updated || 0) +
- (stats.media?.applied || 0)
+ (stats.media?.applied || 0) +
+ (stats.catalogTypes?.applied || 0)
);
}
diff --git a/server/services/catalogSync.userTypes.test.js b/server/services/catalogSync.userTypes.test.js
new file mode 100644
index 0000000000..59d5c00488
--- /dev/null
+++ b/server/services/catalogSync.userTypes.test.js
@@ -0,0 +1,96 @@
+/**
+ * Catalog sync — user-defined-type (catalog v8) federation tests.
+ *
+ * Covers the outbound `catalogTypes` envelope block, the inbound LWW-merge
+ * (`applyUserTypesFromPeer` via `applyRemoteChanges`), and the version gate.
+ * settings + catalogDB are mocked so the suite stays pure (no Postgres / disk).
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// In-memory settings store the merge reads/writes.
+let store = {};
+vi.mock('./settings.js', () => ({
+ getSettings: vi.fn(async () => ({ ...store })),
+ updateSettings: vi.fn(async (patch) => { store = { ...store, ...patch }; return { ...store }; }),
+}));
+
+// catalogDB upserts/changes are no-ops here — we only exercise the catalogTypes
+// path, but applyRemoteChanges dispatches every kind, so stub them all.
+vi.mock('./catalogDB.js', () => ({
+ getScrapChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),
+ getIngredientChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),
+ getSourceChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),
+ getRefChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),
+ getRelationChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),
+ getTagChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),
+ getMediaChangesSince: vi.fn(async () => ({ items: [], hasMore: false })),
+ getMaxSequences: vi.fn(async () => ({ scraps: '0', ingredients: '0', sources: '0', refs: '0', relations: '0', tags: '0', media: '0' })),
+ upsertScrapFromPeer: vi.fn(), upsertIngredientFromPeer: vi.fn(), upsertSourceFromPeer: vi.fn(),
+ upsertRefFromPeer: vi.fn(), upsertRelationFromPeer: vi.fn(), upsertTagFromPeer: vi.fn(),
+ upsertMediaFromPeer: vi.fn(), updateIngredient: vi.fn(),
+}));
+vi.mock('./universeBuilder.js', () => ({ listUniverses: vi.fn(async () => []) }));
+
+const { getChangesSince, applyRemoteChanges } = await import('./catalogSync.js');
+const { PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');
+const { setUserCatalogTypes, getActiveCatalogType } = await import('../lib/catalogTypes.js');
+
+beforeEach(() => {
+ store = {};
+ setUserCatalogTypes([]);
+});
+
+describe('getChangesSince — catalogTypes outbound block', () => {
+ it('rides every envelope from the settings slice', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [] }] };
+ const changes = await getChangesSince('0', 100);
+ expect(changes.catalogTypes).toEqual(store.catalogUserTypes);
+ });
+
+ it('is an empty array when no user types are defined', async () => {
+ const changes = await getChangesSince('0', 100);
+ expect(changes.catalogTypes).toEqual([]);
+ });
+});
+
+describe('applyRemoteChanges — catalogTypes LWW merge', () => {
+ const meta = { schemaVersions: { catalog: PORTOS_SCHEMA_VERSIONS.catalog } };
+
+ it('adopts a first-seen peer type and refreshes the registry', async () => {
+ const stats = await applyRemoteChanges({
+ portosMeta: meta,
+ catalogTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'creed', fields: [], updatedAt: '2026-01-01' }],
+ });
+ expect(stats.catalogTypes.applied).toBe(1);
+ expect(store.catalogUserTypes).toHaveLength(1);
+ expect(getActiveCatalogType('faction')?.label).toBe('Faction');
+ });
+
+ it('LWW: a newer peer type wins, an older one is skipped', async () => {
+ store = { catalogUserTypes: [{ id: 'faction', label: 'Old', primaryContentKey: 'x', fields: [], updatedAt: '2026-01-01' }] };
+ // Older → skipped.
+ let stats = await applyRemoteChanges({ portosMeta: meta, catalogTypes: [{ id: 'faction', label: 'Older', primaryContentKey: 'x', fields: [], updatedAt: '2025-01-01' }] });
+ expect(stats.catalogTypes.applied).toBe(0);
+ expect(stats.catalogTypes.skipped).toBe(1);
+ expect(store.catalogUserTypes[0].label).toBe('Old');
+ // Newer → wins.
+ stats = await applyRemoteChanges({ portosMeta: meta, catalogTypes: [{ id: 'faction', label: 'New', primaryContentKey: 'x', fields: [], updatedAt: '2027-01-01' }] });
+ expect(stats.catalogTypes.applied).toBe(1);
+ expect(store.catalogUserTypes[0].label).toBe('New');
+ });
+
+ it('skips a peer type colliding with a built-in system id', async () => {
+ const stats = await applyRemoteChanges({ portosMeta: meta, catalogTypes: [{ id: 'character', label: 'Hijack', primaryContentKey: 'x', fields: [], updatedAt: '2027-01-01' }] });
+ expect(stats.catalogTypes.applied).toBe(0);
+ expect(stats.catalogTypes.skipped).toBe(1);
+ expect(store.catalogUserTypes ?? []).toHaveLength(0);
+ });
+
+ it('rejects with 412 when the sender is ahead on the catalog schema', async () => {
+ await expect(applyRemoteChanges({
+ portosMeta: { schemaVersions: { catalog: PORTOS_SCHEMA_VERSIONS.catalog + 1 } },
+ catalogTypes: [{ id: 'faction', label: 'Faction', primaryContentKey: 'x', fields: [] }],
+ })).rejects.toMatchObject({ status: 412 });
+ });
+});