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: split server/routes/universeBuilder.js into service-aligned sub-routers (#3392)
[._.]/ Adam Eivyef708fb3029d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 21dfec85cf..7f5e0acf68 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -19,6 +19,7 @@- **"Does this process own the agent?" is now one named predicate.** Ownership is split across `activeAgents` and `runnerAgents` by spawn mode, and which map an agent lands in isn't guessable from its `executionMode` — a `runner-tui` agent is driven locally and registers in `activeAgents` even though the runner owns its process and lists it. That implicit protocol was open-coded at two call sites, one of which had it wrong (above). `isAgentOwnedLocally` in `agentState.js` now owns the invariant, and `syncRunnerAgents` + `cleanupOrphanedAgents` both call it.- `handleAgentCompletion` bails when the persisted record is already terminal — the same check its post-restart branch has always had — so any double-completion path is a no-op rather than a clobbering re-finalize.- **The Music Video page is a composition, not a 1,492-line component.** Its seven co-located concerns are now six named hooks in `client/src/hooks/` (`useMusicVideoYoutubeImport`, `useMusicVideoMidiJob`, `useMusicVideoRenderJob`, `useMusicVideoModelSettings`, `useMusicVideoSceneMedia`, `useMusicVideoManualTempo`) plus seven presentational components in `client/src/components/musicVideo/`, leaving `MusicVideo.jsx` at 529 lines of project/scene CRUD and page shell. Behavior is unchanged — same polling flows, settings persistence, and render lifecycle. (#3386)+- **`/api/universe-builder` is a directory of sub-routers, not one 987-line file.** The 36 endpoints split along the service seams they already delegated to — `expand.js`, `vision.js`, `styleReferences.js`, `referenceSheets.js`, `merge.js`, `crud.js`, `render.js`, `canon.js` — behind a thin `routes/universeBuilder/index.js`, with the zod fragments and image resolvers more than one router composes moved to `shared.js`. Mount order is the load-bearing part and is documented at the mount: every sub-router owning a single-segment static path (`/expand`, `/duplicates`, `/merge*`, …) mounts ahead of `crud.js`, whose `GET /:id` would otherwise swallow it. Verified by resolving 520 method+URL combinations against the old and new routers and confirming every one lands on the same handler. (#3392)- `agentLifecycle.js` imported `getAgent` aliased as `getAgentRecord`, shadowing the real transcript-free reader that was split out in #3368 for exactly this purpose. Both call sites read only `.status`/`.metadata`, but the alias made them hydrate the record: reading and line-splitting a completed run's whole `output.txt` (megabytes on a long TUI run) and potentially rewriting `metadata.json` via `repairCodexTaskSummary`. Now imports the real `getAgentRecord`, read once and shared.## Better audit 2026-08-03 (UX, City scene, game/music/writing focus) — PRs #3401–#3404diff --git a/server/index.js b/server/index.jsindex 06117cac94..3d4a317df5 100644--- a/server/index.js+++ b/server/index.js@@ -120,7 +120,7 @@ import threejsModelsRoutes from './routes/threejsModels.js';import imageTo3dRoutes from './routes/imageTo3d.js';import privacyRoutes from './routes/privacy.js';import writersRoomRoutes from './routes/writersRoom.js';-import universeBuilderRoutes from './routes/universeBuilder.js';+import universeBuilderRoutes from './routes/universeBuilder/index.js';import authorsRoutes from './routes/authors.js';import artistsRoutes from './routes/artists.js';import albumsRoutes from './routes/albums.js';diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 4c2aec47ae..6388f1dc24 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -56,7 +56,7 @@ const router = Router();// #3231 Phase 4 — the per-record image render pin (`imageMode`/`imageModelId`,// the shared universe/series/sprite field pair) on Music Video projects: scene// reference-frame renders resolve through it (imageGen/prepareParams.js).-// Extended at the route layer — the same pattern as routes/universeBuilder.js —+// Extended at the route layer — the same pattern as routes/universeBuilder/ —// because musicVideoValidation.js can't import recordRenderPinFields from// validation.js without a circular import (validation.js re-exports it).const projectCreateSchema = musicVideoProjectCreateSchema.extend(recordRenderPinFields);diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsdeleted file mode 100644index 465bde4c20..0000000000--- a/server/routes/universeBuilder.js+++ /dev/null@@ -1,987 +0,0 @@-/**- * Universe Builder Routes — /api/universe-builder- *- * Universe CRUD plus the AI-assisted workflows that operate on a universe:- * expand/refine, image-based description + canon correction, reference-sheet- * and canon-entry rendering, run history, style references, and canon- * entry management. Each endpoint carries its own doc comment below — this- * header intentionally doesn't enumerate them (it drifted stale when it did).- */--import { Router } from 'express';-import { z } from 'zod';-import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';-import { validateRequest, optionalBooleanMap, llmSchema, isPaginationRequested, paginateArray, recordRenderPinFields, cloudModelIdString } from '../lib/validation.js';-import { RECORD_RENDER_MODEL_MAX } from '../lib/renderTargets.js';-import * as svc from '../services/universeBuilder.js';-import * as canonSvc from '../services/universeCanon.js';-import { expandUniverseCharacter } from '../services/universeCharacterExpand.js';-import {- renderCharacterReferenceSheet,- deleteCharacterReferenceSheet,- listSheetVariants,-} from '../services/universeCharacterSheet.js';-import { BIBLE_KINDS, BIBLE_LIMITS, pruneStaleReferenceSheets } from '../lib/storyBible.js';-import { getUniverseCanonUsage, listLinkedSeriesNames } from '../services/canonUsage.js';-import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';-import { describeEntityFromImages, correctEntityFromImage, VISION_KINDS, VISION_MAX_IMAGES } from '../services/universeVisionDescribe.js';-import { expandEntityFromImages, VISION_EXPAND_MAX_IMAGES } from '../services/universeVisionExpand.js';-import { analyzeUniverseStyleReference } from '../services/universeStyleReference.js';-import { sanitizeFilename, PATHS, resolveGalleryImage } from '../lib/fileUtils.js';-import { existsSync } from 'fs';-import { join } from 'path';-import { refineWorldPrompts } from '../services/universeBuilderRefine.js';-import { promoteVariationToCanon, VALID_TARGET_KINDS } from '../services/universeBuilderPromote.js';-import { autoSortOtherBuckets } from '../services/universeBuilderAutoSort.js';-import { findDuplicateUniverseGroups, findSameNameUniverses } from '../services/duplicateDetection.js';-import { mergeUniverses, buildCascadeContext } from '../services/recordMerge.js';-import { mergeFieldsWithAI } from '../services/recordMergeAI.js';-import { IMAGE_GEN_MODES } from '../services/imageGen/modes.js';-import { renderUniverseJobs } from '../services/universeBuilderRender.js';--const router = Router();--const SERVICE_ERROR_STATUS = {- [svc.ERR_NOT_FOUND]: 404,- [svc.ERR_VALIDATION]: 400,- // Block-until-empty: deleting a universe with live series → 409 (the- // lock-conflict idiom) so the client can show "move these N series first".- [svc.ERR_HAS_LIVE_SERIES]: 409,- // recordMerge validation (unresolved conflicts, bad ids).- MERGE_VALIDATION: 400,- // recordMerge cascade partially completed (a child re-point failed) → 409 so- // the client can surface "merge incomplete, re-run to finish".- MERGE_CASCADE_INCOMPLETE: 409,-};--// Propagate diagnostic context onto the response body via `context`: the-// blocking-series list for a delete-guard 409, or the survivor/loser ids +-// which children failed to re-point for an incomplete merge cascade.-const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS, (err) =>- err?.blockingSeries ? { blockingSeries: err.blockingSeries } : buildCascadeContext(err),-);--// ---- shared zod fragments -----// `id` is optional on input — the service-layer sanitizer mints one with a-// `var-`/`sheet-` prefix when absent. Existing non-empty ids are normalized-// on read/write (trimmed + capped to 80 chars) so renames + bucket-moves-// preserve the link to imageRefs[]; callers should treat the normalized-// form as the canonical id rather than the raw value they supplied.-const entryIdField = z.string().trim().min(1).max(80).optional();-const entryImageRefField = z.string().trim().min(1).max(svc.IMAGE_REF_FILENAME_MAX);-const entryImageRefsField = z.array(entryImageRefField).max(svc.IMAGE_REFS_PER_ENTRY_MAX).optional();-const variationSchema = z.object({- id: entryIdField,- label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),- prompt: z.string().trim().min(1).max(svc.PROMPT_FRAGMENT_MAX),- // Per-item lock — when true, expand preserves this variation across- // re-runs instead of letting the LLM regenerate it.- locked: z.boolean().optional(),- // Render history (newest last). Server stamps this via the collection hook- // when a render completes; clients echo it back on PATCH-the-whole-list flows- // so the sanitizer can preserve it across rename/bucket-move.- imageRefs: entryImageRefsField,-});-const compositeSheetSchema = z.object({- id: entryIdField,- kind: z.enum(svc.COMPOSITE_SHEET_KINDS).optional(),- label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),- prompt: z.string().trim().min(1).max(svc.COMPOSITE_PROMPT_MAX),- // Per-item lock for composite boards (same semantics as variations).- locked: z.boolean().optional(),- imageRefs: entryImageRefsField,-});-const categoryShape = z.object({- // Tags this bucket to one of the 3 canon trunks (or 'other' as the- // un-classified sink). Optional on input — sanitizeCategories resolves a- // sensible default from the built-in map (landscapes→places etc.) or- // falls to 'other'. Added in schema v4.- kind: z.enum(svc.CATEGORY_KINDS).optional(),- variations: z.array(variationSchema).max(svc.VARIATIONS_PER_CATEGORY_MAX),-});-const categoriesSchema = z.record(- z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),- categoryShape,-).refine((categories) => Object.keys(categories).length <= svc.WORLD_CATEGORY_COUNT_MAX, {- message: `categories cannot exceed ${svc.WORLD_CATEGORY_COUNT_MAX} buckets`,-});--// `locked` is a sparse map of `{ field: true }` for the LOCKABLE_FIELDS list.-// `false` is treated the same as omitted — only `true` records a lock so the-// stored shape stays minimal and additive. Accept legacy `influences` key as-// an alias for both `influencesEmbrace` and `influencesAvoid` so older clients-// PATCHing a previously saved lock map still pass validation (sanitizeLocked-// rewrites it on read into the per-list keys).-const lockedSchema = z.object({- ...optionalBooleanMap(svc.LOCKABLE_FIELDS),- influences: z.boolean().optional(),-}).strict();--const influenceEntrySchema = z.string().trim().min(1).max(svc.INFLUENCE_ENTRY_MAX);-const influencesSchema = z.object({- embrace: z.array(influenceEntrySchema).max(svc.INFLUENCES_PER_LIST_MAX).optional().default([]),- avoid: z.array(influenceEntrySchema).max(svc.INFLUENCES_PER_LIST_MAX).optional().default([]),-}).strict();-const styleReferenceSchema = z.object({- id: entryIdField,- title: z.string().trim().min(1).max(svc.STYLE_REFERENCE_TITLE_MAX),- prompt: z.string().trim().min(1).max(svc.STYLE_REFERENCE_PROMPT_MAX),- imageRefs: z.array(entryImageRefField).min(1).max(1),- createdAt: z.string().trim().min(1).max(64).optional(),-}).strict();-const styleReferencesField = z.array(styleReferenceSchema).max(svc.STYLE_REFERENCES_MAX).optional();--// Legacy prose prompts: the v2 universe template carried `stylePrompt` /-// `negativePrompt` as comma-separated prose strings; v3 collapses them into-// the chip-based `influences` lists. Accepting them here (as optional) lets-// a stale client (or an importer of a v2 share-bucket payload) hand us the-// legacy shape — the service-layer sanitizer splits + merges the tokens into-// influences. New callers should send `influences` directly.-const legacyStylePromptField = z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional();-const legacyNegativePromptField = z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional();--// Canon arrays go through `sanitizeBibleList` in the service layer where-// each entry is validated structurally — accept them loosely here so-// patch-the-whole-list flows (e.g. inline canon edits, render-ref hooks)-// don't fail Zod for legitimately rich shapes. Cap at the bible-wide entry-// limit so a malicious payload can't blow up memory.-// Hard cap mirrors BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX (200) with headroom-// — sanitizer truncates anyway, so this just protects the JSON-parse layer.-const canonArrayField = z.array(z.record(z.unknown())).max(500).optional();--const createSchema = z.object({- name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH),- starterPrompt: z.string().trim().max(svc.STARTER_PROMPT_MAX).optional().default(''),- stylePrompt: legacyStylePromptField,- negativePrompt: legacyNegativePromptField,- logline: z.string().trim().max(svc.LOGLINE_MAX).optional().default(''),- premise: z.string().trim().max(svc.PREMISE_MAX).optional().default(''),- styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),- categories: categoriesSchema.optional(),- compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),- influences: influencesSchema.optional(),- styleReferences: styleReferencesField,- // Base "style probe" render filenames — sanitized + capped server-side.- // Match the sanitizer cap so over-the-cap requests get a loud 400 instead- // of a silent 200 with N entries dropped (sanitizer keeps the most recent- // IMAGE_REFS_PER_ENTRY_MAX). Per-element filename cap is shared too.- styleImageRefs: entryImageRefsField,- locked: lockedSchema.optional(),- llm: llmSchema,- // Canon registries on POST (Phase B.4): writers-room promote, share-bucket- // import, and tests can seed a universe with canon at create time instead- // of needing a second PATCH round-trip.- characters: canonArrayField,- places: canonArrayField,- objects: canonArrayField,- // Per-record render pin (#3231 Phase 3) — this universe's default image- // backend + cloud model.- ...recordRenderPinFields,- // Local-only "don't sync to peers" marker — see sanitizeRecordForWire.- ephemeral: z.boolean().optional(),-});-// `origin` is a share-bucket provenance block written by the importer + cleared-// to null by the user; structurally an object or null.-const originField = z.record(z.unknown()).nullable().optional();--const patchSchema = z.object({- name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH).optional(),- starterPrompt: z.string().trim().max(svc.STARTER_PROMPT_MAX).optional(),- // Legacy prose prompts — see legacy*Field comment above. Tolerated on PATCH- // so a stale client tab can still save while the new chip-based UI lands.- stylePrompt: legacyStylePromptField,- negativePrompt: legacyNegativePromptField,- logline: z.string().trim().max(svc.LOGLINE_MAX).optional(),- premise: z.string().trim().max(svc.PREMISE_MAX).optional(),- styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional(),- categories: categoriesSchema.optional(),- compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),- influences: influencesSchema.optional(),- styleReferences: styleReferencesField,- // Base "style probe" render filenames — sanitized + capped server-side.- // Match the sanitizer cap so over-the-cap requests get a loud 400 instead- // of a silent 200 with N entries dropped (sanitizer keeps the most recent- // IMAGE_REFS_PER_ENTRY_MAX). Per-element filename cap is shared too.- styleImageRefs: entryImageRefsField,- locked: lockedSchema.optional(),- llm: llmSchema,- // Canon writes — these flow through sanitizeBibleList server-side so- // schema parity here is just "accept arrays of records." Without these- // entries Zod's default strip behavior silently drops them from the- // patch (PATCHABLE_SCALARS in services/universeBuilder.js reads them- // from the post-Zod body, so they'd never reach the writer).- characters: canonArrayField,- places: canonArrayField,- objects: canonArrayField,- origin: originField,- // Per-record render pin (#3231 Phase 3). Key-present with 'auto'/''/null- // clears; key-absent preserves.- ...recordRenderPinFields,- ephemeral: z.boolean().optional(),-}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });--const expandSchema = z.object({- starterPrompt: z.string().trim().min(1).max(svc.STARTER_PROMPT_MAX),- // Optional structured influences from a prior refinement — passed in so- // the LLM keeps re-expansions on-direction instead of regenerating from- // the bare starter idea.- influences: influencesSchema.optional(),- // Per-item locks the user has set on individual variations / composite- // boards. Listed in the LLM prompt so it doesn't waste tokens regenerating- // them; the client merges them back in after the result returns.- preservedVariations: z.record(- z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),- z.array(variationSchema).max(svc.VARIATIONS_PER_CATEGORY_MAX),- ).optional(),- preservedCompositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),- // Current bible/prompt state — locked entries are echoed verbatim, others- // are starting points the LLM can refine while staying consistent.- logline: z.string().trim().max(svc.LOGLINE_MAX).optional(),- premise: z.string().trim().max(svc.PREMISE_MAX).optional(),- styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional(),- locked: lockedSchema.optional(),- providerId: z.string().trim().max(80).optional(),- model: z.string().trim().max(200).optional(),-});--// `targetKind` is only required when the source bucket's `kind` is 'other'-// (otherwise the service resolves it from the bucket). Enum derived from-// VALID_TARGET_KINDS so the schema and the resolver share one source.-const promoteVariationSchema = z.object({- category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),- label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),- targetKind: z.enum(VALID_TARGET_KINDS).optional(),- providerId: z.string().trim().max(80).optional(),- model: z.string().trim().max(200).optional(),-});--// Auto-sort takes no bucket selection — the service scans for every-// `kind: 'other'` bucket on the universe. Provider/model are optional;-// the service falls back to the active provider when omitted.-const autoSortSchema = z.object({- providerId: z.string().trim().max(80).optional(),- model: z.string().trim().max(200).optional(),-});--const generateVariationsSchema = z.object({- category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),- count: z.number().int().min(1).max(svc.VARIATIONS_PER_CATEGORY_MAX),- existingLabels: z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX))- .max(svc.VARIATIONS_PER_CATEGORY_MAX).optional().default([]),- influences: influencesSchema.optional(),- logline: z.string().trim().max(svc.LOGLINE_MAX).optional().default(''),- premise: z.string().trim().max(svc.PREMISE_MAX).optional().default(''),- styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),- providerId: z.string().trim().max(80).optional(),- model: z.string().trim().max(200).optional(),-});--const refinePromptsSchema = z.object({- starterPrompt: z.string().trim().min(1).max(svc.STARTER_PROMPT_MAX),- // Bible context: passed in so the refiner sees the full seed, refines them- // alongside the prompts, and stays consistent with the universe's narrative.- logline: z.string().trim().max(svc.LOGLINE_MAX).optional().default(''),- premise: z.string().trim().max(svc.PREMISE_MAX).optional().default(''),- styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),- // Structured influences (embrace + avoid) — refined alongside the prompts- // and used as the canonical reference list for renderer-token composition.- influences: influencesSchema.optional(),- // Post-Expand structure — when present, the refiner sees the full universe- // (categories + composites with per-item locks) and may edit/replace/add- // items per the user's feedback. When omitted (pre-Expand iteration), the- // refiner falls back to the bible-only behavior.- categories: categoriesSchema.optional(),- compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),- // Per-field lock map — locked fields are echoed back unchanged regardless- // of what the LLM tries to write.- locked: lockedSchema.optional().default({}),- feedback: z.string().trim().min(1).max(3000),- // Optional gallery image used as a VISUAL style reference — when present the- // refiner forces a vision-capable API provider and folds the image's- // palette/lighting/mood into influences + styleNotes. Resolved to an absolute- // path in the handler before reaching the service.- image: z.string().trim().min(1).max(300).optional(),- providerId: z.string().trim().max(80).optional(),- // Whitespace-only model → undefined so the refiner's defaultModel /- // models[0] fallback kicks in instead of a blank string reaching the- // provider. Mirrors how /api/media-jobs/refine-prompt handles it.- model: z.string().max(200).optional().transform((s) => {- const v = (s ?? '').trim();- return v.length > 0 ? v : undefined;- }),-});--// `selection` per category: 'all' or array of variation labels.-const selectionValueSchema = z.union([z.literal('all'), z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX)).max(svc.VARIATIONS_PER_CATEGORY_MAX)]);-const selectionSchema = z.record(- z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),- selectionValueSchema,-).refine((selection) => Object.keys(selection).length <= svc.WORLD_CATEGORY_COUNT_MAX, {- message: `selection cannot exceed ${svc.WORLD_CATEGORY_COUNT_MAX} buckets`,-});--// `canonSelection` per trunk: 'all' or array of canon-entry names (case-insensitive).-// Settings entries also match on `slugline` so a render queued from the Places-// tab can target an entry the user filed by slugline ("INT. FOUNDRY — DAY").-// Per-trunk cap mirrors the bible sanitizer (`ENTRIES_PER_BIBLE_MAX`) so this-// can't enqueue more entries than the server actually persists; per-string cap-// uses the looser of `NAME_MAX` / `SLUGLINE_MAX` so a places entry filed by-// slugline isn't rejected if those limits ever diverge (both 200 today).-const CANON_TRUNK_KEYS = ['characters', 'places', 'objects'];-const CANON_NEEDLE_MAX = Math.max(BIBLE_LIMITS.NAME_MAX, BIBLE_LIMITS.SLUGLINE_MAX);-const canonSelectionValueSchema = z.union([- z.literal('all'),- z.array(z.string().trim().min(1).max(CANON_NEEDLE_MAX)).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX),-]);-const canonSelectionSchema = z.object(- Object.fromEntries(CANON_TRUNK_KEYS.map((k) => [k, canonSelectionValueSchema.optional()])),-).strict();--const renderSchema = z.object({- // Removed: callers that still send `collectionName` get an explicit 400- // (see the .refine() below) instead of a confusing silent no-op. The- // canonical "Universe: <name>" identity is owned by the universe and- // enforced by the rename-lock — per-render overrides have no semantic- // home in that model.- collectionName: z.unknown().optional(),- // Image-gen knobs — these mirror /api/image-gen/generate so the user can- // pick mode/size/steps without bouncing to the Image page first.- mode: z.enum(IMAGE_GEN_MODES).optional(),- modelId: z.string().trim().max(64).optional(),- // Per-batch cloud model override (#3231 Phase 3) — wins over the universe's- // persisted imageModelId pin and the renderDefaults imageModel pin. Shares- // the model-id charset guard so a bad id can't reach a CLI argv.- cloudModel: cloudModelIdString('cloudModel must be a valid model id').max(RECORD_RENDER_MODEL_MAX).optional(),- width: z.number().int().min(64).max(2048).optional(),- height: z.number().int().min(64).max(2048).optional(),- steps: z.number().int().min(1).max(150).optional(),- cfgScale: z.number().min(0).max(30).optional(),- guidance: z.number().min(0).max(30).optional(),- quantize: z.enum(['3', '4', '5', '6', '8']).optional(),- // Per-variation render count and per-category subset.- promptMode: z.enum(['variations', 'sheets', 'canon', 'all']).optional().default('variations'),- batchPerVariation: z.number().int().min(1).max(20).optional().default(1),- selection: selectionSchema.optional(),- sheetSelection: z.union([z.literal('all'), z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX)).max(svc.COMPOSITE_SHEETS_MAX)]).optional(),- canonSelection: canonSelectionSchema.optional(),- // Per-batch overrides surfaced through the full Image-Gen form. All optional;- // empty values are treated as "use the universe's existing influences."- // `seed` matches /api/image-gen/generate's contract (non-negative integer) —- // local image gen coerces via Number(seed) and would yield NaN for arbitrary- // strings, so reject early at the boundary.- seed: z.number().int().min(0).optional(),- negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),- extraStyle: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),- stylePresetId: z.string().trim().max(80).optional(),- // Matches /api/image-gen/generate's LoRA contract: basenames only (server- // resolves against PATHS.loras), max 8 stacked LoRAs per render. Keeping- // the two routes in sync so a payload that's accepted here can also flow- // through /api/image-gen/generate if we ever proxy it.- loras: z.array(z.object({- filename: z.string().trim().min(1).max(256).regex(/^[^/\\]+$/, 'lora filename must not contain path separators'),- scale: z.number().min(0).max(2),- name: z.string().trim().max(256).optional(),- })).max(8).optional(),-}).refine((body) => body.collectionName === undefined, {- message: 'collectionName is no longer supported — the linked collection follows the universe name automatically. Remove this field.',- path: ['collectionName'],-});--// Backward-compatible by default: returns the full universes array. When a client-// passes `limit`/`offset`, the response becomes the bounded-// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.-router.get('/', asyncHandler(async (req, res) => {- const universes = await svc.listUniverses();- if (!isPaginationRequested(req.query)) {- return res.json(universes);- }- res.json(paginateArray(universes, req.query, { defaultLimit: 50, maxLimit: 500 }));-}));--router.post('/', asyncHandler(async (req, res) => {- const body = validateRequest(createSchema, req.body ?? {});- const created = await svc.createUniverse(body);- // Non-blocking same-name warning (computed at the route layer so the importer,- // which calls the service directly, never pays for the scan). The UI surfaces- // it but may proceed — duplicates are resolved later via Sharing → Duplicates.- const duplicateName = await findSameNameUniverses(created.name, { excludeId: created.id });- res.status(201).json(duplicateName.length ? { ...created, _warnings: { duplicateName } } : created);-}));--// `expand` is a sub-resource — keep it ahead of `/:id` so the wildcard-// doesn't catch "expand" as a universe id.-router.post('/expand', asyncHandler(async (req, res) => {- const body = validateRequest(expandSchema, req.body ?? {});- const result = await expandWorldTemplate(body);- res.json(result);-}));--router.post('/generate-variations', asyncHandler(async (req, res) => {- const body = validateRequest(generateVariationsSchema, req.body ?? {});- const result = await generateCategoryVariations(body);- res.json(result);-}));--// A reference image the vision routes accept from one of two sources:-// - 'upload' → a filename the client already POSTed to /api/screenshots-// (lives under data/screenshots; passed to the runner as a bare-// filename, which it resolves under that dir).-// - 'gallery' → a generated-gallery filename under data/images; resolved here-// to an ABSOLUTE path, which the runner's loadImageAsBase64-// accepts as-is (it only prefixes data/screenshots for bare-// names).-const imageSourceSchema = z.object({- source: z.enum(['upload', 'gallery']),- filename: z.string().trim().min(1).max(300),-});--// Resolve a mixed `[{ source, filename }]` list into runner-loadable paths,-// failing loudly per the source's rules. The runner silently DROPS a missing-// image and still sends the text prompt, so a stale/never-uploaded reference-// would let the model describe with fewer references — or hallucinate from the-// prompt alone if all are missing. Reject up front instead.-function resolveImageSources(images) {- return images.map(({ source, filename }) => {- if (source === 'gallery') {- const abs = resolveGalleryImage(filename);- if (!abs) {- throw new ServerError(`Gallery image not found: ${filename} — pick another and retry.`, { status: 400, code: 'GALLERY_IMAGE_NOT_FOUND' });- }- return abs;- }- // 'upload' — the upload route already sanitizes on write, so a legitimately- // uploaded name round-trips unchanged. A hand-crafted name with path- // components is rejected outright (a 400, not a silent rewrite to a name- // that won't exist), keeping a traversal attempt distinguishable from a- // deleted/never-uploaded file.- const safe = sanitizeFilename(filename);- if (safe !== filename) {- throw new ServerError(`Invalid screenshot filename: ${filename}`, { status: 400, code: 'VALIDATION_ERROR' });- }- if (!existsSync(join(PATHS.screenshots, safe))) {- throw new ServerError(`Screenshot not found: ${safe} — re-upload the image and retry.`, { status: 400, code: 'SCREENSHOT_NOT_FOUND' });- }- return safe;- });-}--// Resolve a SINGLE gallery filename to an absolute path, rejecting a-// traversal attempt or an unknown file up front. Shared by the two-// single-gallery-image vision routes (`analyze-style-reference`,-// `correct-from-image`) that resolve one reference image rather than the-// mixed upload/gallery list `resolveImageSources` handles.-function resolveGalleryImageOrThrow(filename) {- const imageFilename = sanitizeFilename(filename);- if (imageFilename !== filename) {- throw new ServerError(`Invalid gallery image filename: ${filename}`, {- status: 400,- code: 'VALIDATION_ERROR',- });- }- const imagePath = resolveGalleryImage(imageFilename);- if (!imagePath) {- throw new ServerError(`Gallery image not found: ${imageFilename} — upload it again and retry.`, {- status: 400,- code: 'GALLERY_IMAGE_NOT_FOUND',- });- }- return { imageFilename, imagePath };-}--// Vision-to-prose: turn one or more reference images of a character/place/-// object into an image-gen-ready prose description (multiple images → the-// shared/common description). Stateless — the client decides which entry-// field to write the result into. Images come from upload OR the gallery (see-// resolveImageSources). Keep ahead of `/:id` so "describe-from-images" isn't-// parsed as a universe id.-const describeFromImagesSchema = z.object({- kind: z.enum(VISION_KINDS),- name: z.string().trim().max(BIBLE_LIMITS.NAME_MAX).optional(),- context: z.string().trim().max(2000).optional(),- images: z.array(imageSourceSchema).min(1).max(VISION_MAX_IMAGES),- providerId: z.string().trim().max(80).optional(),- model: z.string().trim().max(200).optional(),-});-router.post('/describe-from-images', asyncHandler(async (req, res) => {- const body = validateRequest(describeFromImagesSchema, req.body ?? {});- const screenshots = resolveImageSources(body.images);- const result = await describeEntityFromImages({ ...body, screenshots });- res.json(result);-}));--const analyzeStyleReferenceSchema = z.object({- image: z.string().trim().min(1).max(300),- title: z.string().trim().max(svc.STYLE_REFERENCE_TITLE_MAX).optional(),- prompt: z.string().trim().max(svc.STYLE_REFERENCE_PROMPT_MAX).optional(),- styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),- influences: influencesSchema.optional().default({ embrace: [], avoid: [] }),- locked: lockedSchema.optional().default({}),- providerId: z.string().trim().max(80).optional(),- model: z.string().trim().max(200).optional(),-});--// Stateless review step: analyze the image and return a proposed record plus a-// diff. Persistence only happens after the user chooses reference-only or-// reference-and-adopt in the client.-router.post('/analyze-style-reference', asyncHandler(async (req, res) => {- const body = validateRequest(analyzeStyleReferenceSchema, req.body ?? {});- const { imageFilename, imagePath } = resolveGalleryImageOrThrow(body.image);- res.json(await analyzeUniverseStyleReference({- ...body,- imagePath,- imageFilename,- }));-}));--// Refines the 3 top-level prompts (starter / style / negative) based on-// user feedback. Stateless — the caller decides whether to write the-// result back to a saved universe. Keep ahead of `/:id`.-router.post('/refine-prompts', asyncHandler(async (req, res) => {- const body = validateRequest(refinePromptsSchema, req.body ?? {});- // Resolve the optional style-reference image to an absolute gallery path- // before the service runs — fail loudly on a stale/bogus filename rather than- // letting the runner silently drop it and refine text-only.- let imagePath = null;- if (body.image) {- imagePath = resolveGalleryImage(body.image);- if (!imagePath) {- throw new ServerError(`Gallery image not found: ${body.image} — pick another and retry.`, { status: 400, code: 'GALLERY_IMAGE_NOT_FOUND' });- }- }- res.json(await refineWorldPrompts({ ...body, imagePath }));-}));--// Static-path GETs must register BEFORE `/:id` so they aren't swallowed by-// the parametric route. The catalog lists every registered reference-sheet-// variant — the client renders one row per entry in CharacterReferenceSheetPanel.-router.get('/reference-sheet-variants', asyncHandler(async (_req, res) => {- res.json({ variants: listSheetVariants() });-}));--// ---- Duplicate resolution (static paths — keep BEFORE `/:id`) ------const mergeSchema = z.object({- survivorId: z.string().trim().min(1).max(128),- loserId: z.string().trim().min(1).max(128),- fieldChoices: z.record(z.enum(['survivor', 'loser'])).optional().default({}),- // Free-form per-field values that win over the survivor/loser binary —- // populated by the AI-merge flow (a third unified option) and optionally- // tweaked by the user before submit.- fieldOverrides: z.record(z.string()).optional().default({}),-}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });--const mergeAIResolveSchema = z.object({- survivorId: z.string().trim().min(1).max(128),- loserId: z.string().trim().min(1).max(128),- fields: z.array(z.string().trim().min(1).max(64)).min(1).max(20),- providerId: z.string().trim().max(80).optional(),- model: z.string().trim().max(200).optional(),-}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });--router.get('/duplicates', asyncHandler(async (_req, res) => {- res.json({ groups: await findDuplicateUniverseGroups() });-}));--// Style tokens only (see svc.listUniverseStyles). Must stay ahead of `/:id` so-// the wildcard doesn't catch "styles" as a universe id.-router.get('/styles', asyncHandler(async (_req, res) => {- res.json(await svc.listUniverseStyles());-}));--router.post('/merge/preview', asyncHandler(async (req, res) => {- const body = validateRequest(mergeSchema, req.body ?? {});- const preview = await mergeUniverses(body.survivorId, body.loserId, body.fieldChoices, { dryRun: true, fieldOverrides: body.fieldOverrides })- .catch((err) => { throw mapServiceError(err); });- res.json(preview);-}));--router.post('/merge', asyncHandler(async (req, res) => {- const body = validateRequest(mergeSchema, req.body ?? {});- const result = await mergeUniverses(body.survivorId, body.loserId, body.fieldChoices, { fieldOverrides: body.fieldOverrides })- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Ask the configured AI provider to merge specific conflicting text fields-// into a single unified value per field. Returns `{ merged, skipped, llm, runId }`-// — the client applies `merged` as `fieldOverrides` on the subsequent-// /merge or /merge/preview call. No record state is mutated here.-router.post('/merge/ai-resolve', asyncHandler(async (req, res) => {- const body = validateRequest(mergeAIResolveSchema, req.body ?? {});- const [survivor, loser] = await Promise.all([- svc.getUniverse(body.survivorId).catch((err) => { throw mapServiceError(err); }),- svc.getUniverse(body.loserId).catch((err) => { throw mapServiceError(err); }),- ]);- const result = await mergeFieldsWithAI({- kind: 'universe',- survivor,- loser,- fields: body.fields,- providerId: body.providerId,- model: body.model,- });- res.json(result);-}));--router.get('/:id', asyncHandler(async (req, res) => {- // Read-by-id 404s are benign and high-volume: callers like LoraDatasetDetail- // speculatively fetch a dataset's `character.universeId` ({ silent: true }),- // which 404s whenever that universe was deleted. Classify as `warning` so the- // error middleware skips it instead of spamming ❌ Route error on every- // page reconnect. (Mirrors the media-job archive-lookup precedent.)- const w = await svc.getUniverse(req.params.id).catch((err) => {- const mapped = mapServiceError(err);- if (mapped?.code === svc.ERR_NOT_FOUND) mapped.severity = 'warning';- throw mapped;- });- // Lazy stale-reference-sheet collapse: nulls out any character.referenceSheetImageRef- // whose underlying file was deleted from disk, so the UI never tries to- // render `<img src="/data/image-refs/<gone>">`. Doesn't persist the change- // — next render or PATCH will overwrite cleanly. Sub-millisecond for the- // typical 5-50 character universe.- const pruned = Array.isArray(w?.characters)- ? { ...w, characters: pruneStaleReferenceSheets(w.characters) }- : w;- res.json(pruned);-}));--router.patch('/:id', asyncHandler(async (req, res) => {- const body = validateRequest(patchSchema, req.body ?? {});- const w = await svc.updateUniverse(req.params.id, body).catch((err) => { throw mapServiceError(err); });- // Re-check the same-name warning when the rename actually changed the name.- if ('name' in body) {- const duplicateName = await findSameNameUniverses(w.name, { excludeId: req.params.id });- if (duplicateName.length) { res.json({ ...w, _warnings: { duplicateName } }); return; }- }- res.json(w);-}));--router.delete('/:id', asyncHandler(async (req, res) => {- const r = await svc.deleteUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });- res.json(r);-}));--router.get('/:id/runs', asyncHandler(async (req, res) => {- res.json(await svc.listRuns(req.params.id));-}));--router.post('/:id/render', asyncHandler(async (req, res) => {- const body = validateRequest(renderSchema, req.body ?? {});- // Legacy universes carry no variation/sheet ids on disk. sanitizeTemplate- // mints fresh UUIDs on every read but readState() intentionally does not- // persist them (race against concurrent writers). The render route needs- // ids that are stable across the read→queue→completion lifecycle so the- // collection hook can find the source entry by `entryRef.id`. Gate the- // one-time no-op write on the raw-disk inspection: fully-migrated- // universes skip the write so `updatedAt` doesn't bump on every render- // (which would interfere with LWW sync + trigger spurious re-export).- // Skip entirely for canon-only renders — canon entries already carry- // stable ids (storyBible.js sanitizer), so the raw-disk read + write- // would be pure overhead.- if (body.promptMode !== 'canon' && await svc.needsEntryIdPersist(req.params.id)) {- await svc.updateUniverse(req.params.id, () => ({})).catch((err) => { throw mapServiceError(err); });- }- const result = await renderUniverseJobs(req.params.id, body, mapServiceError);- res.json(result);-}));--// ---- Canon (Phase A of Universe-as-canon refactor) ------const extractCanonSchema = z.object({- corpus: z.string().trim().min(1).max(200_000),- kinds: z.array(z.string().trim().min(1)).optional(),- parallel: z.boolean().optional(),- providerOverride: z.string().trim().max(64).optional(),-});--// Extract characters/places/objects from a prose body into the universe's-// canon arrays. Same LLM path as the series-side extract — just targeting a-// universe so multiple series can share the cast.-router.post('/:id/extract-canon', asyncHandler(async (req, res) => {- const body = validateRequest(extractCanonSchema, req.body ?? {});- const result = await canonSvc.extractCanonFromProse(req.params.id, body)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Promote a {label, prompt} variation into a full canon entry of the-// corresponding trunk (resolved from the bucket's `kind` field, or the-// caller-supplied `targetKind` for 'other'-kinded buckets). The variation-// is removed from its source bucket and the canon entry is appended in a-// single atomic patch.-router.post('/:id/promote-variation', asyncHandler(async (req, res) => {- const body = validateRequest(promoteVariationSchema, req.body ?? {});- const result = await promoteVariationToCanon(req.params.id, body)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Bulk-classify every `kind: 'other'` bucket via one LLM call. Each bucket's-// `kind` is updated atomically in one `updateUniverse` patch; renames the-// LLM suggests are surfaced in the response but not auto-applied (the UI-// can present them as opt-in suggestions).-router.post('/:id/auto-sort', asyncHandler(async (req, res) => {- const body = validateRequest(autoSortSchema, req.body ?? {});- const result = await autoSortOtherBuckets(req.params.id, body)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--const refineCharSchema = z.object({- providerId: z.string().trim().max(64).optional(),- model: z.string().trim().max(128).optional(),-});--router.post('/:id/characters/:entryId/refine', asyncHandler(async (req, res) => {- const body = validateRequest(refineCharSchema, req.body ?? {});- const result = await canonSvc.refineUniverseCharacter(req.params.id, req.params.entryId, body)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Expand a character via one LLM call — fills BLANK extended fields-// (pronouns/age/stats/colorPalette/expressions/...) so a novelist + graphic-// novelist have full reference data. No-clobber on populated fields; locked-// characters return `{ locked: true }` with no LLM call.-router.post('/:id/characters/:entryId/expand', asyncHandler(async (req, res) => {- const body = validateRequest(refineCharSchema, req.body ?? {});- const result = await expandUniverseCharacter(req.params.id, req.params.entryId, body)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Vision-driven expand — a vision model reads reference image(s) (upload or-// gallery) and PROPOSES values for the character's still-blank structured-// fields (palette/visual notes/expressions/...). Review-only: returns the-// proposed `{ field: value }` map; the client applies the kept/edited values-// via the normal entry-PATCH path. No-clobber, characters-only, locked-// characters return `{ locked: true }` with no LLM call.-const expandFromImagesSchema = z.object({- name: z.string().trim().max(BIBLE_LIMITS.NAME_MAX).optional(),- context: z.string().trim().max(2000).optional(),- images: z.array(imageSourceSchema).min(1).max(VISION_EXPAND_MAX_IMAGES),- providerId: z.string().trim().max(80).optional(),- model: z.string().trim().max(200).optional(),-});-router.post('/:id/characters/:entryId/expand-from-images', asyncHandler(async (req, res) => {- const body = validateRequest(expandFromImagesSchema, req.body ?? {});- const screenshots = resolveImageSources(body.images);- const result = await expandEntityFromImages({- universeId: req.params.id,- entryId: req.params.entryId,- name: body.name,- context: body.context,- screenshots,- providerId: body.providerId,- model: body.model,- }).catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Corrective vision analysis for ONE canon entry (character/place/object):-// given the entry's CURRENT descriptor text as context, a vision model-// proposes a CORRECTED replacement — unlike expand-from-images (fills only-// still-blank fields) or describe-from-images (describes blind), this-// overwrites existing text where the image contradicts it. Review-only:-// returns the proposed text for the client to show alongside the current-// value; `apply-image-correction` (below) persists it.-const correctFromImageSchema = z.object({- image: z.string().trim().min(1).max(300),- name: z.string().trim().max(BIBLE_LIMITS.NAME_MAX).optional(),- context: z.string().trim().max(2000).optional(),- providerId: z.string().trim().max(80).optional(),- model: z.string().trim().max(200).optional(),-});-router.post('/:id/canon/:kind/:entryId/correct-from-image', asyncHandler(async (req, res) => {- const { kind } = validateRequest(lockParamsSchema, req.params);- const body = validateRequest(correctFromImageSchema, req.body ?? {});- const { imageFilename, imagePath } = resolveGalleryImageOrThrow(body.image);- const result = await correctEntityFromImage({- universeId: req.params.id,- entryId: req.params.entryId,- kind,- name: body.name,- context: body.context,- screenshot: imagePath,- providerId: body.providerId,- model: body.model,- }).catch((err) => { throw mapServiceError(err); });- res.json({ ...result, imageFilename });-}));--// Persist a reviewed corrective-image analysis: overwrites the entry's-// descriptor field with the reviewed text AND pins the analyzed image as the-// entry's `primaryImageRef` — assigning it as that noun's style/reference-// image so subsequent renders (client-side i2i seeding) use it.-// Cap at the largest per-kind descriptor limit (canonSvc.DESC_LIMIT) rather-// than the unrelated NOTES_MAX — applyCanonImageCorrection silently trims to-// the per-kind limit before persisting, so a looser schema cap here would let-// a request pass validation only to have its tail silently dropped on write.-const applyImageCorrectionSchema = z.object({- description: z.string().trim().min(1).max(Math.max(...Object.values(canonSvc.DESC_LIMIT))),- imageFilename: z.string().trim().min(1).max(300),-});-router.post('/:id/canon/:kind/:entryId/apply-image-correction', asyncHandler(async (req, res) => {- const { kind } = validateRequest(lockParamsSchema, req.params);- const body = validateRequest(applyImageCorrectionSchema, req.body ?? {});- const result = await canonSvc.applyCanonImageCorrection(req.params.id, kind, req.params.entryId, body)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Generate one of the character reference-sheet variants from a structured-// TEXT prompt — no init image required, so it works across codex / local-// backends. The `variant` field selects which prompt-builder + storage slot-// the render targets (defaults to 'standard' = illustrated turnaround).-// Returns immediately with `{ jobId, generationId, variant }`; client-// subscribes to SSE for progress, and the server-side completion handler-// stamps the variant's pointer on success.-const renderReferenceSheetSchema = z.object({- variant: z.string().trim().min(1).max(48).optional(),- overridePrompt: z.string().trim().max(8000).optional(),- overrideNegativePrompt: z.string().trim().max(2000).optional(),- modelId: z.string().trim().max(64).optional(),-});-router.post('/:id/characters/:entryId/render-reference-sheet', asyncHandler(async (req, res) => {- const options = validateRequest(renderReferenceSheetSchema, req.body ?? {});- const result = await renderCharacterReferenceSheet(req.params.id, req.params.entryId, options)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Delete a character's reference sheet — unlinks the PNG from-// `data/image-refs/` and nulls the variant's pointer on every matching-// character so the UI clears reactively without a refetch. `variant` is-// passed via query string (DELETE bodies are awkward across HTTP clients).-const deleteReferenceSheetQuerySchema = z.object({- variant: z.string().trim().min(1).max(48).optional(),-});-router.delete('/:id/characters/:entryId/reference-sheet', asyncHandler(async (req, res) => {- const opts = validateRequest(deleteReferenceSheetQuerySchema, req.query ?? {});- const result = await deleteCharacterReferenceSheet(req.params.id, req.params.entryId, opts)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Cast-wide differentiate — one LLM call rewrites every character so the-// cast as a whole has no visually-colliding pairs. Returns counts + the-// updated universe.-router.post('/:id/characters/differentiate-cast', asyncHandler(async (req, res) => {- const body = validateRequest(refineCharSchema, req.body ?? {});- const result = await canonSvc.differentiateUniverseCast(req.params.id, body)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Cross-reference: per-canon-entry usage across the universe's linked series.-// Read-only aggregation; no LLM calls, no writes. Surfaces which series + how-// many issues each character / place / object appears in, so the user can-// see crossover/cameo footprint at a glance on the Universe Canon page.-router.get('/:id/canon-usage', asyncHandler(async (req, res) => {- const result = await getUniverseCanonUsage(req.params.id)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Thin lookup: linked-series id/name pairs for callers (e.g. NounsStage) that-// only need to label canon-card "from <series>" chips. Skips the O(series ×-// issues × matchers) prose scan that /canon-usage runs.-router.get('/:id/series-names', asyncHandler(async (req, res) => {- const result = await listLinkedSeriesNames(req.params.id)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// ---- Art style references (delta endpoints, #3109) -----//-// Add/remove one reference at a time instead of PATCHing the whole array; see-// `addStyleReference` in services/universeBuilder/crud.js for the rationale.-// The wholesale-replace `{ styleReferences: [...] }` field on PATCH /:id stays-// accepted (older clients, peer imports, the sharing importer).-const addStyleReferenceSchema = z.object({- // `id` is required here (unlike the wholesale-replace field, where the- // sanitizer mints one): the id is what makes a re-sent add idempotent- // server-side, and /analyze-style-reference always returns one. `required`- // only drops the `.optional()` — the trim/length rules stay defined once, on- // the shared `entryIdField`.- reference: styleReferenceSchema.required({ id: true }),- // Present when the user chose "Adopt style + add" — written in the SAME- // queued write as the reference so the pair can't half-land. Both fields- // default, so `adopt: {}` reads as "adopt an empty guide" (an explicit clear)- // instead of reaching the service as `undefined` and clearing influences by- // accident — matching analyzeStyleReferenceSchema's choice for the same pair.- adopt: z.object({- styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),- influences: influencesSchema.optional().default({ embrace: [], avoid: [] }),- }).optional(),-});-router.post('/:id/style-references', asyncHandler(async (req, res) => {- const body = validateRequest(addStyleReferenceSchema, req.body ?? {});- const w = await svc.addStyleReference(req.params.id, body.reference, { adopt: body.adopt })- .catch((err) => { throw mapServiceError(err); });- res.json(w);-}));--// The id is only ever compared against stored reference ids (never used as a-// path/SQL operand), but validate it anyway so an absurdly long param is a 400-// here rather than a silent no-op deeper in.-const removeStyleReferenceParamsSchema = z.object({- referenceId: entryIdField.unwrap(),-});-router.delete('/:id/style-references/:referenceId', asyncHandler(async (req, res) => {- const { referenceId } = validateRequest(removeStyleReferenceParamsSchema, req.params);- const w = await svc.removeStyleReference(req.params.id, referenceId)- .catch((err) => { throw mapServiceError(err); });- res.json(w);-}));--// Lock toggle for canon entries. Locked entries are protected from AI rewrite-// paths (refine, differentiate, re-extract field overwrites).-const setLockSchema = z.object({- locked: z.boolean(),-});-const lockParamsSchema = z.object({- kind: z.enum(BIBLE_KINDS),-});-router.patch('/:id/canon/:kind/:entryId/lock', asyncHandler(async (req, res) => {- const { kind } = validateRequest(lockParamsSchema, req.params);- const body = validateRequest(setLockSchema, req.body ?? {});- const result = await canonSvc.setCanonEntryLock(- req.params.id,- kind,- req.params.entryId,- body.locked,- ).catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Bulk lock/unlock every canon entry of a single kind. Powers the-// "Lock all / Unlock all" buttons in the Universe Builder canon section.-router.patch('/:id/canon/:kind/lock-all', asyncHandler(async (req, res) => {- const { kind } = validateRequest(lockParamsSchema, req.params);- const body = validateRequest(setLockSchema, req.body ?? {});- const result = await canonSvc.setCanonKindLockAll(req.params.id, kind, body.locked)- .catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--// Bulk lock/unlock every variation in a category bucket. Powers the-// per-bucket "Lock all / Unlock all" affordance on the variations grid.-// Omit `category` in the body to apply to every variation in every bucket;-// pass `includeSheets: true` to also flip composite sheets in the same call.-const setVariationsLockAllSchema = z.object({- locked: z.boolean(),- category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX).nullable().optional(),- includeSheets: z.boolean().optional(),-});-router.patch('/:id/variations/lock-all', asyncHandler(async (req, res) => {- const body = validateRequest(setVariationsLockAllSchema, req.body ?? {});- const result = await svc.setVariationsLockAll(req.params.id, {- categoryKey: body.category || null,- locked: body.locked,- includeSheets: body.includeSheets === true,- }).catch((err) => { throw mapServiceError(err); });- res.json(result);-}));--export default router;diff --git a/server/routes/universeBuilder/canon.js b/server/routes/universeBuilder/canon.jsnew file mode 100644index 0000000000..b8bc94b3de--- /dev/null+++ b/server/routes/universeBuilder/canon.js@@ -0,0 +1,117 @@+/**+ * Canon (Phase A of the Universe-as-canon refactor): prose extraction, the+ * per-character LLM refine/expand/differentiate operations, the read-only+ * cross-reference lookups, and the entry/kind lock toggles.+ *+ * Every path here is scoped under `/:id`, so mount order relative to crud.js+ * doesn't matter (no single-segment route can shadow these).+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../../lib/errorHandler.js';+import { validateRequest } from '../../lib/validation.js';+import * as canonSvc from '../../services/universeCanon.js';+import { expandUniverseCharacter } from '../../services/universeCharacterExpand.js';+import { getUniverseCanonUsage, listLinkedSeriesNames } from '../../services/canonUsage.js';+import { mapServiceError, lockParamsSchema } from './shared.js';++const router = Router();++const extractCanonSchema = z.object({+ corpus: z.string().trim().min(1).max(200_000),+ kinds: z.array(z.string().trim().min(1)).optional(),+ parallel: z.boolean().optional(),+ providerOverride: z.string().trim().max(64).optional(),+});++// Extract characters/places/objects from a prose body into the universe's+// canon arrays. Same LLM path as the series-side extract — just targeting a+// universe so multiple series can share the cast.+router.post('/:id/extract-canon', asyncHandler(async (req, res) => {+ const body = validateRequest(extractCanonSchema, req.body ?? {});+ const result = await canonSvc.extractCanonFromProse(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++const refineCharSchema = z.object({+ providerId: z.string().trim().max(64).optional(),+ model: z.string().trim().max(128).optional(),+});++router.post('/:id/characters/:entryId/refine', asyncHandler(async (req, res) => {+ const body = validateRequest(refineCharSchema, req.body ?? {});+ const result = await canonSvc.refineUniverseCharacter(req.params.id, req.params.entryId, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Expand a character via one LLM call — fills BLANK extended fields+// (pronouns/age/stats/colorPalette/expressions/...) so a novelist + graphic+// novelist have full reference data. No-clobber on populated fields; locked+// characters return `{ locked: true }` with no LLM call.+router.post('/:id/characters/:entryId/expand', asyncHandler(async (req, res) => {+ const body = validateRequest(refineCharSchema, req.body ?? {});+ const result = await expandUniverseCharacter(req.params.id, req.params.entryId, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Cast-wide differentiate — one LLM call rewrites every character so the+// cast as a whole has no visually-colliding pairs. Returns counts + the+// updated universe.+router.post('/:id/characters/differentiate-cast', asyncHandler(async (req, res) => {+ const body = validateRequest(refineCharSchema, req.body ?? {});+ const result = await canonSvc.differentiateUniverseCast(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Cross-reference: per-canon-entry usage across the universe's linked series.+// Read-only aggregation; no LLM calls, no writes. Surfaces which series + how+// many issues each character / place / object appears in, so the user can+// see crossover/cameo footprint at a glance on the Universe Canon page.+router.get('/:id/canon-usage', asyncHandler(async (req, res) => {+ const result = await getUniverseCanonUsage(req.params.id)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Thin lookup: linked-series id/name pairs for callers (e.g. NounsStage) that+// only need to label canon-card "from <series>" chips. Skips the O(series ×+// issues × matchers) prose scan that /canon-usage runs.+router.get('/:id/series-names', asyncHandler(async (req, res) => {+ const result = await listLinkedSeriesNames(req.params.id)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Lock toggle for canon entries. Locked entries are protected from AI rewrite+// paths (refine, differentiate, re-extract field overwrites).+const setLockSchema = z.object({+ locked: z.boolean(),+});+router.patch('/:id/canon/:kind/:entryId/lock', asyncHandler(async (req, res) => {+ const { kind } = validateRequest(lockParamsSchema, req.params);+ const body = validateRequest(setLockSchema, req.body ?? {});+ const result = await canonSvc.setCanonEntryLock(+ req.params.id,+ kind,+ req.params.entryId,+ body.locked,+ ).catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Bulk lock/unlock every canon entry of a single kind. Powers the+// "Lock all / Unlock all" buttons in the Universe Builder canon section.+router.patch('/:id/canon/:kind/lock-all', asyncHandler(async (req, res) => {+ const { kind } = validateRequest(lockParamsSchema, req.params);+ const body = validateRequest(setLockSchema, req.body ?? {});+ const result = await canonSvc.setCanonKindLockAll(req.params.id, kind, body.locked)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++export default router;diff --git a/server/routes/universeBuilder/crud.js b/server/routes/universeBuilder/crud.jsnew file mode 100644index 0000000000..0701c6d41d--- /dev/null+++ b/server/routes/universeBuilder/crud.js@@ -0,0 +1,191 @@+/**+ * Universe CRUD — list/create/read/update/delete, the style-token lookup, the+ * per-universe run history, and the bulk variation lock toggle.+ *+ * `GET /styles` is declared ahead of `GET /:id` in this file so the wildcard+ * doesn't swallow it; every OTHER static top-level path lives in a sub-router+ * mounted BEFORE this one (see index.js).+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../../lib/errorHandler.js';+import { validateRequest, llmSchema, isPaginationRequested, paginateArray, recordRenderPinFields } from '../../lib/validation.js';+import { pruneStaleReferenceSheets } from '../../lib/storyBible.js';+import * as svc from '../../services/universeBuilder.js';+import { findSameNameUniverses } from '../../services/duplicateDetection.js';+import {+ mapServiceError,+ entryImageRefsField,+ compositeSheetSchema,+ categoriesSchema,+ lockedSchema,+ influencesSchema,+ styleReferencesField,+ legacyStylePromptField,+ legacyNegativePromptField,+ canonArrayField,+} from './shared.js';++const router = Router();++const createSchema = z.object({+ name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH),+ starterPrompt: z.string().trim().max(svc.STARTER_PROMPT_MAX).optional().default(''),+ stylePrompt: legacyStylePromptField,+ negativePrompt: legacyNegativePromptField,+ logline: z.string().trim().max(svc.LOGLINE_MAX).optional().default(''),+ premise: z.string().trim().max(svc.PREMISE_MAX).optional().default(''),+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),+ categories: categoriesSchema.optional(),+ compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),+ influences: influencesSchema.optional(),+ styleReferences: styleReferencesField,+ // Base "style probe" render filenames — sanitized + capped server-side.+ // Match the sanitizer cap so over-the-cap requests get a loud 400 instead+ // of a silent 200 with N entries dropped (sanitizer keeps the most recent+ // IMAGE_REFS_PER_ENTRY_MAX). Per-element filename cap is shared too.+ styleImageRefs: entryImageRefsField,+ locked: lockedSchema.optional(),+ llm: llmSchema,+ // Canon registries on POST (Phase B.4): writers-room promote, share-bucket+ // import, and tests can seed a universe with canon at create time instead+ // of needing a second PATCH round-trip.+ characters: canonArrayField,+ places: canonArrayField,+ objects: canonArrayField,+ // Per-record render pin (#3231 Phase 3) — this universe's default image+ // backend + cloud model.+ ...recordRenderPinFields,+ // Local-only "don't sync to peers" marker — see sanitizeRecordForWire.+ ephemeral: z.boolean().optional(),+});+// `origin` is a share-bucket provenance block written by the importer + cleared+// to null by the user; structurally an object or null.+const originField = z.record(z.unknown()).nullable().optional();++const patchSchema = z.object({+ name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH).optional(),+ starterPrompt: z.string().trim().max(svc.STARTER_PROMPT_MAX).optional(),+ // Legacy prose prompts — see legacy*Field comment above. Tolerated on PATCH+ // so a stale client tab can still save while the new chip-based UI lands.+ stylePrompt: legacyStylePromptField,+ negativePrompt: legacyNegativePromptField,+ logline: z.string().trim().max(svc.LOGLINE_MAX).optional(),+ premise: z.string().trim().max(svc.PREMISE_MAX).optional(),+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional(),+ categories: categoriesSchema.optional(),+ compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),+ influences: influencesSchema.optional(),+ styleReferences: styleReferencesField,+ // Base "style probe" render filenames — sanitized + capped server-side.+ // Match the sanitizer cap so over-the-cap requests get a loud 400 instead+ // of a silent 200 with N entries dropped (sanitizer keeps the most recent+ // IMAGE_REFS_PER_ENTRY_MAX). Per-element filename cap is shared too.+ styleImageRefs: entryImageRefsField,+ locked: lockedSchema.optional(),+ llm: llmSchema,+ // Canon writes — these flow through sanitizeBibleList server-side so+ // schema parity here is just "accept arrays of records." Without these+ // entries Zod's default strip behavior silently drops them from the+ // patch (PATCHABLE_SCALARS in services/universeBuilder.js reads them+ // from the post-Zod body, so they'd never reach the writer).+ characters: canonArrayField,+ places: canonArrayField,+ objects: canonArrayField,+ origin: originField,+ // Per-record render pin (#3231 Phase 3). Key-present with 'auto'/''/null+ // clears; key-absent preserves.+ ...recordRenderPinFields,+ ephemeral: z.boolean().optional(),+}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });++// Backward-compatible by default: returns the full universes array. When a client+// passes `limit`/`offset`, the response becomes the bounded+// `{ items, total, limit, offset }` envelope every paginated PortOS list shares.+router.get('/', asyncHandler(async (req, res) => {+ const universes = await svc.listUniverses();+ if (!isPaginationRequested(req.query)) {+ return res.json(universes);+ }+ res.json(paginateArray(universes, req.query, { defaultLimit: 50, maxLimit: 500 }));+}));++router.post('/', asyncHandler(async (req, res) => {+ const body = validateRequest(createSchema, req.body ?? {});+ const created = await svc.createUniverse(body);+ // Non-blocking same-name warning (computed at the route layer so the importer,+ // which calls the service directly, never pays for the scan). The UI surfaces+ // it but may proceed — duplicates are resolved later via Sharing → Duplicates.+ const duplicateName = await findSameNameUniverses(created.name, { excludeId: created.id });+ res.status(201).json(duplicateName.length ? { ...created, _warnings: { duplicateName } } : created);+}));++// Style tokens only (see svc.listUniverseStyles). Must stay ahead of `/:id` so+// the wildcard doesn't catch "styles" as a universe id.+router.get('/styles', asyncHandler(async (_req, res) => {+ res.json(await svc.listUniverseStyles());+}));++router.get('/:id', asyncHandler(async (req, res) => {+ // Read-by-id 404s are benign and high-volume: callers like LoraDatasetDetail+ // speculatively fetch a dataset's `character.universeId` ({ silent: true }),+ // which 404s whenever that universe was deleted. Classify as `warning` so the+ // error middleware skips it instead of spamming ❌ Route error on every+ // page reconnect. (Mirrors the media-job archive-lookup precedent.)+ const w = await svc.getUniverse(req.params.id).catch((err) => {+ const mapped = mapServiceError(err);+ if (mapped?.code === svc.ERR_NOT_FOUND) mapped.severity = 'warning';+ throw mapped;+ });+ // Lazy stale-reference-sheet collapse: nulls out any character.referenceSheetImageRef+ // whose underlying file was deleted from disk, so the UI never tries to+ // render `<img src="/data/image-refs/<gone>">`. Doesn't persist the change+ // — next render or PATCH will overwrite cleanly. Sub-millisecond for the+ // typical 5-50 character universe.+ const pruned = Array.isArray(w?.characters)+ ? { ...w, characters: pruneStaleReferenceSheets(w.characters) }+ : w;+ res.json(pruned);+}));++router.patch('/:id', asyncHandler(async (req, res) => {+ const body = validateRequest(patchSchema, req.body ?? {});+ const w = await svc.updateUniverse(req.params.id, body).catch((err) => { throw mapServiceError(err); });+ // Re-check the same-name warning when the rename actually changed the name.+ if ('name' in body) {+ const duplicateName = await findSameNameUniverses(w.name, { excludeId: req.params.id });+ if (duplicateName.length) { res.json({ ...w, _warnings: { duplicateName } }); return; }+ }+ res.json(w);+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ const r = await svc.deleteUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });+ res.json(r);+}));++router.get('/:id/runs', asyncHandler(async (req, res) => {+ res.json(await svc.listRuns(req.params.id));+}));++// Bulk lock/unlock every variation in a category bucket. Powers the+// per-bucket "Lock all / Unlock all" affordance on the variations grid.+// Omit `category` in the body to apply to every variation in every bucket;+// pass `includeSheets: true` to also flip composite sheets in the same call.+const setVariationsLockAllSchema = z.object({+ locked: z.boolean(),+ category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX).nullable().optional(),+ includeSheets: z.boolean().optional(),+});+router.patch('/:id/variations/lock-all', asyncHandler(async (req, res) => {+ const body = validateRequest(setVariationsLockAllSchema, req.body ?? {});+ const result = await svc.setVariationsLockAll(req.params.id, {+ categoryKey: body.category || null,+ locked: body.locked,+ includeSheets: body.includeSheets === true,+ }).catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++export default router;diff --git a/server/routes/universeBuilder/expand.js b/server/routes/universeBuilder/expand.jsnew file mode 100644index 0000000000..44b75d5ec9--- /dev/null+++ b/server/routes/universeBuilder/expand.js@@ -0,0 +1,177 @@+/**+ * LLM-authored world structure: the stateless expand / generate-variations /+ * refine-prompts trio, plus the two per-universe bucket operations that+ * rearrange what those produced (promote-variation, auto-sort).+ *+ * The three stateless routes are static top-level paths — this router mounts+ * BEFORE crud.js so `/:id` can't swallow them.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../../lib/errorHandler.js';+import { validateRequest } from '../../lib/validation.js';+import { resolveGalleryImage } from '../../lib/fileUtils.js';+import * as svc from '../../services/universeBuilder.js';+import { expandWorldTemplate, generateCategoryVariations } from '../../services/universeBuilderExpand.js';+import { refineWorldPrompts } from '../../services/universeBuilderRefine.js';+import { promoteVariationToCanon, VALID_TARGET_KINDS } from '../../services/universeBuilderPromote.js';+import { autoSortOtherBuckets } from '../../services/universeBuilderAutoSort.js';+import {+ mapServiceError,+ variationSchema,+ compositeSheetSchema,+ categoriesSchema,+ lockedSchema,+ influencesSchema,+} from './shared.js';++const router = Router();++const expandSchema = z.object({+ starterPrompt: z.string().trim().min(1).max(svc.STARTER_PROMPT_MAX),+ // Optional structured influences from a prior refinement — passed in so+ // the LLM keeps re-expansions on-direction instead of regenerating from+ // the bare starter idea.+ influences: influencesSchema.optional(),+ // Per-item locks the user has set on individual variations / composite+ // boards. Listed in the LLM prompt so it doesn't waste tokens regenerating+ // them; the client merges them back in after the result returns.+ preservedVariations: z.record(+ z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),+ z.array(variationSchema).max(svc.VARIATIONS_PER_CATEGORY_MAX),+ ).optional(),+ preservedCompositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),+ // Current bible/prompt state — locked entries are echoed verbatim, others+ // are starting points the LLM can refine while staying consistent.+ logline: z.string().trim().max(svc.LOGLINE_MAX).optional(),+ premise: z.string().trim().max(svc.PREMISE_MAX).optional(),+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional(),+ locked: lockedSchema.optional(),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});++// `targetKind` is only required when the source bucket's `kind` is 'other'+// (otherwise the service resolves it from the bucket). Enum derived from+// VALID_TARGET_KINDS so the schema and the resolver share one source.+const promoteVariationSchema = z.object({+ category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),+ label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),+ targetKind: z.enum(VALID_TARGET_KINDS).optional(),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});++// Auto-sort takes no bucket selection — the service scans for every+// `kind: 'other'` bucket on the universe. Provider/model are optional;+// the service falls back to the active provider when omitted.+const autoSortSchema = z.object({+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});++const generateVariationsSchema = z.object({+ category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),+ count: z.number().int().min(1).max(svc.VARIATIONS_PER_CATEGORY_MAX),+ existingLabels: z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX))+ .max(svc.VARIATIONS_PER_CATEGORY_MAX).optional().default([]),+ influences: influencesSchema.optional(),+ logline: z.string().trim().max(svc.LOGLINE_MAX).optional().default(''),+ premise: z.string().trim().max(svc.PREMISE_MAX).optional().default(''),+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});++const refinePromptsSchema = z.object({+ starterPrompt: z.string().trim().min(1).max(svc.STARTER_PROMPT_MAX),+ // Bible context: passed in so the refiner sees the full seed, refines them+ // alongside the prompts, and stays consistent with the universe's narrative.+ logline: z.string().trim().max(svc.LOGLINE_MAX).optional().default(''),+ premise: z.string().trim().max(svc.PREMISE_MAX).optional().default(''),+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),+ // Structured influences (embrace + avoid) — refined alongside the prompts+ // and used as the canonical reference list for renderer-token composition.+ influences: influencesSchema.optional(),+ // Post-Expand structure — when present, the refiner sees the full universe+ // (categories + composites with per-item locks) and may edit/replace/add+ // items per the user's feedback. When omitted (pre-Expand iteration), the+ // refiner falls back to the bible-only behavior.+ categories: categoriesSchema.optional(),+ compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),+ // Per-field lock map — locked fields are echoed back unchanged regardless+ // of what the LLM tries to write.+ locked: lockedSchema.optional().default({}),+ feedback: z.string().trim().min(1).max(3000),+ // Optional gallery image used as a VISUAL style reference — when present the+ // refiner forces a vision-capable API provider and folds the image's+ // palette/lighting/mood into influences + styleNotes. Resolved to an absolute+ // path in the handler before reaching the service.+ image: z.string().trim().min(1).max(300).optional(),+ providerId: z.string().trim().max(80).optional(),+ // Whitespace-only model → undefined so the refiner's defaultModel /+ // models[0] fallback kicks in instead of a blank string reaching the+ // provider. Mirrors how /api/media-jobs/refine-prompt handles it.+ model: z.string().max(200).optional().transform((s) => {+ const v = (s ?? '').trim();+ return v.length > 0 ? v : undefined;+ }),+});++// `expand` is a sub-resource — keep it ahead of `/:id` so the wildcard+// doesn't catch "expand" as a universe id.+router.post('/expand', asyncHandler(async (req, res) => {+ const body = validateRequest(expandSchema, req.body ?? {});+ const result = await expandWorldTemplate(body);+ res.json(result);+}));++router.post('/generate-variations', asyncHandler(async (req, res) => {+ const body = validateRequest(generateVariationsSchema, req.body ?? {});+ const result = await generateCategoryVariations(body);+ res.json(result);+}));++// Refines the 3 top-level prompts (starter / style / negative) based on+// user feedback. Stateless — the caller decides whether to write the+// result back to a saved universe. Keep ahead of `/:id`.+router.post('/refine-prompts', asyncHandler(async (req, res) => {+ const body = validateRequest(refinePromptsSchema, req.body ?? {});+ // Resolve the optional style-reference image to an absolute gallery path+ // before the service runs — fail loudly on a stale/bogus filename rather than+ // letting the runner silently drop it and refine text-only.+ let imagePath = null;+ if (body.image) {+ imagePath = resolveGalleryImage(body.image);+ if (!imagePath) {+ throw new ServerError(`Gallery image not found: ${body.image} — pick another and retry.`, { status: 400, code: 'GALLERY_IMAGE_NOT_FOUND' });+ }+ }+ res.json(await refineWorldPrompts({ ...body, imagePath }));+}));++// Promote a {label, prompt} variation into a full canon entry of the+// corresponding trunk (resolved from the bucket's `kind` field, or the+// caller-supplied `targetKind` for 'other'-kinded buckets). The variation+// is removed from its source bucket and the canon entry is appended in a+// single atomic patch.+router.post('/:id/promote-variation', asyncHandler(async (req, res) => {+ const body = validateRequest(promoteVariationSchema, req.body ?? {});+ const result = await promoteVariationToCanon(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Bulk-classify every `kind: 'other'` bucket via one LLM call. Each bucket's+// `kind` is updated atomically in one `updateUniverse` patch; renames the+// LLM suggests are surfaced in the response but not auto-applied (the UI+// can present them as opt-in suggestions).+router.post('/:id/auto-sort', asyncHandler(async (req, res) => {+ const body = validateRequest(autoSortSchema, req.body ?? {});+ const result = await autoSortOtherBuckets(req.params.id, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++export default router;diff --git a/server/routes/universeBuilder/index.js b/server/routes/universeBuilder/index.jsnew file mode 100644index 0000000000..2b5595c520--- /dev/null+++ b/server/routes/universeBuilder/index.js@@ -0,0 +1,42 @@+/**+ * Universe Builder Routes — /api/universe-builder+ *+ * Universe CRUD plus the AI-assisted workflows that operate on a universe:+ * expand/refine, image-based description + canon correction, reference-sheet+ * and canon-entry rendering, run history, style references, and canon+ * entry management. Each endpoint carries its own doc comment in its+ * sub-router — this header intentionally doesn't enumerate them (it drifted+ * stale when it did).+ *+ * Assembled from domain sub-routers (mirrors the routes/pipeline pattern).+ * Mount order is load-bearing: every sub-router that owns a single-segment+ * STATIC path (`/expand`, `/describe-from-images`, `/analyze-style-reference`,+ * `/refine-prompts`, `/reference-sheet-variants`, `/duplicates`, `/merge*`)+ * must be mounted BEFORE crud.js, whose `GET /:id` would otherwise swallow+ * it. `/styles` is the one static path that lives inside crud.js, declared+ * ahead of `/:id` there. Routers mounted after crud.js own only `/:id/...`+ * multi-segment paths, which no single-segment route can shadow.+ */++import { Router } from 'express';+import expandRoutes from './expand.js';+import visionRoutes from './vision.js';+import styleReferenceRoutes from './styleReferences.js';+import referenceSheetRoutes from './referenceSheets.js';+import mergeRoutes from './merge.js';+import crudRoutes from './crud.js';+import renderRoutes from './render.js';+import canonRoutes from './canon.js';++const router = Router();++router.use(expandRoutes);+router.use(visionRoutes);+router.use(styleReferenceRoutes);+router.use(referenceSheetRoutes);+router.use(mergeRoutes);+router.use(crudRoutes);+router.use(renderRoutes);+router.use(canonRoutes);++export default router;diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder/index.test.jssimilarity index 96%rename from server/routes/universeBuilder.test.jsrename to server/routes/universeBuilder/index.test.jsindex 7ab87b498c..d5599f6080 100644--- a/server/routes/universeBuilder.test.js+++ b/server/routes/universeBuilder/index.test.js@@ -1,10 +1,10 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';-import { request } from '../lib/testHelper.js';-import { errorMiddleware } from '../lib/errorHandler.js';-import { enqueueJob } from '../services/mediaJobQueue/index.js';-import { mockNoPeers, mockNoPeerSync } from '../lib/mockPathsDataRoot.js';-import * as canonSvc from '../services/universeCanon.js';+import { request } from '../../lib/testHelper.js';+import { errorMiddleware } from '../../lib/errorHandler.js';+import { enqueueJob } from '../../services/mediaJobQueue/index.js';+import { mockNoPeers, mockNoPeerSync } from '../../lib/mockPathsDataRoot.js';+import * as canonSvc from '../../services/universeCanon.js';const fileStore = new Map();@@ -13,7 +13,7 @@ const fileStore = new Map();const resolveGalleryImageMock = vi.fn((filename) => (typeof filename === 'string' && !filename.includes('missing') ? `/mock/data/images/${filename}` : null));-vi.mock('../lib/fileUtils.js', () => ({+vi.mock('../../lib/fileUtils.js', () => ({tryReadFile: vi.fn().mockResolvedValue(null),PATHS: { data: '/mock/data', screenshots: '/mock/data/screenshots', images: '/mock/data/images' },ensureDir: vi.fn().mockResolvedValue(undefined),@@ -38,8 +38,8 @@ const describeEntityFromImagesMock = vi.fn(async () => ({ description: 'mock proconst correctEntityFromImageMock = vi.fn(async () => ({descField: 'physicalDescription', currentDescription: 'old', proposedDescription: 'corrected', llm: { provider: 'mock', model: null },}));-vi.mock('../services/universeVisionDescribe.js', async () => {- const actual = await vi.importActual('../services/universeVisionDescribe.js');+vi.mock('../../services/universeVisionDescribe.js', async () => {+ const actual = await vi.importActual('../../services/universeVisionDescribe.js');return {...actual,describeEntityFromImages: (...args) => describeEntityFromImagesMock(...args),@@ -50,13 +50,13 @@ const applyCanonImageCorrectionMock = vi.fn(async (_universeId, kind, entryId, buniverse: { id: _universeId },entry: { id: entryId, [kind === 'character' ? 'physicalDescription' : 'description']: body.description, primaryImageRef: body.imageFilename },}));-vi.mock('../services/universeCanon.js', async () => {- const actual = await vi.importActual('../services/universeCanon.js');+vi.mock('../../services/universeCanon.js', async () => {+ const actual = await vi.importActual('../../services/universeCanon.js');return { ...actual, applyCanonImageCorrection: (...args) => applyCanonImageCorrectionMock(...args) };});const expandEntityFromImagesMock = vi.fn(async () => ({ fields: { pronouns: 'she/her' }, updatedFields: ['pronouns'], llm: { provider: 'mock', model: null } }));-vi.mock('../services/universeVisionExpand.js', async () => {- const actual = await vi.importActual('../services/universeVisionExpand.js');+vi.mock('../../services/universeVisionExpand.js', async () => {+ const actual = await vi.importActual('../../services/universeVisionExpand.js');return { ...actual, expandEntityFromImages: (...args) => expandEntityFromImagesMock(...args) };});const refineWorldPromptsMock = vi.fn(async (args) => ({@@ -64,7 +64,7 @@ const refineWorldPromptsMock = vi.fn(async (args) => ({influences: { embrace: [], avoid: [] }, locked: {}, rationale: 'r', changes: [],providerId: 'mock', model: null, _imagePath: args?.imagePath ?? null,}));-vi.mock('../services/universeBuilderRefine.js', () => ({+vi.mock('../../services/universeBuilderRefine.js', () => ({refineWorldPrompts: (...args) => refineWorldPromptsMock(...args),}));const analyzeUniverseStyleReferenceMock = vi.fn(async (args) => ({@@ -80,13 +80,13 @@ const analyzeUniverseStyleReferenceMock = vi.fn(async (args) => ({rationale: 'mock rationale',llm: { provider: 'mock', model: null },}));-vi.mock('../services/universeStyleReference.js', () => ({+vi.mock('../../services/universeStyleReference.js', () => ({analyzeUniverseStyleReference: (...args) => analyzeUniverseStyleReferenceMock(...args),}));// Both mocks needed: vitest.setup.js's global `instances.js` mock uses importOriginal, which leaves the per-file `peerSync.js` mock unable to suppress the createUniverse dynamic-import hoist error alone.-vi.mock('../services/instances.js', () => mockNoPeers());-vi.mock('../services/sharing/peerSync.js', () => mockNoPeerSync());+vi.mock('../../services/instances.js', () => mockNoPeers());+vi.mock('../../services/sharing/peerSync.js', () => mockNoPeerSync());let uuidCounter = 0;vi.mock('crypto', async () => {@@ -105,10 +105,10 @@ const promoteVariationToCanonMock = vi.fn(async (_universeId, body = {}) => ({runId: 'mock-run',llm: { provider: 'mock', model: null },}));-vi.mock('../services/universeBuilderPromote.js', async () => {+vi.mock('../../services/universeBuilderPromote.js', async () => {// Pass the real VALID_TARGET_KINDS through so the route's Zod enum// can't drift from the source-of-truth list (derived from BIBLE_FIELD).- const actual = await vi.importActual('../services/universeBuilderPromote.js');+ const actual = await vi.importActual('../../services/universeBuilderPromote.js');return {...actual,promoteVariationToCanon: (...args) => promoteVariationToCanonMock(...args),@@ -124,7 +124,7 @@ const autoSortOtherBucketsMock = vi.fn(async (universeId, body = {}) => ({llm: { provider: 'mock', model: body.model || null },runId: 'mock-autosort-run',}));-vi.mock('../services/universeBuilderAutoSort.js', () => ({+vi.mock('../../services/universeBuilderAutoSort.js', () => ({autoSortOtherBuckets: (...args) => autoSortOtherBucketsMock(...args),}));@@ -137,7 +137,7 @@ const expandUniverseCharacterMock = vi.fn(async (universeId, entryId) => ({runId: 'mock-expand-run',providerId: 'mock', model: 'mock',}));-vi.mock('../services/universeCharacterExpand.js', () => ({+vi.mock('../../services/universeCharacterExpand.js', () => ({expandUniverseCharacter: (...args) => expandUniverseCharacterMock(...args),}));@@ -147,14 +147,14 @@ vi.mock('../services/universeCharacterExpand.js', () => ({const renderCharacterReferenceSheetMock = vi.fn();const deleteCharacterReferenceSheetMock = vi.fn();const listSheetVariantsMock = vi.fn();-vi.mock('../services/universeCharacterSheet.js', () => ({+vi.mock('../../services/universeCharacterSheet.js', () => ({renderCharacterReferenceSheet: (...args) => renderCharacterReferenceSheetMock(...args),deleteCharacterReferenceSheet: (...args) => deleteCharacterReferenceSheetMock(...args),listSheetVariants: (...args) => listSheetVariantsMock(...args),}));// Stub the LLM expander so the route test doesn't shell out to a real provider.-vi.mock('../services/universeBuilderExpand.js', () => ({+vi.mock('../../services/universeBuilderExpand.js', () => ({expandWorldTemplate: vi.fn(async ({ starterPrompt }) => ({influences: {embrace: [`mocked style for ${starterPrompt}`],@@ -176,12 +176,12 @@ vi.mock('../services/universeBuilderExpand.js', () => ({}));// Skip provisioning real settings — we only exercise CRUD + expand here.-vi.mock('../services/settings.js', () => ({+vi.mock('../../services/settings.js', () => ({getSettings: vi.fn(async () => ({ imageGen: { mode: 'local', local: { pythonPath: '/usr/bin/python3' } } })),saveSettings: vi.fn(),}));-vi.mock('../services/mediaJobQueue/index.js', () => ({+vi.mock('../../services/mediaJobQueue/index.js', () => ({enqueueJob: vi.fn(({ params }) => ({ jobId: `job-${++uuidCounter}`, position: 1, status: 'queued', params })),}));@@ -206,7 +206,7 @@ const upsertUniverseRec = ({ universeId, universeName }) => {collectionsByUniverseId.set(universeId, rec);return rec;};-vi.mock('../services/mediaCollections.js', () => ({+vi.mock('../../services/mediaCollections.js', () => ({createCollection: vi.fn(async ({ name }) => mockCreateRec(name)),findOrCreateCollectionByName: vi.fn(async ({ name }) => {return collectionsByName.get(name.toLowerCase()) ?? mockCreateRec(name);@@ -232,7 +232,7 @@ vi.mock('../services/mediaCollections.js', () => ({NAME_MAX_LENGTH: 80,}));-vi.mock('../lib/mediaModels.js', () => ({+vi.mock('../../lib/mediaModels.js', () => ({getImageModels: () => [{ id: 'dev', label: 'mflux dev' }],isFlux2: () => false,isZImage: () => false,@@ -242,19 +242,19 @@ vi.mock('../lib/mediaModels.js', () => ({// Controllable listSeries for DELETE /:id → 409 UNIVERSE_HAS_LIVE_SERIES test.// universeBuilder.deleteUniverse() calls listSeries() to guard against live series.const listSeriesMock = vi.fn(async () => []);-vi.mock('../services/pipeline/series.js', async () => {- const actual = await vi.importActual('../services/pipeline/series.js');+vi.mock('../../services/pipeline/series.js', async () => {+ const actual = await vi.importActual('../../services/pipeline/series.js');return { ...actual, listSeries: (...args) => listSeriesMock(...args) };});// Controllable mergeFieldsWithAI for ai-resolve error contract tests.const mergeFieldsWithAIMock = vi.fn();-vi.mock('../services/recordMergeAI.js', async () => {- const actual = await vi.importActual('../services/recordMergeAI.js');+vi.mock('../../services/recordMergeAI.js', async () => {+ const actual = await vi.importActual('../../services/recordMergeAI.js');return { ...actual, mergeFieldsWithAI: (...args) => mergeFieldsWithAIMock(...args) };});-const universeBuilderRoutes = (await import('./universeBuilder.js')).default;+const universeBuilderRoutes = (await import('./index.js')).default;const buildApp = () => {const app = express();@@ -1159,7 +1159,7 @@ describe('universe-builder routes', () => {const b = await request(app).post('/api/universe-builder').send({ name: 'AI-B' });// All requested fields are empty on at least one side — service throws.- const { ServerError } = await import('../lib/errorHandler.js');+ const { ServerError } = await import('../../lib/errorHandler.js');mergeFieldsWithAIMock.mockRejectedValueOnce(new ServerError('No mergeable text fields', { status: 422, code: 'MERGE_AI_NO_MERGEABLE_FIELDS' }),);@@ -1176,7 +1176,7 @@ describe('universe-builder routes', () => {const a = await request(app).post('/api/universe-builder').send({ name: 'NoProvider-A', logline: 'x' });const b = await request(app).post('/api/universe-builder').send({ name: 'NoProvider-B', logline: 'y' });- const { ServerError } = await import('../lib/errorHandler.js');+ const { ServerError } = await import('../../lib/errorHandler.js');mergeFieldsWithAIMock.mockRejectedValueOnce(new ServerError('No AI provider available for AI-assisted merge', { status: 503, code: 'MERGE_AI_NO_PROVIDER' }),);@@ -1193,7 +1193,7 @@ describe('universe-builder routes', () => {const a = await request(app).post('/api/universe-builder').send({ name: 'BadJSON-A', logline: 'x' });const b = await request(app).post('/api/universe-builder').send({ name: 'BadJSON-B', logline: 'y' });- const { ServerError } = await import('../lib/errorHandler.js');+ const { ServerError } = await import('../../lib/errorHandler.js');mergeFieldsWithAIMock.mockRejectedValueOnce(new ServerError('LLM returned invalid JSON for AI merge', { status: 502, code: 'LLM_INVALID_JSON' }),);diff --git a/server/routes/universeBuilder/merge.js b/server/routes/universeBuilder/merge.jsnew file mode 100644index 0000000000..dce782e4e5--- /dev/null+++ b/server/routes/universeBuilder/merge.js@@ -0,0 +1,78 @@+/**+ * Duplicate resolution: the duplicate-group scan plus the merge preview /+ * commit / AI field-resolution trio.+ *+ * All static top-level paths — this router mounts BEFORE crud.js so `/:id`+ * can't swallow `/duplicates`.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../../lib/errorHandler.js';+import { validateRequest } from '../../lib/validation.js';+import * as svc from '../../services/universeBuilder.js';+import { findDuplicateUniverseGroups } from '../../services/duplicateDetection.js';+import { mergeUniverses } from '../../services/recordMerge.js';+import { mergeFieldsWithAI } from '../../services/recordMergeAI.js';+import { mapServiceError } from './shared.js';++const router = Router();++const mergeSchema = z.object({+ survivorId: z.string().trim().min(1).max(128),+ loserId: z.string().trim().min(1).max(128),+ fieldChoices: z.record(z.enum(['survivor', 'loser'])).optional().default({}),+ // Free-form per-field values that win over the survivor/loser binary —+ // populated by the AI-merge flow (a third unified option) and optionally+ // tweaked by the user before submit.+ fieldOverrides: z.record(z.string()).optional().default({}),+}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });++const mergeAIResolveSchema = z.object({+ survivorId: z.string().trim().min(1).max(128),+ loserId: z.string().trim().min(1).max(128),+ fields: z.array(z.string().trim().min(1).max(64)).min(1).max(20),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+}).refine((b) => b.survivorId !== b.loserId, { message: 'survivor and loser must differ' });++router.get('/duplicates', asyncHandler(async (_req, res) => {+ res.json({ groups: await findDuplicateUniverseGroups() });+}));++router.post('/merge/preview', asyncHandler(async (req, res) => {+ const body = validateRequest(mergeSchema, req.body ?? {});+ const preview = await mergeUniverses(body.survivorId, body.loserId, body.fieldChoices, { dryRun: true, fieldOverrides: body.fieldOverrides })+ .catch((err) => { throw mapServiceError(err); });+ res.json(preview);+}));++router.post('/merge', asyncHandler(async (req, res) => {+ const body = validateRequest(mergeSchema, req.body ?? {});+ const result = await mergeUniverses(body.survivorId, body.loserId, body.fieldChoices, { fieldOverrides: body.fieldOverrides })+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Ask the configured AI provider to merge specific conflicting text fields+// into a single unified value per field. Returns `{ merged, skipped, llm, runId }`+// — the client applies `merged` as `fieldOverrides` on the subsequent+// /merge or /merge/preview call. No record state is mutated here.+router.post('/merge/ai-resolve', asyncHandler(async (req, res) => {+ const body = validateRequest(mergeAIResolveSchema, req.body ?? {});+ const [survivor, loser] = await Promise.all([+ svc.getUniverse(body.survivorId).catch((err) => { throw mapServiceError(err); }),+ svc.getUniverse(body.loserId).catch((err) => { throw mapServiceError(err); }),+ ]);+ const result = await mergeFieldsWithAI({+ kind: 'universe',+ survivor,+ loser,+ fields: body.fields,+ providerId: body.providerId,+ model: body.model,+ });+ res.json(result);+}));++export default router;diff --git a/server/routes/universeBuilder/referenceSheets.js b/server/routes/universeBuilder/referenceSheets.jsnew file mode 100644index 0000000000..51fe03dc34--- /dev/null+++ b/server/routes/universeBuilder/referenceSheets.js@@ -0,0 +1,63 @@+/**+ * Character reference sheets: the variant catalog plus render/delete of a+ * single character's sheet.+ *+ * `/reference-sheet-variants` is a static top-level path — this router mounts+ * BEFORE crud.js so `/:id` can't swallow it.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../../lib/errorHandler.js';+import { validateRequest } from '../../lib/validation.js';+import {+ renderCharacterReferenceSheet,+ deleteCharacterReferenceSheet,+ listSheetVariants,+} from '../../services/universeCharacterSheet.js';+import { mapServiceError } from './shared.js';++const router = Router();++// Static-path GETs must register BEFORE `/:id` so they aren't swallowed by+// the parametric route. The catalog lists every registered reference-sheet+// variant — the client renders one row per entry in CharacterReferenceSheetPanel.+router.get('/reference-sheet-variants', asyncHandler(async (_req, res) => {+ res.json({ variants: listSheetVariants() });+}));++// Generate one of the character reference-sheet variants from a structured+// TEXT prompt — no init image required, so it works across codex / local+// backends. The `variant` field selects which prompt-builder + storage slot+// the render targets (defaults to 'standard' = illustrated turnaround).+// Returns immediately with `{ jobId, generationId, variant }`; client+// subscribes to SSE for progress, and the server-side completion handler+// stamps the variant's pointer on success.+const renderReferenceSheetSchema = z.object({+ variant: z.string().trim().min(1).max(48).optional(),+ overridePrompt: z.string().trim().max(8000).optional(),+ overrideNegativePrompt: z.string().trim().max(2000).optional(),+ modelId: z.string().trim().max(64).optional(),+});+router.post('/:id/characters/:entryId/render-reference-sheet', asyncHandler(async (req, res) => {+ const options = validateRequest(renderReferenceSheetSchema, req.body ?? {});+ const result = await renderCharacterReferenceSheet(req.params.id, req.params.entryId, options)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Delete a character's reference sheet — unlinks the PNG from+// `data/image-refs/` and nulls the variant's pointer on every matching+// character so the UI clears reactively without a refetch. `variant` is+// passed via query string (DELETE bodies are awkward across HTTP clients).+const deleteReferenceSheetQuerySchema = z.object({+ variant: z.string().trim().min(1).max(48).optional(),+});+router.delete('/:id/characters/:entryId/reference-sheet', asyncHandler(async (req, res) => {+ const opts = validateRequest(deleteReferenceSheetQuerySchema, req.query ?? {});+ const result = await deleteCharacterReferenceSheet(req.params.id, req.params.entryId, opts)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++export default router;diff --git a/server/routes/universeBuilder/render.js b/server/routes/universeBuilder/render.jsnew file mode 100644index 0000000000..fd715ab6f4--- /dev/null+++ b/server/routes/universeBuilder/render.js@@ -0,0 +1,117 @@+/**+ * Batch render — enqueue image-gen jobs for a universe's variations,+ * composite sheets, and/or canon entries.+ *+ * Scoped under `/:id`, so mount order relative to crud.js doesn't matter.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../../lib/errorHandler.js';+import { validateRequest, cloudModelIdString } from '../../lib/validation.js';+import { RECORD_RENDER_MODEL_MAX } from '../../lib/renderTargets.js';+import { BIBLE_LIMITS } from '../../lib/storyBible.js';+import * as svc from '../../services/universeBuilder.js';+import { IMAGE_GEN_MODES } from '../../services/imageGen/modes.js';+import { renderUniverseJobs } from '../../services/universeBuilderRender.js';+import { mapServiceError } from './shared.js';++const router = Router();++// `selection` per category: 'all' or array of variation labels.+const selectionValueSchema = z.union([z.literal('all'), z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX)).max(svc.VARIATIONS_PER_CATEGORY_MAX)]);+const selectionSchema = z.record(+ z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),+ selectionValueSchema,+).refine((selection) => Object.keys(selection).length <= svc.WORLD_CATEGORY_COUNT_MAX, {+ message: `selection cannot exceed ${svc.WORLD_CATEGORY_COUNT_MAX} buckets`,+});++// `canonSelection` per trunk: 'all' or array of canon-entry names (case-insensitive).+// Settings entries also match on `slugline` so a render queued from the Places+// tab can target an entry the user filed by slugline ("INT. FOUNDRY — DAY").+// Per-trunk cap mirrors the bible sanitizer (`ENTRIES_PER_BIBLE_MAX`) so this+// can't enqueue more entries than the server actually persists; per-string cap+// uses the looser of `NAME_MAX` / `SLUGLINE_MAX` so a places entry filed by+// slugline isn't rejected if those limits ever diverge (both 200 today).+const CANON_TRUNK_KEYS = ['characters', 'places', 'objects'];+const CANON_NEEDLE_MAX = Math.max(BIBLE_LIMITS.NAME_MAX, BIBLE_LIMITS.SLUGLINE_MAX);+const canonSelectionValueSchema = z.union([+ z.literal('all'),+ z.array(z.string().trim().min(1).max(CANON_NEEDLE_MAX)).max(BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX),+]);+const canonSelectionSchema = z.object(+ Object.fromEntries(CANON_TRUNK_KEYS.map((k) => [k, canonSelectionValueSchema.optional()])),+).strict();++const renderSchema = z.object({+ // Removed: callers that still send `collectionName` get an explicit 400+ // (see the .refine() below) instead of a confusing silent no-op. The+ // canonical "Universe: <name>" identity is owned by the universe and+ // enforced by the rename-lock — per-render overrides have no semantic+ // home in that model.+ collectionName: z.unknown().optional(),+ // Image-gen knobs — these mirror /api/image-gen/generate so the user can+ // pick mode/size/steps without bouncing to the Image page first.+ mode: z.enum(IMAGE_GEN_MODES).optional(),+ modelId: z.string().trim().max(64).optional(),+ // Per-batch cloud model override (#3231 Phase 3) — wins over the universe's+ // persisted imageModelId pin and the renderDefaults imageModel pin. Shares+ // the model-id charset guard so a bad id can't reach a CLI argv.+ cloudModel: cloudModelIdString('cloudModel must be a valid model id').max(RECORD_RENDER_MODEL_MAX).optional(),+ width: z.number().int().min(64).max(2048).optional(),+ height: z.number().int().min(64).max(2048).optional(),+ steps: z.number().int().min(1).max(150).optional(),+ cfgScale: z.number().min(0).max(30).optional(),+ guidance: z.number().min(0).max(30).optional(),+ quantize: z.enum(['3', '4', '5', '6', '8']).optional(),+ // Per-variation render count and per-category subset.+ promptMode: z.enum(['variations', 'sheets', 'canon', 'all']).optional().default('variations'),+ batchPerVariation: z.number().int().min(1).max(20).optional().default(1),+ selection: selectionSchema.optional(),+ sheetSelection: z.union([z.literal('all'), z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX)).max(svc.COMPOSITE_SHEETS_MAX)]).optional(),+ canonSelection: canonSelectionSchema.optional(),+ // Per-batch overrides surfaced through the full Image-Gen form. All optional;+ // empty values are treated as "use the universe's existing influences."+ // `seed` matches /api/image-gen/generate's contract (non-negative integer) —+ // local image gen coerces via Number(seed) and would yield NaN for arbitrary+ // strings, so reject early at the boundary.+ seed: z.number().int().min(0).optional(),+ negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),+ extraStyle: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional(),+ stylePresetId: z.string().trim().max(80).optional(),+ // Matches /api/image-gen/generate's LoRA contract: basenames only (server+ // resolves against PATHS.loras), max 8 stacked LoRAs per render. Keeping+ // the two routes in sync so a payload that's accepted here can also flow+ // through /api/image-gen/generate if we ever proxy it.+ loras: z.array(z.object({+ filename: z.string().trim().min(1).max(256).regex(/^[^/\\]+$/, 'lora filename must not contain path separators'),+ scale: z.number().min(0).max(2),+ name: z.string().trim().max(256).optional(),+ })).max(8).optional(),+}).refine((body) => body.collectionName === undefined, {+ message: 'collectionName is no longer supported — the linked collection follows the universe name automatically. Remove this field.',+ path: ['collectionName'],+});++router.post('/:id/render', asyncHandler(async (req, res) => {+ const body = validateRequest(renderSchema, req.body ?? {});+ // Legacy universes carry no variation/sheet ids on disk. sanitizeTemplate+ // mints fresh UUIDs on every read but readState() intentionally does not+ // persist them (race against concurrent writers). The render route needs+ // ids that are stable across the read→queue→completion lifecycle so the+ // collection hook can find the source entry by `entryRef.id`. Gate the+ // one-time no-op write on the raw-disk inspection: fully-migrated+ // universes skip the write so `updatedAt` doesn't bump on every render+ // (which would interfere with LWW sync + trigger spurious re-export).+ // Skip entirely for canon-only renders — canon entries already carry+ // stable ids (storyBible.js sanitizer), so the raw-disk read + write+ // would be pure overhead.+ if (body.promptMode !== 'canon' && await svc.needsEntryIdPersist(req.params.id)) {+ await svc.updateUniverse(req.params.id, () => ({})).catch((err) => { throw mapServiceError(err); });+ }+ const result = await renderUniverseJobs(req.params.id, body, mapServiceError);+ res.json(result);+}));++export default router;diff --git a/server/routes/universeBuilder/shared.js b/server/routes/universeBuilder/shared.jsnew file mode 100644index 0000000000..e33831dfe2--- /dev/null+++ b/server/routes/universeBuilder/shared.js@@ -0,0 +1,196 @@+/**+ * Shared plumbing for the universe-builder sub-routers: the service-error →+ * HTTP status map, the zod fragments that more than one router composes into+ * its own schema, and the two gallery/upload image resolvers the vision ++ * style-reference routes both need.+ */++import { z } from 'zod';+import { existsSync } from 'fs';+import { join } from 'path';+import { ServerError, createServiceErrorMapper } from '../../lib/errorHandler.js';+import { optionalBooleanMap } from '../../lib/validation.js';+import { BIBLE_KINDS } from '../../lib/storyBible.js';+import { sanitizeFilename, PATHS, resolveGalleryImage } from '../../lib/fileUtils.js';+import * as svc from '../../services/universeBuilder.js';+import { buildCascadeContext } from '../../services/recordMerge.js';++const SERVICE_ERROR_STATUS = {+ [svc.ERR_NOT_FOUND]: 404,+ [svc.ERR_VALIDATION]: 400,+ // Block-until-empty: deleting a universe with live series → 409 (the+ // lock-conflict idiom) so the client can show "move these N series first".+ [svc.ERR_HAS_LIVE_SERIES]: 409,+ // recordMerge validation (unresolved conflicts, bad ids).+ MERGE_VALIDATION: 400,+ // recordMerge cascade partially completed (a child re-point failed) → 409 so+ // the client can surface "merge incomplete, re-run to finish".+ MERGE_CASCADE_INCOMPLETE: 409,+};++// Propagate diagnostic context onto the response body via `context`: the+// blocking-series list for a delete-guard 409, or the survivor/loser ids ++// which children failed to re-point for an incomplete merge cascade.+export const mapServiceError = createServiceErrorMapper(SERVICE_ERROR_STATUS, (err) =>+ err?.blockingSeries ? { blockingSeries: err.blockingSeries } : buildCascadeContext(err),+);++// ---- shared zod fragments ----+// `id` is optional on input — the service-layer sanitizer mints one with a+// `var-`/`sheet-` prefix when absent. Existing non-empty ids are normalized+// on read/write (trimmed + capped to 80 chars) so renames + bucket-moves+// preserve the link to imageRefs[]; callers should treat the normalized+// form as the canonical id rather than the raw value they supplied.+export const entryIdField = z.string().trim().min(1).max(80).optional();+export const entryImageRefField = z.string().trim().min(1).max(svc.IMAGE_REF_FILENAME_MAX);+export const entryImageRefsField = z.array(entryImageRefField).max(svc.IMAGE_REFS_PER_ENTRY_MAX).optional();+export const variationSchema = z.object({+ id: entryIdField,+ label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),+ prompt: z.string().trim().min(1).max(svc.PROMPT_FRAGMENT_MAX),+ // Per-item lock — when true, expand preserves this variation across+ // re-runs instead of letting the LLM regenerate it.+ locked: z.boolean().optional(),+ // Render history (newest last). Server stamps this via the collection hook+ // when a render completes; clients echo it back on PATCH-the-whole-list flows+ // so the sanitizer can preserve it across rename/bucket-move.+ imageRefs: entryImageRefsField,+});+export const compositeSheetSchema = z.object({+ id: entryIdField,+ kind: z.enum(svc.COMPOSITE_SHEET_KINDS).optional(),+ label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),+ prompt: z.string().trim().min(1).max(svc.COMPOSITE_PROMPT_MAX),+ // Per-item lock for composite boards (same semantics as variations).+ locked: z.boolean().optional(),+ imageRefs: entryImageRefsField,+});+const categoryShape = z.object({+ // Tags this bucket to one of the 3 canon trunks (or 'other' as the+ // un-classified sink). Optional on input — sanitizeCategories resolves a+ // sensible default from the built-in map (landscapes→places etc.) or+ // falls to 'other'. Added in schema v4.+ kind: z.enum(svc.CATEGORY_KINDS).optional(),+ variations: z.array(variationSchema).max(svc.VARIATIONS_PER_CATEGORY_MAX),+});+export const categoriesSchema = z.record(+ z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),+ categoryShape,+).refine((categories) => Object.keys(categories).length <= svc.WORLD_CATEGORY_COUNT_MAX, {+ message: `categories cannot exceed ${svc.WORLD_CATEGORY_COUNT_MAX} buckets`,+});++// `locked` is a sparse map of `{ field: true }` for the LOCKABLE_FIELDS list.+// `false` is treated the same as omitted — only `true` records a lock so the+// stored shape stays minimal and additive. Accept legacy `influences` key as+// an alias for both `influencesEmbrace` and `influencesAvoid` so older clients+// PATCHing a previously saved lock map still pass validation (sanitizeLocked+// rewrites it on read into the per-list keys).+export const lockedSchema = z.object({+ ...optionalBooleanMap(svc.LOCKABLE_FIELDS),+ influences: z.boolean().optional(),+}).strict();++const influenceEntrySchema = z.string().trim().min(1).max(svc.INFLUENCE_ENTRY_MAX);+export const influencesSchema = z.object({+ embrace: z.array(influenceEntrySchema).max(svc.INFLUENCES_PER_LIST_MAX).optional().default([]),+ avoid: z.array(influenceEntrySchema).max(svc.INFLUENCES_PER_LIST_MAX).optional().default([]),+}).strict();+export const styleReferenceSchema = z.object({+ id: entryIdField,+ title: z.string().trim().min(1).max(svc.STYLE_REFERENCE_TITLE_MAX),+ prompt: z.string().trim().min(1).max(svc.STYLE_REFERENCE_PROMPT_MAX),+ imageRefs: z.array(entryImageRefField).min(1).max(1),+ createdAt: z.string().trim().min(1).max(64).optional(),+}).strict();+export const styleReferencesField = z.array(styleReferenceSchema).max(svc.STYLE_REFERENCES_MAX).optional();++// Legacy prose prompts: the v2 universe template carried `stylePrompt` /+// `negativePrompt` as comma-separated prose strings; v3 collapses them into+// the chip-based `influences` lists. Accepting them here (as optional) lets+// a stale client (or an importer of a v2 share-bucket payload) hand us the+// legacy shape — the service-layer sanitizer splits + merges the tokens into+// influences. New callers should send `influences` directly.+export const legacyStylePromptField = z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional();+export const legacyNegativePromptField = z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional();++// Canon arrays go through `sanitizeBibleList` in the service layer where+// each entry is validated structurally — accept them loosely here so+// patch-the-whole-list flows (e.g. inline canon edits, render-ref hooks)+// don't fail Zod for legitimately rich shapes. Cap at the bible-wide entry+// limit so a malicious payload can't blow up memory.+// Hard cap mirrors BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX (200) with headroom+// — sanitizer truncates anyway, so this just protects the JSON-parse layer.+export const canonArrayField = z.array(z.record(z.unknown())).max(500).optional();++// Canon-entry `kind` path param, shared by the lock toggles (canon.js) and the+// corrective-vision pair (vision.js).+export const lockParamsSchema = z.object({+ kind: z.enum(BIBLE_KINDS),+});++// A reference image the vision routes accept from one of two sources:+// - 'upload' → a filename the client already POSTed to /api/screenshots+// (lives under data/screenshots; passed to the runner as a bare+// filename, which it resolves under that dir).+// - 'gallery' → a generated-gallery filename under data/images; resolved here+// to an ABSOLUTE path, which the runner's loadImageAsBase64+// accepts as-is (it only prefixes data/screenshots for bare+// names).+export const imageSourceSchema = z.object({+ source: z.enum(['upload', 'gallery']),+ filename: z.string().trim().min(1).max(300),+});++// Resolve a mixed `[{ source, filename }]` list into runner-loadable paths,+// failing loudly per the source's rules. The runner silently DROPS a missing+// image and still sends the text prompt, so a stale/never-uploaded reference+// would let the model describe with fewer references — or hallucinate from the+// prompt alone if all are missing. Reject up front instead.+export function resolveImageSources(images) {+ return images.map(({ source, filename }) => {+ if (source === 'gallery') {+ const abs = resolveGalleryImage(filename);+ if (!abs) {+ throw new ServerError(`Gallery image not found: ${filename} — pick another and retry.`, { status: 400, code: 'GALLERY_IMAGE_NOT_FOUND' });+ }+ return abs;+ }+ // 'upload' — the upload route already sanitizes on write, so a legitimately+ // uploaded name round-trips unchanged. A hand-crafted name with path+ // components is rejected outright (a 400, not a silent rewrite to a name+ // that won't exist), keeping a traversal attempt distinguishable from a+ // deleted/never-uploaded file.+ const safe = sanitizeFilename(filename);+ if (safe !== filename) {+ throw new ServerError(`Invalid screenshot filename: ${filename}`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ if (!existsSync(join(PATHS.screenshots, safe))) {+ throw new ServerError(`Screenshot not found: ${safe} — re-upload the image and retry.`, { status: 400, code: 'SCREENSHOT_NOT_FOUND' });+ }+ return safe;+ });+}++// Resolve a SINGLE gallery filename to an absolute path, rejecting a+// traversal attempt or an unknown file up front. Shared by the two+// single-gallery-image vision routes (`analyze-style-reference`,+// `correct-from-image`) that resolve one reference image rather than the+// mixed upload/gallery list `resolveImageSources` handles.+export function resolveGalleryImageOrThrow(filename) {+ const imageFilename = sanitizeFilename(filename);+ if (imageFilename !== filename) {+ throw new ServerError(`Invalid gallery image filename: ${filename}`, {+ status: 400,+ code: 'VALIDATION_ERROR',+ });+ }+ const imagePath = resolveGalleryImage(imageFilename);+ if (!imagePath) {+ throw new ServerError(`Gallery image not found: ${imageFilename} — upload it again and retry.`, {+ status: 400,+ code: 'GALLERY_IMAGE_NOT_FOUND',+ });+ }+ return { imageFilename, imagePath };+}diff --git a/server/routes/universeBuilder/styleReferences.js b/server/routes/universeBuilder/styleReferences.jsnew file mode 100644index 0000000000..1c4efcdb3e--- /dev/null+++ b/server/routes/universeBuilder/styleReferences.js@@ -0,0 +1,91 @@+/**+ * Art style references (#3109): the stateless analyze-then-review step plus+ * the add/remove delta endpoints.+ *+ * `/analyze-style-reference` is a static top-level path — this router mounts+ * BEFORE crud.js so `/:id` can't swallow it.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../../lib/errorHandler.js';+import { validateRequest } from '../../lib/validation.js';+import * as svc from '../../services/universeBuilder.js';+import { analyzeUniverseStyleReference } from '../../services/universeStyleReference.js';+import {+ mapServiceError,+ entryIdField,+ lockedSchema,+ influencesSchema,+ styleReferenceSchema,+ resolveGalleryImageOrThrow,+} from './shared.js';++const router = Router();++const analyzeStyleReferenceSchema = z.object({+ image: z.string().trim().min(1).max(300),+ title: z.string().trim().max(svc.STYLE_REFERENCE_TITLE_MAX).optional(),+ prompt: z.string().trim().max(svc.STYLE_REFERENCE_PROMPT_MAX).optional(),+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),+ influences: influencesSchema.optional().default({ embrace: [], avoid: [] }),+ locked: lockedSchema.optional().default({}),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});++// Stateless review step: analyze the image and return a proposed record plus a+// diff. Persistence only happens after the user chooses reference-only or+// reference-and-adopt in the client.+router.post('/analyze-style-reference', asyncHandler(async (req, res) => {+ const body = validateRequest(analyzeStyleReferenceSchema, req.body ?? {});+ const { imageFilename, imagePath } = resolveGalleryImageOrThrow(body.image);+ res.json(await analyzeUniverseStyleReference({+ ...body,+ imagePath,+ imageFilename,+ }));+}));++// Add/remove one reference at a time instead of PATCHing the whole array; see+// `addStyleReference` in services/universeBuilder/crud.js for the rationale.+// The wholesale-replace `{ styleReferences: [...] }` field on PATCH /:id stays+// accepted (older clients, peer imports, the sharing importer).+const addStyleReferenceSchema = z.object({+ // `id` is required here (unlike the wholesale-replace field, where the+ // sanitizer mints one): the id is what makes a re-sent add idempotent+ // server-side, and /analyze-style-reference always returns one. `required`+ // only drops the `.optional()` — the trim/length rules stay defined once, on+ // the shared `entryIdField`.+ reference: styleReferenceSchema.required({ id: true }),+ // Present when the user chose "Adopt style + add" — written in the SAME+ // queued write as the reference so the pair can't half-land. Both fields+ // default, so `adopt: {}` reads as "adopt an empty guide" (an explicit clear)+ // instead of reaching the service as `undefined` and clearing influences by+ // accident — matching analyzeStyleReferenceSchema's choice for the same pair.+ adopt: z.object({+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),+ influences: influencesSchema.optional().default({ embrace: [], avoid: [] }),+ }).optional(),+});+router.post('/:id/style-references', asyncHandler(async (req, res) => {+ const body = validateRequest(addStyleReferenceSchema, req.body ?? {});+ const w = await svc.addStyleReference(req.params.id, body.reference, { adopt: body.adopt })+ .catch((err) => { throw mapServiceError(err); });+ res.json(w);+}));++// The id is only ever compared against stored reference ids (never used as a+// path/SQL operand), but validate it anyway so an absurdly long param is a 400+// here rather than a silent no-op deeper in.+const removeStyleReferenceParamsSchema = z.object({+ referenceId: entryIdField.unwrap(),+});+router.delete('/:id/style-references/:referenceId', asyncHandler(async (req, res) => {+ const { referenceId } = validateRequest(removeStyleReferenceParamsSchema, req.params);+ const w = await svc.removeStyleReference(req.params.id, referenceId)+ .catch((err) => { throw mapServiceError(err); });+ res.json(w);+}));++export default router;diff --git a/server/routes/universeBuilder/vision.js b/server/routes/universeBuilder/vision.jsnew file mode 100644index 0000000000..4b5e7c7a1e--- /dev/null+++ b/server/routes/universeBuilder/vision.js@@ -0,0 +1,129 @@+/**+ * Vision-driven description of canon entries: describe-from-images (blind+ * prose from reference images), expand-from-images (fill still-blank+ * structured fields), and the corrective correct-from-image →+ * apply-image-correction review pair.+ *+ * `/describe-from-images` is a static top-level path — this router mounts+ * BEFORE crud.js so `/:id` can't swallow it.+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler } from '../../lib/errorHandler.js';+import { validateRequest } from '../../lib/validation.js';+import { BIBLE_LIMITS } from '../../lib/storyBible.js';+import * as canonSvc from '../../services/universeCanon.js';+import { describeEntityFromImages, correctEntityFromImage, VISION_KINDS, VISION_MAX_IMAGES } from '../../services/universeVisionDescribe.js';+import { expandEntityFromImages, VISION_EXPAND_MAX_IMAGES } from '../../services/universeVisionExpand.js';+import {+ mapServiceError,+ imageSourceSchema,+ lockParamsSchema,+ resolveImageSources,+ resolveGalleryImageOrThrow,+} from './shared.js';++const router = Router();++// Vision-to-prose: turn one or more reference images of a character/place/+// object into an image-gen-ready prose description (multiple images → the+// shared/common description). Stateless — the client decides which entry+// field to write the result into. Images come from upload OR the gallery (see+// resolveImageSources). Keep ahead of `/:id` so "describe-from-images" isn't+// parsed as a universe id.+const describeFromImagesSchema = z.object({+ kind: z.enum(VISION_KINDS),+ name: z.string().trim().max(BIBLE_LIMITS.NAME_MAX).optional(),+ context: z.string().trim().max(2000).optional(),+ images: z.array(imageSourceSchema).min(1).max(VISION_MAX_IMAGES),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});+router.post('/describe-from-images', asyncHandler(async (req, res) => {+ const body = validateRequest(describeFromImagesSchema, req.body ?? {});+ const screenshots = resolveImageSources(body.images);+ const result = await describeEntityFromImages({ ...body, screenshots });+ res.json(result);+}));++// Vision-driven expand — a vision model reads reference image(s) (upload or+// gallery) and PROPOSES values for the character's still-blank structured+// fields (palette/visual notes/expressions/...). Review-only: returns the+// proposed `{ field: value }` map; the client applies the kept/edited values+// via the normal entry-PATCH path. No-clobber, characters-only, locked+// characters return `{ locked: true }` with no LLM call.+const expandFromImagesSchema = z.object({+ name: z.string().trim().max(BIBLE_LIMITS.NAME_MAX).optional(),+ context: z.string().trim().max(2000).optional(),+ images: z.array(imageSourceSchema).min(1).max(VISION_EXPAND_MAX_IMAGES),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});+router.post('/:id/characters/:entryId/expand-from-images', asyncHandler(async (req, res) => {+ const body = validateRequest(expandFromImagesSchema, req.body ?? {});+ const screenshots = resolveImageSources(body.images);+ const result = await expandEntityFromImages({+ universeId: req.params.id,+ entryId: req.params.entryId,+ name: body.name,+ context: body.context,+ screenshots,+ providerId: body.providerId,+ model: body.model,+ }).catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Corrective vision analysis for ONE canon entry (character/place/object):+// given the entry's CURRENT descriptor text as context, a vision model+// proposes a CORRECTED replacement — unlike expand-from-images (fills only+// still-blank fields) or describe-from-images (describes blind), this+// overwrites existing text where the image contradicts it. Review-only:+// returns the proposed text for the client to show alongside the current+// value; `apply-image-correction` (below) persists it.+const correctFromImageSchema = z.object({+ image: z.string().trim().min(1).max(300),+ name: z.string().trim().max(BIBLE_LIMITS.NAME_MAX).optional(),+ context: z.string().trim().max(2000).optional(),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});+router.post('/:id/canon/:kind/:entryId/correct-from-image', asyncHandler(async (req, res) => {+ const { kind } = validateRequest(lockParamsSchema, req.params);+ const body = validateRequest(correctFromImageSchema, req.body ?? {});+ const { imageFilename, imagePath } = resolveGalleryImageOrThrow(body.image);+ const result = await correctEntityFromImage({+ universeId: req.params.id,+ entryId: req.params.entryId,+ kind,+ name: body.name,+ context: body.context,+ screenshot: imagePath,+ providerId: body.providerId,+ model: body.model,+ }).catch((err) => { throw mapServiceError(err); });+ res.json({ ...result, imageFilename });+}));++// Persist a reviewed corrective-image analysis: overwrites the entry's+// descriptor field with the reviewed text AND pins the analyzed image as the+// entry's `primaryImageRef` — assigning it as that noun's style/reference+// image so subsequent renders (client-side i2i seeding) use it.+// Cap at the largest per-kind descriptor limit (canonSvc.DESC_LIMIT) rather+// than the unrelated NOTES_MAX — applyCanonImageCorrection silently trims to+// the per-kind limit before persisting, so a looser schema cap here would let+// a request pass validation only to have its tail silently dropped on write.+const applyImageCorrectionSchema = z.object({+ description: z.string().trim().min(1).max(Math.max(...Object.values(canonSvc.DESC_LIMIT))),+ imageFilename: z.string().trim().min(1).max(300),+});+router.post('/:id/canon/:kind/:entryId/apply-image-correction', asyncHandler(async (req, res) => {+ const { kind } = validateRequest(lockParamsSchema, req.params);+ const body = validateRequest(applyImageCorrectionSchema, req.body ?? {});+ const result = await canonSvc.applyCanonImageCorrection(req.params.id, kind, req.params.entryId, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++export default router;diff --git a/server/services/creative/tools/universe.js b/server/services/creative/tools/universe.jsindex 03eb1d4d55..0226a0e3c8 100644--- a/server/services/creative/tools/universe.js+++ b/server/services/creative/tools/universe.js@@ -66,7 +66,7 @@ export const UNIVERSE_TOOLS = [},required: ['universeId'],},- // Mirror the render route's preflight (routes/universeBuilder.js): for a+ // Mirror the render route's preflight (routes/universeBuilder/render.js): for a// non-canon render of a legacy universe, persist the transient// variation/sheet entry ids first (a no-op `updateUniverse` write) so they// stay stable across enqueue → completion and the filename hook can attachdiff --git a/server/services/universeBuilderRender.js b/server/services/universeBuilderRender.jsindex 752bd07e66..aa108179ab 100644--- a/server/services/universeBuilderRender.js+++ b/server/services/universeBuilderRender.js@@ -1,7 +1,7 @@/*** Universe Builder Render Orchestration*- * Extracted from routes/universeBuilder.js POST /:id/render.+ * Extracted from routes/universeBuilder/render.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.