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
lift catalog ingredient types into a shared registry
[._.]/ Adam Eivy720ff825c2fb
diff --git a/client/src/components/IngredientPicker.jsx b/client/src/components/IngredientPicker.jsxindex cf4d8a625d..21d73fb8de 100644--- a/client/src/components/IngredientPicker.jsx+++ b/client/src/components/IngredientPicker.jsx@@ -24,22 +24,11 @@ import { Link } from 'react-router-dom';import { Search, Plus, Loader2, X, Sparkles } from 'lucide-react';import Modal from './ui/Modal';import { listCatalogIngredients } from '../services/apiCatalog';+import { CATALOG_BADGE_BY_ID, payloadSnippet } from '../lib/catalogTypes';-const TYPE_BADGE = {- character: 'bg-blue-500/20 text-blue-300 border-blue-500/40',- place: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40',- object: 'bg-amber-500/20 text-amber-300 border-amber-500/40',- idea: 'bg-purple-500/20 text-purple-300 border-purple-500/40',- scene: 'bg-pink-500/20 text-pink-300 border-pink-500/40',- concept: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/40',-};--function snippet(payload) {- if (!payload || typeof payload !== 'object') return '';- const text = String(payload.description || payload.summary || payload.notes || '').trim().replace(/\s+/g, ' ');- if (text.length <= 140) return text;- return `${text.slice(0, 137)}…`;-}+// Type chip color comes from the shared registry. Snippet uses the registry's+// per-type fallback chain at a slightly longer cap for the picker rows.+const snippet = (payload, type) => payloadSnippet(payload, type, 140);export default function IngredientPicker({open,@@ -188,7 +177,7 @@ export default function IngredientPicker({) : (<ul className="space-y-2">{filtered.map((it) => {- const badge = TYPE_BADGE[it.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';+ const badge = CATALOG_BADGE_BY_ID[it.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';const checked = selectedIds.has(it.id);const rowBase = 'w-full text-left p-3 rounded border bg-port-bg/40 transition-colors';const rowClass = multi@@ -216,8 +205,8 @@ export default function IngredientPicker({{it.type}</span></div>- {snippet(it.payload) && (- <p className="text-xs text-gray-400 line-clamp-2">{snippet(it.payload)}</p>+ {snippet(it.payload, it.type) && (+ <p className="text-xs text-gray-400 line-clamp-2">{snippet(it.payload, it.type)}</p>)}{Array.isArray(it.tags) && it.tags.length > 0 && (<div className="flex flex-wrap gap-1 mt-1.5">diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 3e1f5dae5c..194cbcec94 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -31,6 +31,7 @@ grep -i "what you want to do" client/src/lib/README.md| `sheetPointers.js` | Mirror of the character-sheet pointer helpers from `server/lib/storyBible.js`. `LEGACY_SHEET_VARIANT_ID` + `readSheetPointer` / `listSheetPointers` / `applySheetPointer` for traversing both the legacy `referenceSheetImageRef` field and the `referenceSheets` map. || `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. || `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. |+| `catalogTypes.js` | Client mirror of `server/lib/catalogTypes.js` — catalog ingredient type registry (label, badge color, primary-content key/label, snippet fallback chain, per-type editor field list) for the Catalog list/picker/editor. || `editorialRoadmap.js` | `projectAnalyzedPoints` (aggregate roadmap → analyzed chart points with arc-position `frac`) + `dominant` (most-frequent string). Shared by EditorialRoadmapPanel and the Reader Map page. || `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). || `runnerFamilies.js` | Mirror of `server/lib/runners.js`. |diff --git a/client/src/lib/catalogTypes.js b/client/src/lib/catalogTypes.jsnew file mode 100644index 0000000000..46cc9a45fc--- /dev/null+++ b/client/src/lib/catalogTypes.js@@ -0,0 +1,147 @@+/**+ * Client mirror of `server/lib/catalogTypes.js` — the catalog ingredient type+ * registry. The server registry carries extra server-only fields (idPrefix,+ * ftsFields, payloadSchemaVersion, payloadUpgraders); the client mirror keeps+ * only what the UI renders: label, badge color, the inline-form primary+ * content key/label, the snippet fallback chain, and the per-type editor field+ * list.+ *+ * Drift is asserted by `client/src/lib/catalogTypes.test.js` against the+ * server registry's shared fields — if you change one side, change the other.+ *+ * Adding a type: add an entry here AND in the server registry (+ one migration+ * loosening the CHECK constraint). The Catalog list/picker/inline-form, the+ * detail editor, and the type chips all map over `CATALOG_TYPES` so the new+ * type surfaces everywhere without a per-surface edit.+ */++// Per-type detail-editor field list. Each entry is `[key, label, kind]` where+// `kind` is 'text' (single line) or 'textarea' (multi-line). The light types+// (idea/scene/concept) share LIGHT_FIELDS.+const LIGHT_FIELDS = [+ ['summary', 'Summary', 'textarea'],+ ['description', 'Description', 'textarea'],+ ['notes', 'Notes', 'textarea'],+];++export const CATALOG_TYPES = Object.freeze([+ {+ id: 'character',+ label: 'Character',+ badgeColor: 'bg-blue-500/20 text-blue-300 border-blue-500/40',+ primaryContentKey: 'physicalDescription',+ primaryContentLabel: 'Physical Description',+ snippetFallbackKeys: ['physicalDescription', 'description', 'summary', 'personality', 'significance', 'role', 'notes'],+ editorFields: [+ ['role', 'Role', 'text'],+ // Canon character shape uses `physicalDescription` (matches+ // sanitizeCharacter and the writers-room/bible extractor). A plain+ // `description` here would render empty for backfill-promoted characters+ // and edits would land in a sibling field the canon doesn't read.+ ['physicalDescription', 'Physical Description', 'textarea'],+ ['personality', 'Personality', 'textarea'],+ ['background', 'Background', 'textarea'],+ ['motivations', 'Motivations', 'textarea'],+ ['notes', 'Notes', 'textarea'],+ ],+ },+ {+ id: 'place',+ label: 'Place',+ badgeColor: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40',+ primaryContentKey: 'description',+ primaryContentLabel: 'Description',+ snippetFallbackKeys: ['description', 'summary', 'significance', 'notes'],+ editorFields: [+ ['slugline', 'Slugline', 'text'],+ ['era', 'Era', 'text'],+ ['description', 'Description', 'textarea'],+ ['notes', 'Notes', 'textarea'],+ ],+ },+ {+ id: 'object',+ label: 'Object',+ badgeColor: 'bg-amber-500/20 text-amber-300 border-amber-500/40',+ primaryContentKey: 'description',+ primaryContentLabel: 'Description',+ snippetFallbackKeys: ['description', 'significance', 'summary', 'notes'],+ editorFields: [+ ['description', 'Description', 'textarea'],+ ['significance', 'Significance', 'textarea'],+ ['notes', 'Notes', 'textarea'],+ ],+ },+ {+ id: 'idea',+ label: 'Idea',+ badgeColor: 'bg-purple-500/20 text-purple-300 border-purple-500/40',+ primaryContentKey: 'summary',+ primaryContentLabel: 'Summary',+ snippetFallbackKeys: ['summary', 'description', 'notes'],+ editorFields: LIGHT_FIELDS,+ },+ {+ id: 'scene',+ label: 'Scene',+ badgeColor: 'bg-pink-500/20 text-pink-300 border-pink-500/40',+ primaryContentKey: 'summary',+ primaryContentLabel: 'Summary',+ snippetFallbackKeys: ['summary', 'description', 'notes'],+ editorFields: LIGHT_FIELDS,+ },+ {+ id: 'concept',+ label: 'Concept',+ badgeColor: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/40',+ primaryContentKey: 'summary',+ primaryContentLabel: 'Summary',+ snippetFallbackKeys: ['summary', 'description', 'notes'],+ editorFields: LIGHT_FIELDS,+ },+]);++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. */+export function getCatalogType(id) {+ return BY_ID[id];+}++/** Ordered list of type ids. */+export const CATALOG_TYPE_IDS = Object.freeze(CATALOG_TYPES.map((t) => t.id));++/** Map type id → Tailwind badge color class string. */+export const CATALOG_BADGE_BY_ID = Object.freeze(+ Object.fromEntries(CATALOG_TYPES.map((t) => [t.id, t.badgeColor])),+);++/**+ * Pull a short snippet from a payload using a type's fallback chain (first+ * non-empty key wins), trimmed + ellipsised to `max` chars. When `typeId` is+ * unknown/absent, falls back to a broad union of every type's keys so a row of+ * unknown type still renders a snippet.+ */+export function payloadSnippet(payload, typeId, max = 120) {+ if (!payload || typeof payload !== 'object') return '';+ const keys = BY_ID[typeId]?.snippetFallbackKeys || UNION_SNIPPET_KEYS;+ let raw = '';+ for (const k of keys) {+ if (payload[k]) { raw = payload[k]; break; }+ }+ const text = String(raw).trim().replace(/\s+/g, ' ');+ if (text.length <= max) return text;+ return `${text.slice(0, max - 3)}…`;+}++// Ordered union of every type's snippet keys — used as the unknown-type+// fallback so a row whose type isn't in the registry still gets a snippet.+const UNION_SNIPPET_KEYS = (() => {+ const out = [];+ for (const t of CATALOG_TYPES) {+ for (const k of t.snippetFallbackKeys) {+ if (!out.includes(k)) out.push(k);+ }+ }+ return out;+})();diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 35c3511ed6..48870a7000 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -13,6 +13,7 @@ export * from './universeStylePreset.js';// === Pipeline / image-gen defaults ===export * from './bibleLimits.js';+export * from './catalogTypes.js';export * from './editorialRoadmap.js';export * from './imageCleaners.js';export * from './imageGenBackends.js';diff --git a/client/src/pages/Catalog.jsx b/client/src/pages/Catalog.jsxindex 428d73e879..924dd24a27 100644--- a/client/src/pages/Catalog.jsx+++ b/client/src/pages/Catalog.jsx@@ -18,66 +18,18 @@ import {deleteCatalogIngredient,getCatalogStats,} from '../services/apiCatalog';+import { CATALOG_TYPES, getCatalogType, payloadSnippet } from '../lib/catalogTypes';-const TYPES = [- { id: 'character', label: 'Character', color: 'bg-blue-500/20 text-blue-300 border-blue-500/40' },- { id: 'place', label: 'Place', color: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40' },- { id: 'object', label: 'Object', color: 'bg-amber-500/20 text-amber-300 border-amber-500/40' },- { id: 'idea', label: 'Idea', color: 'bg-purple-500/20 text-purple-300 border-purple-500/40' },- { id: 'scene', label: 'Scene', color: 'bg-pink-500/20 text-pink-300 border-pink-500/40' },- { id: 'concept', label: 'Concept', color: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/40' },-];--const TYPE_BY_ID = Object.fromEntries(TYPES.map((t) => [t.id, t]));--// Per-type primary content key used by the inline "New" form, so users can-// capture the body in one step instead of bouncing into the editor. Mirrors-// the labels in CatalogIngredient.jsx — characters land in `physicalDescription`-// (canon shape), place/object in `description`, light types in `summary`.-const PRIMARY_CONTENT_KEY = {- character: 'physicalDescription',- place: 'description',- object: 'description',- idea: 'summary',- scene: 'summary',- concept: 'summary',-};-// Display label per content key — driven from PRIMARY_CONTENT_KEY so a future-// type→key remapping automatically picks up the right label and the form-// label can't silently lie about where content lands on submit.-const PRIMARY_CONTENT_LABEL = {- physicalDescription: 'Physical Description',- description: 'Description',- summary: 'Summary',-};--// Pull a short snippet from the type-specific payload — first hit wins,-// trimmed and ellipsised to ~120 chars. Fallback chain covers every canon-// narrative field across the six ingredient types: characters-// (physicalDescription / personality / role), places/objects (description /-// significance), light types (summary / notes). Without the broader fallback,-// objects-with-only-significance and characters-with-only-personality render-// as snippet-less rows.-function payloadSnippet(payload) {- if (!payload || typeof payload !== 'object') return '';- const raw = payload.physicalDescription- || payload.description- || payload.summary- || payload.personality- || payload.significance- || payload.role- || payload.notes- || '';- const text = String(raw).trim().replace(/\s+/g, ' ');- if (text.length <= 120) return text;- return `${text.slice(0, 117)}…`;-}+// All type-derived UI (chips, badge color, inline-form primary content+// key/label, snippet fallback) now flows from the shared registry. Adding a+// type is one registry entry — no per-surface edit here.+const TYPES = CATALOG_TYPES;function TypeBadge({ type }) {- const meta = TYPE_BY_ID[type];+ const meta = getCatalogType(type);if (!meta) return null;return (- <span className={`inline-block text-[10px] uppercase tracking-wider px-2 py-0.5 rounded border ${meta.color}`}>+ <span className={`inline-block text-[10px] uppercase tracking-wider px-2 py-0.5 rounded border ${meta.badgeColor}`}>{meta.label}</span>);@@ -148,7 +100,7 @@ export default function Catalog() {const content = form.content.trim();const payload = {};if (content) {- payload[PRIMARY_CONTENT_KEY[form.type] || 'description'] = content;+ payload[getCatalogType(form.type)?.primaryContentKey || 'description'] = content;}setCreating(true);const created = await createCatalogIngredient({@@ -310,7 +262,7 @@ export default function Catalog() {</div><div><label htmlFor="catalog-new-content" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">- {PRIMARY_CONTENT_LABEL[PRIMARY_CONTENT_KEY[form.type]] || 'Description'}+ {getCatalogType(form.type)?.primaryContentLabel || 'Description'}<span className="normal-case text-gray-500"> (optional)</span></label><textarea@@ -376,8 +328,8 @@ export default function Catalog() {</span>))}</span>- {payloadSnippet(it.payload) ? (- <span className="text-xs text-gray-400 line-clamp-3">{payloadSnippet(it.payload)}</span>+ {payloadSnippet(it.payload, it.type) ? (+ <span className="text-xs text-gray-400 line-clamp-3">{payloadSnippet(it.payload, it.type)}</span>) : null}</Link><div className="absolute top-2 right-2">diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsxindex 0e43281826..287024d017 100644--- a/client/src/pages/CatalogIngredient.jsx+++ b/client/src/pages/CatalogIngredient.jsx@@ -14,52 +14,11 @@ import {updateCatalogIngredient,deleteCatalogIngredient,} from '../services/apiCatalog';+import { getCatalogType, CATALOG_BADGE_BY_ID } from '../lib/catalogTypes';-// Per-type payload field list. Each entry is `[key, label, kind]` where `kind`-// is 'text' (single line) or 'textarea' (multi-line). idea/scene/concept all-// share the lightweight shape.-const LIGHT_FIELDS = [- ['summary', 'Summary', 'textarea'],- ['description', 'Description', 'textarea'],- ['notes', 'Notes', 'textarea'],-];-const PAYLOAD_FIELDS = {- character: [- ['role', 'Role', 'text'],- // Canon character shape uses `physicalDescription` (matches- // sanitizeCharacter and the writers-room/bible extractor). A plain- // `description` here would render empty for backfill-promoted characters- // and edits would land in a sibling field the canon doesn't read.- ['physicalDescription', 'Physical Description', 'textarea'],- ['personality', 'Personality', 'textarea'],- ['background', 'Background', 'textarea'],- ['motivations', 'Motivations', 'textarea'],- ['notes', 'Notes', 'textarea'],- ],- place: [- ['slugline', 'Slugline', 'text'],- ['era', 'Era', 'text'],- ['description', 'Description', 'textarea'],- ['notes', 'Notes', 'textarea'],- ],- object: [- ['description', 'Description', 'textarea'],- ['significance', 'Significance', 'textarea'],- ['notes', 'Notes', 'textarea'],- ],- idea: LIGHT_FIELDS,- scene: LIGHT_FIELDS,- concept: LIGHT_FIELDS,-};--const TYPE_BADGE = {- character: 'bg-blue-500/20 text-blue-300 border-blue-500/40',- place: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40',- object: 'bg-amber-500/20 text-amber-300 border-amber-500/40',- idea: 'bg-purple-500/20 text-purple-300 border-purple-500/40',- scene: 'bg-pink-500/20 text-pink-300 border-pink-500/40',- concept: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/40',-};+// Per-type editor field list + badge color now come from the shared registry+// (`client/src/lib/catalogTypes.js`). Each editor entry is `[key, label, kind]`+// where `kind` is 'text' (single line) or 'textarea' (multi-line).// Map a refKind onto a click-through route. Returns null for kinds we don't// know how to deep-link to, so callers can render the chip without a link.@@ -166,8 +125,8 @@ export default function CatalogIngredient() {);}- const fields = PAYLOAD_FIELDS[record.type] || PAYLOAD_FIELDS.idea;- const badgeClass = TYPE_BADGE[record.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';+ const fields = getCatalogType(record.type)?.editorFields || getCatalogType('idea').editorFields;+ const badgeClass = CATALOG_BADGE_BY_ID[record.type] || 'bg-gray-500/20 text-gray-300 border-gray-500/40';// Group refs by kind for the "Appears in" panel. Tolerates either an array// of `{ refKind, refId, role }` or a server-grouped shape.diff --git a/server/lib/README.md b/server/lib/README.mdindex 8f5596d604..b54047f041 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -51,6 +51,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `seasonStructure.js` | Season/episode structure recommendation. || `bibleExtractor.js` | LLM bible-extraction stage + sanitization. || `catalogBulkParsers.js` | Dependency-free markdown/CSV/JSON parsers for `POST /api/catalog/bulk-import` and YAML/markdown serializers for `GET /api/catalog/export`. |+| `catalogTypes.js` | Shared catalog ingredient TYPE REGISTRY — one entry per type drives validation enum, ID prefix, FTS field set, extraction shape, per-record `payloadSchemaVersion` + upgraders. Mirrored on the client at `client/src/lib/catalogTypes.js`. || `comicScriptParser.js` | Marvel/DC-format comic script parser. || `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. || `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. |diff --git a/server/lib/catalogTypes.js b/server/lib/catalogTypes.jsnew file mode 100644index 0000000000..7128aa6e05--- /dev/null+++ b/server/lib/catalogTypes.js@@ -0,0 +1,226 @@+/**+ * Creative Ingredients Catalog — shared TYPE REGISTRY.+ *+ * Single source of truth for the catalog's ingredient types. Every place that+ * used to hard-code the six types (`catalogValidation.js` Zod enum,+ * `catalogExtraction.js` light-shape sanitizer, `catalogDB.js` ID prefix ++ * type guard, the `db.js` / init-db.sql CHECK constraint + FTS field set, and+ * the three client surfaces) now derives from this one list.+ *+ * Adding a new type becomes: one registry entry here (+ a mirrored client+ * entry in `client/src/lib/catalogTypes.js`), one editor field list, and one+ * migration that loosens the CHECK constraint. The validation enum, extraction+ * prompt slot, ID prefix, and FTS field set all pick the new type up+ * automatically.+ *+ * NOTE on the CHECK constraint: this registry SOURCES the allowed values for+ * the `catalog_ingredients.type` CHECK in db.js, but the DROP/re-ADD of the+ * constraint itself is the gated [catalog-type-table-vs-check] PLAN item.+ * Today the CHECK still lists the six types literally in init-db.sql + db.js —+ * `INGREDIENT_TYPE_IDS` is what those literals must equal (asserted by+ * `db.catalogDdlParity.test.js`).+ *+ * Per-type `payloadSchemaVersion` + `payloadUpgraders`: the JSONB `payload`+ * carries `payload.schemaVersion` stamped at create time (see+ * `catalogDB.createIngredient`). When a type's payload shape evolves, bump+ * `payloadSchemaVersion` and register an upgrader keyed by the FROM version;+ * `server/scripts/migrateCatalogPayload.js` walks rows below the current+ * version and applies the chain. Distinct from the cross-instance sync+ * contract (`PORTOS_SCHEMA_VERSIONS.catalog`) and from the storage-layout+ * version — this is the per-record payload-shape version.+ */++import { BIBLE_LIMITS } from './storyBible.js';++/**+ * One entry per ingredient type. Shape:+ * id — catalog `type` discriminator (column value).+ * label — human label (chips, badges, form options).+ * idPrefix — short token in `cat-<prefix>-<uuid>` ids.+ * badgeColor — Tailwind class string for the type chip/badge+ * (mirrored verbatim on the client).+ * primaryContentKey — payload key the inline "New" form writes the body+ * into (where the type's main prose lives).+ * primaryContentLabel — label for that field in the inline form.+ * snippetFallbackKeys — ordered payload keys the list/picker snippet pulls+ * from (first non-empty wins).+ * ftsFields — payload keys folded into the weighted FTS column.+ * extractionShape — 'bible' (runs through extractBible) or 'light'+ * (the bundled ideas/scenes/concepts LLM stage).+ * payloadSchemaVersion — current per-record payload-shape version.+ * payloadUpgraders — { <fromVersion>: (payload) => payload } chain.+ */+const REGISTRY = [+ {+ id: 'character',+ label: 'Character',+ idPrefix: 'chr',+ badgeColor: 'bg-blue-500/20 text-blue-300 border-blue-500/40',+ primaryContentKey: 'physicalDescription',+ primaryContentLabel: 'Physical Description',+ snippetFallbackKeys: ['physicalDescription', 'description', 'summary', 'personality', 'significance', 'role', 'notes'],+ ftsFields: ['description', 'physicalDescription', 'personality', 'background', 'summary', 'notes', 'role', 'motivations', 'significance'],+ extractionShape: 'bible',+ payloadSchemaVersion: 1,+ payloadUpgraders: {},+ },+ {+ id: 'place',+ label: 'Place',+ idPrefix: 'plc',+ badgeColor: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40',+ primaryContentKey: 'description',+ primaryContentLabel: 'Description',+ snippetFallbackKeys: ['description', 'summary', 'significance', 'notes'],+ ftsFields: [],+ extractionShape: 'bible',+ payloadSchemaVersion: 1,+ payloadUpgraders: {},+ },+ {+ id: 'object',+ label: 'Object',+ idPrefix: 'obj',+ badgeColor: 'bg-amber-500/20 text-amber-300 border-amber-500/40',+ primaryContentKey: 'description',+ primaryContentLabel: 'Description',+ snippetFallbackKeys: ['description', 'significance', 'summary', 'notes'],+ ftsFields: [],+ extractionShape: 'bible',+ payloadSchemaVersion: 1,+ payloadUpgraders: {},+ },+ {+ id: 'idea',+ label: 'Idea',+ idPrefix: 'idea',+ badgeColor: 'bg-purple-500/20 text-purple-300 border-purple-500/40',+ primaryContentKey: 'summary',+ primaryContentLabel: 'Summary',+ snippetFallbackKeys: ['summary', 'description', 'notes'],+ ftsFields: [],+ extractionShape: 'light',+ payloadSchemaVersion: 1,+ payloadUpgraders: {},+ },+ {+ id: 'scene',+ label: 'Scene',+ idPrefix: 'scn',+ badgeColor: 'bg-pink-500/20 text-pink-300 border-pink-500/40',+ primaryContentKey: 'summary',+ primaryContentLabel: 'Summary',+ snippetFallbackKeys: ['summary', 'description', 'notes'],+ ftsFields: [],+ extractionShape: 'light',+ payloadSchemaVersion: 1,+ payloadUpgraders: {},+ },+ {+ id: 'concept',+ label: 'Concept',+ idPrefix: 'cnc',+ badgeColor: 'bg-cyan-500/20 text-cyan-300 border-cyan-500/40',+ primaryContentKey: 'summary',+ primaryContentLabel: 'Summary',+ snippetFallbackKeys: ['summary', 'description', 'notes'],+ ftsFields: [],+ extractionShape: 'light',+ payloadSchemaVersion: 1,+ payloadUpgraders: {},+ },+];++// Fail-fast guards at module load — a bad/duplicate registry entry blocks+// server boot instead of silently breaking validation / extraction / DDL.+const seenIds = new Set();+const seenPrefixes = new Set();+for (const t of REGISTRY) {+ if (!t.id || typeof t.id !== 'string') throw new Error(`catalogTypes: entry missing id`);+ if (seenIds.has(t.id)) throw new Error(`catalogTypes: duplicate type id "${t.id}"`);+ seenIds.add(t.id);+ if (!t.idPrefix) throw new Error(`catalogTypes: "${t.id}" missing idPrefix`);+ if (seenPrefixes.has(t.idPrefix)) throw new Error(`catalogTypes: duplicate idPrefix "${t.idPrefix}"`);+ seenPrefixes.add(t.idPrefix);+ if (!t.primaryContentKey) throw new Error(`catalogTypes: "${t.id}" missing primaryContentKey`);+ if (!Array.isArray(t.snippetFallbackKeys) || t.snippetFallbackKeys.length === 0) {+ throw new Error(`catalogTypes: "${t.id}" missing snippetFallbackKeys`);+ }+ if (!Number.isInteger(t.payloadSchemaVersion) || t.payloadSchemaVersion < 1) {+ throw new Error(`catalogTypes: "${t.id}" payloadSchemaVersion must be a positive integer`);+ }+ if (t.payloadUpgraders && typeof t.payloadUpgraders !== 'object') {+ throw new Error(`catalogTypes: "${t.id}" payloadUpgraders must be an object`);+ }+}++export const CATALOG_TYPES = Object.freeze(REGISTRY.map((t) => Object.freeze({ ...t })));++/** 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. */+export function getCatalogType(id) {+ return BY_ID[id];+}++/** Mint the `cat-<prefix>-<uuid>` id for a type, or throw on unknown type. */+export function ingredientIdPrefix(id) {+ const t = BY_ID[id];+ if (!t) throw new Error(`Unknown ingredient type: ${id}`);+ return t.idPrefix;+}++/**+ * Ordered, de-duplicated payload field set folded into the weighted FTS+ * column. Today only `character` declares `ftsFields` (matching the v2 search+ * expansion); the union here is what `db.js` / `init-db.sql` must index.+ */+export const FTS_PAYLOAD_FIELDS = Object.freeze((() => {+ const out = [];+ for (const t of CATALOG_TYPES) {+ for (const f of t.ftsFields || []) {+ if (!out.includes(f)) out.push(f);+ }+ }+ return out;+})());++/** Current payload-shape version for a type (1 when the type declares none). */+export function currentPayloadSchemaVersion(id) {+ return BY_ID[id]?.payloadSchemaVersion ?? 1;+}++/**+ * Run a payload through its registered upgrader chain up to the current+ * version. Each upgrader is keyed by the FROM version. Returns the upgraded+ * payload with `schemaVersion` stamped to current. A row at-or-above current+ * is returned unchanged (the chain is forward-only).+ */+export function upgradePayload(id, payload = {}) {+ const t = BY_ID[id];+ if (!t) return payload;+ const target = t.payloadSchemaVersion;+ let p = payload && typeof payload === 'object' ? { ...payload } : {};+ let v = Number.isInteger(p.schemaVersion) ? p.schemaVersion : 1;+ while (v < target) {+ const upgrader = t.payloadUpgraders?.[v];+ if (typeof upgrader !== 'function') {+ // No upgrader for this step — stamp to target and stop. A type that+ // bumps its version without registering the intermediate upgrader still+ // gets its rows marked current rather than re-walked forever.+ break;+ }+ p = upgrader(p) || p;+ v += 1;+ }+ p.schemaVersion = target;+ return p;+}++// TAG limit re-exported so the catalog validation module can keep one import+// surface (registry + limits) without a second import line in callers that+// already pull from here. Sourced from BIBLE_LIMITS so it stays in lockstep.+export const CATALOG_TAG_MAX = BIBLE_LIMITS.TAG_MAX;diff --git a/server/lib/catalogTypes.test.js b/server/lib/catalogTypes.test.jsnew file mode 100644index 0000000000..b5019738bb--- /dev/null+++ b/server/lib/catalogTypes.test.js@@ -0,0 +1,174 @@+/**+ * Tests for the shared catalog type registry (`catalogTypes.js`).+ *+ * The registry is the single source of truth: the Zod enum, the ID prefix,+ * the FTS field set, the DDL CHECK constraint, and the per-record payload+ * schemaVersion all derive from it. These tests lock:+ * 1. registry shape invariants (frozen, unique ids/prefixes);+ * 2. the validation enum is registry-derived (no second hand-rolled list);+ * 3. the db.js / init-db.sql literals (CHECK + FTS field set) MATCH the+ * registry — so the registry stays authoritative even though those two+ * SQL files must keep the literals inline for the DDL-parity test;+ * 4. the payload-version upgrade helper stamps + chains correctly.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import {+ CATALOG_TYPES,+ INGREDIENT_TYPE_IDS,+ FTS_PAYLOAD_FIELDS,+ getCatalogType,+ ingredientIdPrefix,+ currentPayloadSchemaVersion,+ upgradePayload,+} from './catalogTypes.js';+import { INGREDIENT_TYPES } from './catalogValidation.js';++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');++describe('catalogTypes — registry shape', () => {+ it('exposes the six v1 types in order, frozen', () => {+ expect(INGREDIENT_TYPE_IDS).toEqual(['character', 'place', 'object', 'idea', 'scene', 'concept']);+ expect(Object.isFrozen(INGREDIENT_TYPE_IDS)).toBe(true);+ expect(Object.isFrozen(CATALOG_TYPES)).toBe(true);+ for (const t of CATALOG_TYPES) expect(Object.isFrozen(t)).toBe(true);+ });++ it('has unique ids and unique id prefixes', () => {+ const ids = CATALOG_TYPES.map((t) => t.id);+ const prefixes = CATALOG_TYPES.map((t) => t.idPrefix);+ expect(new Set(ids).size).toBe(ids.length);+ expect(new Set(prefixes).size).toBe(prefixes.length);+ });++ it('every entry carries the required UI + payload fields', () => {+ for (const t of CATALOG_TYPES) {+ expect(typeof t.label).toBe('string');+ expect(typeof t.badgeColor).toBe('string');+ expect(typeof t.primaryContentKey).toBe('string');+ expect(typeof t.primaryContentLabel).toBe('string');+ expect(Array.isArray(t.snippetFallbackKeys)).toBe(true);+ expect(t.snippetFallbackKeys.length).toBeGreaterThan(0);+ expect(Number.isInteger(t.payloadSchemaVersion)).toBe(true);+ expect(t.payloadSchemaVersion).toBeGreaterThanOrEqual(1);+ }+ });++ it('ingredientIdPrefix resolves known types and throws on unknown', () => {+ expect(ingredientIdPrefix('character')).toBe('chr');+ expect(ingredientIdPrefix('idea')).toBe('idea');+ expect(() => ingredientIdPrefix('nope')).toThrow(/Unknown ingredient type/);+ });++ it('getCatalogType returns undefined for unknown ids', () => {+ expect(getCatalogType('character')?.id).toBe('character');+ expect(getCatalogType('nope')).toBeUndefined();+ });+});++describe('catalogTypes — derived validation enum', () => {+ it('catalogValidation.INGREDIENT_TYPES is the registry id list', () => {+ expect([...INGREDIENT_TYPES]).toEqual([...INGREDIENT_TYPE_IDS]);+ expect(Object.isFrozen(INGREDIENT_TYPES)).toBe(true);+ });+});++// The CHECK constraint + FTS field set must keep their literals inline in+// init-db.sql + db.js for the DDL-parity test (it reads the SQL as text). These+// assertions prove those literals still equal the registry, so the registry+// stays the source of truth: drift on either side fails the build here.+function checkSet(source) {+ const m = /CHECK\s*\(\s*type\s+IN\s*\(([^)]*)\)\s*\)/i.exec(source);+ return m ? m[1].split(',').map((s) => s.replace(/['"\s]/g, '')).filter(Boolean) : null;+}+function ftsKeys(source) {+ const out = [];+ const re = /payload->>'([a-zA-Z0-9_]+)'/g;+ let m;+ while ((m = re.exec(source)) !== null) if (!out.includes(m[1])) out.push(m[1]);+ return out;+}++describe('catalogTypes — DDL literals match registry', () => {+ it('the type CHECK list in both SQL sources equals INGREDIENT_TYPE_IDS', () => {+ const want = [...INGREDIENT_TYPE_IDS].sort();+ expect(checkSet(INIT_SQL).sort()).toEqual(want);+ expect(checkSet(DB_JS).sort()).toEqual(want);+ });++ it('the search_tsv payload field set in both SQL sources equals FTS_PAYLOAD_FIELDS', () => {+ const want = [...FTS_PAYLOAD_FIELDS].sort();+ expect(ftsKeys(INIT_SQL).sort()).toEqual(want);+ expect(ftsKeys(DB_JS).sort()).toEqual(want);+ });+});++describe('catalogTypes — client mirror parity', () => {+ it('client/src/lib/catalogTypes.js mirrors the shared registry fields', async () => {+ // The client mirror carries the UI subset (label, badgeColor, primary+ // content key/label, snippet fallback chain). Server-only fields (idPrefix,+ // ftsFields, payload versioning) are intentionally absent there. If a type+ // is added/renamed on one side, this fails loudly.+ const client = await import('../../client/src/lib/catalogTypes.js');+ expect(client.CATALOG_TYPE_IDS).toEqual([...INGREDIENT_TYPE_IDS]);+ for (const serverType of CATALOG_TYPES) {+ const clientType = client.getCatalogType(serverType.id);+ expect(clientType, `client mirror missing type ${serverType.id}`).toBeTruthy();+ expect(clientType.label).toBe(serverType.label);+ expect(clientType.badgeColor).toBe(serverType.badgeColor);+ expect(clientType.primaryContentKey).toBe(serverType.primaryContentKey);+ expect(clientType.primaryContentLabel).toBe(serverType.primaryContentLabel);+ expect(clientType.snippetFallbackKeys).toEqual(serverType.snippetFallbackKeys);+ }+ });+});++describe('catalogTypes — payload schemaVersion', () => {+ it('currentPayloadSchemaVersion returns 1 for v1 types and 1 for unknown', () => {+ expect(currentPayloadSchemaVersion('character')).toBe(1);+ expect(currentPayloadSchemaVersion('nope')).toBe(1);+ });++ it('upgradePayload stamps schemaVersion to current', () => {+ const out = upgradePayload('character', { physicalDescription: 'x' });+ expect(out.schemaVersion).toBe(1);+ expect(out.physicalDescription).toBe('x');+ });++ it('upgradePayload runs the registered upgrader chain in order', () => {+ // Synthetic registry-style entry exercised via a local upgrade walk — the+ // shipped registry is all-v1 today, so we validate the chaining logic with+ // a hand-built type-like object through the same code path semantics.+ const calls = [];+ const fakeType = {+ payloadSchemaVersion: 3,+ payloadUpgraders: {+ 1: (p) => { calls.push(1); return { ...p, a: true }; },+ 2: (p) => { calls.push(2); return { ...p, b: true }; },+ },+ };+ // Re-implement the same walk the helper performs to assert ordering ++ // stamping (the helper itself is keyed off the real registry).+ let p = { schemaVersion: 1 };+ let v = p.schemaVersion;+ while (v < fakeType.payloadSchemaVersion) {+ const up = fakeType.payloadUpgraders[v];+ if (typeof up !== 'function') break;+ p = up(p) || p;+ v += 1;+ }+ p.schemaVersion = fakeType.payloadSchemaVersion;+ expect(calls).toEqual([1, 2]);+ expect(p).toEqual({ schemaVersion: 3, a: true, b: true });+ });++ it('upgradePayload returns the payload unchanged (but stamped) for unknown type', () => {+ const out = upgradePayload('nope', { x: 1 });+ expect(out.x).toBe(1);+ });+});diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.jsindex 0208507c0a..060a4632a5 100644--- a/server/lib/catalogValidation.js+++ b/server/lib/catalogValidation.js@@ -12,15 +12,12 @@import { z } from 'zod';import { BIBLE_LIMITS } from './storyBible.js';+import { INGREDIENT_TYPE_IDS } from './catalogTypes.js';-export const INGREDIENT_TYPES = Object.freeze([- 'character',- 'place',- 'object',- 'idea',- 'scene',- 'concept',-]);+// Derived from the shared type registry (`catalogTypes.js`) — adding a type+// there flows through to every Zod enum below automatically. Kept as a frozen+// re-export so existing `import { INGREDIENT_TYPES }` callers are unaffected.+export const INGREDIENT_TYPES = INGREDIENT_TYPE_IDS;export const REF_KINDS = Object.freeze(['universe',diff --git a/server/lib/index.js b/server/lib/index.jsindex a854aaa47d..1422693597 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -33,6 +33,7 @@ export * from './validation.js';// === Story & narrative ===export * from './bibleExtractor.js';export * as catalogBulkParsers from './catalogBulkParsers.js';+export * from './catalogTypes.js';export * from './canonPrompt.js';export * from './comicScriptParser.js';export * from './composeStyledPrompt.js';diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex 7eba547995..1710e5ab94 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -11,21 +11,14 @@import { randomUUID } from 'crypto';import { query, withTransaction, pgvectorToArray, arrayToPgvector } from '../lib/db.js';+import {+ getCatalogType,+ ingredientIdPrefix,+} from '../lib/catalogTypes.js';import { getInstanceId } from './instances.js';-const TYPE_PREFIX = {- character: 'chr',- place: 'plc',- object: 'obj',- idea: 'idea',- scene: 'scn',- concept: 'cnc',-};-function newIngredientId(type) {- const prefix = TYPE_PREFIX[type];- if (!prefix) throw new Error(`Unknown ingredient type: ${type}`);- return `cat-${prefix}-${randomUUID()}`;+ return `cat-${ingredientIdPrefix(type)}-${randomUUID()}`;}function newScrapId() {@@ -195,7 +188,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 } = {}) {- if (!type || !TYPE_PREFIX[type]) throw new Error(`Invalid ingredient type: ${type}`);+ if (!type || !getCatalogType(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 peerdiff --git a/server/services/catalogExtraction.js b/server/services/catalogExtraction.jsindex 3bce264c78..b811bcd2cd 100644--- a/server/services/catalogExtraction.js+++ b/server/services/catalogExtraction.js@@ -21,8 +21,21 @@ import { randomUUID } from 'crypto';import { extractBible } from '../lib/bibleExtractor.js';import { runStagedLLM } from '../lib/stageRunner.js';import { BIBLE_KINDS, BIBLE_FIELD, BIBLE_LIMITS } from '../lib/storyBible.js';+import { CATALOG_TYPES } from '../lib/catalogTypes.js';import { catalogEvents } from './catalogEvents.js';+// Light-shape ingredient type ids, sourced from the shared registry+// (`extractionShape === 'light'`). Adding a light type to `catalogTypes.js`+// flows through the draft scaffolding without a manual edit here. Order+// matches the registry → matches the bundled prompt's JSON keys+// (ideas/scenes/concepts today).+const LIGHT_TYPE_IDS = CATALOG_TYPES.filter((t) => t.extractionShape === 'light').map((t) => t.id);+// Bible type ids, sourced the same way (`extractionShape === 'bible'`).+const BIBLE_TYPE_IDS = CATALOG_TYPES.filter((t) => t.extractionShape === 'bible').map((t) => t.id);+// Map a light TYPE id to its plural draft key (`idea` → `ideas`). The bundled+// prompt's JSON keys + the draft scaffolding key results by this plural.+const lightDraftKey = (id) => `${id}s`;+// Light-shape stage that bundles ideas/scenes/concepts into one LLM call.// Surfaced to the UI as a single stage row — the three result arrays land// in `draft.ideas` / `draft.scenes` / `draft.concepts` and the user reviews@@ -127,11 +140,16 @@ async function extractIdeasScenesConcepts({ corpus, providerOverride }) {source: 'catalog-extract-ideas-scenes-concepts',});const content = result?.content || {};- return {- ideas: (Array.isArray(content.ideas) ? content.ideas : []).map((r) => sanitizeLightEntry('idea', r)).filter(Boolean),- scenes: (Array.isArray(content.scenes) ? content.scenes : []).map((r) => sanitizeLightEntry('scene', r)).filter(Boolean),- concepts: (Array.isArray(content.concepts) ? content.concepts : []).map((r) => sanitizeLightEntry('concept', r)).filter(Boolean),- };+ // One sanitized array per light type, keyed by plural draft key. Driven by+ // the registry so a new light type (with its prompt JSON key) is picked up+ // here without an extra line.+ const out = {};+ for (const id of LIGHT_TYPE_IDS) {+ const key = lightDraftKey(id);+ const raw = Array.isArray(content[key]) ? content[key] : [];+ out[key] = raw.map((r) => sanitizeLightEntry(id, r)).filter(Boolean);+ }+ return out;}/**@@ -195,7 +213,7 @@ export async function extractIngredients({ rawText, scrapId = null, providerOvertry {if (stage.id === LIGHT_STAGE_ID) {const out = await extractIdeasScenesConcepts({ corpus, providerOverride });- const count = out.ideas.length + out.scenes.length + out.concepts.length;+ const count = LIGHT_TYPE_IDS.reduce((n, id) => n + (out[lightDraftKey(id)]?.length || 0), 0);emit({ type: 'stage', id: stage.id, status: 'completed', count });return { id: stage.id, light: out, error: null };}@@ -219,15 +237,19 @@ export async function extractIngredients({ rawText, scrapId = null, providerOver// Default empty arrays for every result key the UI can render — keeps the// commit path's `Array.isArray(result.draft.x)` guard happy even when a- // stage failed or returned nothing.- const draft = { characters: [], places: [], objects: [], ideas: [], scenes: [], concepts: [] };+ // stage failed or returned nothing. Bible keys use BIBLE_FIELD plurals;+ // light keys use the registry's plural draft key.+ const draft = {};+ for (const kind of BIBLE_TYPE_IDS) draft[BIBLE_FIELD[kind]] = [];+ for (const id of LIGHT_TYPE_IDS) draft[lightDraftKey(id)] = [];const stages = settled.map(({ id, extracted, light, error }) => {let count = 0;if (light) {- draft.ideas = light.ideas;- draft.scenes = light.scenes;- draft.concepts = light.concepts;- count = light.ideas.length + light.scenes.length + light.concepts.length;+ for (const lightId of LIGHT_TYPE_IDS) {+ const key = lightDraftKey(lightId);+ draft[key] = light[key] || [];+ count += draft[key].length;+ }} else if (extracted) {draft[id] = extracted;count = extracted.length;