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

unify catalog ingredient + universe canon entry via bidirectional projection

[._.]/ Adam Eivy4ac0c33e4936
diff --git a/scripts/migrations/054-reconcile-canon-catalog.js b/scripts/migrations/054-reconcile-canon-catalog.js
new file mode 100644
index 0000000000..baaba0104b
--- /dev/null
+++ b/scripts/migrations/054-reconcile-canon-catalog.js
@@ -0,0 +1,31 @@
+/**
+ * Registration stub for the canon↔catalog reconciliation data repair.
+ *
+ * The bidirectional projection (server/services/catalogCanonProjection.js)
+ * keeps an embedded universe-canon entry and its `catalog_ingredients` row in
+ * lockstep going forward. But on the FIRST boot after the upgrade, the two
+ * stores can already disagree (they were copy-on-write mirrors before). The
+ * repair walks every universe canon entry carrying an `ingredientId`,
+ * LWW-merges embedded vs catalog payload on `updatedAt`, and writes the winner
+ * to BOTH sides so they converge.
+ *
+ * The actual repair walks the catalog (Postgres) + universe records, so it
+ * needs the pool — but the `scripts/migrations/` runner executes BEFORE the
+ * pool is initialized (same reason migrations 048–053 are boot-time + stub-
+ * registered). The reconcile therefore runs at boot from
+ * `server/scripts/reconcileCanonCatalog.js` (after `ensureSchema()` + the
+ * bible→catalog backfill + `migrateCatalogPayload`), marker-gated in
+ * `data/catalog-canon-reconcile.applied.json`.
+ *
+ * This stub exists so the change is registered the standard way: it lands in
+ * `data/migrations.applied.json` so the migration ledger and `git log` show
+ * when the canon↔catalog reconciliation was introduced.
+ *
+ * No-op + idempotent: nothing to do in the file runner.
+ */
+
+export default {
+ async up() {
+ console.log('🔁 canon↔catalog reconcile: repair runs at boot (reconcileCanonCatalog.js); nothing to do in the file runner');
+ },
+};
diff --git a/scripts/migrations/054-reconcile-canon-catalog.test.js b/scripts/migrations/054-reconcile-canon-catalog.test.js
new file mode 100644
index 0000000000..fbd822cf3d
--- /dev/null
+++ b/scripts/migrations/054-reconcile-canon-catalog.test.js
@@ -0,0 +1,16 @@
+/**
+ * Migration 054 is a REGISTRATION STUB — the actual canon↔catalog reconcile
+ * runs at boot from server/scripts/reconcileCanonCatalog.js (which needs the
+ * Postgres pool, unavailable to the file runner). This stub exists only so the
+ * change lands in the migration ledger; its `up()` is a logging no-op. The test
+ * just asserts it runs without throwing so the boot runner never crashes on it.
+ */
+
+import { describe, it, expect } from 'vitest';
+import migration from './054-reconcile-canon-catalog.js';
+
+describe('migration 054 — reconcile-canon-catalog (registration stub)', () => {
+ it('is a no-op that resolves without throwing', async () => {
+ await expect(migration.up()).resolves.toBeUndefined();
+ });
+});
diff --git a/server/index.js b/server/index.js
index dc9efb7dde..181918df69 100644
--- a/server/index.js
+++ b/server/index.js
@@ -718,6 +718,14 @@ ensureSelf()
// version, so this is free on steady-state boots.
const { migrateCatalogPayload } = await import('./scripts/migrateCatalogPayload.js');
await migrateCatalogPayload();
+ // One-time canon↔catalog reconciliation: collapse any pre-existing
+ // divergence between an embedded universe-canon entry and its catalog
+ // row (they were copy-on-write mirrors before the bidirectional
+ // projection landed). LWW on updatedAt; writes the winner to both sides.
+ // Runs LAST so promoted rows exist and are at current payload-shape
+ // version; marker-gated in data/catalog-canon-reconcile.applied.json.
+ const { reconcileCanonCatalog } = await import('./scripts/reconcileCanonCatalog.js');
+ await reconcileCanonCatalog();
} catch (err) {
console.error(`🪄 catalog migrations failed at boot: ${err.message}`);
}
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 79631872cf..3a10a5bf89 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -4,6 +4,7 @@
import { Router } from 'express';
import * as catalogDB from '../services/catalogDB.js';
import * as catalogSync from '../services/catalogSync.js';
+import { projectToCanon } from '../services/catalogCanonProjection.js';
import { withTransaction } from '../lib/db.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
@@ -275,6 +276,18 @@ router.patch('/ingredients/:id', asyncHandler(async (req, res) => {
);
if (!updated) throw new ServerError('Ingredient not found', { status: 404 });
res.json(updated);
+ // Fan the catalog edit into every linked universe's embedded canon entry so
+ // the two stores of record never diverge. Best-effort fire-and-forget: it
+ // runs AFTER the response and is outside-request-lifecycle-style fan-out, so
+ // it MUST be try/catch-guarded — an uncaught rejection here (a universe write
+ // failing) would otherwise crash the process with no `next(err)` to bubble to.
+ // A name/payload change is the only thing the cache mirrors; a tag-only edit
+ // (or embedding-only) skips the projection.
+ if (fieldPatch.name !== undefined || fieldPatch.payload !== undefined) {
+ projectToCanon(req.params.id, updated).catch((err) => {
+ console.error(`🔁 catalog→canon projection failed for ${req.params.id}: ${err.message}`);
+ });
+ }
}));
// Revision history for one ingredient (newest first). Local audit trail — see
diff --git a/server/scripts/reconcileCanonCatalog.js b/server/scripts/reconcileCanonCatalog.js
new file mode 100644
index 0000000000..e8544cffad
--- /dev/null
+++ b/server/scripts/reconcileCanonCatalog.js
@@ -0,0 +1,160 @@
+/**
+ * One-time boot reconciliation: collapse any pre-existing divergence between an
+ * embedded universe-canon entry and its `catalog_ingredients` row.
+ *
+ * Before the bidirectional projection (server/services/catalogCanonProjection.js)
+ * landed, the Catalog detail page and the Universe Builder canon surface were
+ * copy-on-write mirrors — an edit on either side went stale on the other. On
+ * the first boot after the upgrade, those two stores can already disagree. This
+ * repair walks every universe canon entry that carries an `ingredientId`,
+ * LWW-merges the embedded payload vs the catalog payload on `updatedAt`, and
+ * writes the WINNER to BOTH sides so they converge. From then on the live
+ * projection keeps them in lockstep.
+ *
+ * Writes:
+ * - universe side: `updateUniverse(..., { silent })` — silent suppresses the
+ * per-universe peer-sync fan-out (this is a local data repair, not a user
+ * edit; peers reconcile on their own boot).
+ * - catalog side: `updateIngredient(..., { source: 'sync' })` so the rewrite
+ * reads as a system reconciliation in the revision history, not a user edit.
+ *
+ * Idempotent + marker-gated (`data/catalog-canon-reconcile.applied.json`): once
+ * a clean pass completes, every subsequent boot is a no-op. A second run over
+ * already-converged rows is a no-op anyway (the LWW comparison finds them
+ * equal-or-fresher and writes nothing material).
+ *
+ * The corresponding `scripts/migrations/054-reconcile-canon-catalog.js` is a
+ * registration stub for the migration ledger — the actual repair runs here
+ * (boot-time) because the `scripts/migrations/` runner executes before the DB
+ * pool is up (same reason migrations 048–053 are boot-time + stubbed).
+ *
+ * Invoked from server/index.js at boot, after `ensureSchema()` + the bible→
+ * catalog backfill + `migrateCatalogPayload`, so every promoted row exists and
+ * is at its current payload-shape version before this reconciles content.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { PATHS } from '../lib/fileUtils.js';
+import { BIBLE_FIELD } from '../lib/storyBible.js';
+import { listUniverses, updateUniverse } from '../services/universeBuilder.js';
+import * as catalogDB from '../services/catalogDB.js';
+// Reuse the live projection's canon-entry→payload strip so a reconcile and a
+// live projection produce byte-identical catalog payloads (a divergent rule
+// would re-introduce the very drift this repair exists to collapse).
+import { entryToPayload } from '../services/catalogCanonProjection.js';
+
+const MARKER_VERSION = 1;
+const MARKER_FILENAME = 'catalog-canon-reconcile.applied.json';
+
+const CANON_ARRAY_KEYS = Object.values(BIBLE_FIELD); // ['characters','places','objects']
+
+async function readMarker() {
+ const path = join(PATHS.data, MARKER_FILENAME);
+ const raw = await readFile(path, 'utf-8').catch(() => null);
+ if (!raw) return null;
+ try { return JSON.parse(raw); } catch { return null; }
+}
+
+async function writeMarker(payload) {
+ const path = join(PATHS.data, MARKER_FILENAME);
+ await writeFile(path, JSON.stringify(payload, null, 2), 'utf-8');
+}
+
+/**
+ * Public entry point. Walk every universe canon entry with an `ingredientId`,
+ * LWW-merge embedded vs catalog payload, write the winner to both sides.
+ * `force` re-runs past the marker (tests / admin re-trigger).
+ */
+export async function reconcileCanonCatalog({ force = false } = {}) {
+ const marker = await readMarker();
+ if (marker?.version === MARKER_VERSION && !force) {
+ return { skipped: true, marker };
+ }
+
+ console.log('🔁 canon↔catalog reconcile: starting');
+ const universes = await listUniverses({ includeDeleted: false });
+ const totals = { universesScanned: 0, scanned: 0, catalogWon: 0, canonWon: 0, errors: 0 };
+
+ for (const universe of universes) {
+ if (universe.deleted) continue;
+ totals.universesScanned++;
+ // Collect per-array, per-entry-id the winning payload to stamp back onto the
+ // embedded entries in ONE silent updateUniverse below. The catalog side is
+ // written inline (one updateIngredient per catalog-loser).
+ const canonPatches = {}; // arrayKey -> { entryId -> winningEntryFields }
+ for (const arrayKey of CANON_ARRAY_KEYS) {
+ const list = Array.isArray(universe[arrayKey]) ? universe[arrayKey] : [];
+ for (const entry of list) {
+ const ingredientId = entry?.ingredientId;
+ if (!ingredientId || !entry?.id) continue; // entries without ingredientId untouched
+ totals.scanned++;
+ try {
+ const row = await catalogDB.getIngredient(ingredientId);
+ if (!row) continue; // dangling backlink — leave both sides alone
+ const entryAt = Date.parse(entry.updatedAt || '') || 0;
+ const rowAt = Date.parse(row.updatedAt || '') || 0;
+ if (rowAt > entryAt) {
+ // Catalog row is newer → it wins. Stamp its name+payload onto the
+ // embedded entry (silent universe write below).
+ (canonPatches[arrayKey] ||= {})[entry.id] = {
+ ...entryToPayload(row.payload || {}),
+ name: row.name,
+ ingredientId,
+ updatedAt: row.updatedAt,
+ };
+ totals.catalogWon++;
+ } else if (entryAt > rowAt) {
+ // Embedded entry is newer → it wins. Write it into the catalog row.
+ await catalogDB.updateIngredient(
+ ingredientId,
+ { name: entry.name, payload: entryToPayload(entry) },
+ { source: 'sync', actor: 'canon-catalog-reconcile' },
+ );
+ totals.canonWon++;
+ }
+ // Equal timestamps → already converged; nothing to do.
+ } catch (err) {
+ console.error(`🔁 reconcile failed (${universe.id}/${arrayKey}/${ingredientId}): ${err.message}`);
+ totals.errors++;
+ }
+ }
+ }
+
+ // Stamp catalog-winner payloads back onto the embedded entries in one silent
+ // write per universe (skips when the catalog never won on this universe).
+ const hasCanonPatch = Object.keys(canonPatches).some((k) => Object.keys(canonPatches[k]).length > 0);
+ if (hasCanonPatch) {
+ await updateUniverse(universe.id, (cur) => {
+ const patch = {};
+ for (const arrayKey of CANON_ARRAY_KEYS) {
+ const byId = canonPatches[arrayKey];
+ if (!byId || Object.keys(byId).length === 0) continue;
+ const list = Array.isArray(cur[arrayKey]) ? cur[arrayKey] : [];
+ patch[arrayKey] = list.map((e) => {
+ const win = e?.id ? byId[e.id] : null;
+ return win ? { ...e, ...win } : e;
+ });
+ }
+ return Object.keys(patch).length > 0 ? patch : null;
+ }, { silent: true }).catch((err) => {
+ console.error(`🔁 reconcile: universe ${universe.id} canon stamp failed: ${err.message}`);
+ totals.errors++;
+ });
+ }
+ }
+
+ const payload = { version: MARKER_VERSION, completedAt: new Date().toISOString(), stats: totals };
+ // Only stamp the completion marker on a clean pass — a row-level failure
+ // withholds it so the (idempotent) reconcile retries next boot.
+ const wroteMarker = totals.errors === 0;
+ if (wroteMarker) await writeMarker(payload);
+
+ console.log(
+ `🔁 canon↔catalog reconcile: ${totals.universesScanned} universes, ${totals.scanned} entries scanned, ` +
+ `${totals.catalogWon} catalog-won, ${totals.canonWon} canon-won, ${totals.errors} errors` +
+ (wroteMarker ? '' : ' — marker NOT written (will retry next boot)'),
+ );
+
+ return { skipped: false, markerWritten: wroteMarker, ...payload };
+}
diff --git a/server/scripts/reconcileCanonCatalog.test.js b/server/scripts/reconcileCanonCatalog.test.js
new file mode 100644
index 0000000000..6699c193d2
--- /dev/null
+++ b/server/scripts/reconcileCanonCatalog.test.js
@@ -0,0 +1,138 @@
+/**
+ * Tests for the boot-time canon↔catalog reconciliation.
+ *
+ * fs/promises (marker), fileUtils (PATHS), universeBuilder (listUniverses /
+ * updateUniverse) and catalogDB (getIngredient / updateIngredient) are mocked,
+ * so this exercises the walk + LWW-merge + dual-write orchestration:
+ * - newer catalog row wins → stamped back onto the embedded canon entry;
+ * - newer embedded entry wins → written into the catalog row;
+ * - entries without an ingredientId are untouched;
+ * - a clean pass writes the marker; a second run is a marker-gated no-op.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const fsState = { marker: null, written: null };
+const dbState = { rows: {}, updates: [] };
+const uniState = { universes: [], canonStamps: [] };
+
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async () => (fsState.marker == null
+ ? Promise.reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ : JSON.stringify(fsState.marker))),
+ writeFile: vi.fn(async (_p, data) => { fsState.written = JSON.parse(data); }),
+}));
+
+vi.mock('../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-data' } }));
+
+vi.mock('../services/universeBuilder.js', () => ({
+ listUniverses: vi.fn(async () => uniState.universes),
+ updateUniverse: vi.fn(async (id, mutator) => {
+ const cur = uniState.universes.find((u) => u.id === id);
+ const patch = mutator(cur || {});
+ uniState.canonStamps.push({ id, patch });
+ return patch;
+ }),
+}));
+
+vi.mock('../services/catalogDB.js', () => ({
+ getIngredient: vi.fn(async (id) => dbState.rows[id] || null),
+ updateIngredient: vi.fn(async (id, patch, ctx) => {
+ dbState.updates.push({ id, patch, ctx });
+ return dbState.rows[id];
+ }),
+}));
+
+const { reconcileCanonCatalog } = await import('./reconcileCanonCatalog.js');
+
+beforeEach(() => {
+ fsState.marker = null;
+ fsState.written = null;
+ dbState.rows = {};
+ dbState.updates = [];
+ uniState.universes = [];
+ uniState.canonStamps = [];
+});
+
+describe('reconcileCanonCatalog', () => {
+ it('catalog row newer → stamps catalog payload back onto the embedded canon entry', async () => {
+ const past = '2026-01-01T00:00:00.000Z';
+ const future = '2026-02-01T00:00:00.000Z';
+ dbState.rows['cat-chr-1'] = { id: 'cat-chr-1', name: 'Ada', payload: { role: 'catalog-role' }, updatedAt: future };
+ uniState.universes = [{
+ id: 'u-1',
+ characters: [{ id: 'e1', ingredientId: 'cat-chr-1', name: 'Ada', role: 'canon-role', updatedAt: past }],
+ }];
+
+ const result = await reconcileCanonCatalog();
+
+ expect(result.skipped).toBe(false);
+ expect(result.stats.catalogWon).toBe(1);
+ expect(result.stats.canonWon).toBe(0);
+ // No catalog write (catalog already authoritative); one canon stamp.
+ expect(dbState.updates).toHaveLength(0);
+ expect(uniState.canonStamps).toHaveLength(1);
+ const stamped = uniState.canonStamps[0].patch.characters[0];
+ expect(stamped.role).toBe('catalog-role');
+ });
+
+ it('embedded canon entry newer → writes it into the catalog row', async () => {
+ const past = '2026-01-01T00:00:00.000Z';
+ const future = '2026-02-01T00:00:00.000Z';
+ dbState.rows['cat-chr-2'] = { id: 'cat-chr-2', name: 'Bee', payload: { role: 'old' }, updatedAt: past };
+ uniState.universes = [{
+ id: 'u-1',
+ characters: [{ id: 'e1', ingredientId: 'cat-chr-2', name: 'Bee', role: 'fresh', updatedAt: future }],
+ }];
+
+ const result = await reconcileCanonCatalog();
+
+ expect(result.stats.canonWon).toBe(1);
+ expect(result.stats.catalogWon).toBe(0);
+ expect(dbState.updates).toHaveLength(1);
+ expect(dbState.updates[0].patch.payload.role).toBe('fresh');
+ expect(dbState.updates[0].ctx.source).toBe('sync');
+ // No canon stamp needed (canon already authoritative).
+ expect(uniState.canonStamps).toHaveLength(0);
+ });
+
+ it('leaves entries without an ingredientId untouched', async () => {
+ uniState.universes = [{
+ id: 'u-1',
+ characters: [{ id: 'e1', name: 'Unpromoted', role: 'x', updatedAt: '2026-01-01T00:00:00.000Z' }],
+ }];
+
+ const result = await reconcileCanonCatalog();
+
+ expect(result.stats.scanned).toBe(0);
+ expect(dbState.updates).toHaveLength(0);
+ expect(uniState.canonStamps).toHaveLength(0);
+ });
+
+ it('writes the completion marker on a clean pass', async () => {
+ dbState.rows['cat-chr-3'] = { id: 'cat-chr-3', name: 'C', payload: {}, updatedAt: '2026-01-01T00:00:00.000Z' };
+ uniState.universes = [{
+ id: 'u-1',
+ characters: [{ id: 'e1', ingredientId: 'cat-chr-3', name: 'C', updatedAt: '2026-01-01T00:00:00.000Z' }],
+ }];
+
+ const result = await reconcileCanonCatalog();
+ expect(result.markerWritten).toBe(true);
+ expect(fsState.written.version).toBe(1);
+ });
+
+ it('second run is a marker-gated no-op', async () => {
+ fsState.marker = { version: 1, completedAt: '2026-01-01T00:00:00.000Z' };
+ dbState.rows['cat-chr-4'] = { id: 'cat-chr-4', name: 'D', payload: { role: 'x' }, updatedAt: '2026-02-01T00:00:00.000Z' };
+ uniState.universes = [{
+ id: 'u-1',
+ characters: [{ id: 'e1', ingredientId: 'cat-chr-4', name: 'D', role: 'y', updatedAt: '2026-01-01T00:00:00.000Z' }],
+ }];
+
+ const result = await reconcileCanonCatalog();
+
+ expect(result.skipped).toBe(true);
+ expect(dbState.updates).toHaveLength(0);
+ expect(uniState.canonStamps).toHaveLength(0);
+ });
+});
diff --git a/server/services/catalogCanonProjection.js b/server/services/catalogCanonProjection.js
new file mode 100644
index 0000000000..0c81742fc5
--- /dev/null
+++ b/server/services/catalogCanonProjection.js
@@ -0,0 +1,203 @@
+/**
+ * Bidirectional projection between an embedded universe-canon entry and its
+ * `catalog_ingredients` row — so the two NEVER diverge.
+ *
+ * Background. A universe canon entry (`universe.characters[]`, `places[]`,
+ * `objects[]`) carries the FULL bible payload PLUS a stable `ingredientId`. The
+ * matching `catalog_ingredients.payload` holds a parallel copy. Before this
+ * module the two were copy-on-write mirrors: the Catalog detail page PATCHed
+ * only the catalog row, and the Universe Builder canon surface PATCHed only
+ * `universe.characters[]`, so an edit on either side silently went stale on the
+ * other. This module collapses them to ONE store of record (the catalog row)
+ * while keeping the embedded entry as a full projection CACHE (v1 decision —
+ * many synchronous renderers / prompt-builders read `universe.characters[].x`).
+ *
+ * Two directions:
+ * projectToCanon(ingredientId, updatedIngredient)
+ * A catalog edit → fan the catalog row's name+payload into the embedded
+ * entry of every universe that references the ingredient. Best-effort /
+ * fire-and-forget at the call site (the catalog PATCH route already
+ * responded); failures are logged single-line and swallowed.
+ *
+ * projectToCatalog(universeId, canonArrays, { guardToken })
+ * A canon edit → write each embedded entry's payload back into its catalog
+ * row. Called SYNCHRONOUSLY inside updateUniverse so the cache can never
+ * lag the authoritative row on the same request.
+ *
+ * Loop safety. projectToCanon calls updateUniverse, and updateUniverse calls
+ * projectToCatalog — an A→B→A cycle. A module-level in-flight guard (`Set` of
+ * ingredient ids currently being projected, plus a per-call `guardToken`)
+ * breaks it: projectToCatalog skips any entry whose ingredientId is guarded, so
+ * the catalog row that a projectToCanon is reading FROM is never written back
+ * to inside the same logical operation. Net effect for a single user edit: each
+ * side is written EXACTLY ONCE (asserted in catalogCanonProjection.test.js).
+ *
+ * Conflict policy. LWW on `updatedAt` (no field-level merge). projectToCatalog
+ * only writes when the embedded entry's `updatedAt` is newer-or-equal to the
+ * catalog row's; projectToCanon always wins (the catalog row IS the store of
+ * record after a catalog edit). The boot reconciler (reconcileCanonCatalog.js)
+ * runs the same LWW comparison to collapse any pre-existing divergence.
+ */
+
+import * as catalogDB from './catalogDB.js';
+import { BIBLE_KIND, BIBLE_FIELD } from '../lib/storyBible.js';
+
+// Catalog `type` ↔ canon array key, derived from the bible registry so a future
+// kind added there flows through without editing this file.
+const TYPE_FOR_ARRAY = Object.freeze(
+ Object.fromEntries(Object.values(BIBLE_KIND).map((k) => [BIBLE_FIELD[k], k])),
+);
+const CANON_ARRAY_KEYS = Object.freeze(Object.values(BIBLE_FIELD));
+
+// Fields that live on the embedded canon entry but are NOT part of the catalog
+// row's `payload` (the catalog row owns `id`/`name`/timestamps as columns, and
+// `ingredientId` is the canon→catalog backlink, not payload content). Stripped
+// both directions so a round-trip is shape-stable and we never smuggle a stale
+// `schemaVersion` from one store into the other.
+const NON_PAYLOAD_KEYS = ['id', 'ingredientId', 'createdAt', 'updatedAt', 'name', 'schemaVersion'];
+
+// In-flight re-entrancy guard. Holds ingredient ids currently mid-projection so
+// the A→B→A cycle (projectToCanon → updateUniverse → projectToCatalog) can't
+// write the originating catalog row a second time. A `Set` (not a single flag)
+// because a multi-universe catalog edit projects into N universes and a single
+// canon edit can touch multiple ingredients.
+const inFlight = new Set();
+
+/**
+ * Build the catalog `payload` from an embedded canon entry (strip the control
+ * keys the row owns as columns + the backlink + schemaVersion). Exported so the
+ * boot reconciler (reconcileCanonCatalog.js) produces a byte-identical payload
+ * — a divergent strip rule between the two would re-introduce the very drift
+ * this module exists to kill.
+ */
+export function entryToPayload(entry) {
+ const payload = { ...(entry && typeof entry === 'object' ? entry : {}) };
+ for (const k of NON_PAYLOAD_KEYS) delete payload[k];
+ return payload;
+}
+
+/**
+ * Project a catalog edit into every universe that references the ingredient.
+ *
+ * Best-effort: returns a stats object `{ universes, written, skipped }` and
+ * never throws on a per-universe failure (logged single-line). The caller (the
+ * catalog PATCH route) invokes this AFTER responding, so a projection hiccup
+ * must not turn a successful edit into an error.
+ */
+export async function projectToCanon(ingredientId, updatedIngredient, deps = {}) {
+ // `deps.updateUniverse` is a test seam (the suite injects a spy to assert the
+ // canon side is written exactly once without a live universe store). Prod
+ // dynamic-imports the real one — a static import would form a require cycle
+ // (universeBuilder imports this module).
+ const updateUniverse = deps.updateUniverse || (await import('./universeBuilder.js')).updateUniverse;
+ if (!ingredientId || !updatedIngredient) return { universes: 0, written: 0, skipped: 0 };
+
+ // Guard the originating ingredient so the updateUniverse → projectToCatalog
+ // echo inside this call can't write the catalog row a second time.
+ inFlight.add(ingredientId);
+ const stats = { universes: 0, written: 0, skipped: 0 };
+ try {
+ const refs = await catalogDB.listRefsForIngredient(ingredientId);
+ const universeIds = [...new Set(
+ refs.filter((r) => r.refKind === 'universe' && r.refId).map((r) => r.refId),
+ )];
+ if (universeIds.length === 0) return stats; // no-universe-ref → silent no-op
+
+ const name = updatedIngredient.name;
+ const payload = entryToPayload(updatedIngredient.payload || {});
+ const updatedAt = updatedIngredient.updatedAt || new Date().toISOString();
+
+ for (const universeId of universeIds) {
+ stats.universes++;
+ // Mutator form: merge the catalog payload into every embedded entry that
+ // carries this ingredientId, across all canon arrays. `silent: true`
+ // suppresses the per-universe peer-sync fan-out so a catalog edit that
+ // touches N universes doesn't emit N recordUpdated events. `guardToken`
+ // threads the originating ingredientId so updateUniverse's synchronous
+ // projectToCatalog skips it (loop break).
+ const result = await updateUniverse(universeId, (cur) => {
+ let touched = false;
+ const patch = {};
+ for (const arrayKey of CANON_ARRAY_KEYS) {
+ const list = Array.isArray(cur[arrayKey]) ? cur[arrayKey] : [];
+ if (!list.some((e) => e?.ingredientId === ingredientId)) continue;
+ patch[arrayKey] = list.map((e) => {
+ if (e?.ingredientId !== ingredientId) return e;
+ touched = true;
+ return { ...e, ...payload, name, ingredientId, updatedAt };
+ });
+ }
+ return touched ? patch : null;
+ }, { silent: true, canonProjectionGuard: ingredientId }).catch((err) => {
+ console.error(`🔁 projectToCanon: universe ${universeId} update failed: ${err.message}`);
+ return null;
+ });
+ if (result) stats.written++;
+ else stats.skipped++;
+ }
+ return stats;
+ } finally {
+ inFlight.delete(ingredientId);
+ }
+}
+
+/**
+ * Project a canon edit into the catalog row for every embedded entry that
+ * carries an `ingredientId`. Called SYNCHRONOUSLY inside updateUniverse after
+ * the canon arrays persist, so the catalog row never lags the embedded cache on
+ * the same request.
+ *
+ * canonArrays — the PERSISTED universe record (or `{ characters, places,
+ * objects }` subset) read straight after the write.
+ * guardToken — when set (a projectToCanon-originated write), the entry whose
+ * ingredientId equals it is skipped (loop break).
+ *
+ * LWW: writes the catalog row only when the embedded entry's `updatedAt` is
+ * newer-or-equal to the stored row's. Best-effort per entry (logged on
+ * failure); returns `{ written, skipped }`.
+ */
+export async function projectToCatalog(universeId, canonArrays, { guardToken = null } = {}) {
+ const stats = { written: 0, skipped: 0 };
+ if (!canonArrays || typeof canonArrays !== 'object') return stats;
+
+ for (const arrayKey of CANON_ARRAY_KEYS) {
+ const list = Array.isArray(canonArrays[arrayKey]) ? canonArrays[arrayKey] : [];
+ const type = TYPE_FOR_ARRAY[arrayKey];
+ for (const entry of list) {
+ const ingredientId = entry?.ingredientId;
+ if (!ingredientId) continue;
+ // Loop break: skip the ingredient the originating projectToCanon is
+ // writing FROM (its catalog row is already authoritative this request).
+ if (ingredientId === guardToken || inFlight.has(ingredientId)) {
+ stats.skipped++;
+ continue;
+ }
+ try {
+ const row = await catalogDB.getIngredient(ingredientId);
+ if (!row) { stats.skipped++; continue; }
+ // LWW on updatedAt — only overwrite the catalog row when the embedded
+ // entry is at-least-as-fresh. An older embedded snapshot (e.g. a
+ // concurrent catalog edit won) is left alone.
+ const entryAt = Date.parse(entry.updatedAt || '') || 0;
+ const rowAt = Date.parse(row.updatedAt || '') || 0;
+ if (entryAt < rowAt) { stats.skipped++; continue; }
+ await catalogDB.updateIngredient(
+ ingredientId,
+ { name: entry.name, payload: entryToPayload(entry) },
+ { source: 'sync', actor: 'canon-projection' },
+ );
+ stats.written++;
+ } catch (err) {
+ console.error(`🔁 projectToCatalog: ingredient ${ingredientId} update failed: ${err.message}`);
+ stats.skipped++;
+ }
+ }
+ }
+ return stats;
+}
+
+// Test seam — lets the unit suite assert the guard set drains to empty after a
+// projection round-trip (no leaked in-flight tokens).
+export function _inFlightSize() {
+ return inFlight.size;
+}
diff --git a/server/services/catalogCanonProjection.test.js b/server/services/catalogCanonProjection.test.js
new file mode 100644
index 0000000000..6b0a6cb1ba
--- /dev/null
+++ b/server/services/catalogCanonProjection.test.js
@@ -0,0 +1,162 @@
+/**
+ * Bidirectional catalog↔canon projection — the highest-risk file in this PR.
+ *
+ * Needs a live Postgres (the same one `npm start` uses) for the catalog rows +
+ * refs; SKIPS cleanly when no DB is reachable. The universe side is INJECTED as
+ * a spy (`updateUniverse` dep) so the suite asserts the projection's fan-out /
+ * loop-break / LWW behavior without standing up a real universe store.
+ *
+ * The load-bearing assertion is "written EXACTLY ONCE": a single catalog edit
+ * that round-trips catalog → canon → (echo) catalog must NOT write the catalog
+ * row a second time. The injected updateUniverse calls the real
+ * `projectToCatalog` (the A→B→A cycle) and we count `updateIngredient` hits.
+ *
+ * `instances.js` stays under the global vitest.setup mock (getPeers → []) so no
+ * created row fans out to live peers; nothing here exercises the
+ * createUniverse/createSeries peerSync import path, so mockNoPeers alone is
+ * sufficient per the CLAUDE.md record-creating-tests rule.
+ */
+
+import { describe, it, expect, afterAll, vi } from 'vitest';
+import { checkHealth, ensureSchema, close } from '../lib/db.js';
+import * as catalogDB from './catalogDB.js';
+import { projectToCanon, projectToCatalog, _inFlightSize } from './catalogCanonProjection.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ const recheck = await checkHealth().catch(() => ({ hasCatalogSchema: false }));
+ if (recheck.hasCatalogSchema) dbReady = true;
+ else skipReason = 'catalog schema not present';
+ }
+}
+if (!dbReady) console.log(`⏭️ catalogCanonProjection.test: skipping suite — ${skipReason || 'no database'}`);
+
+const createdIngredientIds = new Set();
+afterAll(async () => {
+ if (!dbReady) return;
+ for (const id of createdIngredientIds) {
+ await catalogDB.deleteIngredient(id, { hard: true }).catch(() => {});
+ }
+ await close();
+});
+
+// Mint a catalog character row + a universe ref link. Returns the row.
+async function makeLinkedCharacter(universeId, { name = 'Proj Test', payload = {} } = {}) {
+ const ing = await catalogDB.createIngredient({ type: 'character', name, payload });
+ createdIngredientIds.add(ing.id);
+ await catalogDB.linkIngredientToRef(ing.id, 'universe', universeId, 'canon-character');
+ return ing;
+}
+
+describe.skipIf(!dbReady)('catalogCanonProjection', () => {
+ it('projectToCanon fans a catalog edit into every linked universe canon entry', async () => {
+ const uA = `u-proj-${Date.now()}-a`;
+ const uB = `u-proj-${Date.now()}-b`;
+ const ing = await makeLinkedCharacter(uA, { name: 'Multi' });
+ await catalogDB.linkIngredientToRef(ing.id, 'universe', uB, 'canon-character');
+
+ const seenUniverses = [];
+ const updateUniverse = vi.fn(async (universeId, mutator) => {
+ seenUniverses.push(universeId);
+ // Simulate the embedded entry carrying this ingredientId so the mutator
+ // produces a patch (returns null otherwise → counted as skipped).
+ const patch = mutator({ characters: [{ id: 'e1', ingredientId: ing.id, name: 'old' }] });
+ return patch; // truthy → counted as "written"
+ });
+
+ const stats = await projectToCanon(ing.id, { ...ing, name: 'Renamed', payload: { role: 'Hero' } }, { updateUniverse });
+ expect(stats.universes).toBe(2);
+ expect(stats.written).toBe(2);
+ expect(seenUniverses.sort()).toEqual([uA, uB].sort());
+ // Guard set drains — no leaked in-flight token.
+ expect(_inFlightSize()).toBe(0);
+ });
+
+ it('projectToCanon is a silent no-op for an ingredient with no universe ref', async () => {
+ const ing = await catalogDB.createIngredient({ type: 'object', name: 'Lonely Object' });
+ createdIngredientIds.add(ing.id);
+ const updateUniverse = vi.fn();
+ const stats = await projectToCanon(ing.id, ing, { updateUniverse });
+ expect(stats).toEqual({ universes: 0, written: 0, skipped: 0 });
+ expect(updateUniverse).not.toHaveBeenCalled();
+ });
+
+ it('projectToCatalog writes a canon edit into the catalog row (LWW: newer canon wins)', async () => {
+ const uId = `u-proj-${Date.now()}-c`;
+ const ing = await makeLinkedCharacter(uId, { name: 'Canon Edit', payload: { role: 'old-role' } });
+ // Embedded entry is NEWER than the row → it wins.
+ const future = new Date(Date.now() + 60_000).toISOString();
+ const canon = {
+ characters: [{
+ id: 'e1', ingredientId: ing.id, name: 'Canon Edit', role: 'new-role',
+ updatedAt: future,
+ }],
+ };
+ const stats = await projectToCatalog(uId, canon, {});
+ expect(stats.written).toBe(1);
+ const row = await catalogDB.getIngredient(ing.id);
+ expect(row.payload.role).toBe('new-role');
+ });
+
+ it('projectToCatalog LWW skips an OLDER canon snapshot (catalog row newer)', async () => {
+ const uId = `u-proj-${Date.now()}-d`;
+ const ing = await makeLinkedCharacter(uId, { name: 'Fresh Row', payload: { role: 'keep-me' } });
+ // Embedded entry is OLDER than the (just-created) row → it loses, no write.
+ const past = new Date(Date.now() - 60_000).toISOString();
+ const canon = {
+ characters: [{ id: 'e1', ingredientId: ing.id, name: 'Fresh Row', role: 'stale', updatedAt: past }],
+ };
+ const stats = await projectToCatalog(uId, canon, {});
+ expect(stats.written).toBe(0);
+ expect(stats.skipped).toBe(1);
+ const row = await catalogDB.getIngredient(ing.id);
+ expect(row.payload.role).toBe('keep-me');
+ });
+
+ it('re-entrancy guard breaks the A→B→A loop — each side written EXACTLY ONCE', async () => {
+ const uId = `u-proj-${Date.now()}-e`;
+ const ing = await makeLinkedCharacter(uId, { name: 'Loop Guard', payload: { role: 'before' } });
+
+ // Count catalog writes. The injected updateUniverse calls the REAL
+ // projectToCatalog with the originating guard token — which must skip the
+ // originating ingredient and therefore NOT write the catalog row again.
+ const updSpy = vi.spyOn(catalogDB, 'updateIngredient');
+ let catalogWritesInsideEcho = 0;
+
+ const updateUniverse = vi.fn(async (universeId, mutator, opts) => {
+ const before = updSpy.mock.calls.length;
+ // The embedded entry now carries the fresh ingredientId; updateUniverse
+ // would persist canon then synchronously project back to catalog.
+ const canon = {
+ characters: [{
+ id: 'e1', ingredientId: ing.id, name: 'Loop Guard', role: 'after',
+ updatedAt: new Date(Date.now() + 60_000).toISOString(),
+ }],
+ };
+ await projectToCatalog(universeId, canon, { guardToken: opts?.canonProjectionGuard });
+ catalogWritesInsideEcho = updSpy.mock.calls.length - before;
+ return mutator(canon); // truthy
+ });
+
+ const updated = await catalogDB.updateIngredient(ing.id, { payload: { role: 'after' } });
+ const writesAfterPrimary = updSpy.mock.calls.length;
+
+ await projectToCanon(ing.id, updated, { updateUniverse });
+
+ // The echo (projectToCatalog inside updateUniverse) must NOT have written
+ // the originating catalog row — the guard token skipped it.
+ expect(catalogWritesInsideEcho).toBe(0);
+ // Total catalog writes across the whole round-trip: only the primary edit.
+ expect(updSpy.mock.calls.length).toBe(writesAfterPrimary);
+ // Canon side written exactly once.
+ expect(updateUniverse).toHaveBeenCalledTimes(1);
+ expect(_inFlightSize()).toBe(0);
+ updSpy.mockRestore();
+ });
+});
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 57ff5dfb71..9c46f8663b 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -21,8 +21,56 @@ import {
} from '../lib/catalogTypes.js';
import { resolveImageInputPath } from '../lib/fileUtils.js';
import { chunkRawText } from '../lib/catalogChunking.js';
+import { sanitizeCharacter, sanitizePlace, sanitizeObject } from '../lib/storyBible.js';
import { getInstanceId } from './instances.js';
+// Story-bible sanitizers keyed by catalog type, for the registry
+// `extractionShape: 'bible'` types ONLY (character/place/object). The catalog
+// payload is the bible-entry shape MINUS the columns the row owns (id / name /
+// timestamps) — so we sanitize a synthetic entry `{ name, ...payload }`,
+// preserve timestamps, and strip the control fields back out before persist.
+// Scoped strictly to bible types: idea/scene/concept AND user-defined types
+// pass through untouched (running a user type's payload through a storyBible
+// sanitizer would silently drop every field it doesn't recognize).
+const BIBLE_SANITIZERS = Object.freeze({
+ character: sanitizeCharacter,
+ place: sanitizePlace,
+ object: sanitizeObject,
+});
+
+// Control fields the sanitizer stamps onto an entry that are NOT part of the
+// catalog `payload` (the row owns id/name/timestamps as columns). Stripped from
+// the sanitized entry so the stored payload stays shape-stable across the
+// catalog↔canon projection round-trip.
+const SANITIZED_NON_PAYLOAD_KEYS = ['id', 'name', 'createdAt', 'updatedAt'];
+
+/**
+ * Run a bible-type ingredient payload through its storyBible sanitizer so the
+ * structured array editors (color palette / stats / aliases) can't land
+ * malformed rows and the projection round-trip is shape-stable. Returns the
+ * sanitized payload (control fields stripped). Non-bible types (idea/scene/
+ * concept, user-defined) return their payload UNCHANGED. `preserveTimestamps`
+ * keeps the sanitizer from minting fresh ids/timestamps on an existing row.
+ */
+function sanitizeBiblePayload(type, name, payload) {
+ const sanitizer = BIBLE_SANITIZERS[type];
+ if (!sanitizer) return payload && typeof payload === 'object' ? payload : {};
+ const entry = { ...(payload && typeof payload === 'object' ? payload : {}), name: String(name || '').trim() };
+ const sane = sanitizer(entry, { preserveTimestamps: true });
+ if (!sane) return payload && typeof payload === 'object' ? payload : {};
+ const out = { ...sane };
+ for (const k of SANITIZED_NON_PAYLOAD_KEYS) delete out[k];
+ // The storyBible sanitizer only emits known bible fields, so it drops
+ // `schemaVersion`. Preserve the incoming marker (createIngredient re-stamps
+ // it anyway; updateIngredient writes payload verbatim, and the restore route
+ // relies on the marker round-tripping) so a bible payload keeps its shape
+ // version through the sanitize pass.
+ if (payload && typeof payload === 'object' && payload.schemaVersion !== undefined) {
+ out.schemaVersion = payload.schemaVersion;
+ }
+ return out;
+}
+
function newIngredientId(type) {
return `cat-${ingredientIdPrefix(type)}-${randomUUID()}`;
}
@@ -400,6 +448,11 @@ export async function createIngredient({ id: explicitId, type, name, payload = {
// same logical character has the same catalog id on every install. New
// user-initiated creates omit it and we mint a fresh prefix:uuid.
const id = explicitId || newIngredientId(type);
+ // Bible-type hardening: run character/place/object payloads through their
+ // storyBible sanitizer before persist so the structured array editors (color
+ // palette / stats / aliases) can't land malformed rows and the catalog↔canon
+ // projection stays shape-stable. Non-bible / user types pass through.
+ const sanitizedPayload = sanitizeBiblePayload(type, name, payload);
// Stamp the per-record payload-shape version from the registry so a later
// `migrateCatalogPayload` run knows which shape this row was written in.
// An incoming payload may already carry `schemaVersion` (peer backfill) — we
@@ -407,7 +460,7 @@ export async function createIngredient({ id: explicitId, type, name, payload = {
// reflects the shape this install's code actually wrote, not a stale sender
// claim. (The wire `PORTOS_SCHEMA_VERSIONS.catalog` gate covers cross-install
// skew; this is the per-record payload-shape marker, distinct from that.)
- const storedPayload = { ...(payload && typeof payload === 'object' ? payload : {}), schemaVersion: currentPayloadSchemaVersion(type) };
+ const storedPayload = { ...sanitizedPayload, schemaVersion: currentPayloadSchemaVersion(type) };
const originInstanceId = await getInstanceId();
const exec = client ? client.query.bind(client) : query;
// Route freeform tags through the canonical catalog_tags table (creating
@@ -460,9 +513,27 @@ export async function updateIngredient(id, patch = {}, { source = 'user', actor
// adding `Noir` reuses the existing `noir` row instead of accumulating a
// casing variant. `tags: []` (intentional clear) round-trips as an empty
// array; absent `tags` skips normalization entirely (the loop below skips it).
- const normalizedPatch = patch.tags !== undefined
+ let normalizedPatch = patch.tags !== undefined
? { ...patch, tags: await normalizeTags(patch.tags) }
: patch;
+ // Bible-type hardening: when a character/place/object payload is being
+ // written, run it through the storyBible sanitizer (the same one the canon
+ // surface uses) so the array editors can't land malformed rows and the
+ // catalog↔canon projection round-trip stays shape-stable. Look up the current
+ // row for its `type` (and `name`, when the patch doesn't carry one). Scoped
+ // to `extractionShape: 'bible'` types via BIBLE_SANITIZERS — idea/scene/
+ // concept and user-defined types skip this entirely. Embedding-only patches
+ // (no payload) never trigger the lookup.
+ if (normalizedPatch.payload !== undefined) {
+ const current = await getIngredient(id);
+ if (current && BIBLE_SANITIZERS[current.type]) {
+ const name = normalizedPatch.name !== undefined ? normalizedPatch.name : current.name;
+ normalizedPatch = {
+ ...normalizedPatch,
+ payload: sanitizeBiblePayload(current.type, name, normalizedPatch.payload),
+ };
+ }
+ }
const fieldMap = {
name: 'name',
payload: 'payload',
diff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.js
index 8cd3f9f816..70eb7614ea 100644
--- a/server/services/catalogDB.test.js
+++ b/server/services/catalogDB.test.js
@@ -16,6 +16,7 @@
import { describe, it, expect, afterAll } from 'vitest';
import { checkHealth, ensureSchema, close } from '../lib/db.js';
+import { setUserCatalogTypes } from '../lib/catalogTypes.js';
import * as catalogDB from './catalogDB.js';
// Probe the DB ONCE at module load via top-level await, so the suite is
@@ -390,4 +391,90 @@ describe.skipIf(!dbReady)('catalogDB (Postgres CRUD round-trip)', () => {
// Empty query + no embedding → no signal → empty result (no throw).
expect(await catalogDB.hybridSearchIngredients('', null, { limit: 5 })).toEqual([]);
});
+
+ // --- bible-type payload sanitization (array-editor hardening) -----------
+ // character/place/object payloads run through their storyBible sanitizer
+ // before persist so the structured array editors can't land malformed rows
+ // and the catalog↔canon projection round-trip stays shape-stable. idea/scene/
+ // concept (and user-defined types) pass through UNCHANGED.
+
+ it('sanitizes a character payload on create: drops a stats row missing label, caps palette + aliases', async () => {
+ if (!requireDb('bible create sanitize')) return;
+ const created = await catalogDB.createIngredient({
+ type: 'character',
+ name: 'Sanitize Me',
+ payload: {
+ // a stat with no `label` is dropped by sanitizeStat; the labeled one stays
+ stats: [{ value: 'no-label-so-dropped' }, { label: 'Logic', value: '9' }],
+ // 13 colors → capped to COLORS_PER_PALETTE_MAX (12)
+ colorPalette: Array.from({ length: 13 }, (_, i) => ({ name: `c${i}`, hex: '#000000' })),
+ // 13 aliases → capped to ALIASES_PER_ENTRY_MAX (12)
+ aliases: Array.from({ length: 13 }, (_, i) => `alias-${i}`),
+ },
+ });
+ createdIngredientIds.add(created.id);
+
+ expect(created.payload.stats).toHaveLength(1);
+ expect(created.payload.stats[0].label).toBe('Logic');
+ expect(created.payload.stats[0].value).toBe('9');
+ expect(created.payload.colorPalette).toHaveLength(12);
+ expect(created.payload.aliases).toHaveLength(12);
+ });
+
+ it('sanitizes a character payload on update too', async () => {
+ if (!requireDb('bible update sanitize')) return;
+ const created = await catalogDB.createIngredient({ type: 'character', name: 'Update Sanitize' });
+ createdIngredientIds.add(created.id);
+
+ const updated = await catalogDB.updateIngredient(created.id, {
+ payload: {
+ stats: [{ value: 'orphan' }, { label: 'Speed', value: 'fast' }],
+ aliases: Array.from({ length: 20 }, (_, i) => `a${i}`),
+ },
+ });
+ expect(updated.payload.stats).toHaveLength(1);
+ expect(updated.payload.stats[0].label).toBe('Speed');
+ expect(updated.payload.aliases).toHaveLength(12);
+ });
+
+ it('does NOT sanitize idea/scene/concept payloads through a storyBible sanitizer', async () => {
+ if (!requireDb('light type passthrough')) return;
+ const created = await catalogDB.createIngredient({
+ type: 'idea',
+ name: 'Passthrough Idea',
+ payload: {
+ // These keys are NOT in any bible shape — a bible sanitizer would drop
+ // them. They must survive verbatim for non-bible types.
+ summary: 'a thought',
+ arbitraryField: 'kept',
+ stats: [{ value: 'no-label-kept-because-not-sanitized' }],
+ },
+ });
+ createdIngredientIds.add(created.id);
+ expect(created.payload.arbitraryField).toBe('kept');
+ expect(created.payload.summary).toBe('a thought');
+ // stats survives verbatim (not run through sanitizeStat) — the orphan row stays.
+ expect(created.payload.stats).toHaveLength(1);
+ });
+
+ it('does NOT sanitize a user-defined type payload (no storyBible coercion)', async () => {
+ if (!requireDb('user type passthrough')) return;
+ // Register a runtime user type, create a row of it, assert its arbitrary
+ // payload survives verbatim, then clear the registry so the suite is hermetic.
+ setUserCatalogTypes([{ id: 'gadget', label: 'Gadget', fields: [{ key: 'spec', kind: 'string' }] }]);
+ try {
+ const created = await catalogDB.createIngredient({
+ type: 'gadget',
+ name: 'Sonic Driver',
+ payload: { spec: 'reverses polarity', stats: [{ value: 'orphan-kept' }] },
+ });
+ createdIngredientIds.add(created.id);
+ expect(created.payload.spec).toBe('reverses polarity');
+ // A storyBible sanitizer would have dropped the label-less stat; a user
+ // type must NOT be coerced, so it survives.
+ expect(created.payload.stats).toHaveLength(1);
+ } finally {
+ setUserCatalogTypes([]);
+ }
+ });
});
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 31edecb8c2..1de3d8ecb1 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -1032,7 +1032,11 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
// universe is still persisted; peers learn about the change on the next
// normal sync cycle.
const isMutator = typeof patchOrMutator === 'function';
- const { silent = false } = options;
+ // `canonProjectionGuard` is set (to an ingredientId) when this write
+ // ORIGINATED from a catalog→canon projection. Threaded into projectToCatalog
+ // below so the originating catalog row isn't written back a second time
+ // (breaks the projectToCanon → updateUniverse → projectToCatalog loop).
+ const { silent = false, canonProjectionGuard = null } = options;
const s = store();
const { merged, nameChanged, skipped, removedCharacterIds, prevEphemeral, nextEphemeral } = await s.queueRecordWrite(id, async () => {
const cur = await s.loadOne(id);
@@ -1196,6 +1200,21 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
}
await ensureDir(s.recordDir(id));
await atomicWrite(s.recordPath(id), mergedRecord);
+ // Project the freshly-persisted canon arrays back into their catalog rows
+ // SYNCHRONOUSLY (inside the queue) so the authoritative catalog_ingredients
+ // row can never lag the embedded cache on the same request. Best-effort:
+ // projectToCatalog never throws (per-entry failures are logged), but wrap
+ // the import/call anyway — this runs inside the queued write critical
+ // section and an uncaught throw here would reject the whole save. Skipped
+ // when the patch can't have touched canon arrays (rename/scalar PATCH).
+ if (isMutator || 'characters' in patch || 'places' in patch || 'objects' in patch) {
+ try {
+ const { projectToCatalog } = await import('./catalogCanonProjection.js');
+ await projectToCatalog(id, mergedRecord, { guardToken: canonProjectionGuard });
+ } catch (err) {
+ console.error(`🔁 canon→catalog projection failed for ${id}: ${err.message}`);
+ }
+ }
// Diff inside the queue so we read against the freshest merged state;
// gate on patches that could have touched characters (mutator or
// literal-PATCH carrying `characters`) — rename/scalar PATCHes are the