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: save Catalog edits and revision history atomically (#8687)
[._.]/ Adam Eivy70ed660a632f
diff --git a/server/routes/catalog.test.js b/server/routes/catalog.test.jsindex 5b09798548..7dc79d530a 100644--- a/server/routes/catalog.test.js+++ b/server/routes/catalog.test.js@@ -17,9 +17,10 @@import { describe, it, expect, afterAll, vi } from 'vitest';import express from 'express';+import pg from 'pg';import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';-import { checkHealth, ensureSchema, close, query } from '../lib/db.js';+import { checkHealth, ensureSchema, close, query, withTransaction } from '../lib/db.js';import { requireDbOrSkip } from '../lib/dbTestGate.js';// Mock embeddings — the bulk-import + restore routes call these; we don't want a@@ -207,6 +208,124 @@ describe.skipIf(!runDb)('POST /api/catalog/bulk-import — export-bundle ref rec});});+// Inject a real SQL error at the pg transport, retaining its promise/callback+// interface. All other statements (including rollback) still reach portos_test.+async function withRevisionFailure(statement, operation, matchesParams = () => true) {+ const original = pg.Client.prototype.query;+ const spy = vi.spyOn(pg.Client.prototype, 'query').mockImplementation(function (sql, ...args) {+ if (typeof sql === 'string' && statement.test(sql.trim()) && matchesParams(args[0])) {+ const callback = typeof args.at(-1) === 'function' ? args.at(-1) : undefined;+ return original.call(this, 'SELECT 1 / 0', [], callback);+ }+ return original.call(this, sql, ...args);+ });+ try {+ return await operation();+ } finally {+ spy.mockRestore();+ }+}++describe.skipIf(!runDb)('ingredient content and history commit together', () => {+ it('rolls back standalone creation and new tags when the seed revision fails', async () => {+ const id = `cat-idea-rollback-${NONCE}`;+ const tag = `rollback-create-${NONCE}`;+ createdIngredientIds.add(id);+ await expect(withRevisionFailure(/^INSERT INTO catalog_ingredient_revisions/i, () =>+ catalogDB.createIngredient({ id, type: 'idea', name: 'Example rollback', tags: [tag] }),+ )).rejects.toThrow('division by zero');+ expect(await catalogDB.getIngredient(id)).toBeNull();+ expect((await catalogDB.listIngredientRevisions(id)).items).toEqual([]);+ expect((await query('SELECT id FROM catalog_tags WHERE label = $1', [tag])).rows).toEqual([]);+ });++ it.each(['insert', 'prune'])('rolls back public PATCH when revision %s fails', async (stage) => {+ const ing = await catalogDB.createIngredient({ type: 'idea', name: `Before ${NONCE}` });+ createdIngredientIds.add(ing.id);+ const revisions = (await catalogDB.listIngredientRevisions(ing.id)).items;+ const tag = `rollback-patch-${stage}-${NONCE}`;+ const statement = stage === 'insert'+ ? /^INSERT INTO catalog_ingredient_revisions/i+ : /^DELETE FROM catalog_ingredient_revisions/i;+ const response = await withRevisionFailure(statement, () =>+ request(makeApp()).patch(`/api/catalog/ingredients/${ing.id}`)+ .send({ name: 'After', payload: { summary: 'changed' }, tags: [tag] }),+ );+ expect(response.status).toBe(500);+ expect(await catalogDB.getIngredient(ing.id)).toEqual(ing);+ expect((await catalogDB.listIngredientRevisions(ing.id)).items).toEqual(revisions);+ expect((await query('SELECT id FROM catalog_tags WHERE label = $1', [tag])).rows).toEqual([]);+ });++ it('rolls back a public restore when its new revision fails', async () => {+ const ing = await catalogDB.createIngredient({ type: 'concept', name: `Restore rollback ${NONCE}` });+ createdIngredientIds.add(ing.id);+ const original = (await catalogDB.listIngredientRevisions(ing.id)).items[0];+ const edited = await catalogDB.updateIngredient(ing.id, { payload: { schemaVersion: 99, summary: 'keep' } });+ const revisions = (await catalogDB.listIngredientRevisions(ing.id)).items;+ const response = await withRevisionFailure(/^INSERT INTO catalog_ingredient_revisions/i, () =>+ request(makeApp()).post(`/api/catalog/ingredients/${ing.id}/revisions/${original.id}/restore`).send({}),+ );+ expect(response.status).toBe(500);+ expect(await catalogDB.getIngredient(ing.id)).toEqual(edited);+ expect((await catalogDB.listIngredientRevisions(ing.id)).items).toEqual(revisions);+ });++ it('commits public create and PATCH snapshots with their content and attribution', async () => {+ const created = await request(makeApp()).post('/api/catalog/ingredients')+ .send({ type: 'idea', name: `Atomic create ${NONCE}`, payload: { summary: 'initial' } });+ expect(created.status).toBe(201);+ createdIngredientIds.add(created.body.id);+ const seed = (await catalogDB.listIngredientRevisions(created.body.id)).items[0];+ expect(seed).toMatchObject({+ name: created.body.name, payload: created.body.payload, tags: created.body.tags, source: 'user', actor: null,+ });+ const edited = await request(makeApp()).patch(`/api/catalog/ingredients/${created.body.id}`)+ .send({ payload: { schemaVersion: 7, summary: 'edited' }, source: 'refine', actor: 'example-agent' });+ expect(edited.status).toBe(200);+ const revisions = (await catalogDB.listIngredientRevisions(created.body.id)).items;+ expect(revisions).toHaveLength(2);+ expect(revisions.find((rev) => rev.id !== seed.id)).toMatchObject({+ name: edited.body.name, payload: edited.body.payload, tags: edited.body.tags,+ source: 'refine', actor: 'example-agent',+ });+ });++ it('keeps create and update inside a supplied transaction, including reads of uncommitted rows', async () => {+ const id = `cat-chr-owned-${NONCE}`;+ createdIngredientIds.add(id);+ await expect(withTransaction(async (client) => {+ await catalogDB.createIngredient({ id, type: 'character', name: 'Example character' }, { client });+ const edited = await catalogDB.updateIngredient(id, {+ payload: { aliases: [' Example alias ', ''] }, tags: ['example-owned'],+ }, { client });+ expect(edited.payload.aliases).toEqual(['Example alias']);+ expect((await client.query('SELECT id FROM catalog_ingredient_revisions WHERE ingredient_id = $1', [id])).rows).toHaveLength(2);+ throw new Error('cancel outer transaction');+ })).rejects.toThrow('cancel outer transaction');+ expect(await catalogDB.getIngredient(id)).toBeNull();+ expect((await catalogDB.listIngredientRevisions(id)).items).toEqual([]);+ });++ it('rolls back the scrap graph when a later ingredient revision fails', async () => {+ const scrap = await catalogDB.createScrap({ rawText: 'Example source' });+ createdScrapIds.add(scrap.id);+ const firstName = `Example first ${NONCE}`;+ const secondName = `Example second ${NONCE}`;+ const refId = `example-universe-${NONCE}`;+ await expect(withRevisionFailure(/^INSERT INTO catalog_ingredient_revisions/i, () =>+ catalogDB.commitScrap({+ scrapId: scrap.id, universeRef: refId,+ accepted: [{ type: 'idea', name: firstName }, { type: 'idea', name: secondName }],+ }), (params) => params?.[2] === secondName,+ )).rejects.toThrow('division by zero');+ expect((await query('SELECT ingredient_id FROM catalog_ingredient_refs WHERE ref_id = $1', [refId])).rows).toEqual([]);+ expect((await query('SELECT id FROM catalog_ingredients WHERE name = ANY($1)', [[firstName, secondName]])).rows).toEqual([]);+ expect((await query('SELECT ingredient_id FROM catalog_ingredient_sources WHERE scrap_id = $1', [scrap.id])).rows).toEqual([]);+ expect((await query('SELECT id FROM catalog_ingredient_revisions WHERE name = ANY($1)', [[firstName, secondName]])).rows).toEqual([]);+ });+});+describe.skipIf(!runDb)('POST /api/catalog/ingredients/:id/revisions/:revisionId/restore', () => {it('restores the revision payload verbatim, preserving its schemaVersion, and records a new revision', async () => {// Seed an ingredient, then write an "old shape" payload (schemaVersion 0) so@@ -224,7 +343,7 @@ describe.skipIf(!runDb)('POST /api/catalog/ingredients/:id/revisions/:revisionIdconst r = await request(makeApp()).post(`/api/catalog/ingredients/${ing.id}/revisions/${oldRev.id}/restore`)- .send({});+ .send({ source: 'user', actor: 'example-restore' });expect(r.status).toBe(200);expect(r.body.payload.description).toBe('old-shape');@@ -233,6 +352,9 @@ describe.skipIf(!runDb)('POST /api/catalog/ingredients/:id/revisions/:revisionId// The restore is itself recorded as a new revision (auditable/reversible).const { items: after } = await catalogDB.listIngredientRevisions(ing.id);expect(after.length).toBe(revisions.length + 1);+ expect(after.find((rev) => !revisions.some((before) => before.id === rev.id))).toMatchObject({+ name: r.body.name, payload: r.body.payload, tags: r.body.tags, source: 'user', actor: 'example-restore',+ });});it('404s when the revision belongs to a different ingredient', async () => {diff --git a/server/services/catalogDB.registry.test.js b/server/services/catalogDB.registry.test.jsindex 82f0ed3af8..eebbce90ce 100644--- a/server/services/catalogDB.registry.test.js+++ b/server/services/catalogDB.registry.test.js@@ -47,7 +47,10 @@ vi.mock('../lib/db.js', () => ({}],};}),- withTransaction: vi.fn(),+ withTransaction: vi.fn(async (fn) => {+ const { query } = await import('../lib/db.js');+ return fn({ query });+ }),pgvectorToArray: vi.fn(() => null),arrayToPgvector: vi.fn((a) => a),}));diff --git a/server/services/catalogDB/ingredients.js b/server/services/catalogDB/ingredients.jsindex d773fde17c..5e45945e51 100644--- a/server/services/catalogDB/ingredients.js+++ b/server/services/catalogDB/ingredients.js@@ -6,7 +6,7 @@* Also the FTS / vector / hybrid (RRF) search paths over the ingredient corpus.*/-import { query, arrayToPgvector } from '../../lib/db.js';+import { query, withTransaction, arrayToPgvector } from '../../lib/db.js';import { reciprocalRankFusion } from '../../lib/rrfRanking.js';import {getActiveCatalogType,@@ -30,13 +30,20 @@ import { normalizeTags } from './tags.js';// `{ client }` is optional — when supplied, SQL runs on the caller's transaction// client (so the write rolls back if a later step in the same `withTransaction`-// block throws). Absent, falls through to the pool-level `query` as before.+// block throws). Standalone creates own a transaction including tags and history.// See `POST /api/catalog/scraps/:id/commit` for the scrap-commit batch that// needs every per-draft ingredient + source-link to commit-or-rollback together.export async function createIngredient({ id: explicitId, type, name, payload = {}, tags = [], embedding = null, embeddingModel = null } = {}, { client, source = 'user', actor = null } = {}) {if (!type || !getActiveCatalogType(type)) throw new Error(`Invalid ingredient type: ${type}`);if (!name || !String(name).trim()) throw new Error('name is required');+ if (!client) {+ return withTransaction((tx) => createIngredient(+ { id: explicitId, type, name, payload, tags, embedding, embeddingModel },+ { client: tx, source, actor },+ ));+ }+// `explicitId` is used by the backfill when a universe arrives from a peer// already carrying an ingredientId — preserves cross-peer identity so the// same logical character has the same catalog id on every install. New@@ -56,7 +63,7 @@ export async function createIngredient({ id: explicitId, type, name, payload = {// skew; this is the per-record payload-shape marker, distinct from that.)const storedPayload = { ...sanitizedPayload, schemaVersion: currentPayloadSchemaVersion(type) };const originInstanceId = await getInstanceId();- const exec = client ? client.query.bind(client) : query;+ const exec = client.query.bind(client);// Route freeform tags through the canonical catalog_tags table (creating// rows on first use) and seed the type's registry default tags. The freeform// TEXT[] column stores the canonical labels so existing tag-search/GIN paths@@ -87,8 +94,9 @@ export async function createIngredient({ id: explicitId, type, name, payload = {return created;}-export async function getIngredient(id) {- const result = await query(+export async function getIngredient(id, { client } = {}) {+ const exec = client ? client.query.bind(client) : query;+ const result = await exec(`SELECT * FROM catalog_ingredients WHERE id = $1 AND deleted = false`,[id],);@@ -117,7 +125,15 @@ export async function getIngredientTimestamps(ingredientIds) {// change. `source` is one of user|extract|refine|sync (default 'user'); `actor`// is an optional free label (agent run id, provider). Embedding-only patches// (the backfill path) carry no name/payload/tags and so record NO revision.-export async function updateIngredient(id, patch = {}, { source = 'user', actor = null } = {}) {+export async function updateIngredient(id, patch = {}, { client, source = 'user', actor = null } = {}) {+ const touchedContent =+ patch.name !== undefined || patch.payload !== undefined || patch.tags !== undefined;+ // Share one commit boundary for tags, content, snapshot and retention. A+ // caller-owned transaction must never nest or escape through the pool.+ if (touchedContent && !client) {+ return withTransaction((tx) => updateIngredient(id, patch, { client: tx, source, actor }));+ }+ const exec = client ? client.query.bind(client) : query;const fields = [];const params = [];let idx = 1;@@ -126,7 +142,7 @@ export async function updateIngredient(id, patch = {}, { source = 'user', actor// casing variant. `tags: []` (intentional clear) round-trips as an empty// array; absent `tags` skips normalization entirely (the loop below skips it).let normalizedPatch = patch.tags !== undefined- ? { ...patch, tags: await normalizeTags(patch.tags) }+ ? { ...patch, tags: await normalizeTags(patch.tags, { client }) }: patch;// Bible-type hardening: when a character/place/object payload is being// written, run it through the storyBible sanitizer (the same one the canon@@ -137,7 +153,7 @@ export async function updateIngredient(id, patch = {}, { source = 'user', actor// 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);+ const current = await getIngredient(id, { client });if (current && BIBLE_SANITIZERS[current.type]) {const name = normalizedPatch.name !== undefined ? normalizedPatch.name : current.name;normalizedPatch = {@@ -166,12 +182,12 @@ export async function updateIngredient(id, patch = {}, { source = 'user', actorparams.push(normalizedPatch[jsField]);}}- if (fields.length === 0) return getIngredient(id);+ if (fields.length === 0) return getIngredient(id, { client });params.push(id);// Mirrors updateScrap: PATCH on a soft-deleted row returns zero rows so the// route 404s. Revival of soft-deleted rows is intentionally separate via// `reviveDeletedIngredient`, so this filter doesn't conflict with that path.- const result = await query(+ const result = await exec(`UPDATE catalog_ingredients SET ${fields.join(', ')} WHERE id = $${idx} AND deleted = false RETURNING *`,params,);@@ -179,13 +195,10 @@ export async function updateIngredient(id, patch = {}, { source = 'user', actor// Record a revision only when a USER-facing field (name/payload/tags) was// part of this patch AND the row actually exists/updated. Embedding/model-- // only patches skip history entirely. `payload.schemaVersion` is stripped- // from the stored revision diff-by-content check below, but we snapshot the- // committed payload verbatim so a restore round-trips the exact stored shape.- const touchedContent =- patch.name !== undefined || patch.payload !== undefined || patch.tags !== undefined;+ // only patches skip history entirely. Snapshot the stored payload verbatim+ // so a restore round-trips the exact shape, including its schemaVersion.if (updated && touchedContent) {- await recordIngredientRevision(updated, { source, actor });+ await recordIngredientRevision(updated, { source, actor, client });}return updated;}diff --git a/server/services/catalogDBRevisions.test.js b/server/services/catalogDBRevisions.test.jsindex e7efb40290..1572933228 100644--- a/server/services/catalogDBRevisions.test.js+++ b/server/services/catalogDBRevisions.test.js@@ -78,7 +78,10 @@ vi.mock('../lib/db.js', () => ({}return { rows: [] };}),- withTransaction: vi.fn(),+ withTransaction: vi.fn(async (fn) => {+ const { query } = await import('../lib/db.js');+ return fn({ query });+ }),pgvectorToArray: vi.fn(() => null),arrayToPgvector: vi.fn((a) => a),}));