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

refactor: move scrap commit into catalog DB (#4906)

Adam Eivy4ff3d962a293
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index f2e444d2b0..ea516bb9af 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -6,7 +6,6 @@ import * as catalogDB from '../services/catalogDB.js';
import * as catalogSync from '../services/catalogSync.js';
import { resolveRefs, listDanglingRefs } from '../services/catalogRefResolver.js';
import { projectToCanon } from '../services/catalogCanonProjection.js';
-import { withTransaction } from '../lib/db.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, parsePagination } from '../lib/validation.js';
import {
@@ -162,27 +161,10 @@ router.post('/scraps/:id/commit', asyncHandler(async (req, res) => {
const seeds = req.body.accepted.map((d) => ingredientEmbedSeed(d));
const embeds = await embedBatch(seeds);
- // Wrap the per-draft loop in a transaction so a mid-loop failure (DB
- // timeout, future unique-constraint violation, span shape error) rolls back
- // the whole batch instead of leaving some ingredients persisted without
- // their source-link rows.
- const created = await withTransaction(async (client) => {
- const out = [];
- for (let i = 0; i < req.body.accepted.length; i++) {
- const draft = req.body.accepted[i];
- const e = embeds[i];
- const ing = await catalogDB.createIngredient({
- type: draft.type,
- name: draft.name,
- payload: draft.payload || {},
- tags: draft.tags || [],
- embedding: e?.embedding ?? null,
- embeddingModel: e?.model ?? null,
- }, { client, source: 'extract' });
- await catalogDB.linkIngredientToSource(ing.id, scrap.id, draft.span || null, { client });
- out.push(ing);
- }
- return out;
+ const created = await catalogDB.commitScrap({
+ scrapId: scrap.id,
+ accepted: req.body.accepted,
+ embeds,
});
res.status(201).json({ scrap, ingredients: created });
diff --git a/server/services/catalogDB.commit.test.js b/server/services/catalogDB.commit.test.js
new file mode 100644
index 0000000000..9e58ac88de
--- /dev/null
+++ b/server/services/catalogDB.commit.test.js
@@ -0,0 +1,94 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ client: { query: vi.fn() },
+ createIngredient: vi.fn(),
+ linkIngredientToSource: vi.fn(),
+ withTransaction: vi.fn(),
+}));
+
+vi.mock('../lib/db.js', () => ({
+ withTransaction: mocks.withTransaction,
+}));
+
+vi.mock('./catalogDB/ingredients.js', () => ({
+ createIngredient: mocks.createIngredient,
+}));
+
+vi.mock('./catalogDB/refs.js', () => ({
+ linkIngredientToSource: mocks.linkIngredientToSource,
+}));
+
+import { commitScrap } from './catalogDB/commit.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.withTransaction.mockImplementation((fn) => fn(mocks.client));
+});
+
+describe('commitScrap', () => {
+ it('creates accepted ingredients and source links on one transaction client', async () => {
+ mocks.createIngredient
+ .mockResolvedValueOnce({ id: 'cat-chr-example', name: 'Example Character' })
+ .mockResolvedValueOnce({ id: 'cat-plc-example', name: 'Example Place' });
+
+ const created = await commitScrap({
+ scrapId: 'cat-scrap-example',
+ accepted: [
+ { type: 'character', name: 'Example Character', payload: { role: 'lead' }, tags: ['hero'], span: { start: 1, end: 4 } },
+ { type: 'place', name: 'Example Place' },
+ ],
+ embeds: [
+ { embedding: [0.1, 0.2], model: 'example-model' },
+ null,
+ ],
+ });
+
+ expect(mocks.withTransaction).toHaveBeenCalledTimes(1);
+ expect(mocks.createIngredient).toHaveBeenNthCalledWith(1, {
+ type: 'character',
+ name: 'Example Character',
+ payload: { role: 'lead' },
+ tags: ['hero'],
+ embedding: [0.1, 0.2],
+ embeddingModel: 'example-model',
+ }, { client: mocks.client, source: 'extract' });
+ expect(mocks.createIngredient).toHaveBeenNthCalledWith(2, {
+ type: 'place',
+ name: 'Example Place',
+ payload: {},
+ tags: [],
+ embedding: null,
+ embeddingModel: null,
+ }, { client: mocks.client, source: 'extract' });
+ expect(mocks.linkIngredientToSource).toHaveBeenNthCalledWith(
+ 1,
+ 'cat-chr-example',
+ 'cat-scrap-example',
+ { start: 1, end: 4 },
+ { client: mocks.client },
+ );
+ expect(mocks.linkIngredientToSource).toHaveBeenNthCalledWith(
+ 2,
+ 'cat-plc-example',
+ 'cat-scrap-example',
+ null,
+ { client: mocks.client },
+ );
+ expect(created).toEqual([
+ { id: 'cat-chr-example', name: 'Example Character' },
+ { id: 'cat-plc-example', name: 'Example Place' },
+ ]);
+ });
+
+ it('does not swallow a failed transaction step', async () => {
+ const failure = new Error('source link failed');
+ mocks.createIngredient.mockResolvedValue({ id: 'cat-idea-example' });
+ mocks.linkIngredientToSource.mockRejectedValue(failure);
+
+ await expect(commitScrap({
+ scrapId: 'cat-scrap-example',
+ accepted: [{ type: 'idea', name: 'Example Idea' }],
+ })).rejects.toBe(failure);
+ });
+});
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index f3c8835bb7..721f5f43a2 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -24,6 +24,7 @@
* - `catalogDB/refs.js` — source links, external refs, relations, roles
* - `catalogDB/media.js` — media attachments + integrity surface
* - `catalogDB/tags.js` — tag taxonomy / normalization
+ * - `catalogDB/commit.js` — atomic scrap extraction commits
* - `catalogDB/sync.js` — peer-sync change feeds + upserts
* - `catalogDB/facets.js` — export slice / sync bundle / stats / facets
*
@@ -40,5 +41,6 @@ export * from './catalogDB/ingredients.js';
export * from './catalogDB/refs.js';
export * from './catalogDB/media.js';
export * from './catalogDB/tags.js';
+export * from './catalogDB/commit.js';
export * from './catalogDB/sync.js';
export * from './catalogDB/facets.js';
diff --git a/server/services/catalogDB/commit.js b/server/services/catalogDB/commit.js
new file mode 100644
index 0000000000..dfb75e8e1a
--- /dev/null
+++ b/server/services/catalogDB/commit.js
@@ -0,0 +1,35 @@
+/**
+ * Creative Ingredients Catalog — multi-row commit orchestration.
+ *
+ * Keeps transaction ownership inside the catalog data layer so HTTP callers
+ * cannot accidentally persist only part of a scrap's accepted extraction.
+ */
+
+import { withTransaction } from '../../lib/db.js';
+import { createIngredient } from './ingredients.js';
+import { linkIngredientToSource } from './refs.js';
+
+/**
+ * Persist every accepted extraction draft and its source link atomically.
+ * Embeddings are prepared by the caller before this DB-only transaction starts.
+ */
+export async function commitScrap({ scrapId, accepted = [], embeds = [] } = {}) {
+ return withTransaction(async (client) => {
+ const created = [];
+ for (let i = 0; i < accepted.length; i++) {
+ const draft = accepted[i];
+ const embedding = embeds[i];
+ const ingredient = await createIngredient({
+ type: draft.type,
+ name: draft.name,
+ payload: draft.payload || {},
+ tags: draft.tags || [],
+ embedding: embedding?.embedding ?? null,
+ embeddingModel: embedding?.model ?? null,
+ }, { client, source: 'extract' });
+ await linkIngredientToSource(ingredient.id, scrapId, draft.span || null, { client });
+ created.push(ingredient);
+ }
+ return created;
+ });
+}