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: serialize catalog user-type read-modify-write so sync and Settings edits can't erase each other (#9132)
Adam Eivy133f1df5bca2
diff --git a/server/routes/catalog.js b/server/routes/catalog.jsindex d075d88e0a..e823d742e0 100644--- a/server/routes/catalog.js+++ b/server/routes/catalog.js@@ -42,7 +42,7 @@ import {REF_KINDS,} from '../lib/catalogValidation.js';import { getActiveCatalogTypes, setUserCatalogTypes } from '../lib/catalogTypes.js';-import { readUserTypes as readUserTypeSlice, writeUserTypes } from '../services/catalogUserTypes/store.js';+import { updateUserTypes } from '../services/catalogUserTypes/store.js';import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalogBulkParsers.js';import { resolveImageInputPath } from '../lib/fileUtils.js';import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';@@ -824,12 +824,6 @@ router.post('/migration/rerun', asyncHandler(async (req, res) => {// restart. The GET returns the FULL active registry (system + user) normalized// for the client merge, with each entry's `system` flag.-// Read the persisted user-type slice as a plain array (tolerates absent/junk).-const readUserTypes = async () => {- const list = await readUserTypeSlice();- return Array.isArray(list) ? list : [];-};-router.get('/types', asyncHandler(async (req, res) => {// Active registry (system first, then user). Each entry already carries// `system`, `label`, `primaryContentKey`, `snippetFallbackKeys`, and (for@@ -848,23 +842,24 @@ const stampUserType = (body) => {router.post('/types', asyncHandler(async (req, res) => {const body = validateRequest(catalogUserTypeSchema, req.body);- const current = await readUserTypes();- // A LIVE type with this id already exists → conflict. A tombstoned id (or a- // fresh id) is fine: POST revives the tombstone / creates anew, replacing the- // slot in place so the unique-id invariant holds.- const idx = current.findIndex((t) => t.id === body.id);- if (idx !== -1 && !current[idx].deletedAt) {- throw new ServerError(`Catalog type "${body.id}" already exists`, { status: 409 });- }- const stamped = stampUserType(body);- const next = idx === -1- ? [...current, stamped]- : current.map((t, i) => (i === idx ? stamped : t));- // Validate the whole slice (unique-id + system-collision refinements) before- // persisting — a system-id collision (e.g. "character") is rejected here.- validateRequest(catalogUserTypesSettingsSchema, next);- await writeUserTypes(next);- setUserCatalogTypes(next);+ await updateUserTypes((slice) => {+ const current = Array.isArray(slice) ? slice : [];+ // A LIVE type with this id already exists → conflict. A tombstoned id (or a+ // fresh id) is fine: POST revives the tombstone / creates anew, replacing the+ // slot in place so the unique-id invariant holds.+ const idx = current.findIndex((t) => t.id === body.id);+ if (idx !== -1 && !current[idx].deletedAt) {+ throw new ServerError(`Catalog type "${body.id}" already exists`, { status: 409 });+ }+ const stamped = stampUserType(body);+ const next = idx === -1+ ? [...current, stamped]+ : current.map((t, i) => (i === idx ? stamped : t));+ // Validate the whole slice (unique-id + system-collision refinements) before+ // persisting — a system-id collision (e.g. "character") is rejected here.+ validateRequest(catalogUserTypesSettingsSchema, next);+ return next;+ }, setUserCatalogTypes);console.log(`🧩 Catalog: added user type "${body.id}"`);res.status(201).json({ types: getActiveCatalogTypes() });}));@@ -873,51 +868,53 @@ router.patch('/types/:id', asyncHandler(async (req, res) => {// Merge the path id onto the body so a partial PATCH still validates as a// full user-type (id is immutable — the path wins over any body id).const merged = validateRequest(catalogUserTypeSchema, { ...req.body, id: req.params.id });- const current = await readUserTypes();- // Editing a tombstoned (deleted) type is a 404 — it must be re-created via POST.- const idx = current.findIndex((t) => t.id === req.params.id && !t.deletedAt);- if (idx === -1) throw new ServerError(`Catalog type "${req.params.id}" not found`, { status: 404 });- const next = [...current];- next[idx] = stampUserType(merged);- validateRequest(catalogUserTypesSettingsSchema, next);- await writeUserTypes(next);- setUserCatalogTypes(next);+ await updateUserTypes((slice) => {+ const current = Array.isArray(slice) ? slice : [];+ // Editing a tombstoned (deleted) type is a 404 — it must be re-created via POST.+ const idx = current.findIndex((t) => t.id === req.params.id && !t.deletedAt);+ if (idx === -1) throw new ServerError(`Catalog type "${req.params.id}" not found`, { status: 404 });+ const next = [...current];+ next[idx] = stampUserType(merged);+ validateRequest(catalogUserTypesSettingsSchema, next);+ return next;+ }, setUserCatalogTypes);console.log(`🧩 Catalog: updated user type "${req.params.id}"`);res.json({ types: getActiveCatalogTypes() });}));router.delete('/types/:id', asyncHandler(async (req, res) => {- const current = await readUserTypes();- const idx = current.findIndex((t) => t.id === req.params.id && !t.deletedAt);- if (idx === -1) throw new ServerError(`Catalog type "${req.params.id}" not found`, { status: 404 });- // Refuse to delete a type that still has ingredients of that type unless the- // caller explicitly forces it (`?force=true`) — otherwise those rows become- // orphaned (their `type` no longer resolves in the active registry, so the- // detail page falls back to the generic 'idea' editor and the type filter- // drops them). force=true deletes the definition anyway; the rows survive- // and just render under the fallback editor.const force = req.query.force === 'true';- if (!force) {- const { items } = await catalogDB.listIngredients({ type: req.params.id, limit: 1 });- if (items.length > 0) {- throw new ServerError(- `Catalog type "${req.params.id}" has ingredients — pass ?force=true to delete it anyway`,- { status: 409, code: 'CATALOG_TYPE_IN_USE' },- );+ await updateUserTypes(async (slice) => {+ const current = Array.isArray(slice) ? slice : [];+ const idx = current.findIndex((t) => t.id === req.params.id && !t.deletedAt);+ if (idx === -1) throw new ServerError(`Catalog type "${req.params.id}" not found`, { status: 404 });+ // Refuse to delete a type that still has ingredients of that type unless the+ // caller explicitly forces it (`?force=true`) — otherwise those rows become+ // orphaned (their `type` no longer resolves in the active registry, so the+ // detail page falls back to the generic 'idea' editor and the type filter+ // drops them). force=true deletes the definition anyway; the rows survive+ // and just render under the fallback editor.+ if (!force) {+ const { items } = await catalogDB.listIngredients({ type: req.params.id, limit: 1 });+ if (items.length > 0) {+ throw new ServerError(+ `Catalog type "${req.params.id}" has ingredients — pass ?force=true to delete it anyway`,+ { status: 409, code: 'CATALOG_TYPE_IN_USE' },+ );+ }}- }- // Soft-delete: KEEP the entry with a `deletedAt` tombstone (and a fresh- // `updatedAt`) so the deletion federates to peers via the catalogTypes sync- // block. A physical removal would let a peer that still has the definition- // resurrect it on the next pull. setUserCatalogTypes filters tombstones out- // of the active registry, so the type disappears from the UI immediately.- const deletedAt = new Date().toISOString();- const next = current.map((t, i) => (- i === idx ? { ...t, deletedAt, updatedAt: deletedAt } : t- ));- validateRequest(catalogUserTypesSettingsSchema, next);- await writeUserTypes(next);- setUserCatalogTypes(next);+ // Soft-delete: KEEP the entry with a `deletedAt` tombstone (and a fresh+ // `updatedAt`) so the deletion federates to peers via the catalogTypes sync+ // block. A physical removal would let a peer that still has the definition+ // resurrect it on the next pull. setUserCatalogTypes filters tombstones out+ // of the active registry, so the type disappears from the UI immediately.+ const deletedAt = new Date().toISOString();+ const next = current.map((t, i) => (+ i === idx ? { ...t, deletedAt, updatedAt: deletedAt } : t+ ));+ validateRequest(catalogUserTypesSettingsSchema, next);+ return next;+ }, setUserCatalogTypes);console.log(`🧩 Catalog: deleted user type "${req.params.id}"${force ? ' (forced)' : ''}`);res.json({ types: getActiveCatalogTypes() });}));diff --git a/server/services/catalogSync.js b/server/services/catalogSync.jsindex ecd4ba1671..030e886bad 100644--- a/server/services/catalogSync.js+++ b/server/services/catalogSync.js@@ -52,7 +52,7 @@ import {import { compareSchemaVersions, scopeVersionDiff, formatVersionGap, catalogEnvelopeHasLiveRows, PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';import { friendlifyUniverseTags, LEGACY_UNIVERSE_MARKER_TAG } from '../lib/catalogUniverseTags.js';import { canonicalTagKey, setUserCatalogTypes, INGREDIENT_TYPE_IDS } from '../lib/catalogTypes.js';-import { readUserTypes as readUserTypeSlice, writeUserTypes } from './catalogUserTypes/store.js';+import { readUserTypes as readUserTypeSlice, updateUserTypes } from './catalogUserTypes/store.js';const CURSOR_KEYS = ['scraps', 'ingredients', 'sources', 'refs', 'relations', 'tags', 'media'];@@ -372,9 +372,6 @@ export async function applyRemoteChanges(envelope = {}) {* skipped, failed }`.*/export async function applyUserTypesFromPeer(incoming = []) {- const localRaw = await readUserTypeSlice();- const local = Array.isArray(localRaw) ? localRaw : [];- const byId = new Map(local.map((t) => [t.id, t]));let applied = 0;let skipped = 0;// The LWW clock is the LATER of {updatedAt, deletedAt} — a deletion is a@@ -387,32 +384,37 @@ export async function applyUserTypesFromPeer(incoming = []) {const d = typeof t?.deletedAt === 'string' ? t.deletedAt : '';return d > u ? d : u;};- for (const peer of incoming) {- const id = typeof peer?.id === 'string' ? peer.id.trim() : '';- // Skip a malformed entry or one colliding with a built-in system id —- // system types always win and are never represented in this slice.- if (!id || INGREDIENT_TYPE_IDS.includes(id)) { skipped++; continue; }- const existing = byId.get(id);- // LWW: adopt when no local copy, or the peer's clock is STRICTLY newer.- // Must be `>`, not `>=` — an equal clock means the peer is echoing a type- // we already hold, so re-adopting it re-writes the slice and re-counts it- // as an applied change every cycle, and the merge never converges (the peer- // keeps re-sending it on the next envelope). Strict `>` mirrors the SQL LWW- // guard every other catalog kind uses (`EXCLUDED.updated_at > … .updated_at`- // in upsertScrapFromPeer / upsertTagFromPeer): equal clock = no-op = skip.- if (!existing || clockOf(peer) > clockOf(existing)) {- byId.set(id, { ...peer, id });- applied++;- } else {- skipped++;+ // The read-merge-write runs inside the serialized updateUserTypes so a+ // concurrent Settings edit can't be erased by (or erase) this merge. The+ // mutator can be re-entered by a backend retry, so counters reset per run.+ await updateUserTypes((localRaw) => {+ applied = 0;+ skipped = 0;+ const local = Array.isArray(localRaw) ? localRaw : [];+ const byId = new Map(local.map((t) => [t.id, t]));+ for (const peer of incoming) {+ const id = typeof peer?.id === 'string' ? peer.id.trim() : '';+ // Skip a malformed entry or one colliding with a built-in system id —+ // system types always win and are never represented in this slice.+ if (!id || INGREDIENT_TYPE_IDS.includes(id)) { skipped++; continue; }+ const existing = byId.get(id);+ // LWW: adopt when no local copy, or the peer's clock is STRICTLY newer.+ // Must be `>`, not `>=` — an equal clock means the peer is echoing a type+ // we already hold, so re-adopting it re-writes the slice and re-counts it+ // as an applied change every cycle, and the merge never converges (the peer+ // keeps re-sending it on the next envelope). Strict `>` mirrors the SQL LWW+ // guard every other catalog kind uses (`EXCLUDED.updated_at > … .updated_at`+ // in upsertScrapFromPeer / upsertTagFromPeer): equal clock = no-op = skip.+ if (!existing || clockOf(peer) > clockOf(existing)) {+ byId.set(id, { ...peer, id });+ applied++;+ } else {+ skipped++;+ }}- }- if (applied > 0) {- const next = [...byId.values()];- await writeUserTypes(next);- setUserCatalogTypes(next);- console.log(`🧩 Catalog sync: merged ${applied} user type(s) from peer`);- }+ return applied > 0 ? [...byId.values()] : null;+ }, setUserCatalogTypes);+ if (applied > 0) console.log(`🧩 Catalog sync: merged ${applied} user type(s) from peer`);return { applied, skipped, failed: 0 };}diff --git a/server/services/catalogUserTypes/db.js b/server/services/catalogUserTypes/db.jsindex 85063bc118..ad7ca0dcd0 100644--- a/server/services/catalogUserTypes/db.js+++ b/server/services/catalogUserTypes/db.js@@ -43,33 +43,57 @@ export async function readUserTypes() {* `deletedAt` in its data) stays a row so the deletion keeps federating.*/export async function writeUserTypes(list) {- const types = Array.isArray(list) ? list.filter((t) => t && typeof t.id === 'string' && t.id) : [];- await withTransaction(async (client) => {+ await withTransaction((client) => applyWrite(client.query.bind(client), list));+}++// Arbitrary constant key for the per-table advisory lock (`catalog_user_types`).+const USER_TYPES_LOCK_KEY = 90011001;++/**+ * Read-modify-write the slice atomically: takes a transaction-scoped advisory+ * lock, reads inside the transaction, hands the list to `mutator`, and writes+ * its result — so a cross-process writer cannot interleave between the read and+ * the whole-slice authoritative write. A `null`/`undefined` return skips the+ * write. Returns the mutator's list (or the unchanged current list).+ */+export async function updateUserTypes(mutator) {+ return withTransaction(async (client) => {const exec = client.query.bind(client);- const keepIds = [];- for (const t of types) {- keepIds.push(t.id);- // The typed mirror columns are bind-sanitized so a hand-edited/legacy- // record with a malformed timestamp can't make the INSERT throw and abort- // the whole slice write (which runs during boot warm). `data` is verbatim.- const updatedAt = mirrorTimestamp(t.updatedAt, null);- const deletedAt = mirrorTimestamp(t.deletedAt, null);- await exec(- `INSERT INTO catalog_user_types (id, data, updated_at, deleted_at)- VALUES ($1, $2::jsonb, COALESCE($3::timestamptz, NOW()), $4)- ON CONFLICT (id) DO UPDATE SET- data = EXCLUDED.data,- updated_at = EXCLUDED.updated_at,- deleted_at = EXCLUDED.deleted_at`,- [t.id, JSON.stringify(t), updatedAt, deletedAt],- );- }- // Prune rows that left the desired slice. With keepIds empty the whole- // table clears; otherwise delete everything NOT in the list.- if (keepIds.length === 0) {- await exec(`DELETE FROM catalog_user_types`);- } else {- await exec(`DELETE FROM catalog_user_types WHERE id <> ALL($1::text[])`, [keepIds]);- }+ await exec(`SELECT pg_advisory_xact_lock($1)`, [USER_TYPES_LOCK_KEY]);+ const { rows } = await exec(`SELECT data FROM catalog_user_types ORDER BY created_at ASC, id ASC`);+ const current = rows.map(rowToType);+ const next = await mutator(current);+ if (next == null) return current;+ await applyWrite(exec, next);+ return next;});}++async function applyWrite(exec, list) {+ const types = Array.isArray(list) ? list.filter((t) => t && typeof t.id === 'string' && t.id) : [];+ const keepIds = [];+ for (const t of types) {+ keepIds.push(t.id);+ // The typed mirror columns are bind-sanitized so a hand-edited/legacy+ // record with a malformed timestamp can't make the INSERT throw and abort+ // the whole slice write (which runs during boot warm). `data` is verbatim.+ const updatedAt = mirrorTimestamp(t.updatedAt, null);+ const deletedAt = mirrorTimestamp(t.deletedAt, null);+ await exec(+ `INSERT INTO catalog_user_types (id, data, updated_at, deleted_at)+ VALUES ($1, $2::jsonb, COALESCE($3::timestamptz, NOW()), $4)+ ON CONFLICT (id) DO UPDATE SET+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at,+ deleted_at = EXCLUDED.deleted_at`,+ [t.id, JSON.stringify(t), updatedAt, deletedAt],+ );+ }+ // Prune rows that left the desired slice. With keepIds empty the whole+ // table clears; otherwise delete everything NOT in the list.+ if (keepIds.length === 0) {+ await exec(`DELETE FROM catalog_user_types`);+ } else {+ await exec(`DELETE FROM catalog_user_types WHERE id <> ALL($1::text[])`, [keepIds]);+ }+}diff --git a/server/services/catalogUserTypes/store.js b/server/services/catalogUserTypes/store.jsindex 08757a0193..3942e985f3 100644--- a/server/services/catalogUserTypes/store.js+++ b/server/services/catalogUserTypes/store.js@@ -63,7 +63,7 @@ const facade = createPgFileFacade({await migrateCatalogUserTypesToDB();},loadDb: () => import('./db.js'),- makePg: (db) => ({ name: 'postgres', readUserTypes: db.readUserTypes, writeUserTypes: db.writeUserTypes }),+ makePg: (db) => ({ name: 'postgres', readUserTypes: db.readUserTypes, writeUserTypes: db.writeUserTypes, updateUserTypes: db.updateUserTypes }),}),});@@ -86,3 +86,44 @@ export async function readUserTypes() {export async function writeUserTypes(list) {return (await facade.getBackend()).writeUserTypes(list);}++// Per-process write queue: every read-modify-write of the slice runs one at a+// time, so a route edit and a peer-sync apply can't each write a list derived+// from a stale read (writeUserTypes is whole-slice authoritative — the loser's+// rows would be hard-deleted). A rejected task must not wedge the chain.+let writeQueue = Promise.resolve();++/**+ * Serialized read-modify-write of the user-type slice. `mutator(current)` gets+ * the full slice (live + tombstones) and returns the desired next list, or+ * null/undefined to skip the write; it may be async and may throw (the error+ * propagates and nothing is written). `afterWrite(next)` runs inside the lock+ * once persisted (e.g. refreshing the in-process registry) so registry updates+ * apply in write order. Returns the persisted list (or the unchanged current+ * list when the mutator skipped).+ */+export function updateUserTypes(mutator, afterWrite) {+ const run = async () => {+ const backend = await facade.getBackend();+ let wrote = false;+ const wrapped = async (current) => {+ const next = await mutator(Array.isArray(current) ? current : []);+ wrote = next != null;+ return next;+ };+ let result;+ if (backend.updateUserTypes) {+ result = await backend.updateUserTypes(wrapped);+ } else {+ const current = await backend.readUserTypes();+ const next = await wrapped(current);+ if (next != null) await backend.writeUserTypes(next);+ result = next ?? current;+ }+ if (wrote && afterWrite) afterWrite(result);+ return result;+ };+ const task = writeQueue.then(run);+ writeQueue = task.catch(() => {});+ return task;+}diff --git a/server/services/catalogUserTypes/store.test.js b/server/services/catalogUserTypes/store.test.jsindex 8e7d7e09e0..1fe8dbc770 100644--- a/server/services/catalogUserTypes/store.test.js+++ b/server/services/catalogUserTypes/store.test.js@@ -52,3 +52,37 @@ describe('catalog user-type store — file backend (test/escape-hatch)', () => {expect(store.catalogUserTypes).toEqual([]);});});++describe('updateUserTypes — serialized read-modify-write (#9132)', () => {+ it('a route-style edit and a peer-sync merge running concurrently both survive', async () => {+ const { updateUserTypes } = await import('./store.js');+ store = { catalogUserTypes: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] };+ let releaseFirst;+ const gate = new Promise((r) => { releaseFirst = r; });+ // First writer (PATCH-like) stalls after reading; the second (peer tombstone+ // + new type) is queued behind it and must observe the first's write.+ const first = updateUserTypes(async (cur) => {+ await gate;+ return cur.map((t) => (t.id === 'a' ? { ...t, label: 'A2' } : t));+ });+ const second = updateUserTypes((cur) => [+ ...cur.map((t) => (t.id === 'b' ? { ...t, deletedAt: 'T' } : t)),+ { id: 'c', label: 'C' },+ ]);+ releaseFirst();+ await Promise.all([first, second]);+ expect(store.catalogUserTypes).toEqual([+ { id: 'a', label: 'A2' },+ { id: 'b', label: 'B', deletedAt: 'T' },+ { id: 'c', label: 'C' },+ ]);+ });++ it('a throwing mutator writes nothing and does not wedge the queue', async () => {+ const { updateUserTypes } = await import('./store.js');+ store = { catalogUserTypes: [{ id: 'a' }] };+ await expect(updateUserTypes(() => { throw new Error('409'); })).rejects.toThrow('409');+ await updateUserTypes((cur) => [...cur, { id: 'z' }]);+ expect(store.catalogUserTypes).toEqual([{ id: 'a' }, { id: 'z' }]);+ });+});