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

universe-builder: Phase D — promote variation to canon (#281)

[._.]/ Adam Eivyfe2bb13f0c84
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 04fe4f8a83..761e6dd480 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Changed
+- **Promote a variation into canon with one click (Universe Builder Phase D).** Every variation card under Cast / Places / Objects now has a "Promote to canon" button — the server LLM-expands the `{label, prompt}` into a fully fleshed canon entry (per-kind: `physicalDescription` / `personality` for characters; `slugline` / `palette` / `era` / `recurringDetails` for places; `description` / `significance` for objects), removes the source variation in the same atomic write, and adds the new entry to the universe's canon array. The button gates on whether the universe is persisted (the action reads the saved record) and on the bucket's `kind`: buckets from the **Other** tab open a trunk picker (Character / Place / Object) since their kind is ambiguous. Duplicate names by canon entry are refused with a 409 so a re-promote can't silently fork an existing record. Endpoint: `POST /api/universe-builder/:id/promote-variation`.
- **Universe Builder redesign — tabbed trunks replace the long-scroll layout.** The Universe Builder page is now organized into seven tabs — **Bible / Cast / Places / Objects / Composites / Render** (plus **Other** when un-classified buckets exist) — driven by `?tab=…&bucket=…` URL params (deep-linkable, back/forward works, mobile collapses to a `<select>`). Each canon trunk surfaces the universe's canon entries alongside that trunk's sub-buckets in one card grid: filter by sub-bucket via chip strip, "Bulk-render all Cast/Places/Objects" hits canon + every variation under the trunk in one render run, "Bulk-render this bucket" scopes to a single sub-bucket. The **Render** tab consolidates the batch-render controls + adds per-trunk, per-bucket, "All canon" and "All composites" one-click targets. Server-side: `compilePrompts` now accepts `canonSelection` and a new `promptMode: 'canon'` (`'all'` includes canon too), synthesizing the render prompt from `name + physicalDescription / palette / description / recurringDetails / significance` for entries without a hand-authored prompt. The legacy long-scroll layout is gone.
- **CoS agent completion paths now share `finalizeAgent` + `releaseAgentLane` helpers.** The TUI shell-session path, the direct-CLI path, and the runner-mode completion handler used to each carry their own copy of the lane release / completeAgent / completeAgentRun / updateTask / provider-marker / processAgentCompletion sequence. Drift between them silently broke one path at a time. Lane release + tool-execution tracking now run early (before output I/O) via `releaseAgentLane()`, and the centralized state writes (completeAgent → completeAgentRun → updateTask → provider markers → processAgentCompletion) go through `finalizeAgent()` — a future change in either contract is a one-place fix.
- **CoS runner-agent map no longer leaks on hook crashes.** A throw from any post-completion step (memory extraction, JIRA push, provider marker, etc.) used to skip the final `runnerAgents.delete(agentId)` and strand the entry forever. The completion sequence is now wrapped in try/finally; the error still surfaces but the in-memory state stays coherent.
diff --git a/PLAN.md b/PLAN.md
index 1ee651ec1c..ccbea63533 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -10,7 +10,12 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- **Phase A — Data model + migration.** Add `kind: 'characters'|'settings'|'objects'|'other'` field to category sanitizer (`server/services/universeBuilder.js#sanitizeCategories`) and Zod (`server/routes/universeBuilder.js#categoryShape`); default to `'other'` when missing/invalid. Sub-bucket keys remain **globally unique** (no per-trunk namespacing). Migration `scripts/migrations/NNN-categorize-universe-buckets.js` assigns built-in defaults: `landscapes/environments/structures → settings`, `vehicles → objects`. The default `characters` category is retired; its variations backfill into `universe.characters[]` (reuse `backfillCanonFromCategories` logic). All other existing custom categories get `kind: 'other'`; Phase C surfaces them under an **Other** tab with an **Auto-sort** button that LLM-classifies each bucket into the right trunk + a meaningful name.
- **Phase B — Expand contract enrichment.** Teach `buildExpansionPrompt()` (`server/services/universeBuilderExpand.js`) to return rich canon arrays (`characters[]`/`settings[]`/`objects[]` with `physicalDescription`/`palette`/`recurringDetails`/`wardrobe`) alongside the existing `categories` (now kind-tagged) + `compositeSheets`. Update `isExpansionShape()` predicate. Client `handleExpand` in `UniverseBuilder.jsx` merges canon entries into the canon arrays parallel to the category merge (dedupe by name, respect per-entry locks). Categories the LLM emits include a `kind` so they land under the right trunk.
- **Phase C — Layout rewrite.** Tabbed top-level (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state (`?tab=cast&bucket=heroes` per CLAUDE.md linkable-routes convention) — Bible is its own tab (not a sticky header). Per-trunk view = sub-bucket chip filter row + responsive card grid. Unify `CanonCard` + a new card for category variations into a single `EntryCard` component (renders thumbnail from `primaryImageRef` or most recent render). **Canon entries are first-class batch-render targets** alongside category variations and composite sheets: per-bucket actions are "Generate N more" + "Bulk-render this bucket"; per-trunk action is "Bulk-render all Cast/Places/Objects" (includes BOTH canon entries AND every variation in every sub-bucket under that trunk); the Batch Render tab itself offers per-trunk, per-bucket, and "All canon" selectors plus the existing composite-sheets mode. Composite reference images stay intact as their own render mode (no regression). Server-side: extend `compilePrompts` to accept canon entries as render sources (synthesize a prompt from `name + physicalDescription/palette/description`, layered with the universe style preset the same way variations are today). The **Other** tab only appears when un-kinded buckets exist, and shows the **Auto-sort with AI** action. Mobile: tabs collapse to a select dropdown.
- - **Phase D — Polish & promotion.** "Promote variation to canon" action: take a `{label, prompt}` variation, expand it via LLM into a full canon entry (`name`, `physicalDescription`, etc.) and move it from the category bucket into the canon array. Tests for the new components. Extract design to `docs/features/universe-builder.md` if the doc warrants it.
+ - **Phase D — Polish & promotion.** ~~"Promote variation to canon" action~~ shipped: `POST /api/universe-builder/:id/promote-variation` LLM-expands a `{label, prompt}` variation into a full canon entry (per-kind `physicalDescription` / `slugline`+`palette` / `description`+`significance`) and atomically writes the canon append + variation removal in one `updateUniverse` patch. CategoryEditor renders a promote button per row; Other-tab buckets open a trunk picker (since `kind: 'other'` can't be auto-resolved). Duplicate-name collisions short-circuit with a 409 before the LLM call. Deferred: client component tests; standalone design doc (not warranted — CLAUDE.md notes + this PR's prose cover the contract).
+ - **Phase D follow-ups (deferred from the Phase D PR):**
+ - [ ] **Extract `resolveProviderAndModel({providerId, model})` into `server/lib/promptRunner.js`.** The same 5-line `getProviderById/getActiveProvider/resolveEffectiveModel` chain now lives in `expandWorldTemplate` (`universeBuilderExpand.js`), the refine entrypoint (`universeBuilderRefine.js`), AND `promoteVariationToCanon` (`universeBuilderPromote.js`). Three identical copies — consolidate next time we touch any of them.
+ - [ ] **Add `findBibleEntryByName(list, name)` to `server/lib/storyBible.js`.** The "match name OR aliases case-insensitively" pattern lives in `promoteVariationToCanon` (duplicate-collision check) and `foldRetiredCharactersBucket` (seen-set construction) in `universeBuilder.js`. Will land a third caller when the Phase C auto-sort classifier ships.
+ - [ ] **Serialize universe write-paths server-side (`updateUniverse` queue per universe id).** Phase D ships a page-level client gate (`promoting` ref) that prevents the user from triggering concurrent promotes against one universe, but the server-side write path is still vulnerable to multi-client / multi-instance concurrent writes that compute `nextCanon`/`nextVariations` from stale snapshots and clobber each other. Mirror the `issueWriteTail`-style per-record queue pattern in `server/services/pipeline/issues.js` so every `updateUniverse(id, patch)` serializes on `id`. Per CLAUDE.md "Async PATCH races on shared records — serialize writes server-side."
+ - [ ] **Client component tests for `CategoryEditor` promote wiring + `TrunkView` button visibility.** Assert promote button disabled when `!selectedId`, picker opens for `kind: 'other'` buckets, picker option click invokes `onPromote` with the correct `targetKind`. No client vitest infra wired for `UniverseBuilder.jsx` yet — add when the page's first spec lands.
- **Phase C follow-ups (deferred from the Phase C PR):**
- [ ] **Auto-sort with AI** — LLM-classify each `kind: 'other'` bucket into characters/settings/objects + suggest a meaningful name. New server route `POST /api/universe-builder/:id/auto-sort` that sends bucket keys + variation labels to the active LLM and applies the classification. Currently the Other-tab button is a stub that points users at re-running Generate From Idea (Phase B's expand emits kind tags). Land in a follow-up to keep the Phase C PR scoped.
- [ ] **Unify `CanonCard` + variation card into a single `EntryCard`.** Phase C reuses `CanonCard` for canon and `CategoryEditor` for variations inside the same TrunkView. Visual consistency is achieved through shared Tailwind classes; an actual single-component unification (with thumbnail-from-`primaryImageRef`-or-recent-render) is the Phase D card-extraction task.
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 9a8d0bd305..6eb0c966fd 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -12,13 +12,13 @@ import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'reac
import {
Globe2, Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,
Edit3, X, MessageSquarePlus, Play, Lock, Unlock,
- PanelLeftClose, PanelLeftOpen,
+ PanelLeftClose, PanelLeftOpen, ArrowUpCircle,
BookOpen, Users, MapPin, Package, Layers, ImagePlus, FolderTree,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import {
listUniverses, getUniverse, createUniverse, updateUniverse, deleteUniverse, expandUniverse,
- generateCategoryVariations,
+ generateCategoryVariations, promoteVariationToCanon,
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,
@@ -67,6 +67,7 @@ const TRUNK_TABS = [
{ id: TAB_OBJECTS, kind: 'objects', label: 'Objects', icon: Package },
];
const TRUNK_BY_ID = Object.fromEntries(TRUNK_TABS.map((t) => [t.id, t]));
+const TRUNK_BY_KIND = Object.fromEntries(TRUNK_TABS.map((t) => [t.kind, t]));
// Group category buckets by their `kind` tag. Buckets with an unknown / missing
// kind fall into the `other` bin — that bin drives whether the Other tab shows.
@@ -367,6 +368,20 @@ export default function UniverseBuilder() {
// The draft is the editable copy of the currently-selected world. New
// universes start as a draft with no id; saving creates the persisted record.
const [draft, setDraft] = useState(emptyTemplate());
+ // Mount tracker for deferred setState after async work (handlePromoteVariation
+ // can run for 5–30s while the LLM thinks). CLAUDE.md "Deferred work must
+ // respect both staleness and unmount" — never reset to true so dev-mode
+ // double-mount stays clean.
+ const mountedRef = useRef(true);
+ useEffect(() => () => { mountedRef.current = false; }, []);
+ // Page-level in-flight gate for the promote action. Ref + state pair so
+ // the disable check stays synchronous (ref) while still triggering renders
+ // (state). Promote writes to `universe[bibleField]` and `categories[key]`
+ // as wholesale replacements from a stale snapshot — letting two run in
+ // parallel against the same universe would let the second clobber the
+ // first's canon append.
+ const [promoting, setPromoting] = useState(false);
+ const promotingRef = useRef(false);
const [newCategoryName, setNewCategoryName] = useState('');
// True when handleExpand merged new canon entries into the draft that the
// server doesn't yet know about (auto-save failed or hasn't run). On the
@@ -1169,6 +1184,63 @@ export default function UniverseBuilder() {
}
toast.success(`Added ${additionCount} variation${additionCount === 1 ? '' : 's'} to ${humanizeCategory(cat)} — review then Save`);
};
+ // Requires `selectedId` — the server action reads the persisted record,
+ // so an unsaved draft can't be promoted from. The page-level `promoting`
+ // gate prevents two promotes (across buckets or trunks) from racing each
+ // other to stale-snapshot writes against the same universe.
+ const handlePromoteVariation = async (category, variation, { targetKind } = {}) => {
+ if (!selectedId) {
+ toast.error('Save the universe first — promote needs the persisted record');
+ return;
+ }
+ if (!variation?.label) return;
+ if (promotingRef.current) return;
+ promotingRef.current = true;
+ setPromoting(true);
+ const capturedId = selectedId;
+ const toastId = toast.loading(`Promoting "${variation.label}" to canon…`);
+ const result = await promoteVariationToCanon(selectedId, {
+ category,
+ label: variation.label,
+ targetKind,
+ providerId: draft.llm?.provider || undefined,
+ model: draft.llm?.model || undefined,
+ }, { silent: true }).catch((e) => {
+ toast.dismiss(toastId);
+ toast.error(`Promote failed: ${e.message}`);
+ return null;
+ });
+ if (mountedRef.current) {
+ promotingRef.current = false;
+ setPromoting(false);
+ }
+ if (!result?.universe) return;
+ const updated = result.universe;
+ // Always update the cached list — even when the user navigated away mid-
+ // flight, the persisted shape changed and other surfaces should see it.
+ setWorlds((prev) => {
+ const without = prev.filter((w) => w.id !== updated.id);
+ return [updated, ...without];
+ });
+ // Guard: if the user navigated to a different universe during the LLM
+ // call, the response belongs to the previous one — don't clobber the
+ // new draft. The list update above still surfaces the change.
+ if (!mountedRef.current || capturedId !== selectedId) return;
+ // Selective merge: only the canon array + the affected category bucket
+ // changed server-side. Preserve every other draft field (the user may
+ // have typed into logline/premise/influences during the LLM call).
+ setDraft((d) => ({
+ ...d,
+ characters: updated.characters,
+ settings: updated.settings,
+ objects: updated.objects,
+ categories: { ...d.categories, [result.removed.category]: updated.categories?.[result.removed.category] },
+ schemaVersion: updated.schemaVersion,
+ updatedAt: updated.updatedAt,
+ }));
+ toast.dismiss(toastId);
+ toast.success(`Promoted "${variation.label}" → ${result.targetKind} canon`);
+ };
const updateCompositeSheets = (sheets) => setDraft((d) => ({ ...d, compositeSheets: sheets }));
const addCategory = () => {
const key = normalizeCategoryKey(newCategoryName);
@@ -1454,11 +1526,13 @@ export default function UniverseBuilder() {
activeBucket={activeBucket}
setBucket={setBucket}
canRender={canRender}
+ canPromote={!!selectedId && !promoting}
imageCfg={imageCfg}
onUniverseChange={handleCanonChange}
onRemoveBucket={removeCategory}
onUpdateBucket={updateCategory}
onGenerateInBucket={handleGenerateInCategory}
+ onPromoteVariation={(bucket, v) => handlePromoteVariation(bucket, v)}
onBulkRenderBucket={(bucket) => runRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}
onRenderVariation={(bucket, v) => runRender({ promptMode: 'variations', selection: { [bucket]: [v.label] } })}
onBulkRenderTrunk={() => {
@@ -1489,9 +1563,11 @@ export default function UniverseBuilder() {
activeBucket={activeBucket}
setBucket={setBucket}
canRender={canRender}
+ canPromote={!!selectedId && !promoting}
onUpdateBucket={updateCategory}
onRemoveBucket={removeCategory}
onGenerateInBucket={handleGenerateInCategory}
+ onPromoteVariation={(bucket, v, opts) => handlePromoteVariation(bucket, v, opts)}
onBulkRenderBucket={(bucket) => runRender({ promptMode: 'variations', selection: { [bucket]: 'all' } })}
onRenderVariation={(bucket, v) => runRender({ promptMode: 'variations', selection: { [bucket]: [v.label] } })}
onAutoSort={() => {
@@ -1896,7 +1972,12 @@ function CategoryEditor({
category, variations, canRemove = false, onChange, onRemove,
canRender = false, onRenderCategory = null, onRenderVariation = null,
onGenerate = null,
+ // `bucketKind` drives the promote-button UX: when `'other'` (or absent)
+ // the picker opens to choose a trunk; otherwise we promote directly.
+ // `canPromote` gates on universe-persisted (the action reads the saved record).
+ canPromote = false, bucketKind = null, onPromote = null,
}) {
+ const requiresTargetKind = !TRUNK_BY_KIND[bucketKind];
const [adding, setAdding] = useState(false);
const [newLabel, setNewLabel] = useState('');
const [newPrompt, setNewPrompt] = useState('');
@@ -1906,15 +1987,38 @@ function CategoryEditor({
const [genOpen, setGenOpen] = useState(false);
const [genCustom, setGenCustom] = useState('');
const [generating, setGenerating] = useState(false);
+ const [promotingIdx, setPromotingIdx] = useState(null);
+ const [pickerIdx, setPickerIdx] = useState(null);
const genWrapRef = useRef(null);
+ const pickerWrapRef = useRef(null);
useClickOutside(genWrapRef, genOpen, () => setGenOpen(false));
+ useClickOutside(pickerWrapRef, pickerIdx !== null, () => setPickerIdx(null));
useEffect(() => {
if (!genOpen) return undefined;
const onKey = (e) => { if (e.key === 'Escape') setGenOpen(false); };
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [genOpen]);
+ useEffect(() => {
+ if (pickerIdx === null) return undefined;
+ const onKey = (e) => { if (e.key === 'Escape') setPickerIdx(null); };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ }, [pickerIdx]);
+
+ const editorMountedRef = useRef(true);
+ useEffect(() => () => { editorMountedRef.current = false; }, []);
+ const runPromote = async (idx, variation, opts) => {
+ if (!onPromote) return;
+ setPickerIdx(null);
+ setPromotingIdx(idx);
+ try {
+ await onPromote(variation, opts);
+ } finally {
+ if (editorMountedRef.current) setPromotingIdx(null);
+ }
+ };
const runGenerate = async (count) => {
const n = Math.max(GENERATE_CUSTOM_MIN, Math.min(GENERATE_CUSTOM_MAX, parseInt(count, 10) || 0));
@@ -2122,6 +2226,55 @@ function CategoryEditor({
<div className="text-xs text-gray-400 line-clamp-2">{v.prompt}</div>
</div>
<div className="flex items-center gap-1 shrink-0">
+ {onPromote && (() => {
+ const promoteTitle = !canPromote
+ ? 'Save the universe first to enable promote'
+ : requiresTargetKind
+ ? 'Promote to canon — pick a trunk'
+ : 'Promote to canon — LLM expands this variation into a full canon entry';
+ return (
+ <div className="relative" ref={pickerIdx === idx ? pickerWrapRef : null}>
+ <button
+ onClick={() => {
+ if (requiresTargetKind) {
+ setPickerIdx(pickerIdx === idx ? null : idx);
+ return;
+ }
+ runPromote(idx, v);
+ }}
+ disabled={!canPromote || promotingIdx !== null}
+ className="p-1 text-gray-400 hover:text-port-success disabled:opacity-30 disabled:cursor-not-allowed rounded"
+ title={promoteTitle}
+ aria-haspopup={requiresTargetKind ? 'menu' : undefined}
+ aria-expanded={requiresTargetKind ? pickerIdx === idx : undefined}
+ >
+ {promotingIdx === idx
+ ? <Loader2 size={14} className="animate-spin" />
+ : <ArrowUpCircle size={14} />}
+ </button>
+ {pickerIdx === idx && requiresTargetKind && (
+ <div
+ role="menu"
+ className="absolute right-0 top-full mt-1 z-20 w-44 bg-port-card border border-port-border rounded shadow-lg p-1 flex flex-col gap-0.5"
+ >
+ <div className="px-2 pt-1 pb-1 text-[10px] uppercase tracking-wide text-gray-500">
+ Promote to canon as…
+ </div>
+ {TRUNK_TABS.map((trunk) => (
+ <button
+ key={trunk.kind}
+ role="menuitem"
+ onClick={() => runPromote(idx, v, { targetKind: trunk.kind })}
+ className="text-left text-xs px-2 py-1.5 text-gray-200 hover:bg-port-success/20 rounded"
+ >
+ {trunk.label}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ })()}
{onRenderVariation && (
<button
onClick={() => onRenderVariation(v)}
@@ -2492,8 +2645,8 @@ function BucketChipStrip({ buckets, activeBucket, setBucket, showAll = true, ext
// - <bucketKey>: renders that bucket's variations via CategoryEditor
function TrunkView({
trunk, draft, selectedId, buckets, activeBucket, setBucket,
- canRender, imageCfg, onUniverseChange,
- onRemoveBucket, onUpdateBucket, onGenerateInBucket,
+ canRender, canPromote, imageCfg, onUniverseChange,
+ onRemoveBucket, onUpdateBucket, onGenerateInBucket, onPromoteVariation,
onBulkRenderBucket, onRenderVariation, onBulkRenderTrunk,
onAddBucket,
}) {
@@ -2626,6 +2779,9 @@ function TrunkView({
onRenderCategory={() => onBulkRenderBucket(cat)}
onRenderVariation={(v) => onRenderVariation(cat, v)}
onGenerate={(count) => onGenerateInBucket(cat, count)}
+ canPromote={canPromote}
+ bucketKind={draft.categories?.[cat]?.kind ?? trunk.kind}
+ onPromote={onPromoteVariation ? (v) => onPromoteVariation(cat, v) : null}
/>
))}
</section>
@@ -2640,8 +2796,8 @@ function TrunkView({
// Same card grid as TrunkView but no canon plumbing, plus an "Auto-sort"
// action that (eventually) LLM-classifies each bucket into the right trunk.
function OtherTab({
- draft, buckets, activeBucket, setBucket, canRender,
- onUpdateBucket, onRemoveBucket, onGenerateInBucket,
+ draft, buckets, activeBucket, setBucket, canRender, canPromote,
+ onUpdateBucket, onRemoveBucket, onGenerateInBucket, onPromoteVariation,
onBulkRenderBucket, onRenderVariation, onAutoSort,
}) {
return (
@@ -2682,6 +2838,9 @@ function OtherTab({
onRenderCategory={() => onBulkRenderBucket(cat)}
onRenderVariation={(v) => onRenderVariation(cat, v)}
onGenerate={(count) => onGenerateInBucket(cat, count)}
+ canPromote={canPromote}
+ bucketKind={draft.categories?.[cat]?.kind}
+ onPromote={onPromoteVariation ? (v, opts) => onPromoteVariation(cat, v, opts) : null}
/>
))}
</section>
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 0b74344fea..84deb79098 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -194,3 +194,16 @@ export const setUniverseCanonLock = (universeId, kind, entryId, locked) =>
method: 'PATCH',
body: JSON.stringify({ locked }),
});
+
+// Promote a category variation into a full canon entry. `targetKind` is
+// required only when the source bucket's `kind` is 'other' (otherwise the
+// server derives it from the bucket). Pass `{ silent: true }` in `options`
+// when the caller owns its own error toast (per CLAUDE.md).
+export const promoteVariationToCanon = (universeId, {
+ category, label, targetKind, providerId, model,
+} = {}, options = {}) =>
+ request(`/universe-builder/${encodeURIComponent(universeId)}/promote-variation`, {
+ method: 'POST',
+ body: JSON.stringify({ category, label, targetKind, providerId, model }),
+ ...options,
+ });
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index 09f36658d7..0cdf27ce99 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -174,6 +174,22 @@ export const isBlank = (v) => {
export const normalizeBibleName = (name) => String(name || '').trim().toLowerCase();
+// Fields the LLM should NEVER set on a canon entry it just generated.
+// `id/createdAt/updatedAt` get freshly minted by the per-kind sanitizer; a
+// hallucinated `locked: true` would block user edits without a Lock UI click;
+// `sourceSeriesId` is provenance owned by series imports; `imageRefs` +
+// `primaryImageRef` are operational (set by the Render UI / extraction).
+export function stripCanonControlFields(entry) {
+ if (!entry || typeof entry !== 'object') return entry;
+ const {
+ id: _id, createdAt: _ca, updatedAt: _ua,
+ locked: _locked, sourceSeriesId: _ssi,
+ imageRefs: _imgs, primaryImageRef: _primary,
+ ...rest
+ } = entry;
+ return rest;
+}
+
const nowIso = () => new Date().toISOString();
function ensureId(raw, idPrefix) {
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 06080befb4..502991b4b8 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -22,6 +22,7 @@ import { BIBLE_KINDS, BIBLE_LIMITS } from '../lib/storyBible.js';
import { getUniverseCanonUsage } from '../services/canonUsage.js';
import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';
import { refineWorldPrompts } from '../services/universeBuilderRefine.js';
+import { promoteVariationToCanon, VALID_TARGET_KINDS } from '../services/universeBuilderPromote.js';
import { enqueueJob } from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';
@@ -185,6 +186,17 @@ const expandSchema = z.object({
model: z.string().trim().max(200).optional(),
});
+// `targetKind` is only required when the source bucket's `kind` is 'other'
+// (otherwise the service resolves it from the bucket). Enum derived from
+// VALID_TARGET_KINDS so the schema and the resolver share one source.
+const promoteVariationSchema = z.object({
+ category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),
+ label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),
+ targetKind: z.enum(VALID_TARGET_KINDS).optional(),
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+});
+
const generateVariationsSchema = z.object({
category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),
count: z.number().int().min(1).max(svc.VARIATIONS_PER_CATEGORY_MAX),
@@ -496,6 +508,18 @@ router.post('/:id/extract-canon', asyncHandler(async (req, res) => {
res.json(result);
}));
+// Promote a {label, prompt} variation into a full canon entry of the
+// corresponding trunk (resolved from the bucket's `kind` field, or the
+// caller-supplied `targetKind` for 'other'-kinded buckets). The variation
+// is removed from its source bucket and the canon entry is appended in a
+// single atomic patch.
+router.post('/:id/promote-variation', asyncHandler(async (req, res) => {
+ const body = validateRequest(promoteVariationSchema, req.body ?? {});
+ const result = await promoteVariationToCanon(req.params.id, body)
+ .catch((err) => { throw mapServiceError(err); });
+ res.json(result);
+}));
+
const refineCharSchema = z.object({
providerId: z.string().trim().max(64).optional(),
model: z.string().trim().max(128).optional(),
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index 7e7ee063c6..4b17337992 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -18,6 +18,27 @@ vi.mock('crypto', async () => {
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
+// Stub the LLM promote service so route tests don't shell out to a provider.
+// Default mock just echoes back a minimal canon entry shape so the route
+// returns 200 and the schema/validation paths get exercised end-to-end.
+const promoteVariationToCanonMock = vi.fn(async (_universeId, body = {}) => ({
+ universe: { id: _universeId, characters: [], settings: [], objects: [] },
+ entry: { id: 'mock-entry', name: body.label },
+ targetKind: body.targetKind || 'characters',
+ removed: { category: body.category, label: body.label },
+ runId: 'mock-run',
+ llm: { provider: 'mock', model: null },
+}));
+vi.mock('../services/universeBuilderPromote.js', async () => {
+ // Pass the real VALID_TARGET_KINDS through so the route's Zod enum
+ // can't drift from the source-of-truth list (derived from BIBLE_FIELD).
+ const actual = await vi.importActual('../services/universeBuilderPromote.js');
+ return {
+ ...actual,
+ promoteVariationToCanon: (...args) => promoteVariationToCanonMock(...args),
+ };
+});
+
// Stub the LLM expander so the route test doesn't shell out to a real provider.
vi.mock('../services/universeBuilderExpand.js', () => ({
expandWorldTemplate: vi.fn(async ({ starterPrompt }) => ({
@@ -413,4 +434,67 @@ describe('universe-builder routes', () => {
expect(res.status).toBe(400);
expect(res.body.code).toBe('WORLD_BUILDER_EMPTY');
});
+
+ describe('POST /:id/promote-variation', () => {
+ beforeEach(() => {
+ promoteVariationToCanonMock.mockClear();
+ });
+
+ it('forwards the body to the service and returns the result', async () => {
+ const app = buildApp();
+ const res = await request(app)
+ .post('/api/universe-builder/some-id/promote-variation')
+ .send({ category: 'landscapes', label: 'Salt Flats' });
+ expect(res.status).toBe(200);
+ expect(promoteVariationToCanonMock).toHaveBeenCalledWith('some-id', expect.objectContaining({
+ category: 'landscapes',
+ label: 'Salt Flats',
+ }));
+ expect(res.body.entry.name).toBe('Salt Flats');
+ });
+
+ it('passes through targetKind for other-kinded buckets', async () => {
+ const app = buildApp();
+ const res = await request(app)
+ .post('/api/universe-builder/some-id/promote-variation')
+ .send({ category: 'myth_archetypes', label: 'Solstice Mask', targetKind: 'objects' });
+ expect(res.status).toBe(200);
+ expect(promoteVariationToCanonMock).toHaveBeenCalledWith('some-id', expect.objectContaining({
+ targetKind: 'objects',
+ }));
+ });
+
+ it('400s on missing label (Zod schema)', async () => {
+ const app = buildApp();
+ const res = await request(app)
+ .post('/api/universe-builder/some-id/promote-variation')
+ .send({ category: 'landscapes' });
+ expect(res.status).toBe(400);
+ expect(promoteVariationToCanonMock).not.toHaveBeenCalled();
+ });
+
+ it('400s on invalid targetKind enum (Zod schema)', async () => {
+ const app = buildApp();
+ const res = await request(app)
+ .post('/api/universe-builder/some-id/promote-variation')
+ .send({ category: 'landscapes', label: 'A', targetKind: 'monster' });
+ expect(res.status).toBe(400);
+ expect(promoteVariationToCanonMock).not.toHaveBeenCalled();
+ });
+
+ it('maps service ServerError status onto the HTTP response', async () => {
+ promoteVariationToCanonMock.mockRejectedValueOnce(
+ Object.assign(new Error('Bucket not found'), {
+ status: 404,
+ code: 'UNIVERSE_PROMOTE_NO_CATEGORY',
+ }),
+ );
+ const app = buildApp();
+ const res = await request(app)
+ .post('/api/universe-builder/some-id/promote-variation')
+ .send({ category: 'nonexistent', label: 'A' });
+ expect(res.status).toBe(404);
+ expect(res.body.code).toBe('UNIVERSE_PROMOTE_NO_CATEGORY');
+ });
+ });
});
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index 623c9161ae..3a85b1c2fa 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -29,7 +29,7 @@ import {
sanitizeCompositeSheets,
sanitizeInfluences,
} from "./universeBuilder.js";
-import { sanitizeBibleList, BIBLE_KIND, BIBLE_SOURCE } from "../lib/storyBible.js";
+import { sanitizeBibleList, stripCanonControlFields, BIBLE_KIND, BIBLE_SOURCE } from "../lib/storyBible.js";
import { ServerError } from "../lib/errorHandler.js";
import { extractJson as extractJsonShared } from "../lib/jsonExtract.js";
import {
@@ -290,39 +290,17 @@ const normalizeCompositeSheets = (raw) =>
// pre-sanitize so the sanitizer's `ensureSource` allowlist validates it (a
// post-sanitize stamp would bypass that check).
//
-// Strip control + provenance fields from raw entries before sanitizing. The
-// sanitizer preserves whatever it finds for these — an LLM that hallucinates
-// any of them (or copies an example from the prompt) would otherwise inject
-// stale identifiers, false attribution, or phantom "locked" entries that
-// look user-pinned. Expand is creating fresh records; the only field whose
-// provenance we trust is `source` (set to UNIVERSE_EXPAND below).
-//
-// Stripped (the LLM should NEVER supply these):
-// - id, createdAt, updatedAt — sanitizer mints fresh values
-// - locked — sanitizer preserves `=== true`; a hallucinated
-// lock would block user edits without a Lock UI click
-// - sourceSeriesId — provenance (which series imported this entry);
-// expand isn't a series import, so always null
-// - imageRefs, primaryImageRef — visual anchors are operational (set by
-// Render UI / extraction), not creative
+// Sanitize an LLM-emitted canon array through the universe service's
+// per-kind sanitizer. `source` is stamped pre-sanitize so the sanitizer's
+// `ensureSource` allowlist validates it; control fields the LLM should
+// never set (id/locked/imageRefs/etc.) are dropped via stripCanonControlFields
+// — shared with the Promote path so the two LLM entrypoints can't drift.
const normalizeCanonArray = (raw, kind) => {
if (!Array.isArray(raw)) return [];
const stamped = raw.map((e) => {
if (!e || typeof e !== 'object') return e;
- const {
- id: _ignoredId,
- createdAt: _ca,
- updatedAt: _ua,
- locked: _locked,
- sourceSeriesId: _ssi,
- imageRefs: _imgs,
- primaryImageRef: _primary,
- ...rest
- } = e;
- return { ...rest, source: BIBLE_SOURCE.UNIVERSE_EXPAND };
+ return { ...stripCanonControlFields(e), source: BIBLE_SOURCE.UNIVERSE_EXPAND };
});
- // Expand is creating fresh entries; let the sanitizer stamp timestamps
- // instead of preserving (likely-absent) ones from the LLM output.
return sanitizeBibleList(stamped, kind, { preserveTimestamps: false });
};
diff --git a/server/services/universeBuilderPromote.js b/server/services/universeBuilderPromote.js
new file mode 100644
index 0000000000..dcd037c37c
--- /dev/null
+++ b/server/services/universeBuilderPromote.js
@@ -0,0 +1,310 @@
+/**
+ * Universe Builder — promote a {label, prompt} variation into a full canon
+ * entry (Phase D). The LLM expands the variation into a per-kind canon
+ * record; the canon append + variation removal land in one `updateUniverse`
+ * patch so the transition is atomic.
+ */
+
+import { getActiveProvider, getProviderById } from './providers.js';
+import {
+ getUniverse,
+ updateUniverse,
+ normalizeCategoryKey,
+ joinInfluenceList,
+} from './universeBuilder.js';
+import {
+ sanitizeBibleList,
+ stripCanonControlFields,
+ normalizeBibleName,
+ BIBLE_FIELD,
+ BIBLE_SOURCE,
+ BIBLE_LIMITS,
+} from '../lib/storyBible.js';
+import { ServerError } from '../lib/errorHandler.js';
+import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';
+import {
+ resolveEffectiveModel,
+ runPromptThroughProvider,
+} from '../lib/promptRunner.js';
+
+// Inverse of BIBLE_FIELD: trunk-name (canon array key) → singular BIBLE_KIND.
+// Derived from the source-of-truth map so the two can't drift. `other` is
+// intentionally absent — callers must pass `targetKind` to promote out of an
+// unsorted bucket.
+export const KIND_TO_BIBLE = Object.freeze(
+ Object.fromEntries(Object.entries(BIBLE_FIELD).map(([kind, field]) => [field, kind])),
+);
+
+// Exported for the route's Zod enum so the schema and the resolver share
+// one source of truth.
+export const VALID_TARGET_KINDS = Object.freeze(Object.keys(KIND_TO_BIBLE));
+
+const isCharacterShape = (o) =>
+ o && typeof o === 'object' && typeof o.name === 'string';
+const isSettingShape = (o) =>
+ o && typeof o === 'object' && (typeof o.name === 'string' || typeof o.slugline === 'string');
+const isObjectShape = isCharacterShape;
+
+const SHAPE_PREDICATE = {
+ characters: isCharacterShape,
+ settings: isSettingShape,
+ objects: isObjectShape,
+};
+
+const buildPromotePrompt = ({
+ targetKind,
+ variation,
+ category,
+ universe,
+}) => {
+ const embraceTokens = joinInfluenceList(universe.influences?.embrace);
+ const styleContext = [
+ universe.logline ? `LOGLINE: ${universe.logline}` : null,
+ universe.styleNotes ? `STYLE NOTES: ${universe.styleNotes}` : null,
+ embraceTokens ? `EMBRACE INFLUENCES: ${embraceTokens}` : null,
+ ].filter(Boolean).join('\n\n');
+ const styleSection = styleContext
+ ? `\n# Universe context — keep the new canon entry consistent with this established setting\n${styleContext}\n`
+ : '';
+
+ // Per-kind output contract. The sanitizer drops unknown fields, so
+ // listing the field whitelist here is the LLM's only contract.
+ let outputContract;
+ if (targetKind === 'characters') {
+ outputContract = `Return a SINGLE JSON object describing one CHARACTER (do NOT wrap it in an array). Required fields:
+- name: string (max ${BIBLE_LIMITS.NAME_MAX} chars). The human name; default the variation label when no clearer name is implied.
+- physicalDescription: string (max ${BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX} chars). What they look like — face, build, age range, distinguishing marks, signature attire.
+- personality: string (max ${BIBLE_LIMITS.PERSONALITY_MAX} chars). Disposition, voice, defining traits.
+- background: string (max ${BIBLE_LIMITS.BACKGROUND_MAX} chars). Where they come from, role in the world.
+- role: string (max ${BIBLE_LIMITS.ROLE_MAX} chars). Their function in the story (protagonist / mentor / faction lead / etc).
+- prompt: string (max ${BIBLE_LIMITS.PROMPT_MAX} chars). Render-prompt fragment for reference images — comma-separated tokens; do NOT repeat universe style tokens (they're prepended at render time).
+- tags: array of 1-3 short labels (e.g. "protagonist", "antagonist", "supporting").`;
+ } else if (targetKind === 'settings') {
+ outputContract = `Return a SINGLE JSON object describing one SETTING / PLACE. Required fields:
+- name: string (max ${BIBLE_LIMITS.NAME_MAX} chars). Human label like "Foundry City". Default the variation label when no clearer name is implied.
+- slugline: string (max ${BIBLE_LIMITS.SLUGLINE_MAX} chars). Screenplay-style location header like "EXT. FOUNDRY CITY — DAY". Leave empty string when no obvious slugline applies.
+- description: string (max ${BIBLE_LIMITS.SETTING_DESCRIPTION_MAX} chars). What the place looks like + feels like.
+- palette: string (max ${BIBLE_LIMITS.PALETTE_MAX} chars). Dominant colors.
+- era: string (max ${BIBLE_LIMITS.ERA_MAX} chars). Time period / technology level.
+- weather: string (max ${BIBLE_LIMITS.WEATHER_MAX} chars). Typical conditions.
+- recurringDetails: string (max ${BIBLE_LIMITS.RECURRING_DETAILS_MAX} chars). Recognizable motifs that recur across scenes.
+- prompt: string (max ${BIBLE_LIMITS.PROMPT_MAX} chars). Render-prompt fragment — comma-separated tokens; do NOT repeat universe style tokens.
+- tags: array of 1-3 short labels.`;
+ } else {
+ outputContract = `Return a SINGLE JSON object describing one OBJECT / prop / vehicle / artifact. Required fields:
+- name: string (max ${BIBLE_LIMITS.NAME_MAX} chars). Default the variation label when no clearer name is implied.
+- description: string (max ${BIBLE_LIMITS.OBJECT_DESCRIPTION_MAX} chars). What it looks like + what it does.
+- significance: string (max ${BIBLE_LIMITS.SIGNIFICANCE_MAX} chars). Why it matters to the story.
+- prompt: string (max ${BIBLE_LIMITS.PROMPT_MAX} chars). Render-prompt fragment — comma-separated tokens; do NOT repeat universe style tokens.
+- tags: array of 1-3 short labels.`;
+ }
+
+ return `You are a story-bible drafter for a comic/TV production pipeline. The user is promoting an exploratory variation from the "${category}" bucket into a first-class canon entry of kind "${targetKind}". Expand the variation into a fully fleshed canon record consistent with the universe.
+${styleSection}
+# Source variation
+LABEL: ${variation.label}
+PROMPT: ${variation.prompt}
+
+# Output contract
+${outputContract}
+
+# Rules
+- Output JUST the JSON object. NO markdown, NO commentary, NO array wrapper.
+- Use empty strings for optional fields you can't honestly infer — do NOT invent backstory or motifs unsupported by the source variation + universe context.
+- Stay tonally consistent with the LOGLINE / STYLE NOTES / EMBRACE INFLUENCES above when present.`;
+};
+
+const extractEntryJson = (raw, kind) => {
+ if (!raw || typeof raw !== 'string') throw new Error('Empty LLM response');
+ const predicate = SHAPE_PREDICATE[kind] || isCharacterShape;
+ const { value, lastError, lastPreview } = extractJsonShared(raw, {
+ shapePredicate: predicate,
+ });
+ if (value !== undefined) return value;
+ throw new ServerError(
+ 'LLM returned invalid JSON for variation promotion. Try a different model or rerun.',
+ {
+ status: 502,
+ code: 'LLM_INVALID_JSON',
+ context: {
+ details: {
+ reason: lastError?.message || 'no JSON object found',
+ preview: lastPreview || '',
+ },
+ },
+ },
+ );
+};
+
+
+/**
+ * Promote one variation from `universe.categories[category].variations[]`
+ * into the corresponding canon trunk.
+ *
+ * @param {string} universeId
+ * @param {object} options
+ * @param {string} options.category — bucket key (case-insensitive)
+ * @param {string} options.label — variation label (case-insensitive); the
+ * first matching variation in the bucket is promoted.
+ * @param {'characters'|'settings'|'objects'} [options.targetKind] — required
+ * when the source category's `kind` is 'other'; ignored otherwise.
+ * @param {string} [options.providerId]
+ * @param {string} [options.model]
+ */
+export async function promoteVariationToCanon(universeId, options = {}) {
+ const {
+ category: rawCategory,
+ label: rawLabel,
+ targetKind: rawTargetKind,
+ providerId,
+ model,
+ } = options;
+ const categoryKey = normalizeCategoryKey(rawCategory);
+ if (!categoryKey) {
+ throw new ServerError('promoteVariationToCanon: category is required', {
+ status: 400, code: 'UNIVERSE_PROMOTE_NO_CATEGORY',
+ });
+ }
+ if (typeof rawLabel !== 'string' || !rawLabel.trim()) {
+ throw new ServerError('promoteVariationToCanon: label is required', {
+ status: 400, code: 'UNIVERSE_PROMOTE_NO_LABEL',
+ });
+ }
+ const universe = await getUniverse(universeId);
+ const bucket = universe.categories?.[categoryKey];
+ if (!bucket) {
+ throw new ServerError(`Category "${categoryKey}" not found on universe`, {
+ status: 404, code: 'UNIVERSE_PROMOTE_NO_CATEGORY',
+ });
+ }
+ // Resolve target trunk. `kind: 'other'` requires an explicit override —
+ // we won't guess what trunk a custom bucket belongs in (the auto-sort UI
+ // action will be the way to bulk-classify those).
+ let targetKind = bucket.kind;
+ if (targetKind === 'other' || !VALID_TARGET_KINDS.includes(targetKind)) {
+ if (!VALID_TARGET_KINDS.includes(rawTargetKind)) {
+ throw new ServerError(
+ `Bucket "${categoryKey}" has kind "${bucket.kind || 'other'}" — pass targetKind (characters|settings|objects) to promote variations from it`,
+ { status: 400, code: 'UNIVERSE_PROMOTE_NO_TARGET_KIND' },
+ );
+ }
+ targetKind = rawTargetKind;
+ }
+ const bibleKind = KIND_TO_BIBLE[targetKind];
+ const bibleField = BIBLE_FIELD[bibleKind];
+
+ const needle = rawLabel.trim().toLowerCase();
+ const variations = Array.isArray(bucket.variations) ? bucket.variations : [];
+ const sourceIdx = variations.findIndex((v) => typeof v?.label === 'string' && v.label.toLowerCase() === needle);
+ if (sourceIdx < 0) {
+ throw new ServerError(
+ `Variation "${rawLabel}" not found in bucket "${categoryKey}"`,
+ { status: 404, code: 'UNIVERSE_PROMOTE_VARIATION_NOT_FOUND' },
+ );
+ }
+ const variation = variations[sourceIdx];
+
+ // Refuse silent duplicate creation: if a canon entry with the variation's
+ // label already exists, surface a 409 so the UI can suggest "open the
+ // existing entry" or "rename then promote" rather than producing a second
+ // record that the merge logic would silently swallow on next save.
+ const existingCanon = Array.isArray(universe[bibleField]) ? universe[bibleField] : [];
+ const labelKey = normalizeBibleName(variation.label);
+ const collision = existingCanon.find((e) => normalizeBibleName(e?.name) === labelKey
+ || (Array.isArray(e?.aliases) && e.aliases.some((a) => normalizeBibleName(a) === labelKey)));
+ if (collision) {
+ throw new ServerError(
+ `Canon ${targetKind} "${variation.label}" already exists — rename the variation or open the existing entry`,
+ {
+ status: 409,
+ code: 'UNIVERSE_PROMOTE_DUPLICATE',
+ context: { details: { existingId: collision.id } },
+ },
+ );
+ }
+
+ let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;
+ if (!provider) provider = await getActiveProvider();
+ if (!provider) {
+ throw new ServerError('No AI provider available for variation promotion', {
+ status: 503, code: 'UNIVERSE_PROMOTE_NO_PROVIDER',
+ });
+ }
+ const selectedModel = resolveEffectiveModel(provider, model);
+
+ const prompt = buildPromotePrompt({
+ targetKind,
+ variation,
+ category: categoryKey,
+ universe,
+ });
+ console.log(
+ `✨ Universe Builder promote — universe=${universeId.slice(0, 8)} category=${categoryKey} label="${variation.label}" → ${targetKind} via ${provider.name}/${selectedModel || 'default'}`,
+ );
+
+ const { text: raw, runId } = await runPromptThroughProvider({
+ provider,
+ model: selectedModel,
+ prompt,
+ source: 'universe-builder-promote-variation',
+ });
+ console.log(`✨ Universe Builder promote raw — runId=${runId} length=${raw?.length || 0}`);
+
+ // extractEntryJson is shape-gated on the per-kind predicate, so `parsed`
+ // is always an object that matches a canon-entry shape. Default name +
+ // prompt back to the source variation when the LLM omitted them — keeps
+ // the new entry anchored to what the user clicked promote on (rather
+ // than letting an LLM hallucination silently replace the label).
+ const parsed = extractEntryJson(raw, targetKind);
+ const enriched = {
+ ...stripCanonControlFields(parsed),
+ name: (typeof parsed?.name === 'string' && parsed.name.trim()) ? parsed.name.trim() : variation.label,
+ source: BIBLE_SOURCE.UNIVERSE_EXPAND,
+ };
+ if (!enriched.prompt && typeof variation.prompt === 'string' && variation.prompt.trim()) {
+ enriched.prompt = variation.prompt.trim();
+ }
+ const sanitizedList = sanitizeBibleList([enriched], bibleKind, { preserveTimestamps: false });
+ const sanitized = sanitizedList[0] || null;
+ if (!sanitized) {
+ throw new ServerError(
+ `Promoted entry failed sanitization — required fields missing for ${targetKind}`,
+ { status: 502, code: 'UNIVERSE_PROMOTE_INVALID_ENTRY' },
+ );
+ }
+
+ // Build the patch: append the new canon entry + drop the source variation
+ // from its bucket. Both writes go through one updateUniverse so the
+ // transition is atomic (success = entry in canon AND variation gone).
+ const nextCanon = [...existingCanon, sanitized];
+ const nextVariations = variations.filter((_, i) => i !== sourceIdx);
+ const patch = {
+ [bibleField]: nextCanon,
+ categories: {
+ [categoryKey]: { kind: bucket.kind, variations: nextVariations },
+ },
+ };
+ const updated = await updateUniverse(universeId, patch);
+ // updateUniverse re-runs sanitizers; pull the merged entry back out by
+ // id so the response reflects the canonical persisted shape.
+ const persisted = (updated[bibleField] || []).find((e) => e.id === sanitized.id) || sanitized;
+
+ console.log(
+ `✨ Universe Builder promote complete — universe=${universeId.slice(0, 8)} entry=${persisted.id} (${targetKind}) runId=${runId.slice(0, 8)}`,
+ );
+
+ return {
+ universe: updated,
+ entry: persisted,
+ targetKind,
+ removed: { category: categoryKey, label: variation.label },
+ runId,
+ llm: { provider: provider.id, model: selectedModel || null },
+ };
+}
+
+// Test seam.
+export const __testing = {
+ buildPromotePrompt,
+ extractEntryJson,
+};
diff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.js
new file mode 100644
index 0000000000..1accb2a5ce
--- /dev/null
+++ b/server/services/universeBuilderPromote.test.js
@@ -0,0 +1,466 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory file store mirrors universeBuilder.test.js / universeCanon.test.js
+// so a single readState/writeState path roundtrips through the same code the
+// real service uses (no live file I/O).
+const fileStore = new Map();
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
+ readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+}));
+
+let uuidCounter = 0;
+vi.mock('crypto', async () => {
+ const actual = await vi.importActual('crypto');
+ return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
+});
+
+// Stub the provider + LLM dispatch so tests don't need a live runner. The
+// `runPromptThroughProvider` mock is overridden per-test to return the
+// per-kind JSON shape we expect from the LLM.
+const getActiveProviderMock = vi.fn();
+const getProviderByIdMock = vi.fn();
+vi.mock('./providers.js', () => ({
+ getActiveProvider: (...a) => getActiveProviderMock(...a),
+ getProviderById: (...a) => getProviderByIdMock(...a),
+}));
+
+const runPromptThroughProviderMock = vi.fn();
+vi.mock('../lib/promptRunner.js', () => ({
+ runPromptThroughProvider: (...a) => runPromptThroughProviderMock(...a),
+ resolveEffectiveModel: (_provider, model) => model || 'mock-default',
+}));
+
+// Pull services AFTER mocks register so module-level imports resolve through
+// the mock chain.
+const svc = await import('./universeBuilder.js');
+const promoteSvc = await import('./universeBuilderPromote.js');
+const fileUtils = await import('../lib/fileUtils.js');
+
+const seedUniverseWithBucket = async (categories, canon = {}) => {
+ const w = await svc.createUniverse({
+ name: 'Test Universe',
+ starterPrompt: 'test seed',
+ influences: { embrace: ['cel-shading'], avoid: ['lowres'] },
+ });
+ // Plant categories + canon directly via updateUniverse so the sanitizer
+ // tags `kind` correctly (handles 'characters' bucket retirement too).
+ return svc.updateUniverse(w.id, { categories, ...canon });
+};
+
+const mockLlm = (entry) => {
+ runPromptThroughProviderMock.mockResolvedValue({
+ text: JSON.stringify(entry),
+ runId: 'run-promote-1',
+ model: 'mock-default',
+ });
+};
+
+beforeEach(() => {
+ fileStore.clear();
+ uuidCounter = 0;
+ getActiveProviderMock.mockReset();
+ getProviderByIdMock.mockReset();
+ runPromptThroughProviderMock.mockReset();
+ getActiveProviderMock.mockResolvedValue({
+ id: 'provider-mock', name: 'Mock', type: 'api', defaultModel: 'mock-default',
+ });
+});
+
+describe('universeBuilderPromote — happy path', () => {
+ it('promotes a variation from a settings-kinded bucket into universe.settings[]', async () => {
+ const w = await seedUniverseWithBucket({
+ landscapes: {
+ kind: 'settings',
+ variations: [
+ { label: 'Crystalline canyon', prompt: 'vast crystalline canyon, salt flats' },
+ { label: 'Scrap dune sea', prompt: 'rolling dunes of rusted scrap' },
+ ],
+ },
+ });
+ mockLlm({
+ name: 'Crystalline Canyon',
+ description: 'A vast canyon of luminous salt-crystal walls.',
+ palette: 'pale violet, salt white, dust amber',
+ era: 'post-civilization',
+ weather: 'arid, scoured by dust devils',
+ recurringDetails: 'wind chimes carved from crystal',
+ prompt: 'vast crystalline canyon, salt flats, low horizon',
+ tags: ['signature-place'],
+ });
+
+ const result = await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'landscapes',
+ label: 'Crystalline canyon',
+ });
+
+ expect(result.targetKind).toBe('settings');
+ expect(result.entry.name).toBe('Crystalline Canyon');
+ expect(result.entry.palette).toContain('pale violet');
+ expect(result.universe.settings.some((e) => e.name === 'Crystalline Canyon')).toBe(true);
+ // The source variation is removed from its bucket.
+ const remainingLabels = result.universe.categories.landscapes.variations.map((v) => v.label);
+ expect(remainingLabels).toEqual(['Scrap dune sea']);
+ expect(result.removed).toEqual({ category: 'landscapes', label: 'Crystalline canyon' });
+ });
+
+ it('promotes a variation from a characters-kinded bucket into universe.characters[]', async () => {
+ const w = await seedUniverseWithBucket({
+ heroes: {
+ kind: 'characters',
+ variations: [
+ { label: 'Ash the Foundling', prompt: 'lone child of the foundry, soot-stained' },
+ ],
+ },
+ });
+ mockLlm({
+ name: 'Ash',
+ physicalDescription: 'A wiry child, 8 years old, soot-stained skin, copper hair, salvaged goggles.',
+ personality: 'Watchful, slow to speak, quick to act.',
+ background: 'Only survivor of the foundry silence.',
+ role: 'protagonist',
+ prompt: 'child of the foundry, soot-stained, copper hair',
+ tags: ['protagonist'],
+ });
+
+ const result = await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'heroes',
+ label: 'Ash the Foundling',
+ });
+
+ expect(result.targetKind).toBe('characters');
+ expect(result.universe.characters.find((c) => c.name === 'Ash')).toBeTruthy();
+ expect(result.universe.categories.heroes.variations).toEqual([]);
+ });
+
+ it('matches variation labels case-insensitively', async () => {
+ const w = await seedUniverseWithBucket({
+ colonies: {
+ kind: 'settings',
+ variations: [{ label: 'Gas-Giant Drifters', prompt: 'balloon settlements in the upper atmosphere' }],
+ },
+ });
+ mockLlm({ name: 'Gas-Giant Drifters', description: 'A balloon-colony civilization.', prompt: 'balloon settlement' });
+
+ const result = await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'colonies',
+ label: 'gas-giant drifters', // lowercase
+ });
+
+ expect(result.universe.settings.find((s) => s.name === 'Gas-Giant Drifters')).toBeTruthy();
+ });
+
+ it('seeds entry.name from the variation label when the LLM omits name', async () => {
+ const w = await seedUniverseWithBucket({
+ vehicles: {
+ kind: 'objects',
+ variations: [{ label: 'Scavenger Walker Mech', prompt: 'rusted bipedal salvage mech' }],
+ },
+ });
+ mockLlm({
+ // name absent — server should default to variation label
+ description: 'A four-story salvage mech.',
+ significance: 'Built from the bones of the silent foundry.',
+ tags: ['hero-vehicle'],
+ });
+
+ const result = await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'vehicles',
+ label: 'Scavenger Walker Mech',
+ });
+ expect(result.entry.name).toBe('Scavenger Walker Mech');
+ });
+
+ it('seeds entry.prompt from the variation when LLM omits prompt', async () => {
+ const w = await seedUniverseWithBucket({
+ vehicles: {
+ kind: 'objects',
+ variations: [{ label: 'Salvage Mech', prompt: 'rusted bipedal mech, scavenged armor' }],
+ },
+ });
+ mockLlm({ name: 'Salvage Mech', description: 'A walker.' });
+
+ const result = await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'vehicles',
+ label: 'Salvage Mech',
+ });
+ expect(result.entry.prompt).toBe('rusted bipedal mech, scavenged armor');
+ });
+});
+
+describe('universeBuilderPromote — targetKind override + other-bucket gate', () => {
+ it('requires targetKind for `kind: "other"` buckets', async () => {
+ const w = await seedUniverseWithBucket({
+ myth_archetypes: {
+ // No `kind: 'other'` set explicitly — sanitizer defaults to 'other'.
+ variations: [{ label: 'Solstice Mask', prompt: 'midnight procession' }],
+ },
+ });
+ await expect(
+ promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'myth_archetypes',
+ label: 'Solstice Mask',
+ }),
+ ).rejects.toMatchObject({ status: 400, code: 'UNIVERSE_PROMOTE_NO_TARGET_KIND' });
+ });
+
+ it('promotes from an other-bucket when targetKind is provided', async () => {
+ const w = await seedUniverseWithBucket({
+ myth_archetypes: {
+ variations: [{ label: 'Solstice Mask', prompt: 'midnight procession with bone masks' }],
+ },
+ });
+ mockLlm({
+ name: 'The Solstice Mask',
+ description: 'A ritual mask carved from antler bone.',
+ significance: 'Worn only when the long night begins.',
+ tags: ['ritual'],
+ });
+ const result = await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'myth_archetypes',
+ label: 'Solstice Mask',
+ targetKind: 'objects',
+ });
+ expect(result.targetKind).toBe('objects');
+ expect(result.universe.objects.find((o) => o.name === 'The Solstice Mask')).toBeTruthy();
+ });
+
+ it('rejects invalid targetKind even for non-other buckets', async () => {
+ const w = await seedUniverseWithBucket({
+ landscapes: {
+ kind: 'settings',
+ variations: [{ label: 'Salt flats', prompt: 'horizon-spanning salt flats' }],
+ },
+ });
+ // The bucket kind is 'settings', so the server should ignore an
+ // ill-typed targetKind and proceed with the bucket-derived kind. (The
+ // route schema would reject the bad value before reaching here in prod.)
+ mockLlm({ name: 'Salt Flats', description: 'A flat expanse.', prompt: 'horizon salt flats' });
+ const result = await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'landscapes',
+ label: 'Salt flats',
+ targetKind: 'invalid',
+ });
+ expect(result.targetKind).toBe('settings');
+ });
+});
+
+describe('universeBuilderPromote — error paths', () => {
+ it('404s when the category does not exist', async () => {
+ const w = await seedUniverseWithBucket({
+ landscapes: {
+ kind: 'settings',
+ variations: [{ label: 'A', prompt: 'a' }],
+ },
+ });
+ await expect(
+ promoteSvc.promoteVariationToCanon(w.id, { category: 'nonexistent', label: 'A' }),
+ ).rejects.toMatchObject({ status: 404, code: 'UNIVERSE_PROMOTE_NO_CATEGORY' });
+ });
+
+ it('404s when the variation label does not match', async () => {
+ const w = await seedUniverseWithBucket({
+ landscapes: {
+ kind: 'settings',
+ variations: [{ label: 'A', prompt: 'a' }],
+ },
+ });
+ await expect(
+ promoteSvc.promoteVariationToCanon(w.id, { category: 'landscapes', label: 'B' }),
+ ).rejects.toMatchObject({ status: 404, code: 'UNIVERSE_PROMOTE_VARIATION_NOT_FOUND' });
+ });
+
+ it('400s on missing category', async () => {
+ await expect(
+ promoteSvc.promoteVariationToCanon('any', { label: 'x' }),
+ ).rejects.toMatchObject({ status: 400, code: 'UNIVERSE_PROMOTE_NO_CATEGORY' });
+ });
+
+ it('400s on missing label', async () => {
+ await expect(
+ promoteSvc.promoteVariationToCanon('any', { category: 'landscapes' }),
+ ).rejects.toMatchObject({ status: 400, code: 'UNIVERSE_PROMOTE_NO_LABEL' });
+ });
+
+ it('409s when a canon entry with the same name already exists', async () => {
+ const existing = [{
+ name: 'Crystalline Canyon',
+ slugline: 'EXT. CANYON — DAY',
+ description: 'A pre-existing canon entry.',
+ }];
+ const w = await seedUniverseWithBucket(
+ {
+ landscapes: {
+ kind: 'settings',
+ variations: [{ label: 'Crystalline Canyon', prompt: 'salt-crystal walls' }],
+ },
+ },
+ { settings: existing },
+ );
+ await expect(
+ promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'landscapes',
+ label: 'Crystalline Canyon',
+ }),
+ ).rejects.toMatchObject({ status: 409, code: 'UNIVERSE_PROMOTE_DUPLICATE' });
+ // LLM should NOT be invoked when the duplicate check fails up front —
+ // we want a cheap rejection, not a wasted model call.
+ expect(runPromptThroughProviderMock).not.toHaveBeenCalled();
+ });
+
+ it('throws 502 when the LLM returns invalid JSON', async () => {
+ const w = await seedUniverseWithBucket({
+ landscapes: {
+ kind: 'settings',
+ variations: [{ label: 'A', prompt: 'a' }],
+ },
+ });
+ runPromptThroughProviderMock.mockResolvedValue({
+ text: 'this is not json',
+ runId: 'run-x',
+ model: 'mock-default',
+ });
+ await expect(
+ promoteSvc.promoteVariationToCanon(w.id, { category: 'landscapes', label: 'A' }),
+ ).rejects.toMatchObject({ status: 502, code: 'LLM_INVALID_JSON' });
+ });
+
+ it('cherry-picks the first shape-matching inner object when the LLM array-wraps the response', async () => {
+ // jsonExtract.extractJson walks balanced blocks and prefers ones whose
+ // value matches the shape predicate (which keys on `name`). So when the
+ // LLM wraps a single entry in an array, the inner object wins on shape
+ // and is returned directly. The service relies on this contract — there
+ // is no longer a defensive array-unwrap branch.
+ const w = await seedUniverseWithBucket({
+ vehicles: {
+ kind: 'objects',
+ variations: [{ label: 'Salvage Mech', prompt: 'rusted mech' }],
+ },
+ });
+ runPromptThroughProviderMock.mockResolvedValue({
+ text: JSON.stringify([
+ { name: 'Salvage Mech', description: 'A walker.', significance: 'A relic.' },
+ ]),
+ runId: 'run-x', model: 'mock-default',
+ });
+ const result = await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'vehicles', label: 'Salvage Mech',
+ });
+ expect(result.entry.name).toBe('Salvage Mech');
+ expect(result.entry.description).toBe('A walker.');
+ });
+});
+
+describe('universeBuilderPromote — control field stripping', () => {
+ it('drops hallucinated id / locked / imageRefs from the LLM response', async () => {
+ const w = await seedUniverseWithBucket({
+ landscapes: {
+ kind: 'settings',
+ variations: [{ label: 'Salt Flats', prompt: 'horizon salt flats' }],
+ },
+ });
+ mockLlm({
+ id: 'set-hallucinated',
+ name: 'Salt Flats',
+ description: 'A flat expanse.',
+ locked: true, // LLM should NEVER set this
+ imageRefs: ['phantom.png'],
+ primaryImageRef: 'phantom.png',
+ sourceSeriesId: 'srs-phantom',
+ });
+ const result = await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'landscapes',
+ label: 'Salt Flats',
+ });
+ // ID stripped → sanitizer mints a fresh one.
+ expect(result.entry.id).not.toBe('set-hallucinated');
+ // `locked` stripped → user has to explicitly lock from the canon UI.
+ expect(result.entry.locked).toBeUndefined();
+ // Image refs stripped → those are operational, owned by the render UI.
+ expect(result.entry.imageRefs).toEqual([]);
+ expect(result.entry.primaryImageRef).toBe(null);
+ });
+});
+
+describe('universeBuilderPromote — atomicity', () => {
+ it('writes the canon entry and variation removal in a single atomicWrite', async () => {
+ const w = await seedUniverseWithBucket({
+ landscapes: {
+ kind: 'settings',
+ variations: [
+ { label: 'A', prompt: 'a' },
+ { label: 'B', prompt: 'b' },
+ ],
+ },
+ });
+ mockLlm({ name: 'Place A', description: 'place a', prompt: 'a' });
+ const callsBefore = fileUtils.atomicWrite.mock.calls.length;
+ await promoteSvc.promoteVariationToCanon(w.id, {
+ category: 'landscapes',
+ label: 'A',
+ });
+ // Canon append AND variation removal must land in one persistence write
+ // — not two. A two-write split would expose a half-state window where a
+ // crash leaves the variation gone but the canon entry never written
+ // (or vice versa). updateUniverse writes once, so the call delta is 1.
+ expect(fileUtils.atomicWrite.mock.calls.length - callsBefore).toBe(1);
+ // Re-read from the persistence layer (mirrors what a sibling tab would
+ // see): canon has the new entry AND the bucket has lost the variation.
+ const reread = (await svc.listUniverses())[0];
+ expect(reread.settings.find((s) => s.name === 'Place A')).toBeTruthy();
+ expect(reread.categories.landscapes.variations.map((v) => v.label)).toEqual(['B']);
+ });
+});
+
+describe('universeBuilderPromote — prompt content', () => {
+ const { buildPromotePrompt } = promoteSvc.__testing;
+
+ it('embeds universe context (logline, embrace influences) into the prompt', () => {
+ const prompt = buildPromotePrompt({
+ targetKind: 'characters',
+ variation: { label: 'Ash', prompt: 'soot-stained child' },
+ category: 'heroes',
+ universe: {
+ logline: 'A foundry city goes silent.',
+ styleNotes: 'Moebius palette.',
+ influences: { embrace: ['cel-shading', 'dust palette'] },
+ },
+ });
+ expect(prompt).toContain('A foundry city goes silent.');
+ expect(prompt).toContain('Moebius palette.');
+ expect(prompt).toContain('cel-shading, dust palette');
+ expect(prompt).toContain('LABEL: Ash');
+ expect(prompt).toContain('PROMPT: soot-stained child');
+ });
+
+ it('emits the per-kind output contract', () => {
+ const charPrompt = promoteSvc.__testing.buildPromotePrompt({
+ targetKind: 'characters',
+ variation: { label: 'x', prompt: 'x' },
+ category: 'h',
+ universe: {},
+ });
+ expect(charPrompt).toContain('physicalDescription');
+ expect(charPrompt).toContain('personality');
+
+ const settingPrompt = promoteSvc.__testing.buildPromotePrompt({
+ targetKind: 'settings',
+ variation: { label: 'x', prompt: 'x' },
+ category: 'h',
+ universe: {},
+ });
+ expect(settingPrompt).toContain('slugline');
+ expect(settingPrompt).toContain('palette');
+
+ const objectPrompt = promoteSvc.__testing.buildPromotePrompt({
+ targetKind: 'objects',
+ variation: { label: 'x', prompt: 'x' },
+ category: 'h',
+ universe: {},
+ });
+ expect(objectPrompt).toContain('significance');
+ });
+});