Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

breaking: rename World Builder → Universe Builder, add canon-entity foundation

[._.]/ Adam Eivybe9035642a9f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 521b0f8330..0e60ab5b52 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -161,6 +161,38 @@
## Changed
+- **BREAKING — World Builder is now Universe Builder.** A universe can contain
+ many worlds, and stories within the same universe can share canon (characters,
+ places, things) across multiple series — Marvel-style crossovers. This is a
+ pure rename pass; behavior is unchanged. Files (`worldBuilder*.js` →
+ `universeBuilder*.js`, `WorldBuilder.jsx` → `UniverseBuilder.jsx`), routes
+ (`/api/world-builder/*` → `/api/universe-builder/*`), client routes
+ (`/world-builder` → `/universe-builder`), fields (`series.worldId` →
+ `series.universeId`), top-level data key (`worlds: []` → `universes: []` in
+ `data/universe-builder.json`), function names (`getWorld` → `getUniverse`,
+ etc.), constants (`WORLD_ID_MAX` → `UNIVERSE_ID_MAX`), and the
+ `params.worldRun` mediaJobQueue tag (148 existing job records migrated).
+ Back-compat: the `⌘K` palette + voice agent keep `'world'`/`'world-builder'`
+ as aliases for the renamed nav entry, so muscle memory still resolves.
+ Sets up the next phase: lift canon entities (characters/places/objects)
+ from per-series bibles to the universe so multiple series can share them.
+
+- **Pipeline character — "AI: differentiate" button.** Per-character refine on
+ the Nouns page (Universe Builder side coming). Sends the target plus every
+ peer's `physicalDescription` to a new `pipeline-character-refine` prompt
+ and rewrites only the target's `physicalDescription` so no two characters
+ collide on ethnicity, age, hair, silhouette, or signature wardrobe.
+ Preserves evidence + firstAppearance.
+
+- **Character extraction prompt — opinionated commits, not gaps.**
+ `writers-room-characters.md` now requires every renderable axis (ethnicity,
+ age decade, build, hair color/length/texture/style, eye color, distinguishing
+ facial features, signature wardrobe with palette + era, posture). When prose
+ is silent, the LLM is told to COMMIT to a specific choice that differentiates
+ the character from the rest of the cast and log the committed axes in
+ `missingFromProse[]`. The old "do not invent" rule was producing
+ visually-interchangeable characters when prose was sparse on visual specifics.
+
- **Sidebar Pipeline submenu — all series, not 10 recent issues.** The
Create → Pipeline grandchildren now list every series alphabetically
(links to `/pipeline/series/:id`) instead of the 10 most recently updated
diff --git a/CLAUDE.md b/CLAUDE.md
index f2c68ac972..b53365c059 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -153,7 +153,7 @@ When working **directly in the Claude Code TUI** with the user driving, edit the
console.error(`❌ Failed to connect: ${err.message}`);
```
- **LLM response merging — distinguish absent vs intentionally empty.** When merging an LLM response with existing state, "key absent" must preserve the original while "key present with empty value" must apply the intentional clear. Don't use `.length` truthiness as the signal — that conflates the two cases and silently restores values the user (or LLM) just cleared. Conventions:
- - Strings: treat `null`/`undefined` as absent, `""` as a clear. Server helpers like `worldBuilderExpand.trimField` should return `null` for non-strings, not `""`.
+ - Strings: treat `null`/`undefined` as absent, `""` as a clear. Server helpers like `universeBuilderExpand.trimField` should return `null` for non-strings, not `""`.
- Arrays/objects: gate on `Array.isArray(parsed?.field)` / `typeof parsed?.field === 'object'` before deciding to fall back to the original.
- Keep server-side merges and the client's `pick` helpers mirrored — a one-sided change breaks the round-trip.
- **Schema parity when adding fields.** When you add a field to a sanitizer, `createXxx`, or a payload shape, update the corresponding Zod schema (`server/lib/aiToolkit/validation.js` for toolkit shapes, `server/lib/validation.js` for PortOS routes) in the same change. Wire validation into POST and PUT (PUT can use `schema.partial()`); the PortOS convention is *all* inputs validated. Tolerate UI sentinels (`endpoint: ''` for CLI providers) with `z.preprocess(v => v === '' ? undefined : v, …)`. When a service migrates legacy keys on read, the schema must still accept the legacy shape so older clients don't 400 before the migration runs.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 92969087d2..419f191ac1 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -51,7 +51,7 @@ const MediaCollections = lazyWithReload(() => import('./pages/MediaCollections')
const MediaCollectionDetail = lazyWithReload(() => import('./pages/MediaCollectionDetail'));
const MediaModels = lazyWithReload(() => import('./pages/MediaModels'));
const Loras = lazyWithReload(() => import('./pages/Loras'));
-const WorldBuilder = lazyWithReload(() => import('./pages/WorldBuilder'));
+const UniverseBuilder = lazyWithReload(() => import('./pages/UniverseBuilder'));
const VideoTimeline = lazyWithReload(() => import('./pages/VideoTimeline'));
const VideoTimelineEditor = lazyWithReload(() => import('./pages/VideoTimelineEditor'));
const CreativeDirector = lazyWithReload(() => import('./pages/CreativeDirector'));
@@ -206,8 +206,8 @@ export default function App() {
<Route path="timeline/:projectId" element={<VideoTimelineEditor />} />
<Route path="models" element={<MediaModels />} />
<Route path="loras" element={<Loras />} />
- <Route path="world-builder" element={<WorldBuilder />} />
- <Route path="world-builder/:worldId" element={<WorldBuilder />} />
+ <Route path="universe-builder" element={<UniverseBuilder />} />
+ <Route path="universe-builder/:universeId" element={<UniverseBuilder />} />
</Route>
<Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} />
<Route path="video-gen" element={<RedirectWithSearch to="/media/video" />} />
@@ -216,8 +216,8 @@ export default function App() {
<Route path="wiki" element={<Navigate to="/wiki/overview" replace />} />
<Route path="wiki/:tab" element={<Wiki />} />
<Route path="rapid-reader" element={<RapidReaderPage />} />
- <Route path="world-builder" element={<WorldBuilder />} />
- <Route path="world-builder/:worldId" element={<WorldBuilder />} />
+ <Route path="universe-builder" element={<UniverseBuilder />} />
+ <Route path="universe-builder/:universeId" element={<UniverseBuilder />} />
<Route path="writers-room" element={<WritersRoom />} />
<Route path="pipeline" element={<Pipeline />} />
<Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 56953954ea..86a222c0d4 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -194,7 +194,7 @@ const navItems = [
children: [
{ to: '/media', label: 'Media Gen', icon: Layers },
{ to: '/pipeline', label: 'Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },
- { to: '/world-builder', label: 'World Builder', icon: Globe },
+ { to: '/universe-builder', label: 'Universe Builder', icon: Globe },
{ to: '/writers-room', label: 'Writers Room', icon: NotebookPen }
]
},
@@ -979,7 +979,7 @@ export default function Layout() {
location.pathname === '/review' ||
location.pathname.startsWith('/settings') ||
location.pathname.startsWith('/wiki') ||
- location.pathname.startsWith('/world-builder') ||
+ location.pathname.startsWith('/universe-builder') ||
location.pathname.startsWith('/writers-room') ||
location.pathname.startsWith('/agents') ||
location.pathname === '/shell' ||
diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsx
index 20a42aec72..7fba115520 100644
--- a/client/src/components/imageGen/ImageGenControls.jsx
+++ b/client/src/components/imageGen/ImageGenControls.jsx
@@ -1,6 +1,6 @@
// Shared image-gen knob grid. Renders model + resolution + steps + guidance/CFG +
// quantize + (optional) seed in a 2- or 3-column grid that matches the standalone
-// Image Gen page. Used by ImageGen and World Builder batch render so the form
+// Image Gen page. Used by ImageGen and Universe Builder batch render so the form
// looks and behaves the same in both places.
//
// Props are intentionally per-field (value + onChange pairs) rather than a single
diff --git a/client/src/components/pipeline/MediaJobThumb.jsx b/client/src/components/pipeline/MediaJobThumb.jsx
index be7dd68d80..4d6606277c 100644
--- a/client/src/components/pipeline/MediaJobThumb.jsx
+++ b/client/src/components/pipeline/MediaJobThumb.jsx
@@ -16,7 +16,7 @@ import useMediaJobProgress from '../../hooks/useMediaJobProgress';
* does — flips to a "missing" badge with a Retry button (re-arms the
* <video>/<img> via a cache-busting key) when the file 404s.
*/
-export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', kind = 'image' }) {
+export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', kind = 'image', onPreview = null }) {
const { status, progress, step, totalSteps, currentImage, filename, error } =
useMediaJobProgress(jobId, { kind });
// Local missing-media state. Reset when jobId changes so a fresh render
@@ -27,15 +27,22 @@ export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', ki
if (!jobId) return null;
- const dims = size === 'lg'
- ? 'w-32 h-32'
+ // `fill` fills the parent container's width with the image's natural
+ // aspect (object-contain). State-only branches (spinner, missing, failed)
+ // keep a fixed footprint so the row doesn't collapse mid-render.
+ const isFill = size === 'fill';
+ const dims = isFill
+ ? 'w-full'
+ : size === 'lg' ? 'w-32 h-32'
: size === 'md' ? 'w-24 h-24' : 'w-16 h-16';
+ const stateDims = isFill ? 'w-full min-h-[200px]' : dims;
+ const imgFit = isFill ? 'w-full h-auto max-h-[640px] object-contain' : 'w-full h-full object-cover';
if (missing) {
return (
<div
title="Media file missing (deleted from disk)"
- className={`${dims} bg-port-bg rounded border border-port-border flex flex-col items-center justify-center gap-1 text-[10px] text-port-text-muted`}
+ className={`${stateDims} bg-port-bg rounded border border-port-border flex flex-col items-center justify-center gap-1 text-[10px] text-port-text-muted`}
>
<span>missing</span>
<button
@@ -62,27 +69,45 @@ export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', ki
playsInline
aria-label={label}
onError={() => setMissing(true)}
- className={`${dims} object-cover bg-port-bg rounded border border-port-border`}
+ className={isFill
+ ? 'w-full h-auto max-h-[640px] bg-port-bg rounded border border-port-border'
+ : `${dims} object-cover bg-port-bg rounded border border-port-border`}
/>
);
}
if (status === 'completed' && filename) {
+ const imgEl = (
+ <img
+ key={attempt}
+ src={`/data/images/${filename}${cacheBust}`}
+ alt={label}
+ onError={() => setMissing(true)}
+ className={imgFit}
+ loading="lazy"
+ />
+ );
+ const wrapperClass = `block ${dims} bg-port-bg rounded overflow-hidden border border-port-border hover:border-port-accent/50 transition-colors`;
+ if (onPreview) {
+ return (
+ <button
+ type="button"
+ onClick={() => onPreview(filename)}
+ title="Open preview"
+ className={`${wrapperClass} cursor-zoom-in p-0`}
+ >
+ {imgEl}
+ </button>
+ );
+ }
return (
<a
href={`/data/images/${filename}${cacheBust}`}
target="_blank"
rel="noopener noreferrer"
title="Open full image in a new tab"
- className={`block ${dims} bg-port-bg rounded overflow-hidden border border-port-border hover:border-port-accent/50 transition-colors`}
+ className={wrapperClass}
>
- <img
- key={attempt}
- src={`/data/images/${filename}${cacheBust}`}
- alt={label}
- onError={() => setMissing(true)}
- className="w-full h-full object-cover"
- loading="lazy"
- />
+ {imgEl}
</a>
);
}
@@ -94,7 +119,7 @@ export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', ki
return (
<div
title={error || 'Render failed'}
- className={`${dims} bg-port-bg rounded border border-port-error/40 flex flex-col items-center justify-center gap-1 text-[10px] text-port-error`}
+ className={`${stateDims} bg-port-bg rounded border border-port-error/40 flex flex-col items-center justify-center gap-1 text-[10px] text-port-error`}
>
<AlertCircle size={14} />
<span>failed</span>
@@ -109,7 +134,7 @@ export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', ki
return (
<div
title="Render canceled"
- className={`${dims} bg-port-bg rounded border border-port-border flex flex-col items-center justify-center gap-1 text-[10px] text-port-text-muted`}
+ className={`${stateDims} bg-port-bg rounded border border-port-border flex flex-col items-center justify-center gap-1 text-[10px] text-port-text-muted`}
>
<Ban size={14} />
<span>canceled</span>
@@ -122,15 +147,15 @@ export default function MediaJobThumb({ jobId, label = 'Render', size = 'sm', ki
// freshly-decoded latent frame from the diffusion loop.
const pct = totalSteps ? Math.round((step / totalSteps) * 100) : Math.round((progress || 0) * 100);
return (
- <div className={`relative ${dims} bg-port-bg rounded overflow-hidden border border-port-border`}>
+ <div className={`relative ${isFill ? 'w-full min-h-[200px]' : dims} bg-port-bg rounded overflow-hidden border border-port-border`}>
{currentImage ? (
<img
src={`data:image/png;base64,${currentImage}`}
alt={`${label} preview`}
- className="w-full h-full object-cover opacity-70"
+ className={`${imgFit} opacity-70`}
/>
) : (
- <div className="w-full h-full flex items-center justify-center">
+ <div className={`${isFill ? 'min-h-[200px]' : 'w-full h-full'} flex items-center justify-center`}>
<Loader2 size={14} className="animate-spin text-port-accent" />
</div>
)}
diff --git a/client/src/components/pipeline/SeriesLlmPicker.jsx b/client/src/components/pipeline/SeriesLlmPicker.jsx
index 8f292bacf7..efa58ac640 100644
--- a/client/src/components/pipeline/SeriesLlmPicker.jsx
+++ b/client/src/components/pipeline/SeriesLlmPicker.jsx
@@ -5,7 +5,7 @@ import toast from '../ui/Toast';
/**
* Two-select provider+model picker bound to `series.llm`. Saves on change so
* the choice applies to every subsequent LLM call on this series (arc, idea,
- * prose, scripts, auto-run). Mirrors the World Builder `world.llm` picker.
+ * prose, scripts, auto-run). Mirrors the Universe Builder `universe.llm` picker.
*/
export default function SeriesLlmPicker({ series, onSeriesUpdate, disabled = false }) {
const [providers, setProviders] = useState([]);
diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsx
index 57c65e7425..5e888958c9 100644
--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx
+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx
@@ -24,6 +24,8 @@ import {
import { getSettings, updateSettings } from '../../../services/apiSystem';
import { listImageModels } from '../../../services/apiImageVideo';
import MediaJobThumb from '../MediaJobThumb';
+import MediaPreview from '../../media/MediaPreview';
+import useMediaJobProgress from '../../../hooks/useMediaJobProgress';
import Drawer from '../../Drawer';
import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';
import { deriveAvailableBackends } from '../../../lib/imageGenBackends';
@@ -77,6 +79,38 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);
const [imageModels, setImageModels] = useState([]);
const [sysSettings, setSysSettings] = useState(null);
+ // Shared lightbox state. PageRow reports its rendered filename up via
+ // `onFilenameKnown` so the parent can build a navigable items list keyed by
+ // page order — preview prev/next walks rendered pages in page order.
+ const [preview, setPreview] = useState(null);
+ const [filenameByJobId, setFilenameByJobId] = useState({});
+ const onFilenameKnown = useCallback((jobId, filename) => {
+ if (!jobId || !filename) return;
+ setFilenameByJobId((prev) => prev[jobId] === filename ? prev : { ...prev, [jobId]: filename });
+ }, []);
+ const buildPageItem = useCallback((pageIndex, page, filename) => ({
+ key: `comic-page:${filename}`,
+ kind: 'image',
+ filename,
+ previewUrl: `/data/images/${filename}`,
+ downloadUrl: `/data/images/${filename}`,
+ prompt: page?.prompt || `Page ${pageIndex + 1}`,
+ }), []);
+ const previewItems = useMemo(() => {
+ const pageList = Array.isArray(comicPages.pages) ? comicPages.pages : [];
+ return pageList
+ .map((p, idx) => {
+ if (!p.imageJobId) return null;
+ const filename = filenameByJobId[p.imageJobId];
+ if (!filename) return null;
+ return buildPageItem(idx, p, filename);
+ })
+ .filter(Boolean);
+ }, [comicPages.pages, filenameByJobId, buildPageItem]);
+ const openPreview = useCallback((pageIndex, filename, page) => {
+ if (!filename) return;
+ setPreview(buildPageItem(pageIndex, page, filename));
+ }, [buildPageItem]);
const availableBackends = useMemo(
() => deriveAvailableBackends(sysSettings, { excludeExternal: true }),
[sysSettings],
@@ -226,10 +260,14 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
page={page}
renderOpts={renderOpts}
onStageUpdate={onStageUpdate}
+ onPreview={openPreview}
+ onFilenameKnown={onFilenameKnown}
/>
))}
</ul>
+ <MediaPreview preview={preview} setPreview={setPreview} items={previewItems} />
+
{hasScript ? (
<details
className="rounded border border-port-border bg-port-card/40"
@@ -258,7 +296,7 @@ export default function ComicScriptStage({ issue, series, onStageUpdate }) {
);
}
-function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate }) {
+function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate, onPreview, onFilenameKnown }) {
const rawText = useMemo(
() => page.rawText || panelsToMarkdown(page.panels, pageIndex + 1),
[page.rawText, page.panels, pageIndex],
@@ -270,6 +308,21 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate }) {
useEffect(() => { setDraft(rawText); }, [rawText]);
const dirty = draft !== rawText;
+ // Subscribe to the page's render job so we can (a) disable the Render
+ // button while the job is queued/running and (b) bubble the resolved
+ // filename up to the parent for lightbox nav.
+ const { status: jobStatus, filename: jobFilename } = useMediaJobProgress(page.imageJobId);
+ useEffect(() => {
+ if (page.imageJobId && jobFilename) onFilenameKnown?.(page.imageJobId, jobFilename);
+ }, [page.imageJobId, jobFilename, onFilenameKnown]);
+ // Treat 'unknown' (pre-hydration) as in-flight when a jobId exists — avoids
+ // a brief re-enable flash after page reload while the GET /media-jobs/:id
+ // catches up.
+ const jobInFlight = !!page.imageJobId
+ && jobStatus !== 'completed'
+ && jobStatus !== 'failed'
+ && jobStatus !== 'canceled';
+
const handleSave = async () => {
setSaving(true);
const res = await updatePipelineComicPage(issue.id, pageIndex, { rawText: draft })
@@ -324,11 +377,15 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate }) {
<button
type="button"
onClick={handleRender}
- disabled={rendering || dirty}
+ disabled={rendering || dirty || jobInFlight}
className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-accent text-white font-medium disabled:opacity-40"
- title={dirty ? 'Save changes before rendering' : 'Queue a full-page render for this page'}
+ title={dirty
+ ? 'Save changes before rendering'
+ : jobInFlight
+ ? 'Render in progress…'
+ : 'Queue a full-page render for this page'}
>
- {rendering ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}
+ {(rendering || jobInFlight) ? <Loader2 size={12} className="animate-spin" /> : <ImageIcon size={12} />}
Render
</button>
<button
@@ -351,9 +408,14 @@ function PageRow({ issue, pageIndex, page, renderOpts = {}, onStageUpdate }) {
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-xs font-mono leading-relaxed"
placeholder={`## Page ${pageIndex + 1}\n\n### Panel 1\n**Description:** ...`}
/>
- <div className="flex items-center justify-center bg-port-bg border border-port-border rounded min-h-[200px]">
+ <div className="flex items-center justify-center bg-port-bg border border-port-border rounded min-h-[200px] overflow-hidden">
{page.imageJobId ? (
- <MediaJobThumb jobId={page.imageJobId} label={`Page ${pageIndex + 1}`} size="md" />
+ <MediaJobThumb
+ jobId={page.imageJobId}
+ label={`Page ${pageIndex + 1}`}
+ size="fill"
+ onPreview={(filename) => onPreview?.(pageIndex, filename, page)}
+ />
) : (
<span className="text-xs text-gray-500 italic">No render yet — click <em>Render</em>.</span>
)}
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsx
index 6a62a3ab66..a7322870ff 100644
--- a/client/src/components/pipeline/stages/NounsStage.jsx
+++ b/client/src/components/pipeline/stages/NounsStage.jsx
@@ -19,11 +19,11 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import {
Library, Loader2, Users, MapPin, Package,
- ImagePlus, Settings as SettingsIcon, ChevronDown, ChevronRight,
+ ImagePlus, Settings as SettingsIcon, ChevronDown, ChevronRight, WandSparkles,
} from 'lucide-react';
import toast from '../../ui/Toast';
-import { extractPipelineBibles, updatePipelineSeries } from '../../../services/api';
-import { getWorld } from '../../../services/apiWorldBuilder';
+import { extractPipelineBibles, updatePipelineSeries, refinePipelineCharacter } from '../../../services/api';
+import { getUniverse } from '../../../services/apiUniverseBuilder';
import { getSettings, updateSettings, generateImage } from '../../../services/apiSystem';
import { listImageModels } from '../../../services/apiImageVideo';
import {
@@ -34,6 +34,7 @@ import { useAsyncAction } from '../../../hooks/useAsyncAction';
import useMounted from '../../../hooks/useMounted';
import useMediaJobProgress from '../../../hooks/useMediaJobProgress';
import MediaJobThumb from '../MediaJobThumb';
+import MediaPreview from '../../media/MediaPreview';
import Drawer from '../../Drawer';
import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';
import { deriveAvailableBackends } from '../../../lib/imageGenBackends';
@@ -76,12 +77,41 @@ export default function NounsStage({ issue, series, onSeriesUpdate }) {
const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);
const [imageModels, setImageModels] = useState([]);
const [sysSettings, setSysSettings] = useState(null);
- const [world, setWorld] = useState(null);
+ const [universe, setUniverse] = useState(null);
// Per-entry in-flight render: { [entryId]: jobId }. NounCard subscribes to
// job progress and surfaces MediaJobThumb until completion — the entry's
// imageRefs[] is only PATCHed onto the series when the job actually
// finishes, so we never render broken <img>s for files that don't exist yet.
const [renderingJobs, setRenderingJobs] = useState({});
+ // Shared lightbox state — a flat items list across every kind's imageRefs
+ // powers prev/next nav so the user can page through every reference image
+ // in the series without closing/reopening.
+ const [preview, setPreview] = useState(null);
+ const previewItems = useMemo(() => {
+ const items = [];
+ for (const kind of KINDS) {
+ const list = Array.isArray(series?.[kind.key]) ? series[kind.key] : [];
+ for (const entry of list) {
+ const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
+ for (const filename of refs) {
+ items.push({
+ key: `noun:${filename}`,
+ kind: 'image',
+ filename,
+ previewUrl: `/data/images/${filename}`,
+ downloadUrl: `/data/images/${filename}`,
+ prompt: `${entry.name}: ${kind.descFor(entry) || ''}`.trim().replace(/:\s*$/, ''),
+ });
+ }
+ }
+ }
+ return items;
+ }, [series]);
+ const openPreview = useCallback((filename) => {
+ if (!filename) return;
+ const match = previewItems.find((i) => i.filename === filename);
+ if (match) setPreview(match);
+ }, [previewItems]);
const availableBackends = useMemo(
() => deriveAvailableBackends(sysSettings, { excludeExternal: true }),
@@ -102,19 +132,19 @@ export default function NounsStage({ issue, series, onSeriesUpdate }) {
return () => { cancelled = true; };
}, [mountedRef]);
- // Fetch the linked world so reference renders inherit the same
+ // Fetch the linked universe so reference renders inherit the same
// stylePrompt + negativePrompt the comic-page renderer uses. Codex can't
// accept reference images, so a consistent aesthetic is the only knob
// keeping ref images and comic pages visually coherent.
useEffect(() => {
- if (!series?.worldId) { setWorld(null); return; }
+ if (!series?.universeId) { setUniverse(null); return; }
let cancelled = false;
- getWorld(series.worldId).then((w) => {
+ getUniverse(series.universeId).then((w) => {
if (cancelled || !mountedRef.current) return;
- setWorld(w || null);
- }).catch(() => { if (mountedRef.current) setWorld(null); });
+ setUniverse(w || null);
+ }).catch(() => { if (mountedRef.current) setUniverse(null); });
return () => { cancelled = true; };
- }, [series?.worldId, mountedRef]);
+ }, [series?.universeId, mountedRef]);
const persistImageCfg = useCallback(async (next) => {
setImageCfg(next);
@@ -147,6 +177,23 @@ export default function NounsStage({ issue, series, onSeriesUpdate }) {
{ errorMessage: 'Extraction failed' },
);
+ // Per-character in-flight refine. Tracking by id (not a single bool) so
+ // the user can fire refines in serial without the spinner jumping cards.
+ const [refiningCharacterId, setRefiningCharacterId] = useState(null);
+ const handleRefineCharacter = useCallback(async (entryId) => {
+ if (!series || refiningCharacterId) return;
+ setRefiningCharacterId(entryId);
+ const providerId = series.llm?.provider || undefined;
+ const model = series.llm?.model || undefined;
+ const result = await refinePipelineCharacter(series.id, entryId, { providerId, model })
+ .catch((err) => { toast.error(err.message || 'Refine failed'); return null; });
+ if (mountedRef.current) setRefiningCharacterId(null);
+ if (!result || !mountedRef.current) return;
+ onSeriesUpdate?.(result.series);
+ const summary = result.rationale || (result.changes?.[0] ? result.changes[0] : 'description rewritten');
+ toast.success(`Refined description — ${summary.slice(0, 140)}`);
+ }, [series, refiningCharacterId, onSeriesUpdate, mountedRef]);
+
const handleExtract = async () => {
if (!series || !proseReady) return;
const result = await runExtract();
@@ -170,14 +217,14 @@ export default function NounsStage({ issue, series, onSeriesUpdate }) {
return;
}
const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);
- // Inject the world's stylePrompt as a prefix and merge negativePrompts so
+ // Inject the universe's stylePrompt as a prefix and merge negativePrompts so
// ref images and comic pages share the same aesthetic (Codex doesn't
// accept reference images, so style consistency comes from text alone).
const userPrompt = `${entry.name}: ${description}`;
const styled = composeStyledPrompt(
userPrompt,
baseOpts.negativePrompt || '',
- world ? { prompt: world.stylePrompt, negativePrompt: world.negativePrompt } : null,
+ universe ? { prompt: universe.stylePrompt, negativePrompt: universe.negativePrompt } : null,
);
const payload = {
...baseOpts,
@@ -275,6 +322,9 @@ export default function NounsStage({ issue, series, onSeriesUpdate }) {
onRender={(entry) => handleRenderRef(kind, entry)}
onJobCompleted={(entryId, filename) => handleRefCompleted(kind.key, entryId, filename)}
onJobFailed={handleRefFailed}
+ onPreview={openPreview}
+ onRefine={handleRefineCharacter}
+ refiningCharacterId={refiningCharacterId}
/>
))}
@@ -286,11 +336,13 @@ export default function NounsStage({ issue, series, onSeriesUpdate }) {
availableBackends={availableBackends}
/>
</Drawer>
+
+ <MediaPreview preview={preview} setPreview={setPreview} items={previewItems} />
</div>
);
}
-function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted, onJobFailed }) {
+function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningCharacterId }) {
const Icon = kind.icon;
const inIssue = useMemo(() => kind.match(prose, all), [prose, all, kind]);
const inIssueIds = useMemo(() => new Set(inIssue.map((e) => e.id || e.name)), [inIssue]);
@@ -330,6 +382,10 @@ function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted
onRender={() => onRender(entry)}
onJobCompleted={onJobCompleted}
onJobFailed={onJobFailed}
+ onPreview={onPreview}
+ onRefine={onRefine}
+ refining={refiningCharacterId === entry.id}
+ refineDisabled={!!refiningCharacterId && refiningCharacterId !== entry.id}
/>
))}
</ul>
@@ -352,6 +408,10 @@ function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted
onRender={() => onRender(entry)}
onJobCompleted={onJobCompleted}
onJobFailed={onJobFailed}
+ onPreview={onPreview}
+ onRefine={onRefine}
+ refining={refiningCharacterId === entry.id}
+ refineDisabled={!!refiningCharacterId && refiningCharacterId !== entry.id}
/>
))}
</ul>
@@ -362,7 +422,7 @@ function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted
);
}
-function NounCard({ kind, entry, inFlightJobId, onRender, onJobCompleted, onJobFailed }) {
+function NounCard({ kind, entry, inFlightJobId, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refining = false, refineDisabled = false }) {
const description = kind.descFor(entry);
const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];
@@ -401,16 +461,30 @@ function NounCard({ kind, entry, inFlightJobId, onRender, onJobCompleted, onJobF
{description || <em className="text-gray-600">No description yet.</em>}
</p>
</div>
- <button
- type="button"
- onClick={onRender}
- disabled={!description.trim() || !!inFlightJobId}
- className="shrink-0 inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"
- title={description.trim() ? `Render a canonical reference image for ${entry.name}` : 'Add a description first'}
- >
- {inFlightJobId ? <Loader2 size={10} className="animate-spin" /> : <ImagePlus size={10} />}
- Render reference
- </button>
+ <div className="shrink-0 flex flex-col gap-1 items-stretch">
+ {kind.key === 'characters' && onRefine ? (
+ <button
+ type="button"
+ onClick={() => onRefine(entry.id)}
+ disabled={refining || refineDisabled}
+ className="inline-flex items-center justify-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"
+ title={`Rewrite ${entry.name}'s description so they render distinct from every other character`}
+ >
+ {refining ? <Loader2 size={10} className="animate-spin" /> : <WandSparkles size={10} />}
+ AI: differentiate
+ </button>
+ ) : null}
+ <button
+ type="button"
+ onClick={onRender}
+ disabled={!description.trim() || !!inFlightJobId}
+ className="inline-flex items-center justify-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"
+ title={description.trim() ? `Render a canonical reference image for ${entry.name}` : 'Add a description first'}
+ >
+ {inFlightJobId ? <Loader2 size={10} className="animate-spin" /> : <ImagePlus size={10} />}
+ Render reference
+ </button>
+ </div>
</div>
{(refs.length > 0 || inFlightJobId) ? (
<div className="flex items-center gap-2 mt-2 flex-wrap">
@@ -418,13 +492,12 @@ function NounCard({ kind, entry, inFlightJobId, onRender, onJobCompleted, onJobF
<MediaJobThumb jobId={inFlightJobId} label={`${entry.name} reference`} size="sm" />
) : null}
{refs.map((ref) => (
- <a
+ <button
key={ref}
- href={`/data/images/${ref}`}
- target="_blank"
- rel="noopener noreferrer"
+ type="button"
+ onClick={() => onPreview?.(ref)}
title={ref}
- className="w-16 h-16 bg-port-bg rounded overflow-hidden border border-port-border hover:border-port-accent/50"
+ className="w-16 h-16 bg-port-bg rounded overflow-hidden border border-port-border hover:border-port-accent/50 cursor-zoom-in p-0"
>
<img
src={`/data/images/${ref}`}
@@ -432,7 +505,7 @@ function NounCard({ kind, entry, inFlightJobId, onRender, onJobCompleted, onJobF
className="w-full h-full object-cover"
loading="lazy"
/>
- </a>
+ </button>
))}
</div>
) : null}
diff --git a/client/src/components/worldBuilder/InfluenceChipsInput.jsx b/client/src/components/universeBuilder/InfluenceChipsInput.jsx
similarity index 98%
rename from client/src/components/worldBuilder/InfluenceChipsInput.jsx
rename to client/src/components/universeBuilder/InfluenceChipsInput.jsx
index 68470ba6c3..613f9269a4 100644
--- a/client/src/components/worldBuilder/InfluenceChipsInput.jsx
+++ b/client/src/components/universeBuilder/InfluenceChipsInput.jsx
@@ -26,7 +26,7 @@ const TONE_CLASS = {
/**
* Chip input for an influence list (embrace or avoid). Used by both the
- * inline World Builder editor and the Refine modal — extracting one
+ * inline Universe Builder editor and the Refine modal — extracting one
* implementation keeps Enter/comma/paste/Backspace behavior, dedupe rules,
* per-entry caps, and drag-to-reorder in lockstep across both surfaces.
*
diff --git a/client/src/lib/imageGenResolutions.js b/client/src/lib/imageGenResolutions.js
index cbdc136056..f9b255c531 100644
--- a/client/src/lib/imageGenResolutions.js
+++ b/client/src/lib/imageGenResolutions.js
@@ -1,5 +1,5 @@
// Shared resolution presets for image generation. Used by the standalone
-// Image Gen page and the World Builder batch render so the size dropdown
+// Image Gen page and the Universe Builder batch render so the size dropdown
// stays consistent everywhere.
//
// Entries without a `compatible` field are universal. The non-universal
diff --git a/client/src/pages/MediaGen.jsx b/client/src/pages/MediaGen.jsx
index df4ac8789b..7a7c5dfaf9 100644
--- a/client/src/pages/MediaGen.jsx
+++ b/client/src/pages/MediaGen.jsx
@@ -4,7 +4,7 @@ import { Layers, Image as ImageIcon, Film, History, HardDrive, Scissors, FolderO
const TABS = [
{ id: 'image', label: 'Image', icon: ImageIcon },
{ id: 'video', label: 'Video', icon: Film },
- { id: 'world-builder', label: 'World Builder', icon: Globe2 },
+ { id: 'universe-builder', label: 'Universe Builder', icon: Globe2 },
{ id: 'timeline', label: 'Timeline', icon: Scissors },
{ id: 'creative-director', label: 'Creative Director', icon: Clapperboard },
{ id: 'history', label: 'History', icon: History },
diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsx
index 547ad30e98..1e4ef5d151 100644
--- a/client/src/pages/Pipeline.jsx
+++ b/client/src/pages/Pipeline.jsx
@@ -15,7 +15,7 @@ import {
listPipelineSeries,
createPipelineSeries,
deletePipelineSeries,
- listWorlds,
+ listUniverses,
WORLD_LOGLINE_MAX,
WORLD_PREMISE_MAX,
WORLD_STYLE_NOTES_MAX,
@@ -23,7 +23,7 @@ import {
const emptyForm = () => ({
name: '',
- worldId: '',
+ universeId: '',
logline: '',
premise: '',
styleNotes: '',
@@ -31,7 +31,7 @@ const emptyForm = () => ({
export default function Pipeline() {
const [series, setSeries] = useState([]);
- const [worlds, setWorlds] = useState([]);
+ const [universes, setWorlds] = useState([]);
const [loading, setLoading] = useState(true);
const [creating, setCreating] = useState(false);
const [showForm, setShowForm] = useState(false);
@@ -40,10 +40,10 @@ export default function Pipeline() {
useEffect(() => {
Promise.all([
listPipelineSeries().catch(() => []),
- // Worlds are optional — failing the fetch should still let the user
+ // Universes are optional — failing the fetch should still let the user
// create a series without one. Surface the error as a quiet toast.
- listWorlds().catch((err) => {
- toast.error(err.message || 'Failed to load worlds');
+ listUniverses().catch((err) => {
+ toast.error(err.message || 'Failed to load universes');
return [];
}),
]).then(([s, w]) => {
@@ -57,18 +57,18 @@ export default function Pipeline() {
// form fields that are currently empty so a user who's already typed a
// logline doesn't lose it when they pick a world afterwards.
const BIBLE_FIELDS = ['logline', 'premise', 'styleNotes'];
- const handleWorldChange = (worldId) => {
- if (!worldId) {
- setForm((f) => ({ ...f, worldId: '' }));
+ const handleWorldChange = (universeId) => {
+ if (!universeId) {
+ setForm((f) => ({ ...f, universeId: '' }));
return;
}
- const w = worlds.find((x) => x.id === worldId);
+ const w = universes.find((x) => x.id === universeId);
if (!w) {
- setForm((f) => ({ ...f, worldId }));
+ setForm((f) => ({ ...f, universeId }));
return;
}
setForm((f) => {
- const next = { ...f, worldId };
+ const next = { ...f, universeId };
for (const k of BIBLE_FIELDS) {
if (!f[k].trim()) next[k] = w[k] || '';
}
@@ -89,7 +89,7 @@ export default function Pipeline() {
logline: form.logline.trim(),
premise: form.premise.trim(),
styleNotes: form.styleNotes.trim(),
- worldId: form.worldId || undefined,
+ universeId: form.universeId || undefined,
}).catch((err) => {
toast.error(err.message || 'Failed to create series');
return null;
@@ -168,20 +168,20 @@ export default function Pipeline() {
</label>
<select
id="series-world"
- value={form.worldId}
+ value={form.universeId}
onChange={(e) => handleWorldChange(e.target.value)}
className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
>
<option value="">— None —</option>
- {worlds.map((w) => (
+ {universes.map((w) => (
<option key={w.id} value={w.id}>{w.name}</option>
))}
</select>
<p className="text-[11px] text-gray-500 mt-1">
- {form.worldId
+ {form.universeId
? 'Logline / premise / style notes pulled from the world — edit below.'
- : worlds.length === 0
- ? 'No worlds yet. Build one in Media Gen → World Builder.'
+ : universes.length === 0
+ ? 'No universes yet. Build one in Media Gen → Universe Builder.'
: 'Pick a world to auto-fill the bible.'}
</p>
</div>
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index f2e9e55215..0355a14025 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -21,7 +21,7 @@ import ArcCanvas from '../components/pipeline/ArcCanvas';
import {
getPipelineSeries, updatePipelineSeries,
listPipelineIssues,
- listWorlds,
+ listUniverses,
} from '../services/api';
import { recommendStructure, describeStructure } from '../lib/seasonStructure';
@@ -32,7 +32,7 @@ export default function PipelineSeries() {
const navigate = useNavigate();
const [series, setSeries] = useState(null);
const [issues, setIssues] = useState([]);
- const [worlds, setWorlds] = useState([]);
+ const [universes, setWorlds] = useState([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
@@ -44,7 +44,7 @@ export default function PipelineSeries() {
Promise.all([
getPipelineSeries(seriesId),
listPipelineIssues(seriesId),
- listWorlds().catch(() => []),
+ listUniverses().catch(() => []),
])
.then(([s, is, ws]) => {
if (canceled) return;
@@ -92,7 +92,7 @@ export default function PipelineSeries() {
const flushPending = async () => {
if (!series) return false;
const saved = lastSavedRef.current || series;
- const fields = ['name', 'logline', 'premise', 'styleNotes', 'issueCountTarget', 'worldId'];
+ const fields = ['name', 'logline', 'premise', 'styleNotes', 'issueCountTarget', 'universeId'];
const dirty = fields.some((k) => (series[k] ?? '') !== (saved[k] ?? ''))
|| JSON.stringify(series.characters || []) !== JSON.stringify(saved.characters || [])
|| JSON.stringify(series.llm || {}) !== JSON.stringify(saved.llm || {});
@@ -101,7 +101,7 @@ export default function PipelineSeries() {
name: series.name,
logline: series.logline,
premise: series.premise,
- worldId: series.worldId || null,
+ universeId: series.universeId || null,
styleNotes: series.styleNotes,
issueCountTarget: series.issueCountTarget,
characters: series.characters,
@@ -158,7 +158,7 @@ export default function PipelineSeries() {
// Mobile = flex column (grid template ignored); lg+ = grid where the inline
// `gridTemplateColumns` swap between collapsed/expanded widths takes effect.
- // Mirrors the WorldBuilder full-bleed layout so the bible rail sits flush
+ // Mirrors the UniverseBuilder full-bleed layout so the bible rail sits flush
// against the main app sidebar instead of floating inside Layout padding.
const desktopGridCols = sidebarCollapsed ? '32px minmax(0, 1fr)' : '360px minmax(0, 1fr)';
@@ -184,7 +184,7 @@ export default function PipelineSeries() {
<aside className="border-b lg:border-b-0 lg:border-r border-port-border bg-port-card/40 lg:overflow-y-auto">
<BibleSidebar
series={series}
- worlds={worlds}
+ universes={universes}
patchSeries={patchSeries}
onAddCharacter={handleAddCharacter}
onUpdateCharacter={handleUpdateCharacter}
@@ -234,7 +234,7 @@ export default function PipelineSeries() {
);
}
-function BibleSidebar({ series, worlds, patchSeries, onAddCharacter, onUpdateCharacter, onRemoveCharacter, onCollapse }) {
+function BibleSidebar({ series, universes, patchSeries, onAddCharacter, onUpdateCharacter, onRemoveCharacter, onCollapse }) {
return (
<section className="px-3 py-3 space-y-4">
<div className="flex items-center justify-between">
@@ -303,22 +303,22 @@ function BibleSidebar({ series, worlds, patchSeries, onAddCharacter, onUpdateCha
/>
</Field>
- <Field label="Linked World (from World Builder)">
+ <Field label="Linked World (from Universe Builder)">
<div className="flex items-center gap-2">
<select
- value={series.worldId || ''}
- onChange={(e) => patchSeries({ worldId: e.target.value || null })}
+ value={series.universeId || ''}
+ onChange={(e) => patchSeries({ universeId: e.target.value || null })}
className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded text-white"
>
<option value="">— None —</option>
- {worlds.map((w) => <option key={w.id} value={w.id}>{w.name}</option>)}
+ {universes.map((w) => <option key={w.id} value={w.id}>{w.name}</option>)}
</select>
<Link
- to={series.worldId ? `/world-builder` : '/world-builder'}
+ to={series.universeId ? `/universe-builder` : '/universe-builder'}
className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline whitespace-nowrap"
>
<Globe size={12} />
- {series.worldId ? 'Open' : 'Create'}
+ {series.universeId ? 'Open' : 'Create'}
</Link>
</div>
</Field>
diff --git a/client/src/pages/WorldBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
similarity index 96%
rename from client/src/pages/WorldBuilder.jsx
rename to client/src/pages/UniverseBuilder.jsx
index 8d8adbc986..1b54713acf 100644
--- a/client/src/pages/WorldBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -1,5 +1,5 @@
/**
- * World Builder page (Media Gen → World Builder).
+ * Universe Builder page (Media Gen → Universe Builder).
*
* Lets the user describe a universe in one starter prompt, expand it into a
* full set of style + per-category variation prompts via the LLM of their
@@ -16,7 +16,7 @@ import {
} from 'lucide-react';
import toast from '../components/ui/Toast';
import {
- listWorlds, getWorld, createWorld, updateWorld, deleteWorld, expandWorld,
+ listUniverses, getUniverse, createUniverse, updateUniverse, deleteUniverse, expandUniverse,
renderWorld, listWorldRuns, getProviders, refineWorldPrompts, WORLD_CATEGORIES,
WORLD_CATEGORY_KEY_MAX, COMPOSITE_PROMPT_MAX, WORLD_LOGLINE_MAX,
WORLD_PREMISE_MAX, WORLD_STYLE_NOTES_MAX, WORLD_LOCKABLE_FIELDS,
@@ -24,7 +24,7 @@ import {
ensureInfluences, isInfluenceLockField, mergeInfluencesWithLocks,
listImageModels, getSettings,
} from '../services/api';
-import InfluenceChipsInput from '../components/worldBuilder/InfluenceChipsInput';
+import InfluenceChipsInput from '../components/universeBuilder/InfluenceChipsInput';
import BackendChipStrip from '../components/media/BackendChipStrip';
import ImageGenControls from '../components/imageGen/ImageGenControls';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
@@ -80,7 +80,7 @@ const DEFAULT_RENDER_OPTS = {
batchPerVariation: 1,
};
-// Mirror of COMPOSITE_SHEET_KINDS in server/services/worldBuilder.js — keep
+// Mirror of COMPOSITE_SHEET_KINDS in server/services/universeBuilder.js — keep
// in sync when adding kinds.
const COMPOSITE_BOARD_KINDS = [
{ value: 'reference_sheet', label: 'Reference sheet' },
@@ -185,19 +185,19 @@ function InfluencesEditor({ influences, onChange, locked, onToggleLock }) {
);
}
-export default function WorldBuilder() {
+export default function UniverseBuilder() {
// The selected world id lives in the URL so deep-linking + back/forward
- // work. The page is mounted at /world-builder, /world-builder/:worldId,
- // and /media/world-builder(/:worldId) — strip any trailing /<id> off the
+ // work. The page is mounted at /universe-builder, /universe-builder/:universeId,
+ // and /media/universe-builder(/:universeId) — strip any trailing /<id> off the
// current pathname to derive the base for navigation back to the list.
const params = useParams();
const navigate = useNavigate();
const location = useLocation();
- const selectedId = params.worldId || null;
- const basePath = location.pathname.replace(/\/world-builder(?:\/.*)?$/, '/world-builder');
+ const selectedId = params.universeId || null;
+ const basePath = location.pathname.replace(/\/universe-builder(?:\/.*)?$/, '/universe-builder');
const goToWorld = (id) => navigate(id ? `${basePath}/${encodeURIComponent(id)}` : basePath);
- const [worlds, setWorlds] = useState([]);
+ const [universes, setWorlds] = useState([]);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [expanding, setExpanding] = useState(false);
@@ -210,21 +210,21 @@ export default function WorldBuilder() {
const [defaultMode, setDefaultMode] = useState(null);
// The draft is the editable copy of the currently-selected world. New
- // worlds start as a draft with no id; saving creates the persisted record.
+ // universes start as a draft with no id; saving creates the persisted record.
const [draft, setDraft] = useState(emptyTemplate());
const [newCategoryName, setNewCategoryName] = useState('');
// Per-page render knobs. Persisted to localStorage so the user's
// preferred batch size sticks across visits.
const [renderOpts, setRenderOpts] = useState(() => {
- const saved = localStorage.getItem('worldBuilder.renderOpts');
+ const saved = localStorage.getItem('universeBuilder.renderOpts');
if (saved) {
try { return { ...DEFAULT_RENDER_OPTS, ...JSON.parse(saved) }; } catch { /* fall through */ }
}
return DEFAULT_RENDER_OPTS;
});
useEffect(() => {
- localStorage.setItem('worldBuilder.renderOpts', JSON.stringify(renderOpts));
+ localStorage.setItem('universeBuilder.renderOpts', JSON.stringify(renderOpts));
}, [renderOpts]);
const [runs, setRuns] = useState([]);
@@ -247,16 +247,16 @@ export default function WorldBuilder() {
setRefineChanges([]);
};
- // Worlds list collapsed state — desktop only (mobile stacks the sidebar
+ // Universes list collapsed state — desktop only (mobile stacks the sidebar
// above the editor and there's no horizontal-space tradeoff to make).
// Persists across visits so users who prefer a maximized editor stay there.
const [worldsCollapsed, setWorldsCollapsed] = useState(() => {
- try { return localStorage.getItem('worldBuilder.worldsCollapsed') === '1'; } catch { return false; }
+ try { return localStorage.getItem('universeBuilder.worldsCollapsed') === '1'; } catch { return false; }
});
const toggleWorldsCollapsed = () => {
setWorldsCollapsed((prev) => {
const next = !prev;
- try { localStorage.setItem('worldBuilder.worldsCollapsed', next ? '1' : '0'); } catch { /* sandboxed */ }
+ try { localStorage.setItem('universeBuilder.worldsCollapsed', next ? '1' : '0'); } catch { /* sandboxed */ }
return next;
});
};
@@ -264,7 +264,7 @@ export default function WorldBuilder() {
const refresh = async () => {
setLoading(true);
const [list, provData, models, settings] = await Promise.all([
- listWorlds().catch(() => []),
+ listUniverses().catch(() => []),
getProviders().catch(() => ({ providers: [] })),
listImageModels().catch(() => []),
getSettings().catch(() => ({})),
@@ -297,7 +297,7 @@ export default function WorldBuilder() {
}
let cancelled = false;
Promise.all([
- getWorld(selectedId).catch(() => null),
+ getUniverse(selectedId).catch(() => null),
listWorldRuns(selectedId).catch(() => []),
]).then(([w, r]) => {
if (cancelled) return;
@@ -348,8 +348,8 @@ export default function WorldBuilder() {
llm: draft.llm || {},
};
const result = selectedId
- ? await updateWorld(selectedId, payload).catch((e) => { toast.error(`Save failed: ${e.message}`); return null; })
- : await createWorld(payload).catch((e) => { toast.error(`Save failed: ${e.message}`); return null; });
+ ? await updateUniverse(selectedId, payload).catch((e) => { toast.error(`Save failed: ${e.message}`); return null; })
+ : await createUniverse(payload).catch((e) => { toast.error(`Save failed: ${e.message}`); return null; });
setSaving(false);
if (result) {
toast.success(selectedId ? 'World updated' : 'World created');
@@ -376,7 +376,7 @@ export default function WorldBuilder() {
// delete. Otherwise the user would see both a red "Delete failed" toast
// AND a green "World deleted" toast, with the world apparently gone from
// the sidebar even though it's still on disk.
- const ok = await deleteWorld(id)
+ const ok = await deleteUniverse(id)
.then(() => true)
.catch((e) => { toast.error(`Delete failed: ${e.message}`); return false; });
if (!ok) return;
@@ -404,7 +404,7 @@ export default function WorldBuilder() {
const preservedCompositeSheets = (draft.compositeSheets || []).filter((s) => s?.locked === true);
setExpanding(true);
- const result = await expandWorld({
+ const result = await expandUniverse({
starterPrompt: draft.starterPrompt,
// Full prior state + locks ride along so the LLM can keep its output
// consistent with refined/pinned bible fields (see expand prompt builder).
@@ -495,7 +495,7 @@ export default function WorldBuilder() {
setDraft(expandedDraft);
const lockedKeys = Object.keys(locks).filter((k) => locks[k]);
if (lockedKeys.length) {
- console.log(`🔒 World Builder expand preserved ${lockedKeys.length} locked field(s): ${lockedKeys.join(', ')}`);
+ console.log(`🔒 Universe Builder expand preserved ${lockedKeys.length} locked field(s): ${lockedKeys.join(', ')}`);
}
const total = totalVariationCount(expandedDraft);
if (expandedDraft.compositeSheets?.length) {
@@ -506,7 +506,7 @@ export default function WorldBuilder() {
// copy still has empty categories. New (unsaved) drafts still need a
// manual Save since they have no name yet.
if (selectedId && expandedDraft.name?.trim()) {
- const updated = await updateWorld(selectedId, {
+ const updated = await updateUniverse(selectedId, {
name: expandedDraft.name.trim(),
starterPrompt: expandedDraft.starterPrompt || '',
stylePrompt: expandedDraft.stylePrompt || '',
@@ -555,7 +555,7 @@ export default function WorldBuilder() {
if (Array.isArray(patch.compositeSheets)) next.compositeSheets = patch.compositeSheets;
setDraft(next);
if (selectedId && next.name?.trim()) {
- const updated = await updateWorld(selectedId, {
+ const updated = await updateUniverse(selectedId, {
name: next.name.trim(),
starterPrompt: next.starterPrompt || '',
stylePrompt: next.stylePrompt || '',
@@ -711,7 +711,7 @@ export default function WorldBuilder() {
if (selectedId && next.name?.trim()) {
// Fire-and-forget — the in-memory state already reflects the toggle;
// on failure we toast and the next manual Save still recovers.
- updateWorld(selectedId, { locked: nextLocked })
+ updateUniverse(selectedId, { locked: nextLocked })
.catch((e) => toast.error(`Lock save failed: ${e.message}`));
}
return next;
@@ -777,8 +777,8 @@ export default function WorldBuilder() {
<button
onClick={toggleWorldsCollapsed}
className="p-1.5 text-gray-500 hover:text-white"
- title="Show worlds"
- aria-label="Show worlds"
+ title="Show universes"
+ aria-label="Show universes"
>
<PanelLeftOpen size={14} />
</button>
@@ -787,7 +787,7 @@ export default function WorldBuilder() {
<aside className="border-b lg:border-b-0 lg:border-r border-port-border bg-port-card/40 px-3 py-3 flex flex-col gap-2 lg:overflow-y-auto">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold text-white flex items-center gap-2">
- <Globe2 size={16} className="text-port-accent" /> Worlds
+ <Globe2 size={16} className="text-port-accent" /> Universes
</h2>
<div className="flex items-center gap-1">
<button
@@ -800,8 +800,8 @@ export default function WorldBuilder() {
<button
onClick={toggleWorldsCollapsed}
className="hidden lg:inline-flex p-1.5 text-gray-500 hover:text-white"
- title="Collapse worlds"
- aria-label="Collapse worlds"
+ title="Collapse universes"
+ aria-label="Collapse universes"
>
<PanelLeftClose size={14} />
</button>
@@ -809,11 +809,11 @@ export default function WorldBuilder() {
</div>
{loading ? (
<p className="text-xs text-gray-500">Loading…</p>
- ) : worlds.length === 0 ? (
- <p className="text-xs text-gray-500">No worlds yet — click <span className="text-port-accent">New</span> to start.</p>
+ ) : universes.length === 0 ? (
+ <p className="text-xs text-gray-500">No universes yet — click <span className="text-port-accent">New</span> to start.</p>
) : (
<ul className="flex flex-col gap-1 overflow-y-auto">
- {worlds.map((w) => {
+ {universes.map((w) => {
const active = w.id === selectedId;
return (
<li key={w.id}>
diff --git a/client/src/services/api.js b/client/src/services/api.js
index c4063bb732..7de60f1cfd 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -39,7 +39,7 @@ export * from './apiAsk.js';
export * from './apiImageVideo.js';
export * from './apiMediaJobs.js';
export * from './apiWritersRoom.js';
-export * from './apiWorldBuilder.js';
+export * from './apiUniverseBuilder.js';
export * from './apiPipeline.js';
// Default export for simplified imports (get/post/put/delete helpers)
diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.js
index 2f4fc6762a..2c1ba5a73b 100644
--- a/client/src/services/apiPipeline.js
+++ b/client/src/services/apiPipeline.js
@@ -81,6 +81,14 @@ export const extractPipelineBibles = (seriesId, { issueId, corpus, kinds, provid
body: JSON.stringify({ issueId, corpus, kinds, providerOverride, parallel }),
});
+// Rewrite one character's physicalDescription so they render distinct from
+// every peer. Returns { series, entry, rationale, changes }.
+export const refinePipelineCharacter = (seriesId, entryId, { providerId, model } = {}) =>
+ request(`/pipeline/series/${encodeURIComponent(seriesId)}/characters/${encodeURIComponent(entryId)}/refine`, {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model }),
+ });
+
// ---- Issues ----
export const listPipelineIssues = (seriesId) =>
request(`/pipeline/series/${encodeURIComponent(seriesId)}/issues`);
diff --git a/client/src/services/apiWorldBuilder.js b/client/src/services/apiUniverseBuilder.js
similarity index 77%
rename from client/src/services/apiWorldBuilder.js
rename to client/src/services/apiUniverseBuilder.js
index 20564b8305..830531366e 100644
--- a/client/src/services/apiWorldBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -3,41 +3,41 @@ import { request } from './apiCore.js';
export const WORLD_CATEGORIES = ['landscapes', 'environments', 'characters', 'structures', 'vehicles'];
export const WORLD_CATEGORY_KEY_MAX = 64;
export const COMPOSITE_PROMPT_MAX = 4000;
-// Mirror of the bible-field caps in server/services/worldBuilder.js — used by
-// the World Builder + Pipeline forms for maxLength enforcement on inputs.
+// Mirror of the bible-field caps in server/services/universeBuilder.js — used by
+// the Universe Builder + Pipeline forms for maxLength enforcement on inputs.
export const WORLD_LOGLINE_MAX = 500;
export const WORLD_PREMISE_MAX = 4000;
export const WORLD_STYLE_NOTES_MAX = 4000;
// Mirror of INFLUENCE_ENTRY_MAX + INFLUENCES_PER_LIST_MAX in
-// server/services/worldBuilder.js — used by the chip editor for maxLength
+// server/services/universeBuilder.js — used by the chip editor for maxLength
// enforcement and to bound paste-floods of refs.
export const WORLD_INFLUENCE_ENTRY_MAX = 120;
export const WORLD_INFLUENCES_PER_LIST_MAX = 30;
-export const listWorlds = () => request('/world-builder');
-export const getWorld = (id) => request(`/world-builder/${encodeURIComponent(id)}`);
+export const listUniverses = () => request('/universe-builder');
+export const getUniverse = (id) => request(`/universe-builder/${encodeURIComponent(id)}`);
-export const createWorld = (data) => request('/world-builder', {
+export const createUniverse = (data) => request('/universe-builder', {
method: 'POST',
body: JSON.stringify(data),
});
-export const updateWorld = (id, patch) => request(`/world-builder/${encodeURIComponent(id)}`, {
+export const updateUniverse = (id, patch) => request(`/universe-builder/${encodeURIComponent(id)}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
-export const deleteWorld = (id) => request(`/world-builder/${encodeURIComponent(id)}`, {
+export const deleteUniverse = (id) => request(`/universe-builder/${encodeURIComponent(id)}`, {
method: 'DELETE',
});
-export const expandWorld = ({
+export const expandUniverse = ({
starterPrompt, influences,
preservedVariations, preservedCompositeSheets,
logline, premise, styleNotes, stylePrompt, negativePrompt,
locked,
providerId, model,
-} = {}) => request('/world-builder/expand', {
+} = {}) => request('/universe-builder/expand', {
method: 'POST',
body: JSON.stringify({
starterPrompt, influences,
@@ -58,7 +58,7 @@ export const refineWorldPrompts = ({
categories, compositeSheets,
locked,
feedback, providerId, model,
-} = {}) => request('/world-builder/refine-prompts', {
+} = {}) => request('/universe-builder/refine-prompts', {
method: 'POST',
body: JSON.stringify({
starterPrompt, stylePrompt, negativePrompt,
@@ -71,7 +71,7 @@ export const refineWorldPrompts = ({
}),
});
-// Mirror of LOCKABLE_FIELDS in server/services/worldBuilder.js — the lock UI
+// Mirror of LOCKABLE_FIELDS in server/services/universeBuilder.js — the lock UI
// iterates this so a new lockable field only needs adding in two places.
export const WORLD_LOCKABLE_FIELDS = [
'starterPrompt',
@@ -84,7 +84,7 @@ export const WORLD_LOCKABLE_FIELDS = [
'influencesAvoid',
];
-// Mirror of `normalizeLabelKey` in server/services/worldBuilder.js — used for
+// Mirror of `normalizeLabelKey` in server/services/universeBuilder.js — used for
// case-insensitive identity matching between original and refined items.
export const normalizeLabelKey = (label) =>
typeof label === 'string' ? label.trim().toLowerCase() : '';
@@ -114,7 +114,7 @@ export const isInfluenceLockField = (key) => WORLD_INFLUENCE_LOCK_FIELDS.include
// unlocked lists take from `fresh` (the LLM output), falling back to
// `fallback` only when the LLM omitted that list (key absent). An explicit
// `[]` is applied so the user can intentionally clear an unlocked list.
-// Mirrors the server-side mergeInfluencesWithLocks in worldBuilder.js.
+// Mirrors the server-side mergeInfluencesWithLocks in universeBuilder.js.
export const mergeInfluencesWithLocks = (locked, fresh, fallback) => {
const freshSafe = ensureInfluences(fresh);
const fallbackSafe = ensureInfluences(fallback);
@@ -130,9 +130,9 @@ export const mergeInfluencesWithLocks = (locked, fresh, fallback) => {
};
};
-export const renderWorld = (id, options) => request(`/world-builder/${encodeURIComponent(id)}/render`, {
+export const renderWorld = (id, options) => request(`/universe-builder/${encodeURIComponent(id)}/render`, {
method: 'POST',
body: JSON.stringify(options || {}),
});
-export const listWorldRuns = (id) => request(`/world-builder/${encodeURIComponent(id)}/runs`);
+export const listWorldRuns = (id) => request(`/universe-builder/${encodeURIComponent(id)}/runs`);
diff --git a/data.sample/prompts/stages/pipeline-character-refine.md b/data.sample/prompts/stages/pipeline-character-refine.md
new file mode 100644
index 0000000000..49e24b0f4d
--- /dev/null
+++ b/data.sample/prompts/stages/pipeline-character-refine.md
@@ -0,0 +1,52 @@
+# Pipeline — Differentiate Character Description
+
+You are refining one character's `physicalDescription` so they render visually distinct from every other character in the cast. Image-generation models read this field directly — empty, vague, or near-identical descriptions produce interchangeable characters on the page.
+
+## Target character
+
+```json
+{{targetJson}}
+```
+
+## Other characters in the cast (peers — preserve THEIR identity; do not contradict)
+
+```json
+{{peersJson}}
+```
+
+## Style / world context
+
+{{styleClause}}
+
+## Task
+
+Rewrite ONLY the `physicalDescription` of the target so it is **visually distinct** from every peer above.
+
+1. **Specify every renderable axis.** The new description MUST name:
+ - apparent ethnicity / heritage cues (be specific — e.g. East Asian, Afro-Caribbean, Mediterranean, Pacific Islander, Nordic — not generic "white" or "diverse")
+ - age decade (mid-20s vs late-30s vs 50s reads completely different to an image model)
+ - build — height + body type (tall and lanky / compact and broad-shouldered / petite / etc.)
+ - skin tone
+ - hair — color, length, texture, style
+ - eye color
+ - distinguishing facial features (face shape, nose, eyebrows, scars, freckles, jewelry, makeup)
+ - signature wardrobe — specific garments, palette, era cues
+ - posture / silhouette
+
+2. **Preserve evidence from the prose.** Anything in the target's `evidence[]` quotes is a load-bearing detail — keep those cues intact. The same applies to `firstAppearance`. Only ADD specificity where the existing description is vague or silent.
+
+3. **Differentiate from every peer.** Scan each peer's `physicalDescription` and `aliases`. On every axis above, pick a value that does NOT collide with any peer. If two peers already collide on an axis (both have "dark hair, mid-30s"), you don't need to match either — just pick a third option. When in doubt, push your target's choice further from the cluster.
+
+4. **Length 50–100 words.** Dense, image-gen-ready phrasing. Do NOT use the target's name inside this field.
+
+## Output contract
+
+Return ONLY valid JSON, no markdown fence, no commentary:
+
+```json
+{
+ "physicalDescription": "string",
+ "rationale": "1-sentence summary of what you changed and which peers you pushed away from",
+ "changes": ["short bullet of an axis you specified or shifted", "..."]
+}
+```
diff --git a/data.sample/prompts/stages/writers-room-characters.md b/data.sample/prompts/stages/writers-room-characters.md
index e66c890147..71a7986acc 100644
--- a/data.sample/prompts/stages/writers-room-characters.md
+++ b/data.sample/prompts/stages/writers-room-characters.md
@@ -30,7 +30,7 @@ For every named character (or distinct unnamed character — "the bartender", "t
- `name` — canonical name as used most often in the prose. For unnamed characters use a stable role tag like `THE BARTENDER`.
- `aliases` — other names / nicknames / titles used for them.
- `role` — one phrase: `protagonist`, `antagonist`, `love interest`, `mentor`, `supporting`, `minor`, `narrator`, etc.
- - `physicalDescription` — 30–80 words, image-gen-ready. Be specific and visual: age range, build, skin tone, hair color/length/style, eye color, distinguishing features, signature wardrobe / silhouette, posture. Bake in genre/era cues so a model with no story context can render them. Do NOT use the character's name inside this field.
+ - `physicalDescription` — 50–100 words, image-gen-ready. **Every renderable axis MUST be specified** — apparent ethnicity / heritage cues, age range (give a decade window), build (height + body type), skin tone, hair (color + length + style + texture), eye color, distinguishing facial features (face shape, nose, eyebrows, scars, freckles, jewelry, makeup), signature wardrobe (specific garments, palette, era cues), posture/silhouette. Bake in genre/era cues so a model with no story context can render them. Do NOT use the character's name inside this field.
- `personality` — 1–2 sentences on temperament and voice.
- `background` — 1–2 sentences on who they are and where they come from, only what the prose actually establishes.
- `firstAppearance` — short quote (≤ 120 chars) from the prose where they first show up, or null if not clear.
@@ -38,9 +38,15 @@ For every named character (or distinct unnamed character — "the bartender", "t
2. **Respect existing edits.** If a field in the existing profile is already filled in, keep that value verbatim. Only populate empty / missing fields.
-3. **Identify gaps.** For every character (existing AND new), list which fields the prose does not yet support — return them as `missingFromProse`. The writer uses this to decide whether to add detail to the prose or fill the field manually.
+3. **Visually differentiate every character in the cast.** Before finalizing, scan all `physicalDescription` values you're producing AND every non-empty `physicalDescription` in the existing profiles above. **No two characters may be visually interchangeable** — if you produce two adult women in dark jackets with brown hair, an image model will render them as the same person. Pick distinguishing choices across:
+ - ethnicity / heritage (e.g. East Asian, Afro-Caribbean, Mediterranean, Pacific Islander, Nordic — be specific, not generic "white" or "diverse")
+ - age decade (mid-20s vs late-30s vs 50s reads completely different)
+ - hair (color, length, texture, style — don't give two characters the same dark bob)
+ - silhouette (tall and lanky vs compact and broad-shouldered vs petite)
+ - signature garment + palette (one character's "rumpled jacket" should not collide with another's)
+ When two characters would otherwise collide on a dimension, deliberately push one in a different direction.
-4. Do not invent details the prose does not support. If the prose never mentions hair color, leave that out of `physicalDescription` rather than guessing — and call it out in `missingFromProse`.
+4. **Commit when prose is silent, then log it.** When the prose doesn't specify a renderable detail (hair color, ethnicity, exact wardrobe), DO NOT leave `physicalDescription` blank on that axis — pick a specific, opinionated choice that fits the character's role and differentiates them from the rest of the cast. Then list the field path in `missingFromProse` (e.g. `physicalDescription.hairColor`) so the writer knows you committed without prose evidence and can override if needed. The bible drives image gen — empty axes produce identical-looking characters. A committed-but-flagged choice is always better than a gap.
5. Do not include characters who are merely referenced (e.g. "her dead father") unless they appear in a scene. Use your judgment.
diff --git a/data.sample/prompts/stages/writers-room-settings.md b/data.sample/prompts/stages/writers-room-places.md
similarity index 100%
rename from data.sample/prompts/stages/writers-room-settings.md
rename to data.sample/prompts/stages/writers-room-places.md
diff --git a/server/index.js b/server/index.js
index f0eb43155e..737382658f 100644
--- a/server/index.js
+++ b/server/index.js
@@ -87,8 +87,8 @@ import videoTimelineRoutes from './routes/videoTimeline.js';
import mediaJobsRoutes from './routes/mediaJobs.js';
import creativeDirectorRoutes from './routes/creativeDirector.js';
import writersRoomRoutes from './routes/writersRoom.js';
-import worldBuilderRoutes from './routes/worldBuilder.js';
-import { initWorldBuilderCollectionHook } from './services/worldBuilderCollectionHook.js';
+import universeBuilderRoutes from './routes/universeBuilder.js';
+import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';
import pipelineRoutes from './routes/pipeline.js';
import { initMediaJobQueue } from './services/mediaJobQueue/index.js';
import { recoverInFlightProjects } from './services/creativeDirector/recovery.js';
@@ -366,7 +366,7 @@ app.use('/api/video-timeline', videoTimelineRoutes);
app.use('/api/media-jobs', mediaJobsRoutes);
app.use('/api/creative-director', creativeDirectorRoutes);
app.use('/api/writers-room', writersRoomRoutes);
-app.use('/api/world-builder', worldBuilderRoutes);
+app.use('/api/universe-builder', universeBuilderRoutes);
app.use('/api/pipeline', pipelineRoutes);
app.use('/api/image-video/models', imageVideoModelsRoutes);
app.use('/api/loras', lorasRoutes);
@@ -502,9 +502,9 @@ ensureSelf()
.then(() => initSyncLog())
.then(() => initMediaJobQueue())
.then(() => {
- // World Builder needs the media job queue running before it can listen
+ // Universe Builder needs the media job queue running before it can listen
// for `completed` events — so initialize the hook here.
- initWorldBuilderCollectionHook();
+ initUniverseBuilderCollectionHook();
})
.then(() => {
// Fire-and-forget — resume any Creative Director projects that were mid-
diff --git a/server/lib/composeStyledPrompt.js b/server/lib/composeStyledPrompt.js
index ca2456cea8..5dd28b8305 100644
--- a/server/lib/composeStyledPrompt.js
+++ b/server/lib/composeStyledPrompt.js
@@ -10,7 +10,7 @@
* Preset negative appends to user negative so user-specified avoids stay
* first-class.
*
- * Used by World Builder's batch-prompt compiler and any future server-side
+ * Used by Universe Builder's batch-prompt compiler and any future server-side
* caller that needs the same style-prefix convention.
*/
export function composeStyledPrompt(userPrompt, userNegative, preset) {
diff --git a/server/lib/jsonExtract.js b/server/lib/jsonExtract.js
index a7bd7376b5..d116c53149 100644
--- a/server/lib/jsonExtract.js
+++ b/server/lib/jsonExtract.js
@@ -10,11 +10,11 @@
*
* This module collapses three near-identical extractors that all solved
* the same problem:
- * - worldBuilderExpand.js — string-aware brace walker + repair passes
+ * - universeBuilderExpand.js — string-aware brace walker + repair passes
* - mediaPromptRefiner.js#extractRefinementJson — brace walker without repairs
* - stageRunner.js#extractJson — greedy regex
*
- * The richest implementation (worldBuilderExpand) is promoted here and
+ * The richest implementation (universeBuilderExpand) is promoted here and
* the three callers import from this file with optional shape predicates.
*/
diff --git a/server/lib/jsonExtract.test.js b/server/lib/jsonExtract.test.js
index 20eea3dc08..f68a4343fe 100644
--- a/server/lib/jsonExtract.test.js
+++ b/server/lib/jsonExtract.test.js
@@ -75,7 +75,7 @@ describe('jsonExtract.tryParseWithRepair', () => {
// closes the array). Swapping `}}]` → `}]}` is brace-count-neutral
// so the outer container still closes. The slice itself MUST be
// brace-balanced (4 `{`, 4 `}`) — that's the post-findBalancedBlocks
- // shape, lifted from worldBuilderExpand's real production failure.
+ // shape, lifted from universeBuilderExpand's real production failure.
const bad = '{"stylePrompt":"x","categories":{"vehicles":{"variations":[{"label":"a","prompt":"…blister"}}]}}';
expect(tryParseWithRepair(bad)).toEqual({
value: {
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index d5c3456328..b69314de56 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -18,7 +18,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },
{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },
{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },
- { id: 'nav.create.world-builder', path: '/world-builder', label: 'World Builder', section: 'Create', aliases: ['world-builder', 'worldbuilder', 'worldbuild', 'world', 'universe', 'lore'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations'] },
+ { id: 'nav.create.universe-builder', path: '/universe-builder', label: 'Universe Builder', section: 'Create', aliases: ['universe-builder', 'worldbuilder', 'worldbuild', 'world', 'universe', 'lore'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations'] },
{ id: 'nav.create.pipeline', path: '/pipeline', label: 'Pipeline', section: 'Create', aliases: ['pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },
{ id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },
{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },
diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.js
index 2c4648787a..a72d3c14de 100644
--- a/server/lib/navManifest.test.js
+++ b/server/lib/navManifest.test.js
@@ -47,11 +47,11 @@ describe('resolveNavCommand — fuzzy matching', () => {
expect(resolveNavCommand('goals')?.path).toBe('/goals/list');
});
- it('resolves World Builder to its new standalone Create path', () => {
- // Promoted out of /media/world-builder; nav alias must follow.
+ it('resolves Universe Builder to its new standalone Create path', () => {
+ // Promoted out of /media/universe-builder; nav alias must follow.
const hit = resolveNavCommand('world builder');
- expect(hit?.path).toBe('/world-builder');
- expect(hit?.command?.id).toBe('nav.create.world-builder');
+ expect(hit?.path).toBe('/universe-builder');
+ expect(hit?.command?.id).toBe('nav.create.universe-builder');
});
it('resolves "pipeline" to the new Create Pipeline page (not CoS Workflow)', () => {
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index 7a2550678b..38c74d93c2 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -5,7 +5,7 @@
* provider.type → executeCliRun/executeApiRun → accumulate streamed text
* → reject on error" had drifted in failure-handling:
*
- * - worldBuilderExpand#callLLM — CLI: `error || success === false`, API: `error` only
+ * - universeBuilderExpand#callLLM — CLI: `error || success === false`, API: `error` only
* - stageRunner#awaitRunnerCall — CLI: `error || success === false`, API: `error` only
* - mediaPromptRefiner#runRefinePrompt — both: `error || success === false`
* - messageEvaluator#runPrompt — CLI: `error || success === false`, API: `error` only
@@ -90,7 +90,7 @@ export function resolveEffectiveModel(provider, callerModel) {
* @param {object} args
* @param {object} args.provider — { id, type: 'cli'|'api', timeout?, ... }
* @param {string} args.prompt — full text to send to the LLM
- * @param {string} args.source — run-record tag (`'world-builder-expansion'`,
+ * @param {string} args.source — run-record tag (`'universe-builder-expansion'`,
* `'media-prompt-refine'`, `'messages-triage'`, `'staged-llm'`, etc.)
* @param {string} [args.model] — model id hint; ignored when the
* provider doesn't honor it (claude-code, gemini-cli today).
diff --git a/server/lib/worldPromptRenderers.js b/server/lib/universePromptRenderers.js
similarity index 87%
rename from server/lib/worldPromptRenderers.js
rename to server/lib/universePromptRenderers.js
index 464befa27a..a4f627b8a2 100644
--- a/server/lib/worldPromptRenderers.js
+++ b/server/lib/universePromptRenderers.js
@@ -1,7 +1,7 @@
/**
- * Shared renderers that turn a World Builder world's `categories` map and
+ * Shared renderers that turn a Universe Builder universe's `categories` map and
* `compositeSheets` array into prompt-friendly text blocks. Used by both
- * `worldBuilderRefine` (which needs `[LOCKED]` flags) and `arcPlanner` (which
+ * `universeBuilderRefine` (which needs `[LOCKED]` flags) and `arcPlanner` (which
* does not). The two prior copies in those files had drifted in formatting;
* consolidating here keeps the LLM input shape consistent across stages.
*/
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 9a94bf09d7..0e9b84a027 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -33,6 +33,7 @@ import { join, basename, resolve as resolvePath, sep as PATH_SEP } from 'node:pa
import { readFile, writeFile } from 'fs/promises';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
import { cleanImageBuffer, CLEAN_LEVELS } from './imageClean.js';
+import { purgeImageRefFromAllSeries } from '../services/pipeline/series.js';
const router = Router();
@@ -316,7 +317,19 @@ router.post('/cancel', asyncHandler(async (req, res) => {
}));
router.delete('/:filename', asyncHandler(async (req, res) => {
- res.json(await local.deleteImage(req.params.filename));
+ const result = await local.deleteImage(req.params.filename);
+ // Sync pipeline-series noun imageRefs[] so a deleted gallery image stops
+ // showing as a stale thumbnail on the Nouns stage. Best-effort: a series
+ // read/write failure must not block the gallery delete from succeeding.
+ const purge = await purgeImageRefFromAllSeries(req.params.filename)
+ .catch((err) => {
+ console.warn(`⚠️ Pipeline ref purge failed for ${req.params.filename}: ${err?.message || err}`);
+ return { removed: 0 };
+ });
+ if (purge.removed > 0) {
+ console.log(`🧹 Purged ${purge.removed} pipeline noun ref(s) for ${req.params.filename}`);
+ }
+ res.json({ ...result, pipelineRefsRemoved: purge.removed });
}));
router.post('/:filename/visibility', asyncHandler(async (req, res) => {
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index e5a08d5426..5bd17788b1 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -44,11 +44,12 @@ import {
refineComicPanelPrompt,
refineStoryboardScenePrompt,
} from '../services/pipeline/visualStages.js';
+import { refineCharacterDescription } from '../services/pipeline/nounRefine.js';
import { startEpisodeVideoForIssue, ERR_NO_STORYBOARDS } from '../services/pipeline/episodeVideo.js';
import { ASPECT_RATIOS, QUALITIES } from '../lib/creativeDirectorPresets.js';
import { extractScenes, SOURCE_KIND } from '../lib/sceneExtractor.js';
import { parseComicScript } from '../lib/comicScriptParser.js';
-import { llmSchema } from './worldBuilder.js';
+import { llmSchema } from './universeBuilder.js';
import { BIBLE_KIND } from '../lib/storyBible.js';
import { ARC_LIMITS, ARC_STATUSES, SEASON_STATUSES } from '../lib/storyArc.js';
@@ -131,7 +132,7 @@ const seriesCreateSchema = z.object({
name: z.string().trim().min(1).max(seriesSvc.NAME_MAX),
logline: z.string().trim().max(seriesSvc.LOGLINE_MAX).optional().default(''),
premise: z.string().trim().max(seriesSvc.PREMISE_MAX).optional().default(''),
- worldId: z.string().trim().max(seriesSvc.WORLD_ID_MAX).nullable().optional(),
+ universeId: z.string().trim().max(seriesSvc.UNIVERSE_ID_MAX).nullable().optional(),
writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),
characters: z.array(characterSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
settings: z.array(settingSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
@@ -148,7 +149,7 @@ const seriesPatchSchema = z.object({
name: z.string().trim().min(1).max(seriesSvc.NAME_MAX).optional(),
logline: z.string().trim().max(seriesSvc.LOGLINE_MAX).optional(),
premise: z.string().trim().max(seriesSvc.PREMISE_MAX).optional(),
- worldId: z.string().trim().max(seriesSvc.WORLD_ID_MAX).nullable().optional(),
+ universeId: z.string().trim().max(seriesSvc.UNIVERSE_ID_MAX).nullable().optional(),
writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),
characters: z.array(characterSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
settings: z.array(settingSchema).max(seriesSvc.BIBLE_ENTRIES_PER_SERIES_MAX).optional(),
@@ -413,6 +414,21 @@ router.delete('/series/:id', asyncHandler(async (req, res) => {
res.json(r);
}));
+const refineCharacterSchema = z.object({
+ providerId: z.string().trim().max(64).optional(),
+ model: z.string().trim().max(128).optional(),
+});
+
+// LLM-driven rewrite of one character's physicalDescription so the rendered
+// image differs from every peer. Preserves evidence + firstAppearance. Returns
+// the updated series so the client can reactively swap state without a refetch.
+router.post('/series/:id/characters/:entryId/refine', asyncHandler(async (req, res) => {
+ const body = validateRequest(refineCharacterSchema, req.body ?? {});
+ const result = await refineCharacterDescription(req.params.id, req.params.entryId, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
router.get('/series/:id/issues', asyncHandler(async (req, res) => {
// Validate the series exists so a typo returns 404 instead of [] (less
// confusing for the UI).
diff --git a/server/routes/worldBuilder.js b/server/routes/universeBuilder.js
similarity index 87%
rename from server/routes/worldBuilder.js
rename to server/routes/universeBuilder.js
index 381d854b76..da0531580a 100644
--- a/server/routes/worldBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -1,14 +1,14 @@
/**
- * World Builder Routes
+ * Universe Builder Routes
*
- * GET /api/world-builder → World[]
- * POST /api/world-builder → World
- * GET /api/world-builder/:id → World
- * PATCH /api/world-builder/:id → World
- * DELETE /api/world-builder/:id → { id }
- * POST /api/world-builder/expand → { stylePrompt, negativePrompt, categories, compositeSheets, llm }
- * POST /api/world-builder/:id/render → { runId, collectionId, jobIds, promptCount }
- * GET /api/world-builder/:id/runs → Run[]
+ * GET /api/universe-builder → Universe[]
+ * POST /api/universe-builder → Universe
+ * GET /api/universe-builder/:id → Universe
+ * PATCH /api/universe-builder/:id → Universe
+ * DELETE /api/universe-builder/:id → { id }
+ * POST /api/universe-builder/expand → { stylePrompt, negativePrompt, categories, compositeSheets, llm }
+ * POST /api/universe-builder/:id/render → { runId, collectionId, jobIds, promptCount }
+ * GET /api/universe-builder/:id/runs → Run[]
*/
import { Router } from 'express';
@@ -16,9 +16,9 @@ import { z } from 'zod';
import { randomUUID } from 'crypto';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import * as svc from '../services/worldBuilder.js';
-import { expandWorldTemplate } from '../services/worldBuilderExpand.js';
-import { refineWorldPrompts } from '../services/worldBuilderRefine.js';
+import * as svc from '../services/universeBuilder.js';
+import { expandWorldTemplate } from '../services/universeBuilderExpand.js';
+import { refineWorldPrompts } from '../services/universeBuilderRefine.js';
import { enqueueJob } from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
import { findOrCreateCollectionByName, NAME_MAX_LENGTH as COLLECTION_NAME_MAX } from '../services/mediaCollections.js';
@@ -145,14 +145,14 @@ const refinePromptsSchema = z.object({
stylePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),
negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),
// Bible context: passed in so the refiner sees the full seed, refines them
- // alongside the prompts, and stays consistent with the world's narrative.
+ // 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 world
+ // 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.
@@ -183,7 +183,7 @@ const selectionSchema = z.record(
const renderSchema = z.object({
// Optional friendly name for the resulting collection. If omitted, server
- // synthesizes "World: <name> (timestamp)".
+ // synthesizes "Universe: <name> (timestamp)".
collectionName: z.string().trim().min(1).max(COLLECTION_NAME_MAX).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.
@@ -203,16 +203,16 @@ const renderSchema = z.object({
});
router.get('/', asyncHandler(async (_req, res) => {
- res.json(await svc.listWorlds());
+ res.json(await svc.listUniverses());
}));
router.post('/', asyncHandler(async (req, res) => {
const body = validateRequest(createSchema, req.body ?? {});
- res.status(201).json(await svc.createWorld(body));
+ res.status(201).json(await svc.createUniverse(body));
}));
// `expand` is a sub-resource — keep it ahead of `/:id` so the wildcard
-// doesn't catch "expand" as a world id.
+// 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);
@@ -221,25 +221,25 @@ router.post('/expand', asyncHandler(async (req, res) => {
// 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 world. Keep ahead of `/:id`.
+// result back to a saved universe. Keep ahead of `/:id`.
router.post('/refine-prompts', asyncHandler(async (req, res) => {
const body = validateRequest(refinePromptsSchema, req.body ?? {});
res.json(await refineWorldPrompts(body));
}));
router.get('/:id', asyncHandler(async (req, res) => {
- const w = await svc.getWorld(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const w = await svc.getUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });
res.json(w);
}));
router.patch('/:id', asyncHandler(async (req, res) => {
const body = validateRequest(patchSchema, req.body ?? {});
- const w = await svc.updateWorld(req.params.id, body).catch((err) => { throw mapServiceError(err); });
+ const w = await svc.updateUniverse(req.params.id, body).catch((err) => { throw mapServiceError(err); });
res.json(w);
}));
router.delete('/:id', asyncHandler(async (req, res) => {
- const r = await svc.deleteWorld(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const r = await svc.deleteUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });
res.json(r);
}));
@@ -249,9 +249,9 @@ router.get('/:id/runs', asyncHandler(async (req, res) => {
router.post('/:id/render', asyncHandler(async (req, res) => {
const body = validateRequest(renderSchema, req.body ?? {});
- const world = await svc.getWorld(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const universe = await svc.getUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });
- const compiled = svc.compilePrompts(world, {
+ const compiled = svc.compilePrompts(universe, {
promptMode: body.promptMode,
selection: body.selection,
sheetSelection: body.sheetSelection,
@@ -302,23 +302,23 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
}
// Provision the collection up front so renders can be tagged as they
- // complete. The completion hook (worldBuilderCollectionHook) will add
+ // complete. The completion hook (universeBuilderCollectionHook) will add
// each finished image's filename to this collection. Repeat renders of
- // the same world reuse the existing `World: <name>` bucket so per-world
+ // the same universe reuse the existing `Universe: <name>` bucket so per-universe
// output accumulates in one place instead of fragmenting into a fresh
// date-suffixed collection per run.
const collectionName = body.collectionName?.trim()
- || `World: ${world.name}`;
+ || `Universe: ${universe.name}`;
const collection = await findOrCreateCollectionByName({
name: collectionName.slice(0, COLLECTION_NAME_MAX),
- description: `World Builder renders for "${world.name}"`,
+ description: `Universe Builder renders for "${universe.name}"`,
});
const runId = randomUUID();
const jobIds = [];
// Map cfgScale → guidance the same way /api/image-gen/generate does. The
// mediaJobQueue calls imageGen/local.generateImage() directly (not the
- // dispatcher), so without this mapping the World Builder UI's CFG control
+ // dispatcher), so without this mapping the Universe Builder UI's CFG control
// would silently no-op for local renders.
const guidance = body.guidance ?? body.cfgScale;
const baseParams = {
@@ -338,9 +338,9 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
// Tag every job so the completion hook can route the result back
// into the run's collection without us having to thread additional
// arguments through the queue.
- worldRun: {
+ universeRun: {
runId,
- worldId: world.id,
+ universeId: universe.id,
collectionId: collection.id,
category: item.category,
label: item.label,
@@ -366,14 +366,14 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
const run = await svc.recordRun({
id: runId,
- worldId: world.id,
+ universeId: universe.id,
collectionId: collection.id,
jobIds,
promptCount: compiled.length,
createdAt: new Date().toISOString(),
});
- console.log(`🌍 World Builder render — world=${world.name} prompts=${compiled.length} mode=${mode} runId=${runId.slice(0, 8)}`);
+ console.log(`🌍 Universe Builder render — universe=${universe.name} prompts=${compiled.length} mode=${mode} runId=${runId.slice(0, 8)}`);
res.json({
runId: run.id,
diff --git a/server/routes/worldBuilder.test.js b/server/routes/universeBuilder.test.js
similarity index 75%
rename from server/routes/worldBuilder.test.js
rename to server/routes/universeBuilder.test.js
index 829200402a..980e6be51d 100644
--- a/server/routes/worldBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -19,7 +19,7 @@ vi.mock('crypto', async () => {
});
// Stub the LLM expander so the route test doesn't shell out to a real provider.
-vi.mock('../services/worldBuilderExpand.js', () => ({
+vi.mock('../services/universeBuilderExpand.js', () => ({
expandWorldTemplate: vi.fn(async ({ starterPrompt }) => ({
stylePrompt: 'mocked style for ' + starterPrompt,
negativePrompt: 'blurry',
@@ -32,7 +32,7 @@ vi.mock('../services/worldBuilderExpand.js', () => ({
},
compositeSheets: [
{ kind: 'reference_sheet', label: 'Mock costume sheet', prompt: 'mocked complete costume reference sheet with lineup, materials, fasteners, palette' },
- { kind: 'world_pitch_poster', label: 'Mock world pitch poster', prompt: 'mocked world summary concept pitch poster with hero panorama, inset cultures, palette, materials, and theme icons' },
+ { kind: 'world_pitch_poster', label: 'Mock universe pitch poster', prompt: 'mocked universe summary concept pitch poster with hero panorama, inset cultures, palette, materials, and theme icons' },
],
llm: { provider: 'anthropic', model: 'claude' },
})),
@@ -74,17 +74,17 @@ vi.mock('../lib/mediaModels.js', () => ({
isErnie: () => false,
}));
-const worldBuilderRoutes = (await import('./worldBuilder.js')).default;
+const universeBuilderRoutes = (await import('./universeBuilder.js')).default;
const buildApp = () => {
const app = express();
app.use(express.json());
- app.use('/api/world-builder', worldBuilderRoutes);
+ app.use('/api/universe-builder', universeBuilderRoutes);
app.use(errorMiddleware);
return app;
};
-describe('world-builder routes', () => {
+describe('universe-builder routes', () => {
beforeEach(() => {
fileStore.clear();
uuidCounter = 0;
@@ -92,27 +92,27 @@ describe('world-builder routes', () => {
});
it('GET / returns []', async () => {
- const res = await request(buildApp()).get('/api/world-builder');
+ const res = await request(buildApp()).get('/api/universe-builder');
expect(res.status).toBe(200);
expect(res.body).toEqual([]);
});
- it('POST / creates a world', async () => {
+ it('POST / creates a universe', async () => {
const res = await request(buildApp())
- .post('/api/world-builder')
- .send({ name: 'My World', starterPrompt: 'cyber forest' });
+ .post('/api/universe-builder')
+ .send({ name: 'My Universe', starterPrompt: 'cyber forest' });
expect(res.status).toBe(201);
expect(res.body.id).toBe('uuid-1');
- expect(res.body.name).toBe('My World');
+ expect(res.body.name).toBe('My Universe');
// All five categories populated even when not supplied.
expect(Object.keys(res.body.categories).sort()).toEqual(
['characters', 'environments', 'landscapes', 'structures', 'vehicles'],
);
});
- it('POST / accepts dynamic world-building categories', async () => {
+ it('POST / accepts dynamic universe-building categories', async () => {
const res = await request(buildApp())
- .post('/api/world-builder')
+ .post('/api/universe-builder')
.send({
name: 'Colonies',
categories: {
@@ -127,7 +127,7 @@ describe('world-builder routes', () => {
it('POST / accepts composite sheet prompts', async () => {
const res = await request(buildApp())
- .post('/api/world-builder')
+ .post('/api/universe-builder')
.send({
name: 'Sheets',
compositeSheets: [
@@ -140,13 +140,13 @@ describe('world-builder routes', () => {
expect(res.body.compositeSheets[0].label).toBe('Gas-Giant Drifters sheet');
});
- it('POST / accepts world pitch poster composite prompts', async () => {
+ it('POST / accepts universe pitch poster composite prompts', async () => {
const res = await request(buildApp())
- .post('/api/world-builder')
+ .post('/api/universe-builder')
.send({
name: 'Pitch Posters',
compositeSheets: [
- { kind: 'world_pitch_poster', label: 'World summary concept pitch poster', prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language strip, color palette, materials, light atmosphere, and theme icons.' },
+ { kind: 'world_pitch_poster', label: 'Universe summary concept pitch poster', prompt: 'Create a cinematic universe summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language strip, color palette, materials, light atmosphere, and theme icons.' },
],
});
expect(res.status).toBe(201);
@@ -156,34 +156,34 @@ describe('world-builder routes', () => {
it('POST / rejects missing name', async () => {
const res = await request(buildApp())
- .post('/api/world-builder')
+ .post('/api/universe-builder')
.send({ starterPrompt: 'cyber forest' });
expect(res.status).toBe(400);
});
it('PATCH /:id updates fields', async () => {
const app = buildApp();
- const c = await request(app).post('/api/world-builder').send({ name: 'A' });
+ const c = await request(app).post('/api/universe-builder').send({ name: 'A' });
const res = await request(app)
- .patch(`/api/world-builder/${c.body.id}`)
+ .patch(`/api/universe-builder/${c.body.id}`)
.send({ name: 'B', stylePrompt: 'oil painting' });
expect(res.status).toBe(200);
expect(res.body.name).toBe('B');
expect(res.body.stylePrompt).toBe('oil painting');
});
- it('DELETE /:id removes the world', async () => {
+ it('DELETE /:id removes the universe', async () => {
const app = buildApp();
- const c = await request(app).post('/api/world-builder').send({ name: 'A' });
- const del = await request(app).delete(`/api/world-builder/${c.body.id}`);
+ const c = await request(app).post('/api/universe-builder').send({ name: 'A' });
+ const del = await request(app).delete(`/api/universe-builder/${c.body.id}`);
expect(del.status).toBe(200);
- const list = await request(app).get('/api/world-builder');
+ const list = await request(app).get('/api/universe-builder');
expect(list.body).toEqual([]);
});
it('POST /expand returns LLM expansion', async () => {
const res = await request(buildApp())
- .post('/api/world-builder/expand')
+ .post('/api/universe-builder/expand')
.send({ starterPrompt: 'moebius scifi' });
expect(res.status).toBe(200);
expect(res.body.stylePrompt).toContain('moebius scifi');
@@ -194,7 +194,7 @@ describe('world-builder routes', () => {
it('POST /:id/render queues image jobs and records run', async () => {
const app = buildApp();
- const created = await request(app).post('/api/world-builder').send({
+ const created = await request(app).post('/api/universe-builder').send({
name: 'Render Test',
stylePrompt: 'style',
negativePrompt: 'neg',
@@ -204,21 +204,21 @@ describe('world-builder routes', () => {
},
});
const res = await request(app)
- .post(`/api/world-builder/${created.body.id}/render`)
+ .post(`/api/universe-builder/${created.body.id}/render`)
.send({ batchPerVariation: 2, mode: 'local' });
expect(res.status).toBe(200);
expect(res.body.promptCount).toBe(6); // 3 variations × 2 batch
expect(res.body.jobIds).toHaveLength(6);
expect(res.body.collectionId).toBe('col-1');
// Run is recorded.
- const runs = await request(app).get(`/api/world-builder/${created.body.id}/runs`);
+ const runs = await request(app).get(`/api/universe-builder/${created.body.id}/runs`);
expect(runs.body).toHaveLength(1);
expect(runs.body[0].promptCount).toBe(6);
});
it('POST /:id/render queues custom category prompts', async () => {
const app = buildApp();
- const created = await request(app).post('/api/world-builder').send({
+ const created = await request(app).post('/api/universe-builder').send({
name: 'Clothing',
stylePrompt: 'moebius, clean reference sheet',
categories: {
@@ -226,7 +226,7 @@ describe('world-builder routes', () => {
},
});
const res = await request(app)
- .post(`/api/world-builder/${created.body.id}/render`)
+ .post(`/api/universe-builder/${created.body.id}/render`)
.send({ mode: 'local', selection: { clothing_styles: 'all' } });
expect(res.status).toBe(200);
expect(res.body.promptCount).toBe(1);
@@ -235,7 +235,7 @@ describe('world-builder routes', () => {
it('POST /:id/render queues composite sheet prompts', async () => {
const app = buildApp();
- const created = await request(app).post('/api/world-builder').send({
+ const created = await request(app).post('/api/universe-builder').send({
name: 'Composite Clothing',
stylePrompt: 'moebius, clean reference sheet',
compositeSheets: [
@@ -243,57 +243,57 @@ describe('world-builder routes', () => {
],
});
const res = await request(app)
- .post(`/api/world-builder/${created.body.id}/render`)
+ .post(`/api/universe-builder/${created.body.id}/render`)
.send({ mode: 'local', promptMode: 'sheets' });
expect(res.status).toBe(200);
expect(res.body.promptCount).toBe(1);
expect(res.body.jobIds).toHaveLength(1);
});
- it('POST /:id/render reuses the same collection on repeat renders of the same world', async () => {
+ it('POST /:id/render reuses the same collection on repeat renders of the same universe', async () => {
const app = buildApp();
- const created = await request(app).post('/api/world-builder').send({
- name: 'Repeat World',
+ const created = await request(app).post('/api/universe-builder').send({
+ name: 'Repeat Universe',
categories: {
landscapes: { variations: [{ label: 'A', prompt: 'a' }] },
},
});
const first = await request(app)
- .post(`/api/world-builder/${created.body.id}/render`)
+ .post(`/api/universe-builder/${created.body.id}/render`)
.send({ mode: 'local' });
expect(first.status).toBe(200);
const second = await request(app)
- .post(`/api/world-builder/${created.body.id}/render`)
+ .post(`/api/universe-builder/${created.body.id}/render`)
.send({ mode: 'local' });
expect(second.status).toBe(200);
expect(second.body.collectionId).toBe(first.body.collectionId);
- // The auto-generated name has no date suffix — bare `World: <name>`.
- expect(second.body.collectionName).toBe('World: Repeat World');
+ // The auto-generated name has no date suffix — bare `Universe: <name>`.
+ expect(second.body.collectionName).toBe('Universe: Repeat Universe');
expect(second.body.collectionName).not.toMatch(/\d{4}-\d{2}-\d{2}/);
});
it('POST /:id/render reuses an existing collection when collectionName matches', async () => {
const app = buildApp();
- const created = await request(app).post('/api/world-builder').send({
- name: 'Custom Bucket World',
+ const created = await request(app).post('/api/universe-builder').send({
+ name: 'Custom Bucket Universe',
categories: {
landscapes: { variations: [{ label: 'A', prompt: 'a' }] },
},
});
const first = await request(app)
- .post(`/api/world-builder/${created.body.id}/render`)
+ .post(`/api/universe-builder/${created.body.id}/render`)
.send({ mode: 'local', collectionName: 'Shared Bucket' });
const second = await request(app)
- .post(`/api/world-builder/${created.body.id}/render`)
+ .post(`/api/universe-builder/${created.body.id}/render`)
.send({ mode: 'local', collectionName: ' shared bucket ' });
expect(second.body.collectionId).toBe(first.body.collectionId);
});
it('POST /:id/render rejects when no variations exist', async () => {
const app = buildApp();
- const created = await request(app).post('/api/world-builder').send({ name: 'Empty' });
+ const created = await request(app).post('/api/universe-builder').send({ name: 'Empty' });
const res = await request(app)
- .post(`/api/world-builder/${created.body.id}/render`)
+ .post(`/api/universe-builder/${created.body.id}/render`)
.send({ mode: 'local' });
expect(res.status).toBe(400);
expect(res.body.code).toBe('WORLD_BUILDER_EMPTY');
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index f09d4dec63..be7f3a66e1 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -194,7 +194,7 @@ router.delete('/works/:id/characters/:characterId', asyncHandler(async (req, res
res.json(await deleteCharacter(req.params.id, req.params.characterId));
}));
-// ---------- settings (locations / world bible) ----------
+// ---------- settings (locations / universe bible) ----------
router.get('/works/:id/settings', asyncHandler(async (req, res) => {
res.json(await listSettings(req.params.id));
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index fde2a2860b..6fa7371a37 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -135,7 +135,7 @@ export async function createCollection({ name, description = '' }) {
}
// Find an existing collection by case-insensitive trimmed name, else create
-// a fresh one. Lets repeat-render callers (World Builder) append into a
+// a fresh one. Lets repeat-render callers (Universe Builder) append into a
// single per-world bucket without growing a new collection on every run.
export async function findOrCreateCollectionByName({ name, description = '' }) {
const trimmed = typeof name === 'string' ? name.trim() : '';
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index a87bee9df0..f64a25364f 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -25,8 +25,8 @@ import { getSeries, updateSeries } from './series.js';
import { listIssues } from './issues.js';
import { sanitizeArc, sanitizeSeasonList, sanitizeSeason, buildSeason } from '../../lib/storyArc.js';
import { recommendStructure, describeStructure } from '../../lib/seasonStructure.js';
-import { getWorld } from '../worldBuilder.js';
-import { renderCategoriesForPrompt, renderCompositesForPrompt } from '../../lib/worldPromptRenderers.js';
+import { getUniverse } from '../universeBuilder.js';
+import { renderCategoriesForPrompt, renderCompositesForPrompt } from '../../lib/universePromptRenderers.js';
export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';
const makeErr = (message, code) => Object.assign(new Error(message), { code });
@@ -54,9 +54,9 @@ function renderPriorSeason(s, priorIssues) {
// The world is the canonical source for factions, characters, environments,
// etc. — without this, the arc planner would only see the series' own
// characters/settings/objects which are usually empty pre-prose.
-async function loadWorldContext(worldId) {
- if (!worldId) return null;
- const world = await getWorld(worldId).catch(() => null);
+async function loadWorldContext(universeId) {
+ if (!universeId) return null;
+ const world = await getUniverse(universeId).catch(() => null);
if (!world) return null;
const embrace = Array.isArray(world.influences?.embrace) ? world.influences.embrace : [];
@@ -85,7 +85,7 @@ const EMPTY_WORLD_CONTEXT = {
worldStyleNotes: '',
worldInfluencesEmbrace: '(none)',
worldInfluencesAvoid: '(none)',
- worldCategoriesText: '(none — series has no linked World Builder world)',
+ worldCategoriesText: '(none — series has no linked Universe Builder world)',
worldCompositesText: '(none)',
};
@@ -93,7 +93,7 @@ const EMPTY_WORLD_CONTEXT = {
// that chain (verify → resolve) don't reload the same world twice.
async function resolveWorldContext(series, preloaded) {
if (preloaded) return preloaded;
- return (await loadWorldContext(series.worldId)) || EMPTY_WORLD_CONTEXT;
+ return (await loadWorldContext(series.universeId)) || EMPTY_WORLD_CONTEXT;
}
// The `recommendedStructure` field encodes comic-as-TV norms (6–10 per
diff --git a/server/services/pipeline/arcPlanner.test.js b/server/services/pipeline/arcPlanner.test.js
index 5740675f53..348b4daa8f 100644
--- a/server/services/pipeline/arcPlanner.test.js
+++ b/server/services/pipeline/arcPlanner.test.js
@@ -26,7 +26,7 @@ vi.mock('../../lib/stageRunner.js', () => ({
const seriesSvc = await import('./series.js');
const issuesSvc = await import('./issues.js');
const seasonsSvc = await import('./seasons.js');
-const worldSvc = await import('../worldBuilder.js');
+const worldSvc = await import('../universeBuilder.js');
const planner = await import('./arcPlanner.js');
async function setupSeries(overrides = {}) {
@@ -118,7 +118,7 @@ describe('arcPlanner — generateArcOverview', () => {
it('feeds the linked world\'s categories + composite sheets into the prompt context', async () => {
// Create a world with factions + a composite sheet, then a series linked to it.
- const world = await worldSvc.createWorld({
+ const world = await worldSvc.createUniverse({
name: 'Clandestiny',
starterPrompt: 'paranormal investigators in a candy-bright city',
logline: 'World logline',
@@ -138,7 +138,7 @@ describe('arcPlanner — generateArcOverview', () => {
{ kind: 'reference_sheet', label: 'Rival agencies branding', prompt: 'comparison sheet' },
],
});
- const s = await setupSeries({ worldId: world.id });
+ const s = await setupSeries({ universeId: world.id });
stageRunnerSpy = vi.fn(async () => ({
content: {
@@ -159,8 +159,8 @@ describe('arcPlanner — generateArcOverview', () => {
expect(ctx.worldInfluencesAvoid).toContain('gritty');
});
- it('renders an "(no linked world)" placeholder when the series has no worldId', async () => {
- const s = await setupSeries({ worldId: null });
+ it('renders an "(no linked world)" placeholder when the series has no universeId', async () => {
+ const s = await setupSeries({ universeId: null });
stageRunnerSpy = vi.fn(async () => ({
content: { logline: 'L', summary: 'S', themes: [], protagonistArc: 'A', seasonOutlines: [] },
runId: 'r1', providerId: 'p', model: 'm',
diff --git a/server/services/pipeline/nounRefine.js b/server/services/pipeline/nounRefine.js
new file mode 100644
index 0000000000..40c4b2d44c
--- /dev/null
+++ b/server/services/pipeline/nounRefine.js
@@ -0,0 +1,110 @@
+/**
+ * Refine a single character's `physicalDescription` so it renders visually
+ * distinct from the rest of the cast. The LLM sees the target + every peer's
+ * existing description and is asked to commit to specific differentiating
+ * choices (ethnicity, age, hair, silhouette, wardrobe palette, ...).
+ *
+ * Reads/writes go through `getSeries` / `updateSeries` so the regular
+ * sanitize-on-write pass still runs.
+ */
+
+import { getSeries, updateSeries } from './series.js';
+import { getUniverse } from '../universeBuilder.js';
+import { runStagedLLM } from '../../lib/stageRunner.js';
+import { ServerError } from '../../lib/errorHandler.js';
+
+const KIND_FIELD = Object.freeze({
+ characters: 'physicalDescription',
+});
+
+// Slimmed-down peer shape sent to the prompt. Drops timestamps + ids the LLM
+// doesn't need so the prompt stays inside the context budget when the cast
+// grows past a few entries.
+function peerForPrompt(entry) {
+ return {
+ name: entry.name,
+ aliases: Array.isArray(entry.aliases) ? entry.aliases : [],
+ role: entry.role || '',
+ physicalDescription: entry.physicalDescription || entry.description || '',
+ };
+}
+
+function targetForPrompt(entry) {
+ return {
+ name: entry.name,
+ aliases: Array.isArray(entry.aliases) ? entry.aliases : [],
+ role: entry.role || '',
+ physicalDescription: entry.physicalDescription || '',
+ evidence: Array.isArray(entry.evidence) ? entry.evidence : [],
+ firstAppearance: entry.firstAppearance || null,
+ };
+}
+
+export async function refineCharacterDescription(seriesId, entryId, options = {}) {
+ const kind = 'characters';
+ const field = KIND_FIELD[kind];
+ if (!field) {
+ throw new ServerError(`Unsupported noun kind: ${kind}`, { status: 400, code: 'PIPELINE_NOUN_KIND' });
+ }
+
+ const series = await getSeries(seriesId);
+ const list = Array.isArray(series[kind]) ? series[kind] : [];
+ const idx = list.findIndex((e) => e.id === entryId);
+ if (idx < 0) {
+ throw new ServerError(`Character ${entryId} not found in series`, {
+ status: 404, code: 'PIPELINE_NOUN_NOT_FOUND',
+ });
+ }
+ const target = list[idx];
+ const peers = list.filter((_, i) => i !== idx);
+
+ // Style clause: universe stylePrompt (if linked) + series styleNotes, dropped
+ // into the prompt as plain text. The LLM doesn't need the full universe JSON —
+ // it only steers wardrobe/era cues toward the established aesthetic.
+ const universe = series.universeId ? await getUniverse(series.universeId).catch(() => null) : null;
+ const styleBits = [
+ universe?.stylePrompt ? `Universe aesthetic: ${universe.stylePrompt}` : null,
+ series.styleNotes ? `Series notes: ${series.styleNotes}` : null,
+ ].filter(Boolean);
+ const styleClause = styleBits.length
+ ? styleBits.join('\n')
+ : '(none provided — pick choices that fit the character\'s role and genre)';
+
+ const result = await runStagedLLM('pipeline-character-refine', {
+ targetJson: JSON.stringify(targetForPrompt(target), null, 2),
+ peersJson: JSON.stringify(peers.map(peerForPrompt), null, 2),
+ styleClause,
+ }, {
+ providerOverride: options.providerId,
+ modelOverride: options.model,
+ returnsJson: true,
+ source: 'pipeline-character-refine',
+ });
+
+ const refined = (result.content?.physicalDescription || '').trim();
+ if (!refined) {
+ throw new ServerError('LLM returned an empty physicalDescription', {
+ status: 502, code: 'PIPELINE_NOUN_REFINE_EMPTY',
+ });
+ }
+ const rationale = (result.content?.rationale || '').trim();
+ const changes = Array.isArray(result.content?.changes)
+ ? result.content.changes.map((c) => String(c).slice(0, 240)).filter(Boolean).slice(0, 12)
+ : [];
+
+ const nextList = list.map((e, i) => i === idx ? { ...e, [field]: refined } : e);
+ const updated = await updateSeries(seriesId, { [kind]: nextList });
+ const updatedEntry = (updated[kind] || []).find((e) => e.id === entryId) || null;
+
+ console.log(`✨ Pipeline character refine — series=${seriesId.slice(0, 8)} entry=${entryId.slice(0, 8)} runId=${(result.runId || '').slice(0, 8)}`);
+
+ return {
+ series: updated,
+ entry: updatedEntry,
+ rationale,
+ changes,
+ runId: result.runId,
+ providerId: result.providerId,
+ model: result.model,
+ };
+}
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 9916460929..e1b943f52e 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -39,7 +39,7 @@ export const CHARACTERS_PER_SERIES_MAX = BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX;
export const BIBLE_ENTRIES_PER_SERIES_MAX = BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX;
export const IMAGE_REFS_PER_CHARACTER_MAX = BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX;
export const IMAGE_REF_MAX = BIBLE_LIMITS.IMAGE_REF_MAX;
-export const WORLD_ID_MAX = 64;
+export const UNIVERSE_ID_MAX = 64;
export const WRITERS_ROOM_WORK_ID_MAX = 64;
export const TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);
export const ISSUE_COUNT_TARGET_MAX = 999;
@@ -68,7 +68,7 @@ const sanitizeSeries = (raw) => {
name,
logline: trimTo(raw.logline, LOGLINE_MAX),
premise: trimTo(raw.premise, PREMISE_MAX),
- worldId: trimTo(raw.worldId, WORLD_ID_MAX) || null,
+ universeId: trimTo(raw.universeId, UNIVERSE_ID_MAX) || null,
// Bidirectional link to a Writers Room work (item 6 of the DRY
// unification). Set by the "Promote to pipeline" flow; never auto-cleared.
writersRoomWorkId: trimTo(raw.writersRoomWorkId, WRITERS_ROOM_WORK_ID_MAX) || null,
@@ -122,7 +122,7 @@ export async function createSeries(input = {}) {
name,
logline: input.logline || '',
premise: input.premise || '',
- worldId: input.worldId || null,
+ universeId: input.universeId || null,
writersRoomWorkId: input.writersRoomWorkId || null,
characters: input.characters || [],
settings: input.settings || [],
@@ -155,7 +155,7 @@ export async function updateSeries(id, patch = {}) {
...('name' in patch ? { name: patch.name } : {}),
...('logline' in patch ? { logline: patch.logline } : {}),
...('premise' in patch ? { premise: patch.premise } : {}),
- ...('worldId' in patch ? { worldId: patch.worldId } : {}),
+ ...('universeId' in patch ? { universeId: patch.universeId } : {}),
...('writersRoomWorkId' in patch ? { writersRoomWorkId: patch.writersRoomWorkId } : {}),
...('characters' in patch ? { characters: patch.characters } : {}),
...('settings' in patch ? { settings: patch.settings } : {}),
@@ -174,6 +174,42 @@ export async function updateSeries(id, patch = {}) {
return merged;
}
+/**
+ * Strip a filename from every `imageRefs[]` across every series's
+ * characters/settings/objects. Called by the image-delete route so a noun
+ * card stops pointing at a file the user just deleted from the gallery.
+ *
+ * Returns `{ removed }` — total references stripped across all series.
+ * Skips the write when nothing matched, so a delete of a non-noun image
+ * (the common case) is a cheap no-op read.
+ */
+const BIBLE_KEYS = ['characters', 'settings', 'objects'];
+export async function purgeImageRefFromAllSeries(filename) {
+ if (!filename || typeof filename !== 'string') return { removed: 0 };
+ const state = await readState();
+ let removed = 0;
+ const nextSeries = state.series.map((s) => {
+ let touched = false;
+ const patched = { ...s };
+ for (const key of BIBLE_KEYS) {
+ const list = Array.isArray(s[key]) ? s[key] : null;
+ if (!list) continue;
+ const nextList = list.map((entry) => {
+ const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : null;
+ if (!refs || !refs.includes(filename)) return entry;
+ const trimmed = refs.filter((f) => f !== filename);
+ removed += refs.length - trimmed.length;
+ touched = true;
+ return { ...entry, imageRefs: trimmed };
+ });
+ if (touched) patched[key] = nextList;
+ }
+ return touched ? { ...patched, updatedAt: new Date().toISOString() } : s;
+ });
+ if (removed > 0) await writeState({ series: nextSeries });
+ return { removed };
+}
+
/**
* Run bible extraction across the requested kinds and merge results into a
* series. The route layer used to thread extract → merge → patch itself,
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index 66ef737c9c..d085e22734 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -32,7 +32,7 @@ describe('pipeline series service', () => {
name: 'Salt Run',
logline: 'A foundry city goes silent.',
premise: 'Long-form premise about a salt-mining city...',
- worldId: 'world-123',
+ universeId: 'world-123',
styleNotes: 'moebius linework, washed sepia',
targetFormat: 'comic+tv',
issueCountTarget: 6,
@@ -44,7 +44,7 @@ describe('pipeline series service', () => {
expect(s.id).toMatch(/^ser-/);
expect(s.name).toBe('Salt Run');
expect(s.logline).toBe('A foundry city goes silent.');
- expect(s.worldId).toBe('world-123');
+ expect(s.universeId).toBe('world-123');
expect(s.targetFormat).toBe('comic+tv');
expect(s.issueCountTarget).toBe(6);
// Empty-name character dropped; Lina gets a chr- id.
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index 9f7bcc8184..fee115b892 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -48,7 +48,7 @@ function buildStageContext({ series, issue, stageId, seedInput }) {
logline: series.logline,
premise: series.premise,
styleNotes: series.styleNotes,
- worldId: series.worldId || '',
+ universeId: series.universeId || '',
characters: series.characters || [],
},
issue: {
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index bd20f7eef5..404232ab75 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -33,7 +33,7 @@ vi.mock('../providers.js', () => ({
vi.mock('../runner.js', () => ({
createRun: vi.fn(async () => ({ runId: `run-${++uuidCounter}` })),
// Stub executeApiRun: call onData with a canned response immediately, then
- // onComplete with success. Mirrors what worldBuilderExpand.test.js doesn't
+ // onComplete with success. Mirrors what universeBuilderExpand.test.js doesn't
// need to do (it mocks the upstream expander), but we test the lower-level
// text-stage runner here.
executeApiRun: vi.fn(async (runId, provider, model, prompt, _cwd, _shots, onData, onComplete) => {
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index 3d22a1ec6b..ff29c3ff25 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -27,7 +27,7 @@ import { enqueueJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { getSeries } from './series.js';
import { getIssue, updateStage, VISUAL_STAGE_IDS } from './issues.js';
-import { getWorld } from '../worldBuilder.js';
+import { getUniverse } from '../universeBuilder.js';
import { ServerError } from '../../lib/errorHandler.js';
import {
buildScenePrompt, buildSettingByKey, matchSceneSetting,
@@ -59,7 +59,7 @@ const loadBibleContext = async (issueId) => {
const issueChain = (async () => {
const issue = await getIssue(issueId);
const series = await getSeries(issue.seriesId);
- const world = series.worldId ? await getWorld(series.worldId).catch(() => null) : null;
+ const world = series.universeId ? await getUniverse(series.universeId).catch(() => null) : null;
return { issue, series, world };
})();
const [chain, settings] = await Promise.all([issueChain, getSettings()]);
diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.js
index d143ecbb37..9a553e0af5 100644
--- a/server/services/pipeline/visualStages.test.js
+++ b/server/services/pipeline/visualStages.test.js
@@ -46,7 +46,7 @@ vi.mock('../settings.js', () => ({
getSettings: vi.fn(async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' }, mode: 'local' }, videoGen: {} })),
}));
-vi.mock('../worldBuilder.js', () => ({ getWorld: vi.fn(async () => null) }));
+vi.mock('../universeBuilder.js', () => ({ getUniverse: vi.fn(async () => null) }));
const enqueueJobMock = vi.fn(() => ({ jobId: 'job-fake-1234' }));
vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: (...a) => enqueueJobMock(...a) }));
diff --git a/server/services/runner.js b/server/services/runner.js
index bbadbcd61b..6c97dbada1 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -142,7 +142,7 @@ export function hasModelFlag(args) {
* (`--model=X` / `-m=X`). Returns null when no model flag is present or the
* separated form has no value following the flag.
*
- * Used by refiners (mediaPromptRefiner, worldBuilderRefine) so the model
+ * Used by refiners (mediaPromptRefiner, universeBuilderRefine) so the model
* reported back to the caller / persisted on the run record matches what
* the CLI will actually run when the user has hard-coded a model in args.
*/
diff --git a/server/services/worldBuilder.js b/server/services/universeBuilder.js
similarity index 86%
rename from server/services/worldBuilder.js
rename to server/services/universeBuilder.js
index c285a759e5..434916911c 100644
--- a/server/services/worldBuilder.js
+++ b/server/services/universeBuilder.js
@@ -1,24 +1,24 @@
/**
- * World Builder Service
+ * Universe Builder Service
*
- * Stores user-created "world templates" — sci-fi/fantasy/etc. universe
+ * Stores user-created "universe templates" — sci-fi/fantasy/etc. universe
* descriptions expanded by an LLM into a structured prompt set:
*
* - stylePrompt + negativePrompt (positive style fragment + negative prompt)
- * - categories: named prompt buckets, seeded with common world-art buckets
+ * - categories: named prompt buckets, seeded with common universe-art buckets
* like landscapes / characters / vehicles, but open to project-specific
* buckets like colonies, factions, species, clothing_styles, or raider_clans
* (each with a list of `variations` — short prompt fragments)
* - compositeSheets: complete board/poster prompts that combine several
- * buckets into one image, e.g. a colony costume guide or a world summary
+ * buckets into one image, e.g. a colony costume guide or a universe summary
* concept pitch poster
*
* From those pieces the route can compile a flat list of full prompts and
- * enqueue them as image-gen jobs, all tagged with the same `worldId` and
+ * enqueue them as image-gen jobs, all tagged with the same `universeId` and
* `runId` so the resulting renders form a self-contained collection.
*
- * Persisted to data/world-builder.json. Renders for a run land in a
- * media-collections.json collection named "World: <worldName>" (or any
+ * Persisted to data/universe-builder.json. Renders for a run land in a
+ * media-collections.json collection named "Universe: <worldName>" (or any
* other name the user picks at kickoff).
*/
@@ -27,7 +27,7 @@ import { randomUUID } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';
-const STATE_PATH = join(PATHS.data, 'world-builder.json');
+const STATE_PATH = join(PATHS.data, 'universe-builder.json');
export const ERR_NOT_FOUND = 'NOT_FOUND';
export const ERR_VALIDATION = 'VALIDATION_ERROR';
@@ -42,7 +42,7 @@ export const PROMPT_FRAGMENT_MAX = 2000;
export const COMPOSITE_PROMPT_MAX = 4000;
export const VARIATION_LABEL_MAX = 120;
// Narrative bible fields — surfaced into the Pipeline "new series" form so a
-// world's logline/premise/style notes can seed a production series in one click.
+// universe's logline/premise/style notes can seed a production series in one click.
export const LOGLINE_MAX = 500;
export const PREMISE_MAX = 4000;
export const STYLE_NOTES_MAX = 4000;
@@ -57,7 +57,7 @@ export const WORLD_CATEGORY_COUNT_MAX = 30;
// Influences — structured reference lists that deterministically inform
// stylePrompt (embrace) and negativePrompt (avoid) at render-compile time.
-// They are the canonical record of the world's direction so re-expansions
+// They are the canonical record of the universe's direction so re-expansions
// inherit it; the LLM still authors the prose stylePrompt around them.
export const INFLUENCE_ENTRY_MAX = 120;
export const INFLUENCES_PER_LIST_MAX = 30;
@@ -99,7 +99,7 @@ export const LOCKABLE_FIELD_LABELS = Object.freeze({
export const INFLUENCE_LOCK_FIELDS = Object.freeze(['influencesEmbrace', 'influencesAvoid']);
export const isInfluenceLockField = (key) => INFLUENCE_LOCK_FIELDS.includes(key);
-// Starter buckets the UI surfaces for a fresh world. They remain for
+// Starter buckets the UI surfaces for a fresh universe. They remain for
// compatibility, but saved templates may carry any additional sanitized
// category keys the LLM or user creates.
export const WORLD_CATEGORIES = Object.freeze([
@@ -110,7 +110,7 @@ export const WORLD_CATEGORIES = Object.freeze([
'vehicles',
]);
-const DEFAULT_STATE = { worlds: [], runs: [] };
+const DEFAULT_STATE = { universes: [], runs: [] };
const isStr = (v) => typeof v === 'string';
const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
@@ -159,7 +159,7 @@ const sanitizeCompositeSheet = (raw) => {
const sanitizeCategory = (raw) => {
// Per-category structure: { variations: [{ label, prompt }] }. Cap so a
- // runaway LLM can't blow up the world template; matches the route schema.
+ // runaway LLM can't blow up the universe template; matches the route schema.
if (!raw || typeof raw !== 'object') return { variations: [] };
const variations = [];
if (Array.isArray(raw.variations)) {
@@ -244,7 +244,7 @@ export const sanitizeInfluences = (raw = {}) => {
// `fresh` (the LLM output), falling back to `fallback` ONLY when the LLM
// omitted that list (key absent). An explicit `[]` is applied so the user
// can intentionally clear an unlocked list. Mirrors `mergeInfluencesWithLocks`
-// in client/services/apiWorldBuilder.js.
+// in client/services/apiUniverseBuilder.js.
export const mergeInfluencesWithLocks = (locked, fresh, fallback) => {
const freshSafe = sanitizeInfluences(fresh);
const fallbackSafe = sanitizeInfluences(fallback);
@@ -302,7 +302,7 @@ export const sanitizeLocked = (raw = {}) => {
if (raw[key] === true) out[key] = true;
}
// Migration: prior schema had a single `influences` lock covering both
- // embrace + avoid. Expand into the two per-list locks so existing worlds
+ // embrace + avoid. Expand into the two per-list locks so existing universes
// keep working without a data migration step.
if (raw.influences === true) {
out.influencesEmbrace = true;
@@ -368,10 +368,10 @@ const sanitizeTemplate = (raw) => {
const sanitizeRun = (raw) => {
if (!raw || typeof raw !== 'object') return null;
if (!isStr(raw.id) || !raw.id) return null;
- if (!isStr(raw.worldId) || !raw.worldId) return null;
+ if (!isStr(raw.universeId) || !raw.universeId) return null;
return {
id: raw.id,
- worldId: raw.worldId,
+ universeId: raw.universeId,
collectionId: isStr(raw.collectionId) ? raw.collectionId : null,
jobIds: Array.isArray(raw.jobIds) ? raw.jobIds.filter(isStr).slice(0, MAX_RUN_JOB_IDS) : [],
promptCount: Number.isFinite(raw.promptCount) ? raw.promptCount : 0,
@@ -382,31 +382,31 @@ const sanitizeRun = (raw) => {
async function readState() {
await ensureDir(PATHS.data);
const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });
- const worlds = Array.isArray(raw.worlds) ? raw.worlds.map(sanitizeTemplate).filter(Boolean) : [];
+ const universes = Array.isArray(raw.universes) ? raw.universes.map(sanitizeTemplate).filter(Boolean) : [];
const runs = Array.isArray(raw.runs) ? raw.runs.map(sanitizeRun).filter(Boolean) : [];
- return { worlds, runs };
+ return { universes, runs };
}
async function writeState(state) {
await atomicWrite(STATE_PATH, state);
}
-export async function listWorlds() {
- const { worlds } = await readState();
- // Newest first — matches user expectation for a "your worlds" list.
- return [...worlds].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
+export async function listUniverses() {
+ const { universes } = await readState();
+ // Newest first — matches user expectation for a "your universes" list.
+ return [...universes].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
}
-export async function getWorld(id) {
- const { worlds } = await readState();
- const w = worlds.find((x) => x.id === id);
- if (!w) throw makeErr(`World not found: ${id}`, ERR_NOT_FOUND);
+export async function getUniverse(id) {
+ const { universes } = await readState();
+ const w = universes.find((x) => x.id === id);
+ if (!w) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
return w;
}
-export async function createWorld(input = {}) {
+export async function createUniverse(input = {}) {
const name = trimTo(input.name, NAME_MAX_LENGTH);
- if (!name) throw makeErr(`World name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);
+ if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);
const state = await readState();
const now = new Date().toISOString();
const next = sanitizeTemplate({
@@ -426,20 +426,20 @@ export async function createWorld(input = {}) {
createdAt: now,
updatedAt: now,
});
- state.worlds.push(next);
+ state.universes.push(next);
await writeState(state);
return next;
}
-export async function updateWorld(id, patch = {}) {
+export async function updateUniverse(id, patch = {}) {
const state = await readState();
- const idx = state.worlds.findIndex((w) => w.id === id);
- if (idx < 0) throw makeErr(`World not found: ${id}`, ERR_NOT_FOUND);
- const cur = state.worlds[idx];
+ const idx = state.universes.findIndex((w) => w.id === id);
+ if (idx < 0) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
+ const cur = state.universes[idx];
// Merge `categories` per-key — a partial PATCH that only includes
// `landscapes` must NOT wipe characters/structures/etc. Whole categories
- // not present in the patch are kept as-is from the current world.
+ // not present in the patch are kept as-is from the current universe.
const mergedCategories = 'categories' in patch
? { ...cur.categories, ...(patch.categories || {}) }
: cur.categories;
@@ -480,19 +480,19 @@ export async function updateWorld(id, patch = {}) {
llm: mergedLlm,
updatedAt: new Date().toISOString(),
});
- if (!merged) throw makeErr('Invalid world payload', ERR_VALIDATION);
- state.worlds[idx] = merged;
+ if (!merged) throw makeErr('Invalid universe payload', ERR_VALIDATION);
+ state.universes[idx] = merged;
await writeState(state);
return merged;
}
-export async function deleteWorld(id) {
+export async function deleteUniverse(id) {
const state = await readState();
- const before = state.worlds.length;
- state.worlds = state.worlds.filter((w) => w.id !== id);
- if (state.worlds.length === before) throw makeErr(`World not found: ${id}`, ERR_NOT_FOUND);
- // Drop runs referencing the deleted world — they're useless without it.
- state.runs = state.runs.filter((r) => r.worldId !== id);
+ const before = state.universes.length;
+ state.universes = state.universes.filter((w) => w.id !== id);
+ if (state.universes.length === before) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);
+ // Drop runs referencing the deleted universe — they're useless without it.
+ state.runs = state.runs.filter((r) => r.universeId !== id);
await writeState(state);
return { id };
}
@@ -508,9 +508,9 @@ export async function recordRun(run) {
return sanitized;
}
-export async function listRuns(worldId = null) {
+export async function listRuns(universeId = null) {
const { runs } = await readState();
- const filtered = worldId ? runs.filter((r) => r.worldId === worldId) : runs;
+ const filtered = universeId ? runs.filter((r) => r.universeId === universeId) : runs;
return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
}
@@ -540,8 +540,8 @@ export function composeInfluenceTokens(structured = [], prose = '') {
}
/**
- * Compile the world template into an ordered list of full image-gen
- * prompts. Each entry combines the world's style prompt with one
+ * Compile the universe template into an ordered list of full image-gen
+ * prompts. Each entry combines the universe's style prompt with one
* variation from a chosen category.
*
* selection: { landscapes: 'all' | string[], characters: ... }
@@ -551,14 +551,14 @@ export function composeInfluenceTokens(structured = [], prose = '') {
*
* batchPerVariation: how many renders per variation (1..20)
*/
-export function compilePrompts(world, options = {}) {
- if (!world) return [];
+export function compilePrompts(universe, options = {}) {
+ if (!universe) return [];
const promptMode = ['variations', 'sheets', 'all'].includes(options.promptMode)
? options.promptMode
: 'variations';
const selection = options.selection && typeof options.selection === 'object'
? options.selection
- : Object.fromEntries(getWorldCategoryKeys(world.categories).map((c) => [c, 'all']));
+ : Object.fromEntries(getWorldCategoryKeys(universe.categories).map((c) => [c, 'all']));
const normalizedSelection = {};
for (const [key, value] of Object.entries(selection)) {
const normalized = normalizeCategoryKey(key);
@@ -567,8 +567,8 @@ export function compilePrompts(world, options = {}) {
const batchPerVariation = Math.max(1, Math.min(20, Number(options.batchPerVariation) || 1));
const stylePreset = {
- prompt: composeInfluenceTokens(world.influences?.embrace, world.stylePrompt),
- negativePrompt: composeInfluenceTokens(world.influences?.avoid, world.negativePrompt),
+ prompt: composeInfluenceTokens(universe.influences?.embrace, universe.stylePrompt),
+ negativePrompt: composeInfluenceTokens(universe.influences?.avoid, universe.negativePrompt),
};
const compiled = [];
@@ -576,7 +576,7 @@ export function compilePrompts(world, options = {}) {
for (const category of getWorldCategoryKeys(normalizedSelection)) {
const sel = normalizedSelection[category];
if (!sel) continue;
- const variations = world.categories?.[category]?.variations || [];
+ const variations = universe.categories?.[category]?.variations || [];
const filtered = sel === 'all'
? variations
: variations.filter((v) => Array.isArray(sel) && sel.some((s) => s.toLowerCase() === v.label.toLowerCase()));
@@ -597,7 +597,7 @@ export function compilePrompts(world, options = {}) {
if (promptMode === 'sheets' || promptMode === 'all') {
const sheetSelection = options.sheetSelection || 'all';
- const sheets = world.compositeSheets || [];
+ const sheets = universe.compositeSheets || [];
const filteredSheets = sheetSelection === 'all'
? sheets
: sheets.filter((s) => Array.isArray(sheetSelection) && sheetSelection.some((label) => label.toLowerCase() === s.label.toLowerCase()));
diff --git a/server/services/worldBuilder.test.js b/server/services/universeBuilder.test.js
similarity index 87%
rename from server/services/worldBuilder.test.js
rename to server/services/universeBuilder.test.js
index 62017bf588..f7ed9139d7 100644
--- a/server/services/worldBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -19,10 +19,10 @@ vi.mock("crypto", async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
-const svc = await import("./worldBuilder.js");
+const svc = await import("./universeBuilder.js");
const seedWorld = async (overrides = {}) =>
- svc.createWorld({
+ svc.createUniverse({
name: "Moebius SciFi",
starterPrompt: "moebius and scavengers reign meets prophet",
stylePrompt: "moebius linework, scavengers reign palette",
@@ -46,17 +46,17 @@ const seedWorld = async (overrides = {}) =>
...overrides,
});
-describe("worldBuilder service", () => {
+describe("universeBuilder service", () => {
beforeEach(() => {
fileStore.clear();
uuidCounter = 0;
});
- it("listWorlds returns [] for fresh state", async () => {
- expect(await svc.listWorlds()).toEqual([]);
+ it("listUniverses returns [] for fresh state", async () => {
+ expect(await svc.listUniverses()).toEqual([]);
});
- it("createWorld persists with sanitized categories", async () => {
+ it("createUniverse persists with sanitized categories", async () => {
const w = await seedWorld();
expect(w.id).toBe("uuid-1");
expect(w.name).toBe("Moebius SciFi");
@@ -70,7 +70,7 @@ describe("worldBuilder service", () => {
expect(w.categories.environments.variations).toHaveLength(0);
});
- it("createWorld preserves custom world-building categories", async () => {
+ it("createUniverse preserves custom universe-building categories", async () => {
const w = await seedWorld({
categories: {
"Clothing Styles": {
@@ -101,7 +101,7 @@ describe("worldBuilder service", () => {
expect(w.categories.landscapes.variations).toHaveLength(0);
});
- it("createWorld persists composite sheet prompts separately from categories", async () => {
+ it("createUniverse persists composite sheet prompts separately from categories", async () => {
const w = await seedWorld({
compositeSheets: [
{
@@ -121,34 +121,34 @@ describe("worldBuilder service", () => {
]);
});
- it("createWorld persists world pitch poster prompts separately from categories", async () => {
+ it("createUniverse persists universe pitch poster prompts separately from categories", async () => {
const w = await seedWorld({
compositeSheets: [
{
kind: "world_pitch_poster",
- label: "World summary concept pitch poster",
+ label: "Universe summary concept pitch poster",
prompt:
- "Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.",
+ "Create a cinematic universe summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.",
},
],
});
expect(w.compositeSheets).toEqual([
{
kind: "world_pitch_poster",
- label: "World summary concept pitch poster",
+ label: "Universe summary concept pitch poster",
prompt:
- "Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.",
+ "Create a cinematic universe summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.",
},
]);
});
- it("createWorld rejects empty name", async () => {
- await expect(svc.createWorld({ name: "" })).rejects.toThrow(
+ it("createUniverse rejects empty name", async () => {
+ await expect(svc.createUniverse({ name: "" })).rejects.toThrow(
/name is required/,
);
});
- it("createWorld persists narrative bible fields (logline / premise / styleNotes)", async () => {
+ it("createUniverse persists narrative bible fields (logline / premise / styleNotes)", async () => {
const w = await seedWorld({
logline: "A foundry city goes silent, and the only survivor is a child.",
premise:
@@ -167,9 +167,9 @@ describe("worldBuilder service", () => {
);
});
- it("updateWorld patches narrative bible fields independently of categories", async () => {
+ it("updateUniverse patches narrative bible fields independently of categories", async () => {
const w = await seedWorld({ logline: "original logline" });
- const patched = await svc.updateWorld(w.id, {
+ const patched = await svc.updateUniverse(w.id, {
logline: "new logline",
premise: "new premise",
styleNotes: "new style notes",
@@ -182,7 +182,7 @@ describe("worldBuilder service", () => {
expect(patched.stylePrompt).toBe(w.stylePrompt);
});
- it("createWorld trims bible fields to their max length", async () => {
+ it("createUniverse trims bible fields to their max length", async () => {
const w = await seedWorld({
logline: "x".repeat(svc.LOGLINE_MAX + 50),
premise: "y".repeat(svc.PREMISE_MAX + 50),
@@ -193,9 +193,9 @@ describe("worldBuilder service", () => {
expect(w.styleNotes).toHaveLength(svc.STYLE_NOTES_MAX);
});
- it("updateWorld merges partial patches", async () => {
+ it("updateUniverse merges partial patches", async () => {
const w = await seedWorld();
- const patched = await svc.updateWorld(w.id, {
+ const patched = await svc.updateUniverse(w.id, {
name: "Renamed",
stylePrompt: "new style",
});
@@ -206,24 +206,24 @@ describe("worldBuilder service", () => {
expect(patched.categories.landscapes.variations).toHaveLength(2);
});
- it("updateWorld throws NOT_FOUND for unknown id", async () => {
+ it("updateUniverse throws NOT_FOUND for unknown id", async () => {
await expect(
- svc.updateWorld("no-such", { name: "X" }),
+ svc.updateUniverse("no-such", { name: "X" }),
).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
- it("deleteWorld removes the world and its runs", async () => {
+ it("deleteUniverse removes the universe and its runs", async () => {
const w = await seedWorld();
await svc.recordRun({
id: "run-1",
- worldId: w.id,
+ universeId: w.id,
collectionId: "col-1",
jobIds: ["j1"],
promptCount: 3,
});
expect(await svc.listRuns(w.id)).toHaveLength(1);
- await svc.deleteWorld(w.id);
- expect(await svc.listWorlds()).toEqual([]);
+ await svc.deleteUniverse(w.id);
+ expect(await svc.listUniverses()).toEqual([]);
expect(await svc.listRuns(w.id)).toEqual([]);
});
@@ -355,15 +355,15 @@ describe("worldBuilder service", () => {
});
});
- it("tags world pitch poster prompts separately from reference sheets", async () => {
+ it("tags universe pitch poster prompts separately from reference sheets", async () => {
const w = await seedWorld({
categories: {},
compositeSheets: [
{
kind: "world_pitch_poster",
- label: "World pitch poster",
+ label: "Universe pitch poster",
prompt:
- "cinematic world summary pitch poster, hero panorama, inset cultures, palette, themes",
+ "cinematic universe summary pitch poster, hero panorama, inset cultures, palette, themes",
},
],
});
@@ -371,7 +371,7 @@ describe("worldBuilder service", () => {
expect(compiled).toHaveLength(1);
expect(compiled[0]).toMatchObject({
category: "world_pitch_posters",
- label: "World pitch poster",
+ label: "Universe pitch poster",
});
});
@@ -392,7 +392,7 @@ describe("worldBuilder service", () => {
});
describe("influences", () => {
- it("round-trips embrace + avoid lists through createWorld", async () => {
+ it("round-trips embrace + avoid lists through createUniverse", async () => {
const w = await seedWorld({
influences: {
embrace: ["Moebius", "cel-shading"],
@@ -438,11 +438,11 @@ describe("worldBuilder service", () => {
expect(w.influences.embrace).toHaveLength(svc.INFLUENCES_PER_LIST_MAX);
});
- it("updateWorld replaces influence lists wholesale (does not merge)", async () => {
+ it("updateUniverse replaces influence lists wholesale (does not merge)", async () => {
const w = await seedWorld({
influences: { embrace: ["A", "B"], avoid: ["X"] },
});
- const patched = await svc.updateWorld(w.id, {
+ const patched = await svc.updateUniverse(w.id, {
influences: { embrace: ["C"] },
});
// Wholesale replace: avoid is gone because the patch didn't carry it.
@@ -551,7 +551,7 @@ describe("worldBuilder service", () => {
locked: { logline: true, influencesEmbrace: true },
});
expect(w.locked).toEqual({ logline: true, influencesEmbrace: true });
- const patched = await svc.updateWorld(w.id, {
+ const patched = await svc.updateUniverse(w.id, {
locked: { styleNotes: true },
});
expect(patched.locked).toEqual({ styleNotes: true });
@@ -566,7 +566,7 @@ describe("worldBuilder service", () => {
it("migrates legacy `locked.influences: true` into per-list locks", async () => {
// Prior schema combined embrace + avoid into one `influences` lock. The
- // sanitizer now splits it into two so existing on-disk worlds keep working
+ // sanitizer now splits it into two so existing on-disk universes keep working
// without a data migration step.
const w = await seedWorld({ locked: { influences: true, premise: true } });
expect(w.locked).toEqual({
@@ -580,8 +580,8 @@ describe("worldBuilder service", () => {
describe("sanitizers", () => {
it("drops malformed variations on read", async () => {
// Manually plant invalid state — sanitizeTemplate strips it on read.
- fileStore.set("/mock/data/world-builder.json", {
- worlds: [
+ fileStore.set("/mock/data/universe-builder.json", {
+ universes: [
{
id: "w1",
name: "X",
@@ -603,7 +603,7 @@ describe("worldBuilder service", () => {
],
runs: [],
});
- const list = await svc.listWorlds();
+ const list = await svc.listUniverses();
expect(list[0].categories.landscapes.variations).toHaveLength(1);
expect(list[0].categories.landscapes.variations[0].label).toBe("Good");
});
diff --git a/server/services/worldBuilderCollectionHook.js b/server/services/universeBuilderCollectionHook.js
similarity index 75%
rename from server/services/worldBuilderCollectionHook.js
rename to server/services/universeBuilderCollectionHook.js
index bf62073024..6a2aad3030 100644
--- a/server/services/worldBuilderCollectionHook.js
+++ b/server/services/universeBuilderCollectionHook.js
@@ -1,8 +1,8 @@
/**
- * World Builder — collection hook.
+ * Universe Builder — collection hook.
*
* Subscribes to mediaJobEvents and, for each completed image job that
- * carries `params.worldRun.collectionId`, files the rendered filename
+ * carries `params.universeRun.collectionId`, files the rendered filename
* into that collection.
*
* Mounted once at server boot from server/index.js so it can listen for
@@ -16,7 +16,7 @@ import { addItem, ERR_DUPLICATE } from './mediaCollections.js';
let registeredHandler = null;
-export function initWorldBuilderCollectionHook() {
+export function initUniverseBuilderCollectionHook() {
// Idempotent: a stray double-init (test reload, future refactor) would
// otherwise register two listeners and double-file every completed image.
if (registeredHandler) return;
@@ -29,7 +29,7 @@ export function initWorldBuilderCollectionHook() {
registeredHandler = (job) => {
void (async () => {
if (!job || job.kind !== 'image') return;
- const tag = job.params?.worldRun;
+ const tag = job.params?.universeRun;
if (!tag?.collectionId) return;
const filename = job.result?.filename;
if (!filename || typeof filename !== 'string') return;
@@ -39,21 +39,21 @@ export function initWorldBuilderCollectionHook() {
// A duplicate (same filename rendered twice in the same run) is
// expected when batchPerVariation > 1 and the gen output collides.
if (err?.code === ERR_DUPLICATE) return 'duplicate';
- console.log(`⚠️ world-builder collection hook failed for ${filename}: ${err?.message || String(err)}`);
+ console.log(`⚠️ universe-builder collection hook failed for ${filename}: ${err?.message || String(err)}`);
return 'failed';
});
if (status === 'added') {
- console.log(`🌍 world-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} → ${filename}`);
+ console.log(`🌍 universe-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} → ${filename}`);
} else if (status === 'duplicate') {
- console.log(`🌍 world-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} duplicate skipped: ${filename}`);
+ console.log(`🌍 universe-builder run=${tag.runId?.slice(0, 8)} category=${tag.category} duplicate skipped: ${filename}`);
}
})().catch((err) => {
// Last-resort net for synchronous throws (unexpected job shape, etc).
- console.log(`⚠️ world-builder collection hook crashed: ${err?.message || err}`);
+ console.log(`⚠️ universe-builder collection hook crashed: ${err?.message || err}`);
});
};
mediaJobEvents.on('completed', registeredHandler);
- console.log('🌍 World Builder collection hook initialized');
+ console.log('🌍 Universe Builder collection hook initialized');
}
// Test-only reset hook so suites that re-init can do so cleanly. Removes the
diff --git a/server/services/worldBuilderExpand.js b/server/services/universeBuilderExpand.js
similarity index 78%
rename from server/services/worldBuilderExpand.js
rename to server/services/universeBuilderExpand.js
index e73a67cb1c..dbb7c9f63a 100644
--- a/server/services/worldBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -1,5 +1,5 @@
/**
- * World Builder — LLM expansion.
+ * Universe Builder — LLM expansion.
*
* Takes a starter prompt like:
* "moebius and scavengers reign meets Prophet inspired sci fi universe"
@@ -26,7 +26,7 @@ import {
sanitizeCategories,
sanitizeCompositeSheets,
sanitizeInfluences,
-} from "./worldBuilder.js";
+} from "./universeBuilder.js";
import { ServerError } from "../lib/errorHandler.js";
import { extractJson as extractJsonShared } from "../lib/jsonExtract.js";
import {
@@ -36,7 +36,7 @@ import {
const LABEL_MAX = 80;
-// Bible/prompt fields the LLM sees as "current world state" so re-expansion
+// Bible/prompt fields the LLM sees as "current universe state" so re-expansion
// stays consistent with prior refinements. Derived from LOCKABLE_FIELDS so a
// new lockable field automatically reaches this prompt; excludes starterPrompt
// (already shown above as the seed) and influences (rendered in its own
@@ -88,7 +88,7 @@ function buildExpansionPrompt({
const anyLocked = stateLines.length
&& Object.keys(locked || {}).some((k) => locked[k] === true);
const currentStateSection = stateLines.length
- ? `\n# Current world state — established context for this expansion${anyLocked ? '. Fields marked [LOCKED] MUST be echoed unchanged in your output' : ''}.
+ ? `\n# Current universe state — established context for this expansion${anyLocked ? '. Fields marked [LOCKED] MUST be echoed unchanged in your output' : ''}.
${stateLines.join('\n\n')}\n`
: '';
@@ -118,7 +118,7 @@ ${stateLines.join('\n\n')}\n`
${preservedVariationLines.length ? `Pinned variations:\n${preservedVariationLines.join("\n")}\n` : ""}${preservedSheetLines.length ? `Pinned composite boards:\n${preservedSheetLines.join("\n")}\n` : ""}`
: "";
- return `You are a world-building prompt engineer for a Stable-Diffusion-style image generation pipeline AND a story-bible drafter for a comic/TV production pipeline. You will turn the user's starter idea into (a) a structured prompt set that produces a visually consistent universe across many renders, and (b) a short narrative bible that downstream writing stages can ingest.
+ return `You are a universe-building prompt engineer for a Stable-Diffusion-style image generation pipeline AND a story-bible drafter for a comic/TV production pipeline. You will turn the user's starter idea into (a) a structured prompt set that produces a visually consistent universe across many renders, and (b) a short narrative bible that downstream writing stages can ingest.
# Starter idea
${starterPrompt}
@@ -126,15 +126,15 @@ ${influencesSection}${currentStateSection}${preservedSection}
# Output contract
Return a SINGLE JSON object. NO markdown, NO commentary. The object MUST have these top-level keys:
-- logline: string. ONE sentence (≤500 chars) capturing the world's central tension/hook — protagonist-agnostic if no protagonist is implied. Example: "A foundry city goes silent — and the only survivor is a child."
+- logline: string. ONE sentence (≤500 chars) capturing the universe's central tension/hook — protagonist-agnostic if no protagonist is implied. Example: "A foundry city goes silent — and the only survivor is a child."
- premise: string. 1-3 short paragraphs (≤4000 chars total) describing the setting, the central conflict or situation, the stakes, and the tone. Write it as the elevator pitch a showrunner would hand to a writers' room. No bullet points; prose only.
- styleNotes: string. A prose paragraph (≤4000 chars) describing the visual + tonal style for the story bible — references (artists, films, comics, games), mood, palette, pacing, narrative voice. This is read by writers + creative directors, not the image model, so use full sentences instead of comma-separated tokens.
-- influences: object { "embrace": [string], "avoid": [string] }. Short canonical reference labels (max 120 chars each, max 30 per list) — artists, comics, films, directors, palettes, materials, eras the world EMBRACES; styles, tropes, palettes the world AVOIDS. The renderer prepends these to stylePrompt/negativePrompt verbatim, so each entry should read as a clean prompt token (e.g. "Moebius", "cel-shading", "Ghibli painterly", "neon cyberpunk"). When influence input is provided above, preserve those entries unless the starter idea explicitly contradicts them.
+- influences: object { "embrace": [string], "avoid": [string] }. Short canonical reference labels (max 120 chars each, max 30 per list) — artists, comics, films, directors, palettes, materials, eras the universe EMBRACES; styles, tropes, palettes the universe AVOIDS. The renderer prepends these to stylePrompt/negativePrompt verbatim, so each entry should read as a clean prompt token (e.g. "Moebius", "cel-shading", "Ghibli painterly", "neon cyberpunk"). When influence input is provided above, preserve those entries unless the starter idea explicitly contradicts them.
- stylePrompt: string. A single comma-separated style fragment (lighting, color palette, render quality, artist references) that will be PREFIXED to every variation prompt. Keep under 400 characters. No subject nouns — those go in variations. Echo the embrace influences here so the renderer-side prompt is self-contained even before the structured prepend kicks in.
-- negativePrompt: string. Comma-separated tokens to avoid (e.g. "blurry, lowres, watermark, extra fingers"). Tailor to the world's aesthetic. Echo the avoid influences here.
+- negativePrompt: string. Comma-separated tokens to avoid (e.g. "blurry, lowres, watermark, extra fingers"). Tailor to the universe's aesthetic. Echo the avoid influences here.
- categories: object. Atomic reusable buckets. Use snake_case keys. Start from these common buckets when useful:
${WORLD_CATEGORIES.map((c) => ` - ${c}`).join("\n")}
- Add, remove, or rename buckets to fit the user's actual world-building task. Do not force every project into the starter buckets.
+ Add, remove, or rename buckets to fit the user's actual universe-building task. Do not force every project into the starter buckets.
Useful extra buckets include colonies, factions, tribes, species, cultures, clothing_styles, material_palettes, fasteners_and_closures, tools, rituals, raider_clans, vehicles, settlements, and artifacts.
- compositeSheets: array. Complete, ready-to-render composite board prompts. Each item has { "kind": "reference_sheet" | "world_pitch_poster", "label": string, "prompt": string up to 4000 chars }. These are NOT atomic fragments; each prompt must describe one complete board/poster that combines multiple buckets into a single image.
@@ -147,26 +147,26 @@ Do NOT use \`[...]\`, \`…\`, or any other placeholder/elision tokens — every
Concrete compositeSheets examples:
{ "kind": "reference_sheet", "label": "Gas-Giant Drifters costume sheet", "prompt": "Create a clean illustrated costume reference sheet for Gas-Giant Drifters, a human colony living on floating platforms and balloon settlements high in a gas giant atmosphere. Show a simplified character lineup with five figures: kite child, storm scout, main hero, sky elder, and rig worker. Include material swatches for sailcloth, balloon-skin, rubberized algae fabric, salvaged foil, flex-ceramic patches, storm-glass lenses, braided tether cord, and copper wire ornament. Include fastener/accessory icons for buckles, spring clips, pressure rings, carabiner hooks, breathing collar, goggles, tether belt, strapped sky boots, and wind streamer tabs. Include a color strip: storm blue, saffron, hot coral, orange, slate gray, cream, electric cyan, copper, cloud white. Minimal readable layout, elegant negative space, light background hints of balloon platforms and storm clouds, not baroque, not hyper-detailed." }
- { "kind": "world_pitch_poster", "label": "World summary concept pitch poster", "prompt": "Create a cinematic world summary concept pitch poster for the whole setting. Use an editorial art-board layout: one dominant hero panorama showing the signature world location, several smaller inset environment and culture images, a small creature/species lineup, visual-language thumbnails, color palette strip, material/texture swatches, light-and-atmosphere notes, and theme icons. Include large title typography and a short subtitle/logline area, plus readable section headers such as The World, The Feel, Aesthetic, Environments, Cultures, Tone, Color Palette, Materials & Textures, and Light & Atmosphere. Keep body copy as short graphic blocks, not dense paragraphs. The poster should feel like a concept pitch board for a film/series/game, with clear hierarchy, elegant negative space, and cohesive art direction." }
+ { "kind": "world_pitch_poster", "label": "Universe summary concept pitch poster", "prompt": "Create a cinematic universe summary concept pitch poster for the whole setting. Use an editorial art-board layout: one dominant hero panorama showing the signature universe location, several smaller inset environment and culture images, a small creature/species lineup, visual-language thumbnails, color palette strip, material/texture swatches, light-and-atmosphere notes, and theme icons. Include large title typography and a short subtitle/logline area, plus readable section headers such as The Universe, The Feel, Aesthetic, Environments, Cultures, Tone, Color Palette, Materials & Textures, and Light & Atmosphere. Keep body copy as short graphic blocks, not dense paragraphs. The poster should feel like a concept pitch board for a film/series/game, with clear hierarchy, elegant negative space, and cohesive art direction." }
# Rules
-- Generate 5-12 categories total, choosing the buckets that serve the starter idea. Generate 4-10 variations per category. They must be visually distinct from each other but stylistically consistent with the world.
+- Generate 5-12 categories total, choosing the buckets that serve the starter idea. Generate 4-10 variations per category. They must be visually distinct from each other but stylistically consistent with the universe.
- Generate 3-8 compositeSheets when the starter idea involves clothing systems, colonies, factions, cultures, species, vehicles, settlements, props, posters, decks, or other grouped visual-design systems.
-- For broad world/universe/story settings, always include 1-3 "world_pitch_poster" compositeSheets in addition to any "reference_sheet" boards. These are summary concept pitch posters, not atomic character or environment sheets.
+- For broad universe/universe/story settings, always include 1-3 "world_pitch_poster" compositeSheets in addition to any "reference_sheet" boards. These are summary concept pitch posters, not atomic character or environment sheets.
- "label" is a short name a human can recognize (e.g. "Crystalline canyon basin", "Scavenger walker mech").
- "prompt" describes the SUBJECT only — the stylePrompt is automatically prepended at render time, so do NOT repeat style tokens in each variation.
- Do not include camera/aspect tokens; the renderer adds those.
-- Ground the world in the references provided. If the starter mentions specific artists, comics, films, games, or moods, weave them into stylePrompt.
-- If the user asks for style sheets, reference sheets, clothing guides, materials, colonies, factions, tribes, species, pirate/raider groups, world summary boards, concept pitch posters, or pitch-deck posters, create specific categories for the atomic facts AND create compositeSheets for the complete boards.
+- Ground the universe in the references provided. If the starter mentions specific artists, comics, films, games, or moods, weave them into stylePrompt.
+- If the user asks for style sheets, reference sheets, clothing guides, materials, colonies, factions, tribes, species, pirate/raider groups, universe summary boards, concept pitch posters, or pitch-deck posters, create specific categories for the atomic facts AND create compositeSheets for the complete boards.
- For colony clothing systems, include functional details like fasteners, closures, textile/material logic, silhouettes, class/role markers, weather or pressure adaptations, and culturally specific ornamentation.
- Reference-sheet prompts must include a clear board structure: title/subject, 4-6 figure lineup roles when relevant, materials swatches, fasteners/accessories icons, color palette strip, background hint, and simplicity constraints such as minimal readable layout, fewer tiny objects, clean silhouettes, not baroque, not hyper-detailed.
-- World pitch poster prompts must include a clear editorial poster structure: world title/subtitle/logline area, dominant hero panorama, inset environment/culture/creature images, visual-language strip, color palette, materials/textures, light/atmosphere, themes/icons, and concise labeled blocks for world, feel, aesthetic, environments, cultures, and tone. Mention that body copy should be short, clean, and readable; avoid dense tiny text.
-- If the world needs pitch posters, do not put "text" in the negativePrompt. Prefer "watermark, logo, unreadable tiny text, text artifacts" so title/section typography remains possible.
-- When "Current world state" is provided above: treat it as the established world. Fields marked [LOCKED] MUST be echoed in your output exactly as given — do not reword, expand, or trim them. Unlocked current-state fields are starting points; you may refine them, but stay consistent with locked fields, the starter idea, and influences.
+- Universe pitch poster prompts must include a clear editorial poster structure: universe title/subtitle/logline area, dominant hero panorama, inset environment/culture/creature images, visual-language strip, color palette, materials/textures, light/atmosphere, themes/icons, and concise labeled blocks for universe, feel, aesthetic, environments, cultures, and tone. Mention that body copy should be short, clean, and readable; avoid dense tiny text.
+- If the universe needs pitch posters, do not put "text" in the negativePrompt. Prefer "watermark, logo, unreadable tiny text, text artifacts" so title/section typography remains possible.
+- When "Current universe state" is provided above: treat it as the established universe. Fields marked [LOCKED] MUST be echoed in your output exactly as given — do not reword, expand, or trim them. Unlocked current-state fields are starting points; you may refine them, but stay consistent with locked fields, the starter idea, and influences.
- Output JUST the JSON object. No prose before or after.`;
}
-// Prefer a block that *looks like* a world-expansion response (has any of
+// Prefer a block that *looks like* a universe-expansion response (has any of
// stylePrompt / negativePrompt / categories / compositeSheets at the top
// level). The expansion prompt includes literal JSON examples like
// { "label": "Crystalline canyon basin", "prompt": "…" }
@@ -195,7 +195,7 @@ const extractJson = (raw) => {
});
if (value !== undefined) return value;
throw new ServerError(
- "LLM returned invalid JSON for world expansion. Try a different model or rerun.",
+ "LLM returned invalid JSON for universe expansion. Try a different model or rerun.",
{
status: 502,
code: "LLM_INVALID_JSON",
@@ -212,7 +212,7 @@ const extractJson = (raw) => {
const normalizeCategories = (raw) => {
// The LLM occasionally returns variations as a flat array of strings or
// skips the wrapping `{ variations: [...] }` object. Coerce both shapes
- // here so the world template stays consistent. Preserve custom buckets
+ // here so the universe template stays consistent. Preserve custom buckets
// (e.g. colonies, factions, clothing_styles) instead of forcing everything
// into the starter categories.
const out = {};
@@ -267,7 +267,7 @@ const normalizeCompositeSheets = (raw) =>
);
/**
- * Expand a starter prompt into a structured world template draft.
+ * Expand a starter prompt into a structured universe template draft.
* Returns { stylePrompt, negativePrompt, categories, compositeSheets, llm: { provider, model } }.
*
* @param {object} options
@@ -304,7 +304,7 @@ export async function expandWorldTemplate({
: null;
if (!provider) provider = await getActiveProvider();
if (!provider)
- throw new Error("No AI provider available for world expansion");
+ throw new Error("No AI provider available for universe expansion");
// resolveEffectiveModel mirrors what promptRunner resolves internally
// so the log line below + the returned `llm.model` field reflect what
// actually executed. For CLI providers with a baked --model/-m flag
@@ -333,7 +333,7 @@ export async function expandWorldTemplate({
? preservedCompositeSheets.length
: 0;
console.log(
- `🌍 World Builder expanding via ${provider.name}/${selectedModel || "default"} — influences in: ${totalIn ? `embrace=${safeInfluences.embrace.length} avoid=${safeInfluences.avoid.length}` : "none"} preserved: variations=${preservedVarCount} sheets=${preservedSheetCount}`,
+ `🌍 Universe Builder expanding via ${provider.name}/${selectedModel || "default"} — influences in: ${totalIn ? `embrace=${safeInfluences.embrace.length} avoid=${safeInfluences.avoid.length}` : "none"} preserved: variations=${preservedVarCount} sheets=${preservedSheetCount}`,
);
// runId is logged so a user debugging an empty expansion can find the
@@ -342,17 +342,17 @@ export async function expandWorldTemplate({
provider,
model: selectedModel,
prompt: fullPrompt,
- source: "world-builder-expansion",
+ source: "universe-builder-expansion",
});
// Log raw response shape so a "0 variations" outcome is debuggable from
// the server console alone — the runId points at data/runs/<id>/output.txt
// for the full transcript.
console.log(
- `🌍 World Builder raw response — runId=${runId} length=${raw?.length || 0}`,
+ `🌍 Universe Builder raw response — runId=${runId} length=${raw?.length || 0}`,
);
const parsed = extractJson(raw);
console.log(
- `🌍 World Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(",")}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(",")}] compositeSheets=${Array.isArray(parsed?.compositeSheets) ? parsed.compositeSheets.length : 0}`,
+ `🌍 Universe Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(",")}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(",")}] compositeSheets=${Array.isArray(parsed?.compositeSheets) ? parsed.compositeSheets.length : 0}`,
);
// Distinguish "LLM omitted this key" (return null → client keeps draft)
@@ -392,11 +392,11 @@ export async function expandWorldTemplate({
0,
);
console.log(
- `🌍 World Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, bible=${logline ? "yes" : "no"} (${perCat})`,
+ `🌍 Universe Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, bible=${logline ? "yes" : "no"} (${perCat})`,
);
if (totalVariations === 0 && compositeSheets.length === 0) {
console.warn(
- `⚠️ World Builder expansion produced 0 variations — inspect data/runs/${runId}/output.txt for the raw LLM response`,
+ `⚠️ Universe Builder expansion produced 0 variations — inspect data/runs/${runId}/output.txt for the raw LLM response`,
);
}
diff --git a/server/services/worldBuilderExpand.test.js b/server/services/universeBuilderExpand.test.js
similarity index 89%
rename from server/services/worldBuilderExpand.test.js
rename to server/services/universeBuilderExpand.test.js
index dff462a2e5..c5815fd333 100644
--- a/server/services/worldBuilderExpand.test.js
+++ b/server/services/universeBuilderExpand.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
-import { __testing } from "./worldBuilderExpand.js";
-import { WORLD_CATEGORIES } from "./worldBuilder.js";
+import { __testing } from "./universeBuilderExpand.js";
+import { WORLD_CATEGORIES } from "./universeBuilder.js";
const {
extractJson,
@@ -14,7 +14,7 @@ const EXPANSION_PROMPT = buildExpansionPrompt({
starterPrompt: "fixture starter",
});
-describe("worldBuilderExpand.extractJson", () => {
+describe("universeBuilderExpand.extractJson", () => {
it("parses a raw JSON object", () => {
const obj = {
stylePrompt: "a, b, c",
@@ -86,7 +86,7 @@ describe("worldBuilderExpand.extractJson", () => {
});
it("repairs Codex CLI orphan-brace corruption (`}}]` → `}]`) inside the response", () => {
- // Real-world: Codex produced `{"label":"...","prompt":"…blister"}}]}}}`
+ // Real-universe: Codex produced `{"label":"...","prompt":"…blister"}}]}}}`
// — an extra `}` snuck in between the variation's close-brace and the
// array's `]`. extractJson must recover that to a parsed expansion shape.
const badJson =
@@ -107,12 +107,12 @@ describe("worldBuilderExpand.extractJson", () => {
]);
});
- it("prefers a world-expansion-shaped object over an in-prompt JSON example", () => {
+ it("prefers a universe-expansion-shaped object over an in-prompt JSON example", () => {
// The actual prompt template includes literal JSON example variations:
// { "label": "Crystalline canyon basin", "prompt": "…" }
// These are valid JSON and brace-balance cleanly, but they aren't the
// response. extractJson must skip them and return the larger object that
- // has the world-expansion top-level keys.
+ // has the universe-expansion top-level keys.
const raw = [
"codex",
'{ "label": "Crystalline canyon basin", "prompt": "vast crystalline canyon, salt flats" }',
@@ -141,7 +141,7 @@ describe("worldBuilderExpand.extractJson", () => {
});
});
-describe("worldBuilderExpand.normalizeCategories", () => {
+describe("universeBuilderExpand.normalizeCategories", () => {
it("returns all canonical categories with empty variations on empty input", () => {
const out = normalizeCategories({});
for (const key of WORLD_CATEGORIES) {
@@ -217,7 +217,7 @@ describe("worldBuilderExpand.normalizeCategories", () => {
});
});
-describe("worldBuilderExpand.normalizeCompositeSheets", () => {
+describe("universeBuilderExpand.normalizeCompositeSheets", () => {
it("keeps complete composite reference-sheet prompts", () => {
const out = normalizeCompositeSheets([
{
@@ -247,21 +247,21 @@ describe("worldBuilderExpand.normalizeCompositeSheets", () => {
]);
});
- it("preserves world pitch poster board kind", () => {
+ it("preserves universe pitch poster board kind", () => {
const out = normalizeCompositeSheets([
{
kind: "world_pitch_poster",
- label: "World summary concept pitch poster",
+ label: "Universe summary concept pitch poster",
prompt:
- "Create a cinematic world summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.",
+ "Create a cinematic universe summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.",
},
]);
expect(out).toEqual([
{
kind: "world_pitch_poster",
- label: "World summary concept pitch poster",
+ label: "Universe summary concept pitch poster",
prompt:
- "Create a cinematic world summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.",
+ "Create a cinematic universe summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.",
},
]);
});
@@ -279,22 +279,22 @@ describe("worldBuilderExpand.normalizeCompositeSheets", () => {
});
});
-describe("worldBuilderExpand.EXPANSION_PROMPT", () => {
- it("allows dynamic world-building buckets and reference-sheet domains", () => {
+describe("universeBuilderExpand.EXPANSION_PROMPT", () => {
+ it("allows dynamic universe-building buckets and reference-sheet domains", () => {
expect(EXPANSION_PROMPT).toContain("Add, remove, or rename buckets");
expect(EXPANSION_PROMPT).toContain("colonies, factions, tribes, species");
expect(EXPANSION_PROMPT).toContain("clothing guides");
expect(EXPANSION_PROMPT).toContain("raider_clans");
expect(EXPANSION_PROMPT).toContain("compositeSheets");
expect(EXPANSION_PROMPT).toContain("world_pitch_poster");
- expect(EXPANSION_PROMPT).toContain("world summary concept pitch poster");
+ expect(EXPANSION_PROMPT).toContain("universe summary concept pitch poster");
expect(EXPANSION_PROMPT).toContain("materials swatches");
});
it("asks the LLM to emit a narrative bible (logline / premise / styleNotes)", () => {
// The pipeline pulls these straight into the New Series form, so the
// contract has to stay in the prompt. If this assertion fails, double-
- // check that worldBuilderExpand.js still hydrates the three fields too.
+ // check that universeBuilderExpand.js still hydrates the three fields too.
expect(EXPANSION_PROMPT).toContain("logline:");
expect(EXPANSION_PROMPT).toContain("premise:");
expect(EXPANSION_PROMPT).toContain("styleNotes:");
@@ -326,12 +326,12 @@ describe("worldBuilderExpand.EXPANSION_PROMPT", () => {
expect(out).toContain("Avoid: Ghibli painterly");
});
- it("omits the Current world state section when no bible/prompt fields are provided", () => {
+ it("omits the Current universe state section when no bible/prompt fields are provided", () => {
const out = buildExpansionPrompt({ starterPrompt: "seed" });
- expect(out).not.toContain("# Current world state");
+ expect(out).not.toContain("# Current universe state");
});
- it("includes provided bible + prompt fields as Current world state context", () => {
+ it("includes provided bible + prompt fields as Current universe state context", () => {
const out = buildExpansionPrompt({
starterPrompt: "seed",
priorLogline: "A foundry city goes silent.",
@@ -340,7 +340,7 @@ describe("worldBuilderExpand.EXPANSION_PROMPT", () => {
priorStylePrompt: "moebius linework, dust palette",
priorNegativePrompt: "blurry, lowres",
});
- expect(out).toContain("# Current world state");
+ expect(out).toContain("# Current universe state");
expect(out).toContain("LOGLINE: A foundry city goes silent.");
expect(out).toContain("PREMISE: Three families inherit the silence.");
expect(out).toContain("STYLE NOTES: Tarkovsky pacing, Moebius palette.");
@@ -384,7 +384,7 @@ describe("worldBuilderExpand.EXPANSION_PROMPT", () => {
expect(out).toMatch(/Avoid \[LOCKED\]: Ghibli/);
});
- it("skips empty bible/prompt fields from Current world state", () => {
+ it("skips empty bible/prompt fields from Current universe state", () => {
const out = buildExpansionPrompt({
starterPrompt: "seed",
priorLogline: "Just a logline.",
diff --git a/server/services/worldBuilderRefine.js b/server/services/universeBuilderRefine.js
similarity index 93%
rename from server/services/worldBuilderRefine.js
rename to server/services/universeBuilderRefine.js
index 2c029701f0..25454043de 100644
--- a/server/services/worldBuilderRefine.js
+++ b/server/services/universeBuilderRefine.js
@@ -1,14 +1,14 @@
/**
- * World Builder — refine the 3 top-level prompts (starter idea, style prompt,
+ * Universe Builder — refine the 3 top-level prompts (starter idea, style prompt,
* negative prompt) based on user feedback. Mirrors the media prompt-refine
- * flow (see `mediaPromptRefiner.js`) but operates on a world template rather
+ * flow (see `mediaPromptRefiner.js`) but operates on a universe template rather
* than an individual render.
*
* The LLM gets the originals + a free-form feedback string and returns:
* { starterPrompt, stylePrompt, negativePrompt, rationale, changes? }
*
* The caller (route → UI) presents the refined fields for review before they
- * overwrite the draft, so the LLM never silently mutates a saved world.
+ * overwrite the draft, so the LLM never silently mutates a saved universe.
*/
import { ServerError } from "../lib/errorHandler.js";
@@ -18,7 +18,7 @@ import { resolveEffectiveModel } from "../lib/promptRunner.js";
import {
renderCategoriesForPrompt as renderCategoriesShared,
renderCompositesForPrompt as renderCompositesShared,
-} from "../lib/worldPromptRenderers.js";
+} from "../lib/universePromptRenderers.js";
import {
COMPOSITE_PROMPT_MAX,
COMPOSITE_SHEETS_MAX,
@@ -40,7 +40,7 @@ import {
sanitizeCompositeSheets,
sanitizeInfluences,
sanitizeLocked,
-} from "./worldBuilder.js";
+} from "./universeBuilder.js";
const MAX_FEEDBACK = 3000;
const MAX_RATIONALE = 1200;
@@ -191,20 +191,20 @@ ${lockedRules.join("\n")}
const structureRules = hasStructure
? `
-STRUCTURE RULES (the world has been expanded — categories and composite sheets are part of this refinement):
+STRUCTURE RULES (the universe has been expanded — categories and composite sheets are part of this refinement):
- Each category groups related prompt variations (factions, characters, vehicles, etc.). Each variation is { "label", "prompt" } and may be flagged [LOCKED].
- Each composite sheet is a multi-subject board (kind "reference_sheet" or "world_pitch_poster") with { "label", "prompt" }, also [LOCKED]-flaggable.
- Variations / composites flagged [LOCKED] must be returned with their EXACT original label + prompt — do not rephrase, expand, trim, or "lightly clean up" them. The server discards changes to locked items.
- Unlocked variations / composites may be rewritten, replaced (same label, new prompt), or REMOVED if the user's feedback warrants it. Removing an item means omitting it from the response.
- EXPLICIT REMOVAL IS A DIRECT ORDER. If the user names a specific variation, composite, faction, character, location, or other entity to remove ("drop X", "remove X", "delete X", "get rid of X", "no more X"), you MUST:
(a) OMIT any variation whose label matches X from the response entirely (do not return it under a renamed label either).
- (b) OMIT any composite sheet whose primary subject IS X — even if a sibling subject remains. For example, if the user removes "Faction A" and a sheet is titled "Faction A vs Faction B branding sheet", omit the whole sheet; replace it with a single-subject sheet for Faction B only if the world still warrants it.
+ (b) OMIT any composite sheet whose primary subject IS X — even if a sibling subject remains. For example, if the user removes "Faction A" and a sheet is titled "Faction A vs Faction B branding sheet", omit the whole sheet; replace it with a single-subject sheet for Faction B only if the universe still warrants it.
(c) SCRUB every textual reference to X from the prompts of any remaining unlocked composites and variations (faction lists, inset panels, comparison columns, callouts, etc.). Rewrite those prompts so X is not mentioned. If a remaining unlocked composite's prompt becomes incoherent once X is scrubbed, remove that composite too.
(d) References to X inside LOCKED items (locked variations, locked composites, locked narrative fields) cannot be edited — leave them, but do not let them tempt you into re-adding X under a new label. The server will not re-add X just because a locked field still mentions it.
- You MAY ADD new variations to any existing category, propose ENTIRELY NEW categories, and ADD new composite sheets when the feedback motivates it. Use snake_case keys for new category names (e.g. "secret_rituals").
- Keep category counts manageable: at most ${WORLD_CATEGORY_COUNT_MAX} total categories, ${VARIATIONS_PER_CATEGORY_MAX} variations per category, ${COMPOSITE_SHEETS_MAX} composite sheets.
- Variation prompts ≤${PROMPT_FRAGMENT_MAX} chars; composite prompts ≤${COMPOSITE_PROMPT_MAX} chars; labels ≤${VARIATION_LABEL_MAX} chars.
-- When updating an unlocked composite that references a renamed/removed variation, update the composite's prompt to match — keep the world internally consistent.
+- When updating an unlocked composite that references a renamed/removed variation, update the composite's prompt to match — keep the universe internally consistent.
- For LOCKED influence lists in this refine: preserve every existing token IN ORDER, but you MAY APPEND new tokens at the end. You may NOT remove, reorder, or rewrite existing locked tokens. The server enforces order preservation regardless.
`
: "";
@@ -225,16 +225,16 @@ ${renderCompositesForPrompt(compositeSheets) || " (none)"}
"compositeSheets": [ { "kind": "reference_sheet" | "world_pitch_poster", "label": "<short label>", "prompt": "<full board prompt>", "locked": true } ]`
: "";
- return `You are a senior world-building editor for a Stable-Diffusion-style image-generation pipeline AND a story-bible drafter for a comic/TV production pipeline.
+ return `You are a senior universe-building editor for a Stable-Diffusion-style image-generation pipeline AND a story-bible drafter for a comic/TV production pipeline.
-The user has seven top-level fields that define a "world":
-- STARTER IDEA — the high-concept seed the world expander fans out into categories.
+The user has seven top-level fields that define a "universe":
+- STARTER IDEA — the high-concept seed the universe expander fans out into categories.
- STYLE PROMPT — comma-separated visual style tokens prepended to every render (palette, lighting, render quality, artist references).
- NEGATIVE PROMPT — comma-separated tokens to avoid in renders.
- LOGLINE — one-sentence narrative hook.
- PREMISE — 1-3 paragraph elevator pitch (setting, conflict, stakes, tone).
- STYLE NOTES — narrative-side prose about references, mood, palette, pacing, voice.
-- INFLUENCES — structured { embrace: [string], avoid: [string] } reference list. The renderer prepends embrace verbatim to the style prompt and avoid verbatim to the negative prompt, so this is the canonical record of "what direction is this world pointing." Each entry is a short prompt-token-style label (e.g. "Moebius", "cel-shading", "Ghibli painterly"). Max 30 entries per list, max 120 chars each.
+- INFLUENCES — structured { embrace: [string], avoid: [string] } reference list. The renderer prepends embrace verbatim to the style prompt and avoid verbatim to the negative prompt, so this is the canonical record of "what direction is this universe pointing." Each entry is a short prompt-token-style label (e.g. "Moebius", "cel-shading", "Ghibli painterly"). Max 30 entries per list, max 120 chars each.
The user has given feedback about the story, mood, style, or design they want refined. Rewrite ALL seven fields so they more faithfully express the user's intention and stay internally consistent. Output the COMPLETE rewritten text/values for each — not a placeholder, not a summary, not a diff.
@@ -252,10 +252,10 @@ ${lockedSection}Return ONLY valid JSON in this schema (replace every <…> with
}
Rules:
-- Preserve story/character/world DNA from the originals unless the user's feedback explicitly contradicts it.
+- Preserve story/character/universe DNA from the originals unless the user's feedback explicitly contradicts it.
- The "starterPrompt" stays a clean high-concept seed — no category content (landscapes, factions, etc.) and no style-direction prose. The structured "influences" field carries that direction so re-expansions inherit it deterministically.
- The "stylePrompt" must be comma-separated visual-style tokens only. No subject nouns. No camera/aspect tokens. Under 400 characters. It SHOULD echo every "embrace" influence so the prompt is self-contained even before the structured prepend kicks in.
-- The "negativePrompt" must be comma-separated tokens. It SHOULD echo every "avoid" influence. If the world relies on text/typography (e.g. pitch posters), avoid putting "text" in negatives — prefer "watermark, logo, unreadable tiny text, text artifacts".
+- The "negativePrompt" must be comma-separated tokens. It SHOULD echo every "avoid" influence. If the universe relies on text/typography (e.g. pitch posters), avoid putting "text" in negatives — prefer "watermark, logo, unreadable tiny text, text artifacts".
- The "influences" lists are the canonical reference set. Add what the user's feedback embraces, drop what's no longer relevant, and add explicit avoids for things they're moving away from. Keep entries short (a name, a movement, a palette descriptor) — they're prepended verbatim to the renderer prompt.
- The "logline", "premise", and "styleNotes" must stay narratively coherent with the refined influences and style prompts.
- Apply the user's feedback decisively. If they ask for a different style/mood/era, move toward it in influences + style prompt + styleNotes, and name the things to avoid in negativePrompt + influences.avoid.
@@ -354,7 +354,7 @@ async function runRefine(provider, model, prompt) {
providerId: provider.id,
model,
prompt,
- source: "world-builder-refine",
+ source: "universe-builder-refine",
});
let text = "";
@@ -365,7 +365,7 @@ async function runRefine(provider, model, prompt) {
const onComplete = (result) => {
if (result?.error || result?.success === false) {
reject(
- new ServerError(result?.error || "World refinement failed", {
+ new ServerError(result?.error || "Universe refinement failed", {
status: 502,
code: "WORLD_REFINE_FAILED",
}),
@@ -408,7 +408,7 @@ async function runRefine(provider, model, prompt) {
}
/**
- * Refine world fields. Operates in two modes:
+ * Refine universe fields. Operates in two modes:
* - Bible-only (pre-Expand): categories + compositeSheets omitted; behavior
* matches the original refine — rewrite the seven scalar/influence fields
* per feedback.
@@ -482,7 +482,7 @@ export async function refineWorldPrompts({
: null;
if (!provider) provider = await getActiveProvider();
if (!provider) {
- throw new ServerError("No AI provider available for world refinement", {
+ throw new ServerError("No AI provider available for universe refinement", {
status: 400,
code: "NO_PROVIDER",
});
@@ -500,7 +500,7 @@ export async function refineWorldPrompts({
// decision table.
const selectedModel = resolveEffectiveModel(provider, model) || "";
if (!selectedModel && provider.type === "api") {
- throw new ServerError("Model is required for world refinement", {
+ throw new ServerError("Model is required for universe refinement", {
status: 400,
code: "MODEL_REQUIRED",
});
@@ -533,7 +533,7 @@ export async function refineWorldPrompts({
parsed = extractRefinementJson(text || "");
} catch (e) {
console.warn(
- `⚠️ world-refine [${provider.id}/${selectedModel || "default"} runId=${runId}] parse failed: ${e.message} (response size: ${(text || "").length} chars)`,
+ `⚠️ universe-refine [${provider.id}/${selectedModel || "default"} runId=${runId}] parse failed: ${e.message} (response size: ${(text || "").length} chars)`,
);
throw new ServerError(e.message, {
status: 502,
diff --git a/server/services/worldBuilderRefine.test.js b/server/services/universeBuilderRefine.test.js
similarity index 95%
rename from server/services/worldBuilderRefine.test.js
rename to server/services/universeBuilderRefine.test.js
index 548a1f4f90..0446aa67c5 100644
--- a/server/services/worldBuilderRefine.test.js
+++ b/server/services/universeBuilderRefine.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
-import { __testing } from "./worldBuilderRefine.js";
-import { mergeInfluencesWithLocksAdditive } from "./worldBuilder.js";
+import { __testing } from "./universeBuilderRefine.js";
+import { mergeInfluencesWithLocksAdditive } from "./universeBuilder.js";
const {
extractRefinementJson,
@@ -10,10 +10,10 @@ const {
mergeCompositesWithLocks,
} = __testing;
-describe("worldBuilderRefine.extractRefinementJson", () => {
+describe("universeBuilderRefine.extractRefinementJson", () => {
it("parses a raw refinement object", () => {
const obj = {
- starterPrompt: "a darker scavenger world",
+ starterPrompt: "a darker scavenger universe",
stylePrompt: "gritty palette, deep shadows",
negativePrompt: "cute, neon",
rationale: "pushed mood toward grim",
@@ -45,10 +45,10 @@ describe("worldBuilderRefine.extractRefinementJson", () => {
// the real response below it.
'{"starterPrompt":"<full rewritten…>","stylePrompt":"<…>","negativePrompt":"<…>"}',
"codex response:",
- '{"starterPrompt":"a darker world","stylePrompt":"gritty","negativePrompt":""}',
+ '{"starterPrompt":"a darker universe","stylePrompt":"gritty","negativePrompt":""}',
].join("\n");
const out = extractRefinementJson(raw);
- expect(out.starterPrompt).toBe("a darker world");
+ expect(out.starterPrompt).toBe("a darker universe");
expect(out.stylePrompt).toBe("gritty");
});
@@ -72,7 +72,7 @@ describe("worldBuilderRefine.extractRefinementJson", () => {
});
});
-describe("worldBuilderRefine.buildWorldRefinePrompt", () => {
+describe("universeBuilderRefine.buildWorldRefinePrompt", () => {
it("includes all three originals + feedback verbatim", () => {
const out = buildWorldRefinePrompt({
starterPrompt: "moebius scavengers",
@@ -196,7 +196,7 @@ describe("worldBuilderRefine.buildWorldRefinePrompt", () => {
});
});
-describe("worldBuilderRefine.collapseStyleDirectionDupes", () => {
+describe("universeBuilderRefine.collapseStyleDirectionDupes", () => {
it("returns input untouched when no Style direction block is present", () => {
expect(collapseStyleDirectionDupes("a foundry city goes silent")).toBe(
"a foundry city goes silent",
@@ -247,7 +247,7 @@ describe("worldBuilderRefine.collapseStyleDirectionDupes", () => {
});
});
-describe("worldBuilderRefine.buildWorldRefinePrompt — structure-aware path", () => {
+describe("universeBuilderRefine.buildWorldRefinePrompt — structure-aware path", () => {
it("emits an ORIGINAL CATEGORIES block + structure schema when categories are passed", () => {
const out = buildWorldRefinePrompt({
starterPrompt: "seed",
@@ -304,7 +304,7 @@ describe("worldBuilderRefine.buildWorldRefinePrompt — structure-aware path", (
});
});
-describe("worldBuilderRefine.mergeCategoriesWithLocks", () => {
+describe("universeBuilderRefine.mergeCategoriesWithLocks", () => {
it("preserves locked variations and replaces unlocked ones from LLM output", () => {
const original = {
factions: {
@@ -387,7 +387,7 @@ describe("worldBuilderRefine.mergeCategoriesWithLocks", () => {
});
});
-describe("worldBuilderRefine.mergeCompositesWithLocks", () => {
+describe("universeBuilderRefine.mergeCompositesWithLocks", () => {
it("preserves locked composites verbatim and rewrites unlocked ones", () => {
const original = [
{ kind: "world_pitch_poster", label: "Pitch", prompt: "original pitch", locked: true },
@@ -406,7 +406,7 @@ describe("worldBuilderRefine.mergeCompositesWithLocks", () => {
});
});
-describe("worldBuilder.mergeInfluencesWithLocksAdditive (refine-time)", () => {
+describe("universeBuilder.mergeInfluencesWithLocksAdditive (refine-time)", () => {
it("preserves locked tokens in order and APPENDS new tokens from LLM", () => {
const merged = mergeInfluencesWithLocksAdditive(
{ influencesEmbrace: true, influencesAvoid: true },