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 canon→catalog projection LWW clock bugs (stamp edited entries; stable reconcile snapshot)
[._.]/ Adam Eivy74f9beb06b86
diff --git a/server/scripts/reconcileCanonCatalog.js b/server/scripts/reconcileCanonCatalog.jsindex 846c365aa7..826f6f34e2 100644--- a/server/scripts/reconcileCanonCatalog.js+++ b/server/scripts/reconcileCanonCatalog.js@@ -76,6 +76,21 @@ export async function reconcileCanonCatalog({ force = false } = {}) {const universes = await listUniverses({ includeDeleted: false });const totals = { universesScanned: 0, scanned: 0, catalogWon: 0, canonWon: 0, errors: 0 };+ // Stable snapshot of each catalog row's ORIGINAL `updatedAt` clock, keyed by+ // ingredientId, captured the first time we see the row. The same ingredient+ // can be embedded in multiple universes; writing a canon-winner bumps the+ // row's `updated_at` to NOW(), which — without this snapshot — would make a+ // LATER universe's genuinely-newer embedded copy lose to the artificially+ // fresh row and get clobbered. Comparing every universe against the pre-pass+ // clock keeps the winner determination stable across the whole reconcile.+ const rowClockAtStart = new Map();+ // High-water mark of the canon-winner clock already written to each catalog+ // row this pass. When the same ingredient is embedded in several universes+ // and more than one copy beats the ORIGINAL row, only the NEWEST embedded+ // copy may win — a later but older copy must not clobber the newer one we+ // already wrote.+ const canonWinnerClock = new Map();+for (const universe of universes) {if (universe.deleted) continue;totals.universesScanned++;@@ -93,7 +108,13 @@ export async function reconcileCanonCatalog({ force = false } = {}) {const row = await catalogDB.getIngredient(ingredientId);if (!row) continue; // dangling backlink — leave both sides aloneconst entryAt = Date.parse(entry.updatedAt || '') || 0;- const rowAt = Date.parse(row.updatedAt || '') || 0;+ // Compare against the row's clock AS OF the start of this pass, not+ // its live value — a canon-winner write earlier in the pass bumped+ // `updated_at` to now and would otherwise wrongly win here.+ if (!rowClockAtStart.has(ingredientId)) {+ rowClockAtStart.set(ingredientId, Date.parse(row.updatedAt || '') || 0);+ }+ const rowAt = rowClockAtStart.get(ingredientId);if (rowAt > entryAt) {// Catalog row is newer → it wins. Stamp its name+payload onto the// embedded entry (silent universe write below).@@ -104,13 +125,16 @@ export async function reconcileCanonCatalog({ force = false } = {}) {updatedAt: row.updatedAt,};totals.catalogWon++;- } else if (entryAt > rowAt) {- // Embedded entry is newer → it wins. Write it into the catalog row.+ } else if (entryAt > rowAt && entryAt > (canonWinnerClock.get(ingredientId) || 0)) {+ // Embedded entry beats the original row AND any canon-winner already+ // written this pass → it wins. Write it into the catalog row and+ // raise the high-water mark so an older sibling copy can't clobber it.await catalogDB.updateIngredient(ingredientId,{ name: entry.name, payload: entryToPayload(entry) },{ source: 'sync', actor: 'canon-catalog-reconcile' },);+ canonWinnerClock.set(ingredientId, entryAt);totals.canonWon++;}// Equal timestamps → already converged; nothing to do.diff --git a/server/scripts/reconcileCanonCatalog.test.js b/server/scripts/reconcileCanonCatalog.test.jsindex 6699c193d2..ac6cc1a451 100644--- a/server/scripts/reconcileCanonCatalog.test.js+++ b/server/scripts/reconcileCanonCatalog.test.js@@ -39,6 +39,13 @@ 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 });+ // Simulate the real DB trigger: a write bumps updated_at to "now" (a clock+ // strictly later than any fixture timestamp). This is what makes the+ // mid-pass clock-mutation bug observable — a later universe comparing+ // against the LIVE row would see this fresh clock.+ if (dbState.rows[id]) {+ dbState.rows[id] = { ...dbState.rows[id], ...patch, updatedAt: '2099-01-01T00:00:00.000Z' };+ }return dbState.rows[id];}),}));@@ -96,6 +103,33 @@ describe('reconcileCanonCatalog', () => {expect(uniState.canonStamps).toHaveLength(0);});+ it('multi-universe: the NEWEST embedded copy wins; a mid-pass row bump cannot clobber it', async () => {+ // Same ingredient embedded in three universes. Original catalog row is the+ // oldest. Two embedded copies beat it (u-mid @ Feb, u-new @ Mar); the third+ // (u-old @ 2025) loses to the original. The newest (u-new, Mar) must end up+ // in the catalog row — NOT u-mid just because it was iterated, and NOT lost+ // to the artificially-fresh clock the first write stamps on the row.+ dbState.rows['cat-chr-m'] = { id: 'cat-chr-m', name: 'Multi', payload: { v: 'orig' }, updatedAt: '2026-01-01T00:00:00.000Z' };+ uniState.universes = [+ { id: 'u-old', characters: [{ id: 'e', ingredientId: 'cat-chr-m', name: 'Multi', v: 'old', updatedAt: '2025-01-01T00:00:00.000Z' }] },+ { id: 'u-mid', characters: [{ id: 'e', ingredientId: 'cat-chr-m', name: 'Multi', v: 'mid', updatedAt: '2026-02-01T00:00:00.000Z' }] },+ { id: 'u-new', characters: [{ id: 'e', ingredientId: 'cat-chr-m', name: 'Multi', v: 'new', updatedAt: '2026-03-01T00:00:00.000Z' }] },+ ];++ const result = await reconcileCanonCatalog();++ // u-old loses to the original row (catalog stamped back onto it); u-mid and+ // u-new each beat the ORIGINAL row, but only the strictly-newer copy writes.+ const payloadsWritten = dbState.updates.map((u) => u.patch.payload.v);+ // The FINAL catalog content must be the newest embedded copy ('new'),+ // regardless of write order, and 'mid' must never be the last write.+ expect(dbState.rows['cat-chr-m'].payload.v).toBe('new');+ expect(payloadsWritten).toContain('new');+ expect(payloadsWritten[payloadsWritten.length - 1]).toBe('new');+ // u-old never wins.+ expect(payloadsWritten).not.toContain('old');+ });+it('leaves entries without an ingredientId untouched', async () => {uniState.universes = [{id: 'u-1',diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 1de3d8ecb1..25a1ec5360 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -1011,6 +1011,41 @@ export async function insertUniverseWithId(input = {}) {return next;}+// Canon array keys carrying bible entries that project to catalog rows.+const CANON_ARRAY_KEYS = ['characters', 'places', 'objects'];++// Compare two canon entries for CONTENT equality, ignoring `updatedAt` (the+// field we're deciding whether to bump). A cheap stable-stringify is enough —+// entries are small plain objects and a false "changed" only costs a redundant+// projection write, never correctness.+function canonEntryContentEqual(a, b) {+ const strip = (e) => { const { updatedAt: _x, ...rest } = e || {}; return rest; };+ return JSON.stringify(strip(a)) === JSON.stringify(strip(b));+}++// Stamp `updatedAt = now` on every canon entry in `next` whose content differs+// from its same-id entry in `prev` (or that is new). Mutates `next`'s arrays in+// place. So the embedded entry's LWW clock truthfully reflects a real edit —+// the bible sanitizer otherwise preserves the prior timestamp and the+// canon→catalog projection would skip a genuine change. Untouched entries keep+// their old timestamp so this never manufactures projection churn.+function stampChangedCanonEntries(prev, next) {+ const now = new Date().toISOString();+ for (const key of CANON_ARRAY_KEYS) {+ const nextList = Array.isArray(next[key]) ? next[key] : null;+ if (!nextList) continue;+ const prevById = new Map(+ (Array.isArray(prev?.[key]) ? prev[key] : []).map((e) => [e?.id, e]),+ );+ next[key] = nextList.map((entry) => {+ if (!entry?.id) return entry;+ const before = prevById.get(entry.id);+ if (before && canonEntryContentEqual(before, entry)) return entry;+ return { ...entry, updatedAt: now };+ });+ }+}+export async function updateUniverse(id, patchOrMutator = {}, options = {}) {// The queued section covers only the universe-builder read/modify/write// cycle. The cross-file media-collection rename runs *after* the queue@@ -1188,6 +1223,16 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {updatedAt: new Date().toISOString(),});if (!mergedRecord) throw makeErr('Invalid universe payload', ERR_VALIDATION);+ // Stamp `updatedAt = now` on every canon entry whose CONTENT changed vs the+ // pre-write record. The bible sanitizer preserves a present `updatedAt`, so+ // an inline edit / AI rewrite that does `{ ...e, ...patch }` keeps the OLD+ // timestamp — which makes the canon→catalog projection's LWW clock lie (a+ // catalog row that's merely newer-by-clock would win and the canon edit+ // would never reach the catalog row, breaking lockstep). Bumping the clock+ // on genuine content changes makes the embedded entry's timestamp truthful+ // so projectToCatalog correctly carries the edit across. Unchanged entries+ // keep their old timestamp (no spurious revisions / no projection churn).+ stampChangedCanonEntries(cur, mergedRecord);// Persist the stale-reference-sheet null at write time so the on-disk// record catches up with what the GET-route pruner shows. Otherwise a// PATCH that omits `characters` (e.g. rename) merges from `cur` anddiff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex 89f40767cf..5907afd13b 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -277,6 +277,38 @@ describe("universeBuilder service", () => {expect(patched.influences.avoid).toEqual(w.influences.avoid);});+ it("bumps updatedAt on a canon entry whose content changed, leaves an untouched entry's timestamp", async () => {+ // Two canon characters; edit only the first's content. The edited entry's+ // updatedAt must advance (so the canon→catalog projection's LWW clock is+ // truthful and the edit reaches the catalog row); the untouched entry keeps+ // its timestamp (no spurious projection churn).+ const w = await svc.createUniverse({+ name: "CanonClock",+ characters: [+ { name: "Ada", physicalDescription: "tall" },+ { name: "Bee", physicalDescription: "short" },+ ],+ });+ const [ada0, bee0] = w.characters;+ expect(ada0?.updatedAt).toBeTruthy();++ // Patch only Ada's description via the mutator form (the `{ ...e, ...patch }`+ // shape that previously preserved the stale updatedAt).+ const patched = await svc.updateUniverse(w.id, (cur) => ({+ characters: cur.characters.map((c) =>+ c.id === ada0.id ? { ...c, physicalDescription: "towering" } : c,+ ),+ }));++ const ada1 = patched.characters.find((c) => c.id === ada0.id);+ const bee1 = patched.characters.find((c) => c.id === bee0.id);+ expect(ada1.physicalDescription).toBe("towering");+ // Edited entry's clock advanced…+ expect(new Date(ada1.updatedAt).getTime()).toBeGreaterThan(new Date(ada0.updatedAt).getTime());+ // …untouched entry's clock unchanged.+ expect(bee1.updatedAt).toBe(bee0.updatedAt);+ });+it("persists styleImageRefs (base style-probe renders); dedupes on create + patches wholesale", async () => {const w = await svc.createUniverse({ name: "Probe", styleImageRefs: ["a.png", "a.png", "b.png"] });expect(w.styleImageRefs).toEqual(["a.png", "b.png"]); // dedupe via sanitizeEntryImageRefs