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
fix: preserve independent canon edits during catalog projection (#12502)
[._.]/ Adam Eivyc1a495347d15
diff --git a/server/services/catalogCanonProjection.echo.test.js b/server/services/catalogCanonProjection.echo.test.jsnew file mode 100644index 0000000000..85b7f28e41--- /dev/null+++ b/server/services/catalogCanonProjection.echo.test.js@@ -0,0 +1,84 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('./catalogDB.js', () => ({+ getIngredient: vi.fn(),+ getIngredientIdentityIds: vi.fn(async (id) => [id, `${id}-alias`]),+ listRefsForIngredient: vi.fn(async () => [{ refKind: 'universe', refId: 'universe-a' }]),+ getIngredientTimestamps: vi.fn(async (ids) => new Map(ids.map((id) => [id, '2026-01-01T00:00:00.000Z']))),+ updateIngredient: vi.fn(async () => ({})),+}));+vi.mock('./catalogDB/identityAccess.js', () => ({ getCatalogIdentityAccess: vi.fn(async () => null) }));++import * as catalogDB from './catalogDB.js';+import { projectToCanon, projectToCatalog } from './catalogCanonProjection.js';++const entry = (ingredientId) => ({+ id: `entry-${ingredientId}`, ingredientId, name: 'Independent edit',+ updatedAt: '2026-02-01T00:00:00.000Z',+});+const ingredient = { id: 'ingredient-a', name: 'Catalog edit', payload: {}, updatedAt: '2026-01-01T00:00:00.000Z' };++// Pause at the universe write boundary; no timers, live storage, or peer traffic.+function heldProjection() {+ const entered = Promise.withResolvers();+ const release = Promise.withResolvers();+ const updateUniverse = async (universeId, mutator, options) => {+ const projected = await mutator({ characters: [entry('ingredient-a-alias')] });+ entered.resolve({ universeId, projected, options });+ await release.promise;+ return projected;+ };+ return { entered: entered.promise, release: release.resolve, updateUniverse };+}++beforeEach(() => {+ vi.clearAllMocks();+ catalogDB.getIngredient.mockResolvedValue(ingredient);+});++describe('operation-scoped catalog projection echoes', () => {+ it('lets independent saves in the same and another universe write while a forward projection waits', async () => {+ const held = heldProjection();+ const forward = projectToCanon(ingredient.id, ingredient, held);+ await held.entered;+ try {+ for (const universeId of ['universe-a', 'universe-b']) {+ expect(await projectToCatalog(universeId, { characters: [entry(ingredient.id)] }))+ .toEqual({ written: 1, skipped: 0 });+ }+ expect(catalogDB.updateIngredient).toHaveBeenCalledTimes(2);+ } finally {+ held.release();+ await forward;+ }+ });++ it.each([[0, 1], [1, 0]])('preserves each echo guard when overlapping calls settle %s then %s', async (first, second) => {+ const held = [heldProjection(), heldProjection()];+ const pending = held.map((deps) => projectToCanon(ingredient.id, ingredient, deps));+ const calls = await Promise.all(held.map((op) => op.entered));+ try {+ held[first].release();+ await pending[first];+ for (const index of [first, second]) {+ const { universeId, projected, options } = calls[index];+ expect(projected.characters[0].ingredientId).toBe(ingredient.id);+ const result = await projectToCatalog(universeId, {+ characters: [...projected.characters, entry('ingredient-a-alias'), entry('ingredient-b')],+ }, {+ guardToken: options.canonProjectionGuard,+ guardIdentityIds: options.canonProjectionIdentityIds,+ });+ // The guard covers canonical and alias echoes only, even after another+ // overlapping projection finishes. Unrelated canon still writes.+ expect(result).toEqual({ written: 1, skipped: 2 });+ }+ expect(catalogDB.updateIngredient.mock.calls.map(([id]) => id)).toEqual(['ingredient-b', 'ingredient-b']);+ expect(await projectToCatalog('universe-a', { characters: [entry(ingredient.id)] }))+ .toEqual({ written: 1, skipped: 0 });+ } finally {+ held.forEach((op) => op.release());+ await Promise.all(pending);+ }+ });+});diff --git a/server/services/catalogCanonProjection.js b/server/services/catalogCanonProjection.jsindex 6c1b9c7fe4..7e89f14670 100644--- a/server/services/catalogCanonProjection.js+++ b/server/services/catalogCanonProjection.js@@ -25,12 +25,10 @@* 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).+ * projectToCatalog — an A→B→A cycle. Each call carries its canonical id and+ * aliases through updateUniverse so only that operation's own echo is skipped.+ * Independent canon edits still run the normal freshness checks, even while a+ * forward projection for the same ingredient is pending.** Conflict policy. LWW on `updatedAt` (no field-level merge). projectToCatalog* only writes when the embedded entry's `updatedAt` is newer-or-equal to the@@ -55,13 +53,6 @@ const CANON_ARRAY_KEYS = Object.freeze(Object.values(BIBLE_FIELD));// `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@@ -97,68 +88,63 @@ export async function projectToCanon(ingredientId, updatedIngredient, deps = {})if (await getCatalogIdentityAccess(ingredientId)) return { universes: 0, written: 0, skipped: 1 };const identityIds = new Set(await catalogDB.getIngredientIdentityIds(ingredientId));- for (const id of identityIds) inFlight.add(id);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 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;- const sourceAt = Date.parse(updatedAt || '');+ const name = updatedIngredient.name;+ const payload = entryToPayload(updatedIngredient.payload || {});+ const updatedAt = updatedIngredient.updatedAt;+ const sourceAt = Date.parse(updatedAt || '');- for (const universeId of universeIds) {- stats.universes++;- // Mutator form: replace the mirrored payload on every embedded entry that- // carries this ingredientId, across all canon arrays. Preserve only the- // canon entry's control fields: merging onto the whole entry would retain- // fields removed by an edit or revision restore and let stale canon data- // leak back into Catalog on the next reverse projection. `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).- let touched = false;- const result = await updateUniverse(universeId, async (cur) => {- // Read without taking the catalog write queue: reverse projection already- // runs inside this universe queue. Waiting on both queues can deadlock.- const current = await catalogDB.getIngredient(ingredientId);- if (!current || current.id !== ingredientId || !Number.isFinite(sourceAt)- || Date.parse(current.updatedAt || '') !== sourceAt- || current.name !== name- || !isDeepStrictEqual(entryToPayload(current.payload || {}), payload)) return null;- const patch = {};- for (const arrayKey of CANON_ARRAY_KEYS) {- const list = Array.isArray(cur[arrayKey]) ? cur[arrayKey] : [];- if (!list.some((e) => identityIds.has(e?.ingredientId))) continue;- patch[arrayKey] = list.map((e) => {- if (!identityIds.has(e?.ingredientId)) return e;- // Alias-backed entries are archived context, not newer edits of- // the canonical identity; an explicit catalog edit refreshes them.- if (e.ingredientId === ingredientId && Date.parse(e.updatedAt || '') > sourceAt) return e;- touched = true;- const controlFields = Object.fromEntries(- NON_PAYLOAD_KEYS.filter((key) => e[key] !== undefined).map((key) => [key, e[key]]),- );- return { ...controlFields, ...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 && touched) stats.written++;- else stats.skipped++;- }- return stats;- } finally {- for (const id of identityIds) inFlight.delete(id);+ for (const universeId of universeIds) {+ stats.universes++;+ // Mutator form: replace the mirrored payload on every embedded entry that+ // carries this ingredientId, across all canon arrays. Preserve only the+ // canon entry's control fields: merging onto the whole entry would retain+ // fields removed by an edit or revision restore and let stale canon data+ // leak back into Catalog on the next reverse projection. `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).+ let touched = false;+ const result = await updateUniverse(universeId, async (cur) => {+ // Read without taking the catalog write queue: reverse projection already+ // runs inside this universe queue. Waiting on both queues can deadlock.+ const current = await catalogDB.getIngredient(ingredientId);+ if (!current || current.id !== ingredientId || !Number.isFinite(sourceAt)+ || Date.parse(current.updatedAt || '') !== sourceAt+ || current.name !== name+ || !isDeepStrictEqual(entryToPayload(current.payload || {}), payload)) return null;+ const patch = {};+ for (const arrayKey of CANON_ARRAY_KEYS) {+ const list = Array.isArray(cur[arrayKey]) ? cur[arrayKey] : [];+ if (!list.some((e) => identityIds.has(e?.ingredientId))) continue;+ patch[arrayKey] = list.map((e) => {+ if (!identityIds.has(e?.ingredientId)) return e;+ // Alias-backed entries are archived context, not newer edits of+ // the canonical identity; an explicit catalog edit refreshes them.+ if (e.ingredientId === ingredientId && Date.parse(e.updatedAt || '') > sourceAt) return e;+ touched = true;+ const controlFields = Object.fromEntries(+ NON_PAYLOAD_KEYS.filter((key) => e[key] !== undefined).map((key) => [key, e[key]]),+ );+ return { ...controlFields, ...payload, name, ingredientId, updatedAt };+ });+ }+ return touched ? patch : null;+ }, { silent: true, canonProjectionGuard: ingredientId, canonProjectionIdentityIds: [...identityIds] }).catch((err) => {+ console.error(`🔁 projectToCanon: universe ${universeId} update failed: ${err.message}`);+ return null;+ });+ if (result && touched) stats.written++;+ else stats.skipped++;}+ return stats;}/**@@ -171,12 +157,13 @@ export async function projectToCanon(ingredientId, updatedIngredient, deps = {})* objects }` subset) read straight after the write.* guardToken — when set (a projectToCanon-originated write), the entry whose* ingredientId equals it is skipped (loop break).+ * guardIdentityIds — aliases captured by that originating operation, also skipped.** 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 } = {}) {+export async function projectToCatalog(universeId, canonArrays, { guardToken = null, guardIdentityIds = [] } = {}) {const stats = { written: 0, skipped: 0 };if (!canonArrays || typeof canonArrays !== 'object') return stats;@@ -184,6 +171,8 @@ export async function projectToCatalog(universeId, canonArrays, { guardToken = n// the loop break up front, so the batched lookup below asks only for rows we// could actually write. A universe with N canon entries used to cost N// single-row SELECTs here (#3941); it now costs one.+ const guardedIds = new Set(guardIdentityIds);+ if (guardToken) guardedIds.add(guardToken);const candidates = [];for (const arrayKey of CANON_ARRAY_KEYS) {const list = Array.isArray(canonArrays[arrayKey]) ? canonArrays[arrayKey] : [];@@ -192,7 +181,7 @@ export async function projectToCatalog(universeId, canonArrays, { guardToken = nif (!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)) {+ if (guardedIds.has(ingredientId)) {stats.skipped++;continue;}@@ -252,9 +241,3 @@ export async function projectToCatalog(universeId, canonArrays, { guardToken = n}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.ordering.test.js b/server/services/catalogCanonProjection.ordering.test.jsindex 07d0619a17..2dcdbb66d9 100644--- a/server/services/catalogCanonProjection.ordering.test.js+++ b/server/services/catalogCanonProjection.ordering.test.js@@ -133,14 +133,13 @@ describe('catalog projection ordering through persisted universe writes', () =>edited = await updateUniverse(universeId, (cur) => ({characters: cur.characters.map((entry) => ({ ...entry, name: 'Universe edit' })),}));+ expect(row.name).toBe('Universe edit');+ expect(catalog.updateIngredient).toHaveBeenCalledTimes(1);} finally {release.resolve();await projection;}expect(await persistedEntry()).toMatchObject({ name: 'Universe edit', updatedAt: edited.characters[0].updatedAt });- // The independent in-flight reverse-sync suppression remains tracked in #12502.- // Once that projection ends, an ordinary canon save still carries the edit.- await updateUniverse(universeId, (cur) => ({ characters: cur.characters }));expect(row.name).toBe('Universe edit');});diff --git a/server/services/catalogCanonProjection.test.js b/server/services/catalogCanonProjection.test.jsindex 86572568ba..85fe5f328f 100644--- a/server/services/catalogCanonProjection.test.js+++ b/server/services/catalogCanonProjection.test.js@@ -21,7 +21,7 @@ import { describe, it, expect, afterAll, vi } from 'vitest';import { checkHealth, ensureSchema, close } from '../lib/db.js';import { requireDbOrSkip } from '../lib/dbTestGate.js';import * as catalogDB from './catalogDB.js';-import { projectToCanon, projectToCatalog, _inFlightSize } from './catalogCanonProjection.js';+import { projectToCanon, projectToCatalog } from './catalogCanonProjection.js';let dbReady = false;let skipReason = '';@@ -171,7 +171,6 @@ describe.skipIf(!runDb)('catalogCanonProjection', () => {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/universeBuilder/crud.js b/server/services/universeBuilder/crud.jsindex a513ea2077..684ce5309a 100644--- a/server/services/universeBuilder/crud.js+++ b/server/services/universeBuilder/crud.js@@ -426,6 +426,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {// 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).+ // `canonProjectionIdentityIds` carries aliases scoped to that same operation.// `options.replaceCategories: true` replaces the whole `categories` map with// the patch's instead of unioning it per-key. Used by the conflict-journal// "restore mine" path so a faithful restore of the archived snapshot drops a@@ -445,7 +446,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {// the share-bucket importer's remote LWW apply passes it, so the winning// source revision's clock survives and the next one can still win (#10761).const {- silent = false, canonProjectionGuard = null, replaceCategories = false,+ silent = false, canonProjectionGuard = null, canonProjectionIdentityIds = [], replaceCategories = false,touchesCanon = true, updatedAt: incomingUpdatedAt = null,} = options;const s = store();@@ -667,7 +668,7 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {if (touchesCanon && (isMutator || 'characters' in patch || 'places' in patch || 'objects' in patch)) {try {const { projectToCatalog } = await import('../catalogCanonProjection.js');- await projectToCatalog(id, mergedRecord, { guardToken: canonProjectionGuard });+ await projectToCatalog(id, mergedRecord, { guardToken: canonProjectionGuard, guardIdentityIds: canonProjectionIdentityIds });} catch (err) {console.error(`🔁 canon→catalog projection failed for ${id}: ${err.message}`);}