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
refactor: extract render orchestration, brain cascade, folder-open, and RRF ranking into services/lib
[._.]/ Adam Eivy11f3c32bf3c4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7c4c4dfcc4..41f4fecd3e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -21,6 +21,7 @@- **Workspace-root validation on git/scaffold routes** — git operations and app scaffolding refuse paths outside allowed workspace roots; file staging uses literal pathspecs (no git glob expansion); `env` removed from the shell command allowlist so process secrets can't land in persisted job output.- **Route validation + linkable tabs** — jira, loops, CoS, digital-twin, automation-schedule, and history inputs are now Zod-validated; Prompt Manager and Messages triage tabs live in the URL (deep-linkable); previously-swallowed client errors are logged.- **Helper consolidation** — filename sanitization and MIME maps unified in fileUtils (was 3 copies); GSD/app document saves use atomic writes; client components use the canonical formatters and shared command API instead of local re-implementations.+- **Service extractions** — universe-builder render orchestration, brain bucket cascade/ordering, system folder-open, and reciprocal-rank-fusion moved out of routes into services/lib; the canonPrompt client/server mirror is now enforced by a parity test.- **A watched TUI run no longer false-times-out after finishing its work** — companion fix to *Live TUI runs are now viewable AND drivable in the Shell page* (above). One-shot AI runs that drive a terminal UI (Claude Code, Codex, etc.) write their completed answer to a response file and then return to an interactive prompt **without exiting**. The runner only auto-completed such a run via output-idle — which is paused while you watch it in the Shell page (so it isn't snapped shut mid-read). With the process never exiting and idle paused, a watched run had no terminus but the 10-minute hard timeout — at which point it was marked **failed**, its already-written result was **discarded**, and a useless fallback retry ran in its place. The runner now watches for the response file as the model's authoritative "done" signal and completes the run the moment it's written — even while you're watching — since once the file exists the task is genuinely finished. A second safety net salvages the file on hard timeout: if the result was written but completion stalled for any other reason, the run finishes as **success** with that result instead of throwing it away and falling back. So a long editorial pass you keep open in the Shell tab now lands its findings when the model finishes, instead of silently dying at 10 minutes. (`server/lib/tuiPromptRunner.js`)diff --git a/server/lib/README.md b/server/lib/README.mdindex c12d8fc2ba..05b379bb5a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -113,6 +113,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `bashResolver.js` | `resolveBashBinary()` — resolves the POSIX `bash` for running bundled `*.sh` scripts (e.g. `scripts/db.sh`). On Windows a bare `bash` often resolves (via PM2's PATH) to WSL, which mounts drives at `/mnt/h` and can't see a `H:/...` drive path (exit 127); this prefers Git Bash (PORTOS_BASH override → standard install dirs → derived from `git` on PATH → bare `bash`). No-op (`bash`) on non-Windows. |+| `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. || `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, and Windows `taskkill /T /F` tree-kill. Used by `appBuilder.js` and `appUpdater.js`. || `commandSecurity.js` | Allowlist of safe shell commands. || `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |@@ -150,6 +151,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `vectorMath.js` | Vector math utilities (cosine, etc.). || `memoryQuery.js` | Pure memory-index helpers: meta projection, filter/sort, search/hybrid meta filters, RRF fusion. || `memoryStats.js` | macOS-correct memory accounting (handles "Pages free" quirk). |+| `rrfRanking.js` | Pure `reciprocalRankFusion(textResults, vectorResults, options)` — merges two ranked lists via RRF scoring (Cormack 2009). Used by `catalogDB.hybridSearchIngredients`. |## Extraction & parsingdiff --git a/server/lib/canonPrompt.mirror.test.js b/server/lib/canonPrompt.mirror.test.jsnew file mode 100644index 0000000000..f6d4608567--- /dev/null+++ b/server/lib/canonPrompt.mirror.test.js@@ -0,0 +1,139 @@+/**+ * Mirror parity test for server/lib/canonPrompt.js ↔ client/src/lib/canonPrompt.js+ *+ * The mirrored portion includes:+ * - SHORT_SPEC, PREVIEW_SPEC, RICH_SPEC constant bodies+ * - normalizeKind, fragmentsFromSequence, sequenceHasAnyField function bodies+ * - shortCanonDescriptorFragments, richCanonDescriptorFragments,+ * mapCanonDescriptorFragments, flattenCanonDescriptorFragments,+ * descriptorForCanonEntry, previewCanonFragments, hasCanonDescriptorContent+ * function bodies+ *+ * The server-only section (flattenStats, flattenPalette, flattenWardrobes,+ * flattenProps, flattenNamedList, etc.) is NOT checked — those are explicitly+ * excluded from the mirror contract by the "Server-only" comment.+ *+ * Comparison strategy: strip single-line and multi-line comments, then+ * normalize whitespace before diffing. This means JSDoc divergence between+ * the two sides does NOT fail the test — only code logic differences do.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { resolve } from 'path';+import { fileURLToPath } from 'url';+import { dirname } from 'path';++const __dirname = dirname(fileURLToPath(import.meta.url));++const SERVER_PATH = resolve(__dirname, 'canonPrompt.js');+const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/canonPrompt.js');++/** Strip single-line (//) and block (/* ... */) comments, then normalize whitespace. */+function stripCommentsAndNormalize(src) {+ // Remove block comments (non-greedy, including JSDoc)+ let s = src.replace(/\/\*[\s\S]*?\*\//g, '');+ // Remove single-line comments+ s = s.replace(/\/\/[^\n]*/g, '');+ // Collapse runs of whitespace (including newlines) to a single space+ s = s.replace(/\s+/g, ' ').trim();+ return s;+}++/**+ * Extract the body of a named declaration from source text.+ *+ * Matches:+ * - `function NAME(` ... balanced braces+ * - `const NAME = Object.freeze(` ... balanced parens+ * - `export function NAME(` ... balanced braces+ * - `export const NAME = Object.freeze(` ... balanced parens/objects+ *+ * Returns the matched text (declaration through closing delimiter), or null.+ */+function extractDeclaration(src, name) {+ // Find the start of the declaration (with or without `export`)+ const startRe = new RegExp(+ `(?:export\\s+)?(?:function|const|async function)\\s+${name}[\\s=(]`,+ );+ const match = startRe.exec(src);+ if (!match) return null;++ const start = match.index;+ let depth = 0;+ let i = start;+ let foundOpen = false;++ // Walk forward tracking brace/paren depth to find the end of the declaration+ while (i < src.length) {+ const ch = src[i];+ if (ch === '{' || ch === '(') {+ depth++;+ foundOpen = true;+ } else if (ch === '}' || ch === ')') {+ depth--;+ if (foundOpen && depth === 0) {+ return src.slice(start, i + 1);+ }+ }+ i++;+ }+ return null;+}++// Declarations that must be textually identical (code-only, comments stripped)+const MIRRORED_NAMES = [+ 'SHORT_SPEC',+ 'PREVIEW_SPEC',+ 'RICH_SPEC',+ 'normalizeKind',+ 'fragmentsFromSequence',+ 'sequenceHasAnyField',+ 'shortCanonDescriptorFragments',+ 'richCanonDescriptorFragments',+ 'mapCanonDescriptorFragments',+ 'flattenCanonDescriptorFragments',+ 'descriptorForCanonEntry',+ 'previewCanonFragments',+ 'hasCanonDescriptorContent',+];++describe('canonPrompt server↔client mirror parity', () => {+ const serverSrc = readFileSync(SERVER_PATH, 'utf8');+ const clientSrc = readFileSync(CLIENT_PATH, 'utf8');++ // Sanity-check that both files were read+ it('both files are non-empty', () => {+ expect(serverSrc.length).toBeGreaterThan(100);+ expect(clientSrc.length).toBeGreaterThan(100);+ });++ // The server file should contain the "Server-only" boundary marker+ it('server file has the Server-only boundary comment', () => {+ expect(serverSrc).toMatch(/Server-only/);+ });++ for (const name of MIRRORED_NAMES) {+ it(`${name} is present and identical on both sides (code only)`, () => {+ const serverDecl = extractDeclaration(serverSrc, name);+ const clientDecl = extractDeclaration(clientSrc, name);++ expect(serverDecl, `server/lib/canonPrompt.js is missing declaration: ${name}`).not.toBeNull();+ expect(clientDecl, `client/src/lib/canonPrompt.js is missing declaration: ${name}`).not.toBeNull();++ const serverNorm = stripCommentsAndNormalize(serverDecl);+ const clientNorm = stripCommentsAndNormalize(clientDecl);++ expect(clientNorm, `"${name}" code diverged between server and client`).toBe(serverNorm);+ });+ }++ // Ensure server-only exports are NOT present in the client file+ const SERVER_ONLY_NAMES = ['flattenStats', 'flattenPalette', 'flattenWardrobes', 'flattenProps', 'flattenNamedList'];+ for (const name of SERVER_ONLY_NAMES) {+ it(`${name} is server-only (absent from client bundle)`, () => {+ const clientDecl = extractDeclaration(clientSrc, name);+ expect(clientDecl, `${name} should be server-only but was found in client/src/lib/canonPrompt.js`).toBeNull();+ });+ }+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 7a505d62b4..f6fc2915a6 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -109,6 +109,7 @@ export * from './gitArgs.js';export * from './gitForge.js';export * from './gitOutputParsers.js';export * from './gitRemote.js';+export * from './openFolder.js';export * from './processEnv.js';export * from './pythonSetup.js';@@ -131,6 +132,7 @@ export * from './tailscale.js';export * from './bm25.js';export * from './memoryQuery.js';export * from './memoryStats.js';+export * from './rrfRanking.js';export * from './vectorMath.js';// === Extraction & parsing ===diff --git a/server/lib/openFolder.js b/server/lib/openFolder.jsnew file mode 100644index 0000000000..e0a6b2068e--- /dev/null+++ b/server/lib/openFolder.js@@ -0,0 +1,40 @@+/**+ * Cross-platform "open folder in system file manager" helper.+ *+ * Extracted from routes/brain.js POST /links/:id/open-folder.+ * The child process is detached and unref'd so the spawned file manager+ * outlives the Node process without blocking it. The child 'error' handler+ * is wired so a spawn failure (e.g. missing xdg-open on a headless server)+ * logs rather than crashing the Node process.+ */++import { spawn } from 'child_process';++/**+ * Open a local path in the system file manager (Finder / Explorer / Nautilus).+ *+ * @param {string} localPath - Absolute path to open.+ * @returns {void}+ */+export function openFolderInSystemExplorer(localPath) {+ let cmd, args;+ const platform = process.platform;++ if (platform === 'darwin') {+ cmd = 'open';+ args = [localPath];+ } else if (platform === 'win32') {+ cmd = 'explorer';+ args = [localPath];+ } else {+ cmd = 'xdg-open';+ args = [localPath];+ }++ const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true });+ child.on('error', (err) => {+ console.error(`❌ openFolderInSystemExplorer spawn failed (${cmd}): ${err.message}`);+ });+ child.unref();+ console.log(`📂 Opened folder: ${localPath}`);+}diff --git a/server/lib/rrfRanking.js b/server/lib/rrfRanking.jsnew file mode 100644index 0000000000..bb82721803--- /dev/null+++ b/server/lib/rrfRanking.js@@ -0,0 +1,51 @@+/**+ * Reciprocal Rank Fusion (RRF) scoring helper.+ *+ * Pure function — no imports from services. Extracted from+ * server/services/catalogDB.js hybridSearchIngredients (inline ~64 lines).+ *+ * RRF merges two ranked lists (e.g. FTS + vector similarity) into a single+ * score: score += weight / (K + rank) for each list the item appears in.+ * Default K=60 follows the original Cormack et al. paper.+ *+ * References:+ * Cormack, G.V., Clarke, C.L., Buettcher, S. (2009). Reciprocal Rank Fusion+ * outperforms Condorcet and individual Rank Learning Methods.+ */++/**+ * Merge two ranked result arrays via Reciprocal Rank Fusion.+ *+ * @param {Array<object>} textResults - FTS results in rank order (best first).+ * Each element must have an `id` field. The `row` property is passed through+ * to the caller so the DB row can be mapped after scoring.+ * @param {Array<object>} vectorResults - Vector similarity results in rank order.+ * @param {object} [options]+ * @param {number} [options.k=60] - RRF smoothing constant.+ * @param {number} [options.ftsWeight=0.4] - Score contribution weight for FTS ranks.+ * @param {number} [options.vectorWeight=0.6] - Score contribution weight for vector ranks.+ * @returns {Map<string|number, { row: object, ftsRank: number|null, vectorRank: number|null, rrfScore: number }>}+ * Map keyed by item id. Callers sort and slice as needed.+ */+export function reciprocalRankFusion(textResults, vectorResults, options = {}) {+ const { k = 60, ftsWeight = 0.4, vectorWeight = 0.6 } = options;+ const rrf = new Map();++ (textResults || []).forEach((row, rank) => {+ const cur = rrf.get(row.id) || { row, ftsRank: null, vectorRank: null, rrfScore: 0 };+ cur.row = row;+ cur.ftsRank = rank + 1;+ cur.rrfScore += ftsWeight / (k + rank + 1);+ rrf.set(row.id, cur);+ });++ (vectorResults || []).forEach((row, rank) => {+ const cur = rrf.get(row.id) || { row, ftsRank: null, vectorRank: null, rrfScore: 0 };+ if (!cur.row) cur.row = row;+ cur.vectorRank = rank + 1;+ cur.rrfScore += vectorWeight / (k + rank + 1);+ rrf.set(row.id, cur);+ });++ return rrf;+}diff --git a/server/lib/rrfRanking.test.js b/server/lib/rrfRanking.test.jsnew file mode 100644index 0000000000..68ba8f1cb0--- /dev/null+++ b/server/lib/rrfRanking.test.js@@ -0,0 +1,113 @@+import { describe, it, expect } from 'vitest';+import { reciprocalRankFusion } from './rrfRanking.js';++const row = (id, extra = {}) => ({ id, ...extra });++describe('reciprocalRankFusion', () => {+ it('returns empty map for empty inputs', () => {+ expect(reciprocalRankFusion([], []).size).toBe(0);+ expect(reciprocalRankFusion(null, null).size).toBe(0);+ expect(reciprocalRankFusion(undefined, undefined).size).toBe(0);+ });++ it('scores FTS-only results', () => {+ const rrf = reciprocalRankFusion([row('a'), row('b')], []);+ expect(rrf.has('a')).toBe(true);+ expect(rrf.has('b')).toBe(true);+ const a = rrf.get('a');+ const b = rrf.get('b');+ // rank 1 > rank 2+ expect(a.rrfScore).toBeGreaterThan(b.rrfScore);+ expect(a.ftsRank).toBe(1);+ expect(a.vectorRank).toBeNull();+ });++ it('scores vector-only results', () => {+ const rrf = reciprocalRankFusion([], [row('x'), row('y')]);+ const x = rrf.get('x');+ const y = rrf.get('y');+ expect(x.rrfScore).toBeGreaterThan(y.rrfScore);+ expect(x.vectorRank).toBe(1);+ expect(x.ftsRank).toBeNull();+ });++ it('fuses scores when an item appears in both lists', () => {+ // 'shared' is rank 1 in FTS and rank 1 in vector+ // 'fts-only' is rank 2 in FTS+ // 'vec-only' is rank 2 in vector+ const rrf = reciprocalRankFusion(+ [row('shared'), row('fts-only')],+ [row('shared'), row('vec-only')],+ );+ const shared = rrf.get('shared');+ const ftsOnly = rrf.get('fts-only');+ const vecOnly = rrf.get('vec-only');+ // shared received both FTS and vector contributions+ expect(shared.rrfScore).toBeGreaterThan(ftsOnly.rrfScore);+ expect(shared.rrfScore).toBeGreaterThan(vecOnly.rrfScore);+ expect(shared.ftsRank).toBe(1);+ expect(shared.vectorRank).toBe(1);+ });++ it('respects custom k, ftsWeight, vectorWeight', () => {+ // With ftsWeight=1, vectorWeight=0: only FTS contributes+ const rrf = reciprocalRankFusion(+ [row('a')],+ [row('b')],+ { k: 60, ftsWeight: 1, vectorWeight: 0 },+ );+ const a = rrf.get('a');+ const b = rrf.get('b');+ expect(a.rrfScore).toBeGreaterThan(0);+ expect(b.rrfScore).toBe(0);+ });++ it('score is monotonically decreasing with rank', () => {+ const items = [row('a'), row('b'), row('c'), row('d')];+ const rrf = reciprocalRankFusion(items, []);+ const scores = ['a', 'b', 'c', 'd'].map((id) => rrf.get(id).rrfScore);+ for (let i = 0; i < scores.length - 1; i++) {+ expect(scores[i]).toBeGreaterThan(scores[i + 1]);+ }+ });++ it('handles tie in rank position (same index in both lists) correctly', () => {+ // Both lists have 'a' at rank 1 and 'b' at rank 2+ const rrf = reciprocalRankFusion(+ [row('a'), row('b')],+ [row('a'), row('b')],+ { k: 60, ftsWeight: 0.5, vectorWeight: 0.5 },+ );+ const a = rrf.get('a');+ const b = rrf.get('b');+ // 'a' has same rank across both lists as 'b' does — a ranks 1/1, b ranks 2/2+ // a should still score higher than b because 1/(60+1) > 1/(60+2)+ expect(a.rrfScore).toBeGreaterThan(b.rrfScore);+ // Both have contributions from both signals+ expect(a.ftsRank).toBe(1);+ expect(a.vectorRank).toBe(1);+ expect(b.ftsRank).toBe(2);+ expect(b.vectorRank).toBe(2);+ });++ it('preserves row data from first encounter', () => {+ const ftsRow = { id: 'x', rank: 0.9 };+ const vecRow = { id: 'x', similarity: 0.8 };+ const rrf = reciprocalRankFusion([ftsRow], [vecRow]);+ // FTS came first — row should be the FTS row+ expect(rrf.get('x').row).toBe(ftsRow);+ });++ it('returns correct ftsRank and vectorRank as 1-indexed', () => {+ const rrf = reciprocalRankFusion(+ [row('p'), row('q'), row('r')],+ [row('r'), row('p')],+ );+ expect(rrf.get('p').ftsRank).toBe(1);+ expect(rrf.get('p').vectorRank).toBe(2);+ expect(rrf.get('q').ftsRank).toBe(2);+ expect(rrf.get('q').vectorRank).toBeNull();+ expect(rrf.get('r').ftsRank).toBe(3);+ expect(rrf.get('r').vectorRank).toBe(1);+ });+});diff --git a/server/routes/brain.js b/server/routes/brain.jsindex 15f002a893..00e0741755 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -9,9 +9,9 @@*/import { Router } from 'express';-import { spawn } from 'child_process';import { existsSync } from 'fs';import * as brainService from '../services/brain.js';+import { openFolderInSystemExplorer } from '../lib/openFolder.js';import { getProviderById } from '../services/providers.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';@@ -72,8 +72,10 @@ router.post('/capture', asyncHandler(async (req, res) => {*/router.get('/inbox', asyncHandler(async (req, res) => {const data = validateRequest(inboxQuerySchema, req.query);- const entries = await brainService.getInboxLog(data);- const counts = await brainService.getInboxLogCounts();+ const [entries, counts] = await Promise.all([+ brainService.getInboxLog(data),+ brainService.getInboxLogCounts(),+ ]);res.json({ entries, counts });}));@@ -780,24 +782,7 @@ router.post('/links/:id/open-folder', asyncHandler(async (req, res) => {});}- // Cross-platform folder open command- const platform = process.platform;- let cmd, args;-- if (platform === 'darwin') {- cmd = 'open';- args = [link.localPath];- } else if (platform === 'win32') {- cmd = 'explorer';- args = [link.localPath];- } else {- cmd = 'xdg-open';- args = [link.localPath];- }-- spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref();- console.log(`📂 Opened folder: ${link.localPath}`);-+ openFolderInSystemExplorer(link.localPath);res.json({ message: 'Folder opened', path: link.localPath });}));@@ -879,14 +864,7 @@ router.get('/buckets', asyncHandler(async (req, res) => {*/router.post('/buckets', asyncHandler(async (req, res) => {const { name, color, icon } = validateRequest(bucketInputSchema, req.body);- const existing = await brainService.getBuckets();- const nextOrder = existing.reduce((max, b) => Math.max(max, b.order ?? 0), -1) + 1;- const bucket = await brainService.createBucket({- name,- color: color || 'accent',- icon: icon || '',- order: nextOrder- });+ const bucket = await brainService.createBucketAppended({ name, color, icon });console.log(`🗂️ Created bucket: ${bucket.id} (${bucket.name})`);res.status(201).json(bucket);}));@@ -931,18 +909,9 @@ router.delete('/buckets/:id', asyncHandler(async (req, res) => {throw new ServerError('Bucket not found', { status: 404, code: 'NOT_FOUND' });}- const links = await brainService.getLinks();- let unassigned = 0;- for (const link of links) {- if (link.bucketId === req.params.id) {- await brainService.updateLink(link.id, { bucketId: null });- unassigned++;- }- }-- await brainService.deleteBucket(req.params.id);- console.log(`🗂️ Deleted bucket: ${req.params.id} (unassigned ${unassigned} links)`);- res.json({ deleted: true, unassigned });+ const result = await brainService.deleteBucketAndUnlinkChildren(req.params.id);+ console.log(`🗂️ Deleted bucket: ${req.params.id} (unassigned ${result.unassigned} links)`);+ res.json(result);}));// =============================================================================diff --git a/server/routes/brain.test.js b/server/routes/brain.test.jsindex f6b4704f36..d1a3aab521 100644--- a/server/routes/brain.test.js+++ b/server/routes/brain.test.js@@ -66,8 +66,10 @@ vi.mock('../services/brain.js', () => ({getBuckets: vi.fn(),getBucketById: vi.fn(),createBucket: vi.fn(),+ createBucketAppended: vi.fn(),updateBucket: vi.fn(),- deleteBucket: vi.fn()+ deleteBucket: vi.fn(),+ deleteBucketAndUnlinkChildren: vi.fn()}));// Mock the brain graph service@@ -1247,18 +1249,18 @@ describe('Brain Routes', () => {});describe('POST /api/brain/buckets', () => {- it('creates a bucket appended after existing ones', async () => {- brainService.getBuckets.mockResolvedValue([{ id: 'b1', order: 0 }, { id: 'b2', order: 1 }]);- brainService.createBucket.mockImplementation(async (data) => ({ id: 'b3', ...data }));+ it('delegates to createBucketAppended with the validated fields', async () => {+ brainService.createBucketAppended.mockImplementation(async (data) => ({ id: 'b3', order: 2, ...data }));const res = await request(app).post('/api/brain/buckets').send({ name: 'Disney' });expect(res.status).toBe(201);- expect(brainService.createBucket).toHaveBeenCalledWith(expect.objectContaining({ name: 'Disney', order: 2 }));+ expect(brainService.createBucketAppended).toHaveBeenCalledWith({ name: 'Disney', color: undefined, icon: undefined });+ expect(res.body.name).toBe('Disney');});it('rejects an empty name with 400', async () => {const res = await request(app).post('/api/brain/buckets').send({ name: '' });expect(res.status).toBe(400);- expect(brainService.createBucket).not.toHaveBeenCalled();+ expect(brainService.createBucketAppended).not.toHaveBeenCalled();});it('rejects an invalid color with 400', async () => {@@ -1351,30 +1353,21 @@ describe('Brain Routes', () => {});describe('DELETE /api/brain/buckets/:id', () => {- it('deletes the bucket and unassigns its links', async () => {+ it('delegates to deleteBucketAndUnlinkChildren and returns its result', async () => {brainService.getBucketById.mockResolvedValue({ id: 'b1', name: 'Disney' });- brainService.getLinks.mockResolvedValue([- { id: 'l1', bucketId: 'b1' },- { id: 'l2', bucketId: 'b2' },- { id: 'l3', bucketId: 'b1' }- ]);- brainService.updateLink.mockResolvedValue({});- brainService.deleteBucket.mockResolvedValue(true);+ brainService.deleteBucketAndUnlinkChildren.mockResolvedValue({ deleted: true, unassigned: 2 });const res = await request(app).delete('/api/brain/buckets/b1');expect(res.status).toBe(200);- expect(res.body.unassigned).toBe(2);- expect(brainService.updateLink).toHaveBeenCalledWith('l1', { bucketId: null });- expect(brainService.updateLink).toHaveBeenCalledWith('l3', { bucketId: null });- expect(brainService.updateLink).not.toHaveBeenCalledWith('l2', { bucketId: null });- expect(brainService.deleteBucket).toHaveBeenCalledWith('b1');+ expect(res.body).toEqual({ deleted: true, unassigned: 2 });+ expect(brainService.deleteBucketAndUnlinkChildren).toHaveBeenCalledWith('b1');});it('returns 404 for an unknown bucket', async () => {brainService.getBucketById.mockResolvedValue(null);const res = await request(app).delete('/api/brain/buckets/missing');expect(res.status).toBe(404);- expect(brainService.deleteBucket).not.toHaveBeenCalled();+ expect(brainService.deleteBucketAndUnlinkChildren).not.toHaveBeenCalled();});});diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex bf6804e0f3..3803464f3c 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -13,7 +13,6 @@import { Router } from 'express';import { z } from 'zod';-import { randomUUID } from 'crypto';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, optionalBooleanMap, llmSchema } from '../lib/validation.js';import * as svc from '../services/universeBuilder.js';@@ -30,18 +29,11 @@ import { expandWorldTemplate, generateCategoryVariations } from '../services/uniimport { refineWorldPrompts } from '../services/universeBuilderRefine.js';import { promoteVariationToCanon, VALID_TARGET_KINDS } from '../services/universeBuilderPromote.js';import { autoSortOtherBuckets } from '../services/universeBuilderAutoSort.js';-import { enqueueJob } from '../services/mediaJobQueue/index.js';-import { getSettings } from '../services/settings.js';-import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';import { findDuplicateUniverseGroups, findSameNameUniverses } from '../services/duplicateDetection.js';import { mergeUniverses, buildCascadeContext } from '../services/recordMerge.js';import { mergeFieldsWithAI } from '../services/recordMergeAI.js';-import { registerUniverseBuilderRun } from '../services/universeBuilderCollectionHook.js';-import { getImageModels, isFlux2 } from '../lib/mediaModels.js';-import { usesDiffusersRunner } from '../lib/runners.js';-import { IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/modes.js';-import { resolveImageCleaners } from '../services/imageGen/index.js';-import { getStylePresetById } from '../lib/writersRoomStylePresets.js';+import { IMAGE_GEN_MODES } from '../services/imageGen/modes.js';+import { renderUniverseJobs } from '../services/universeBuilderRender.js';const router = Router();@@ -524,192 +516,8 @@ router.post('/:id/render', asyncHandler(async (req, res) => {if (body.promptMode !== 'canon' && await svc.needsEntryIdPersist(req.params.id)) {await svc.updateUniverse(req.params.id, () => ({})).catch((err) => { throw mapServiceError(err); });}- const universe = await svc.getUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });-- // Resolve a style preset (server-side authoritative list) so the embrace- // tokens are deterministic for this render even if the client sent a stale- // preset object. Unknown ids are ignored (server is the source of truth).- const stylePreset = getStylePresetById(body.stylePresetId);- // `negativePrompt` is the schema field; `extraNegative` is compilePrompts'- // option name (avoids shadowing `negativePrompt` on each compiled item).- const compiled = svc.compilePrompts(universe, {- promptMode: body.promptMode,- selection: body.selection,- sheetSelection: body.sheetSelection,- canonSelection: body.canonSelection,- batchPerVariation: body.batchPerVariation,- extraStyle: body.extraStyle,- extraNegative: body.negativePrompt,- stylePresetPrompt: stylePreset?.prompt,- stylePresetNegative: stylePreset?.negativePrompt,- });- if (!compiled.length) {- throw new ServerError('No prompts to render — add canon entries, variations, or composite sheets first', {- status: 400, code: 'WORLD_BUILDER_EMPTY',- });- }-- const settings = await getSettings();- const mode = body.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;-- // Reject `external` mode upfront — batch rendering against a remote SD-API- // would block this request for the entire batch, and we don't want to leave- // an orphaned media collection behind when we discover this mid-loop below.- if (mode !== IMAGE_GEN_MODE.LOCAL && mode !== IMAGE_GEN_MODE.CODEX) {- throw new ServerError(- 'Batch render requires local or codex mode — switch image-gen mode in Settings → Image Gen',- { status: 400, code: 'WORLD_BUILDER_EXTERNAL_UNSUPPORTED' },- );- }-- // Mirror the upfront validation /api/image-gen/generate does so a doomed- // batch fails before any jobs land in the queue.- if (mode === IMAGE_GEN_MODE.CODEX && !settings.imageGen?.codex?.enabled) {- throw new ServerError(- 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },- );- }- if (mode === IMAGE_GEN_MODE.LOCAL) {- const py = settings.imageGen?.local?.pythonPath || null;- const allModels = getImageModels();- if (body.modelId && !allModels.some((m) => m.id === body.modelId)) {- throw new ServerError(`Unknown modelId: ${body.modelId}`, { status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' });- }- const selectedModel = allModels.find((m) => m.id === body.modelId)- ?? allModels.find((m) => m.id === 'dev')- ?? allModels[0];- if (selectedModel && !isFlux2(selectedModel) && !usesDiffusersRunner(selectedModel) && !py) {- throw new ServerError(- 'Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',- { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },- );- }- }-- // Provision the collection up front so renders can be tagged as they- // complete. The completion hook (universeBuilderCollectionHook) will add- // each finished image's filename to this collection. Resolution is- // universeId-first (not name-first) so a re-render finds the existing- // linked bucket even if the universe was hand-renamed or another- // universe happens to share the same display name. Name-only matching- // would either fork the bucket on rename or hijack a foreign universe's- // collection — the atomic helper rules out both.- const collection = await findOrCreateUniverseCollection({- universeId: universe.id,- universeName: universe.name,- description: `Universe Builder renders for "${universe.name}"`,- });-- const runId = randomUUID();- const jobIds = [];- // Map cfgScale → guidance the same way /api/image-gen/generate does. The- // mediaJobQueue calls imageGen/local.generateImage() directly (not the- // dispatcher), so without this mapping the Universe Builder UI's CFG control- // would silently no-op for local renders.- const guidance = body.guidance ?? body.cfgScale;- // Local image gen reads `loraFilenames` (basenames) + `loraScales` (parallel- // array of numbers), not the `[{filename, scale}]` UI shape. Convert here so- // every enqueued job actually applies the user's LoRA selection.- const loraFilenames = Array.isArray(body.loras) && body.loras.length- ? body.loras.map((l) => l.filename)- : undefined;- const loraScales = Array.isArray(body.loras) && body.loras.length- ? body.loras.map((l) => l.scale)- : undefined;- const baseParams = {- width: body.width,- height: body.height,- steps: body.steps,- cfgScale: body.cfgScale,- guidance,- quantize: body.quantize,- seed: body.seed,- loraFilenames,- loraScales,- };-- // Parallel-indexed mapping from jobId → entryRef so the client can show a- // per-entry pending loader (MediaJobThumb-style) on the variation / sheet /- // canon row that owns this render. Only entries with a stable `id` carry an- // entryRef in `compiled` (the sanitizer mints ids on every write now, so- // legacy id-less records are the only gap).- const entryJobs = [];- // Register the run BEFORE enqueueing any jobs — the queue may dispatch and- // emit `completed` synchronously for the first job, and without prior- // registration the completion hook can't coalesce the run's- // emitRecordUpdated calls. `compiled.length` is the authoritative expected- // count (each compiled item produces exactly one job below).- registerUniverseBuilderRun({ runId, universeId: universe.id, jobCount: compiled.length });- for (const item of compiled) {- const params = {- ...baseParams,- prompt: item.prompt,- negativePrompt: item.negativePrompt || undefined,- // Tag every job so the completion hook can route the result back- // into the run's collection without us having to thread additional- // arguments through the queue. `entryRef` (when present — variations- // and composite sheets gain it once the universe has been written- // through the current sanitizer) lets the hook also append the- // rendered filename to the source variation/sheet/canon entry's- // `imageRefs[]` so the Universe Builder can show the latest render- // as an avatar next to each item.- universeRun: {- runId,- universeId: universe.id,- collectionId: collection.id,- category: item.category,- label: item.label,- ...(item.entryRef ? { entryRef: item.entryRef } : {}),- },- };- let queued;- // The queue dispatches directly to imageGen/{codex,local}.generateImage,- // bypassing imageGen/index.js's dispatcher that resolves cleaners for- // direct callers. Resolve here so the per-mode cleanC2PA + denoise- // settings apply to Universe Builder batch renders the same way they- // do for /api/image-gen/generate and pipeline renders.- const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);- if (mode === IMAGE_GEN_MODE.CODEX) {- const c = settings.imageGen?.codex || {};- queued = enqueueJob({- kind: 'image',- params: { mode: IMAGE_GEN_MODE.CODEX, codexPath: c.codexPath, model: c.model, cleanC2PA, denoise, ...params },- });- } else {- // mode === IMAGE_GEN_MODE.LOCAL (validated upfront).- const py = settings.imageGen?.local?.pythonPath || null;- queued = enqueueJob({- kind: 'image',- params: { pythonPath: py, modelId: body.modelId, cleanC2PA, denoise, ...params },- });- }- jobIds.push(queued.jobId);- if (item.entryRef) entryJobs.push({ jobId: queued.jobId, entryRef: item.entryRef });- }-- const run = await svc.recordRun({- id: runId,- universeId: universe.id,- collectionId: collection.id,- jobIds,- promptCount: compiled.length,- createdAt: new Date().toISOString(),- });-- console.log(`🌍 Universe Builder render — universe=${universe.name} prompts=${compiled.length} mode=${mode} runId=${runId.slice(0, 8)}`);-- res.json({- runId: run.id,- collectionId: collection.id,- collectionName: collection.name,- promptCount: compiled.length,- jobIds,- // Per-entry mapping for client-side pending-state UI. Empty when the- // batch only contains entries without stable ids (legacy fallback).- entryJobs,- mode,- });+ const result = await renderUniverseJobs(req.params.id, body, mapServiceError);+ res.json(result);}));// ---- Canon (Phase A of Universe-as-canon refactor) ----diff --git a/server/services/brain.js b/server/services/brain.jsindex 91f3ef01f6..b1f8c17214 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -781,3 +781,30 @@ export const getBucketById = storage.getBucketById;export const createBucket = storage.createBucket;export const updateBucket = storage.updateBucket;export const deleteBucket = storage.deleteBucket;++/**+ * Create a bucket appended after all existing ones (next-order logic).+ * Folds the next-order computation into the service so the route stays thin.+ */+export async function createBucketAppended({ name, color, icon }) {+ const existing = await storage.getBuckets();+ const nextOrder = existing.reduce((max, b) => Math.max(max, b.order ?? 0), -1) + 1;+ return storage.createBucket({ name, color: color || 'accent', icon: icon || '', order: nextOrder });+}++/**+ * Delete a bucket and unassign (bucketId → null) all links that belonged to it.+ * Links survive; they fall back to the ungrouped list rather than being orphaned.+ */+export async function deleteBucketAndUnlinkChildren(id) {+ const links = await storage.getLinks();+ let unassigned = 0;+ for (const link of links) {+ if (link.bucketId === id) {+ await storage.updateLink(link.id, { bucketId: null });+ unassigned++;+ }+ }+ await storage.deleteBucket(id);+ return { deleted: true, unassigned };+}diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex 30ae5bd7a1..41d7fd1305 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -1068,4 +1068,52 @@ describe('brain service', () => {expect(getSummary).toBe(storage.getSummary);});});++ // ===========================================================================+ // Bucket orchestration (next-order append + delete-with-unlink)+ // ===========================================================================++ describe('createBucketAppended', () => {+ it('appends after the highest existing order and applies defaults', async () => {+ const { createBucketAppended } = await import('./brain.js');+ storage.getBuckets.mockResolvedValue([{ id: 'b1', order: 0 }, { id: 'b2', order: 4 }]);+ storage.createBucket.mockImplementation(async (data) => ({ id: 'b3', ...data }));++ const bucket = await createBucketAppended({ name: 'Disney' });++ expect(storage.createBucket).toHaveBeenCalledWith({ name: 'Disney', color: 'accent', icon: '', order: 5 });+ expect(bucket.id).toBe('b3');+ });++ it('starts at order 0 when no buckets exist', async () => {+ const { createBucketAppended } = await import('./brain.js');+ storage.getBuckets.mockResolvedValue([]);+ storage.createBucket.mockImplementation(async (data) => ({ id: 'b1', ...data }));++ await createBucketAppended({ name: 'First', color: 'success', icon: '⭐' });++ expect(storage.createBucket).toHaveBeenCalledWith({ name: 'First', color: 'success', icon: '⭐', order: 0 });+ });+ });++ describe('deleteBucketAndUnlinkChildren', () => {+ it('unassigns only the bucket\'s links, then deletes the bucket', async () => {+ const { deleteBucketAndUnlinkChildren } = await import('./brain.js');+ storage.getLinks.mockResolvedValue([+ { id: 'l1', bucketId: 'b1' },+ { id: 'l2', bucketId: 'b2' },+ { id: 'l3', bucketId: 'b1' }+ ]);+ storage.updateLink.mockResolvedValue({});+ storage.deleteBucket.mockResolvedValue(true);++ const result = await deleteBucketAndUnlinkChildren('b1');++ expect(result).toEqual({ deleted: true, unassigned: 2 });+ expect(storage.updateLink).toHaveBeenCalledWith('l1', { bucketId: null });+ expect(storage.updateLink).toHaveBeenCalledWith('l3', { bucketId: null });+ expect(storage.updateLink).not.toHaveBeenCalledWith('l2', { bucketId: null });+ expect(storage.deleteBucket).toHaveBeenCalledWith('b1');+ });+ });});diff --git a/server/services/catalogDB.js b/server/services/catalogDB.jsindex 9c46f8663b..05b7dbef22 100644--- a/server/services/catalogDB.js+++ b/server/services/catalogDB.js@@ -11,6 +11,7 @@import { randomUUID } from 'crypto';import { query, withTransaction, pgvectorToArray, arrayToPgvector } from '../lib/db.js';+import { reciprocalRankFusion } from '../lib/rrfRanking.js';import {getActiveCatalogType,ingredientIdPrefix,@@ -815,18 +816,7 @@ export async function hybridSearchIngredients(queryText, queryEmbedding, optionsvecRows = r.rows;}- const rrf = new Map();- ftsRows.forEach((row, rank) => {- const cur = rrf.get(row.id) || { row, ftsRank: null, vectorRank: null, rrfScore: 0 };- cur.row = row; cur.ftsRank = rank + 1; cur.rrfScore += ftsWeight / (RRF_K + rank + 1);- rrf.set(row.id, cur);- });- vecRows.forEach((row, rank) => {- const cur = rrf.get(row.id) || { row, ftsRank: null, vectorRank: null, rrfScore: 0 };- if (!cur.row) cur.row = row;- cur.vectorRank = rank + 1; cur.rrfScore += vectorWeight / (RRF_K + rank + 1);- rrf.set(row.id, cur);- });+ const rrf = reciprocalRankFusion(ftsRows, vecRows, { k: RRF_K, ftsWeight, vectorWeight });return Array.from(rrf.values()).map((d) => ({diff --git a/server/services/universeBuilderRender.js b/server/services/universeBuilderRender.jsnew file mode 100644index 0000000000..5f78d70ee9--- /dev/null+++ b/server/services/universeBuilderRender.js@@ -0,0 +1,220 @@+/**+ * Universe Builder Render Orchestration+ *+ * Extracted from routes/universeBuilder.js POST /:id/render.+ * Owns the full render-job flow: settings validation, image-mode resolution,+ * compilePrompts, LoRA resolution, findOrCreateUniverseCollection,+ * registerUniverseBuilderRun, job enqueue loop, run record.+ *+ * The route handler becomes: validate → renderUniverseJobs → res.json.+ */++import { randomUUID } from 'crypto';+import * as svc from './universeBuilder.js';+import { enqueueJob } from './mediaJobQueue/index.js';+import { getSettings } from './settings.js';+import { findOrCreateUniverseCollection } from './mediaCollections.js';+import { registerUniverseBuilderRun } from './universeBuilderCollectionHook.js';+import { getImageModels, isFlux2 } from '../lib/mediaModels.js';+import { usesDiffusersRunner } from '../lib/runners.js';+import { IMAGE_GEN_MODE } from './imageGen/modes.js';+import { resolveImageCleaners } from './imageGen/index.js';+import { getStylePresetById } from '../lib/writersRoomStylePresets.js';+import { ServerError } from '../lib/errorHandler.js';++/**+ * Orchestrate a full Universe Builder render batch.+ *+ * @param {string} universeId - The universe id.+ * @param {object} body - Validated render request body (renderSchema shape).+ * @param {function} mapServiceError - Error mapper from the route.+ * @returns {Promise<object>} Response payload: { runId, collectionId, collectionName, promptCount, jobIds, entryJobs, mode }+ */+export async function renderUniverseJobs(universeId, body, mapServiceError) {+ const universe = await svc.getUniverse(universeId).catch((err) => { throw mapServiceError(err); });++ // Resolve a style preset (server-side authoritative list) so the embrace+ // tokens are deterministic for this render even if the client sent a stale+ // preset object. Unknown ids are ignored (server is the source of truth).+ const stylePreset = getStylePresetById(body.stylePresetId);+ // `negativePrompt` is the schema field; `extraNegative` is compilePrompts'+ // option name (avoids shadowing `negativePrompt` on each compiled item).+ const compiled = svc.compilePrompts(universe, {+ promptMode: body.promptMode,+ selection: body.selection,+ sheetSelection: body.sheetSelection,+ canonSelection: body.canonSelection,+ batchPerVariation: body.batchPerVariation,+ extraStyle: body.extraStyle,+ extraNegative: body.negativePrompt,+ stylePresetPrompt: stylePreset?.prompt,+ stylePresetNegative: stylePreset?.negativePrompt,+ });+ if (!compiled.length) {+ throw new ServerError('No prompts to render — add canon entries, variations, or composite sheets first', {+ status: 400, code: 'WORLD_BUILDER_EMPTY',+ });+ }++ const settings = await getSettings();+ const mode = body.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;++ // Reject `external` mode upfront — batch rendering against a remote SD-API+ // would block this request for the entire batch, and we don't want to leave+ // an orphaned media collection behind when we discover this mid-loop below.+ if (mode !== IMAGE_GEN_MODE.LOCAL && mode !== IMAGE_GEN_MODE.CODEX) {+ throw new ServerError(+ 'Batch render requires local or codex mode — switch image-gen mode in Settings → Image Gen',+ { status: 400, code: 'WORLD_BUILDER_EXTERNAL_UNSUPPORTED' },+ );+ }++ // Mirror the upfront validation /api/image-gen/generate does so a doomed+ // batch fails before any jobs land in the queue.+ if (mode === IMAGE_GEN_MODE.CODEX && !settings.imageGen?.codex?.enabled) {+ throw new ServerError(+ 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',+ { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },+ );+ }+ if (mode === IMAGE_GEN_MODE.LOCAL) {+ const py = settings.imageGen?.local?.pythonPath || null;+ const allModels = getImageModels();+ if (body.modelId && !allModels.some((m) => m.id === body.modelId)) {+ throw new ServerError(`Unknown modelId: ${body.modelId}`, { status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' });+ }+ const selectedModel = allModels.find((m) => m.id === body.modelId)+ ?? allModels.find((m) => m.id === 'dev')+ ?? allModels[0];+ if (selectedModel && !isFlux2(selectedModel) && !usesDiffusersRunner(selectedModel) && !py) {+ throw new ServerError(+ 'Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',+ { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },+ );+ }+ }++ // Provision the collection up front so renders can be tagged as they+ // complete. The completion hook (universeBuilderCollectionHook) will add+ // each finished image's filename to this collection. Resolution is+ // universeId-first (not name-first) so a re-render finds the existing+ // linked bucket even if the universe was hand-renamed or another+ // universe happens to share the same display name. Name-only matching+ // would either fork the bucket on rename or hijack a foreign universe's+ // collection — the atomic helper rules out both.+ const collection = await findOrCreateUniverseCollection({+ universeId: universe.id,+ universeName: universe.name,+ description: `Universe Builder renders for "${universe.name}"`,+ });++ const runId = randomUUID();+ const jobIds = [];+ // Map cfgScale → guidance the same way /api/image-gen/generate does. The+ // mediaJobQueue calls imageGen/local.generateImage() directly (not the+ // dispatcher), so without this mapping the Universe Builder UI's CFG control+ // would silently no-op for local renders.+ const guidance = body.guidance ?? body.cfgScale;+ // Local image gen reads `loraFilenames` (basenames) + `loraScales` (parallel+ // array of numbers), not the `[{filename, scale}]` UI shape. Convert here so+ // every enqueued job actually applies the user's LoRA selection.+ const loraFilenames = Array.isArray(body.loras) && body.loras.length+ ? body.loras.map((l) => l.filename)+ : undefined;+ const loraScales = Array.isArray(body.loras) && body.loras.length+ ? body.loras.map((l) => l.scale)+ : undefined;+ const baseParams = {+ width: body.width,+ height: body.height,+ steps: body.steps,+ cfgScale: body.cfgScale,+ guidance,+ quantize: body.quantize,+ seed: body.seed,+ loraFilenames,+ loraScales,+ };++ // Parallel-indexed mapping from jobId → entryRef so the client can show a+ // per-entry pending loader (MediaJobThumb-style) on the variation / sheet /+ // canon row that owns this render. Only entries with a stable `id` carry an+ // entryRef in `compiled` (the sanitizer mints ids on every write now, so+ // legacy id-less records are the only gap).+ const entryJobs = [];+ // Register the run BEFORE enqueueing any jobs — the queue may dispatch and+ // emit `completed` synchronously for the first job, and without prior+ // registration the completion hook can't coalesce the run's+ // emitRecordUpdated calls. `compiled.length` is the authoritative expected+ // count (each compiled item produces exactly one job below).+ registerUniverseBuilderRun({ runId, universeId: universe.id, jobCount: compiled.length });+ for (const item of compiled) {+ const params = {+ ...baseParams,+ prompt: item.prompt,+ negativePrompt: item.negativePrompt || undefined,+ // Tag every job so the completion hook can route the result back+ // into the run's collection without us having to thread additional+ // arguments through the queue. `entryRef` (when present — variations+ // and composite sheets gain it once the universe has been written+ // through the current sanitizer) lets the hook also append the+ // rendered filename to the source variation/sheet/canon entry's+ // `imageRefs[]` so the Universe Builder can show the latest render+ // as an avatar next to each item.+ universeRun: {+ runId,+ universeId: universe.id,+ collectionId: collection.id,+ category: item.category,+ label: item.label,+ ...(item.entryRef ? { entryRef: item.entryRef } : {}),+ },+ };+ let queued;+ // The queue dispatches directly to imageGen/{codex,local}.generateImage,+ // bypassing imageGen/index.js's dispatcher that resolves cleaners for+ // direct callers. Resolve here so the per-mode cleanC2PA + denoise+ // settings apply to Universe Builder batch renders the same way they+ // do for /api/image-gen/generate and pipeline renders.+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);+ if (mode === IMAGE_GEN_MODE.CODEX) {+ const c = settings.imageGen?.codex || {};+ queued = enqueueJob({+ kind: 'image',+ params: { mode: IMAGE_GEN_MODE.CODEX, codexPath: c.codexPath, model: c.model, cleanC2PA, denoise, ...params },+ });+ } else {+ // mode === IMAGE_GEN_MODE.LOCAL (validated upfront).+ const py = settings.imageGen?.local?.pythonPath || null;+ queued = enqueueJob({+ kind: 'image',+ params: { pythonPath: py, modelId: body.modelId, cleanC2PA, denoise, ...params },+ });+ }+ jobIds.push(queued.jobId);+ if (item.entryRef) entryJobs.push({ jobId: queued.jobId, entryRef: item.entryRef });+ }++ const run = await svc.recordRun({+ id: runId,+ universeId: universe.id,+ collectionId: collection.id,+ jobIds,+ promptCount: compiled.length,+ createdAt: new Date().toISOString(),+ });++ console.log(`🌍 Universe Builder render — universe=${universe.name} prompts=${compiled.length} mode=${mode} runId=${runId.slice(0, 8)}`);++ return {+ runId: run.id,+ collectionId: collection.id,+ collectionName: collection.name,+ promptCount: compiled.length,+ jobIds,+ // Per-entry mapping for client-side pending-state UI. Empty when the+ // batch only contains entries without stable ids (legacy fallback).+ entryJobs,+ mode,+ };+}diff --git a/server/services/universeBuilderRender.test.js b/server/services/universeBuilderRender.test.jsnew file mode 100644index 0000000000..f87c444b43--- /dev/null+++ b/server/services/universeBuilderRender.test.js@@ -0,0 +1,15 @@+/**+ * Smoke test for universeBuilderRender.js+ *+ * Verifies the module imports correctly and exports the expected function.+ * Full integration tests for the render flow live in universeBuilder.test.js.+ */++import { describe, it, expect } from 'vitest';++describe('universeBuilderRender', () => {+ it('exports renderUniverseJobs as a function', async () => {+ const mod = await import('./universeBuilderRender.js');+ expect(typeof mod.renderUniverseJobs).toBe('function');+ });+});