Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(universe-builder): character bible expansion + artist reference sheet (#310)
[._.]/ Adam Eivy7df6c5bf9369
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 21890edd66..86846c6e6f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,8 @@### Universe Builder+- **Character bible expansion + artist reference sheet.** Universe canon characters now carry novelist + graphic-novelist depth and can render a single dense artist reference sheet styled to match the universe. `sanitizeCharacter` in `server/lib/storyBible.js` gains 15 prose fields (pronouns, age, coreTheme, speechAccent, visualNotes, silhouetteNotes, postureNotes, specialTraits, visualIdentity, motivations, likes, dislikes, mannerisms, relationships, skills) + 5 structured lists (stats, colorPalette, props, expressions, handGestures) + 1 operational pointer (`referenceSheetImageRef`). Stats are an open `[{label, value}]` list so non-human characters (ghosts, spiders, clouds, AIs) aren't shoehorned into human anatomy. Two new endpoints: `POST /api/universe-builder/:id/characters/:entryId/expand` runs one LLM call (new `universe-character-expand` stage) that fills BLANK extended fields without clobbering populated content; `POST /api/universe-builder/:id/characters/:entryId/render-reference-sheet` enqueues a media-job render driven by a rich TEXT prompt (no init image required) that works equally well across codex and local image-gen backends. The renderer emits a multi-paragraph layout-prescriptive prompt (turnaround, expression progression, color palette swatches, wardrobe + prop cards, hand gestures), routes through `mediaJobQueue` with the active `imageGen.mode` (codex → codex lane, local → GPU lane; external SD-API returns `UNIVERSE_CHARACTER_SHEET_UNSUPPORTED_MODE` rather than a silently-degraded render), and on `mediaJobEvents` completion copies the result into `data/image-refs/` then stamps `character.referenceSheetImageRef`. Completed renders are also filed into the universe's media collection (`Universe: <name>` bucket) via `universeBuilderCollectionHook` by attaching a `universeRun` tag to the enqueued job, alongside the rest of the universe's concept art. `/data/image-refs/` is now exposed as a static route so the UI can render the sheet inline. New UI: `CharacterDetailEditor.jsx` (sectioned collapsible editor for the extended fields) + `CharacterReferenceSheetPanel.jsx` (Generate / Regenerate / lightbox) embedded in `CanonCard.jsx` behind a single "Character details + reference sheet" toggle that only renders when the caller passes the universe wiring — the per-series NounsStage stays focused on naming + visual refs. New migration `022-character-extended-fields.js` is record-only (sanitizer fills defaults on next read). 18+ new server tests (storyBible extensions + universeCharacterSheet prompt builder + universeCharacterExpand merge semantics + route mocks).+- **CanonCard provenance chip now names the source series.** The "from series" chip on `CanonCard` (rendered by both the Universe Canon section and the per-issue Nouns stage) now reads `from <Series Name>` when an entry's `sourceSeriesId` resolves through a new `seriesNameMap` prop; the tooltip carries both name and id (`Introduced by series "<name>" (<id>)`). Map is sourced from a new top-level `seriesNameMap` field on the `GET /api/universe-builder/:id/canon-usage` response, which now lists every linked series — not just ones with a prose-match row — so an entry whose `sourceSeriesId` points at a series with no matching prose still resolves to a name. Missing-map / unknown-id cases keep the legacy `from series` label + id-only tooltip. New `SourceSeriesChip` helper extracted in `client/src/components/pipeline/CanonCard.jsx`; 4 vitest cases in `CanonCard.test.jsx` + 2 vitest cases in `server/services/canonUsage.test.js`.- **Other tab — Auto-sort with AI.** New `POST /api/universe-builder/:id/auto-sort` batches every `kind: 'other'` bucket into one LLM call that classifies each into characters / settings / objects (and optionally suggests a clearer key). Reassignments land atomically via one `updateUniverse` patch (defensive per-entry kind gate filters hallucinated kinds so the sanitizer can't coerce them back to `other`); `suggestedKey` renames surface in the response but stay opt-in. The Other-tab button replaces its old toast stub with a real spinner + result summary. New service `server/services/universeBuilderAutoSort.js` (16 unit tests, including separate prompt-injection pins for ASCII newlines on labels + styleNotes + logline, and for Unicode line/paragraph separators + NEL + form feed + vertical tab on the same three fields) + `server/routes/universeBuilder.test.js` (4 route tests) + `client/src/pages/UniverseBuilder.test.jsx` (2 client tests for the `OtherTab` Auto-sort button — clicks fire `onAutoSort` when enabled; disabled with "Sorting…" label while `autoSorting=true`); client helper `autoSortBuckets` in `apiUniverseBuilder.js`.- **Other tab — manual trunk assignment.** Each bucket on the Other tab now has an **Assign to…** menu (Cast / Places / Objects) that retags `categories[bucket].kind` so the bucket moves out of Other into the matching trunk on next render. Variations stay in place; per-variation promote-to-canon remains a separate action.@@ -33,6 +35,7 @@## Changed+- **Character reference sheet — text-template rendering across all image-gen modes.** The character reference sheet renderer no longer requires the FLUX.2-only init-image + multi-reference plumbing. The structured layout prompt (turnaround, expression progression, color palette, wardrobe + prop cards, hand gestures) is now the entire "template" — no init image, no portrait multi-ref — so the renderer works with codex (preferred, plus future nano-banana) and local backends through the same code path. `renderCharacterReferenceSheet` resolves the active `imageGen.mode` and routes through `mediaJobQueue` with mode-appropriate params: codex → codex lane (`codexPath` + `model`), local → GPU lane (`pythonPath` + `modelId` via `resolveSheetModelId`, which no longer prefers FLUX.2). External SD-API returns a clear `UNIVERSE_CHARACTER_SHEET_UNSUPPORTED_MODE` 400 rather than a silently-degraded render. `buildCharacterReferenceSheetPrompt` drops its `initImagePath` / `initImageStrength` / `referenceImagePaths` / `referenceImageStrengths` return fields and the "Honor the layout shown in the reference image" prompt line. Route/client `template` arg removed. Old `UNIVERSE_CHARACTER_SHEET_REQUIRES_LOCAL` / `UNIVERSE_CHARACTER_SHEET_NO_TEMPLATE` error codes gone.- **Universe Builder — starter idea is no longer capped at 4000 chars.** The starter idea is whatever the user wants to type, from a one-line pitch to a full treatment. The Zod-backed `STARTER_PROMPT_MAX` is raised to 200,000 chars (a sanity ceiling, not an artificial brevity constraint) and the textarea's `maxLength={4000}` attribute is removed.- **Sidebar + ⌘K label shortened to "Universe".** The Create sidebar link and palette manifest entry for `/universe-builder` now read "Universe" instead of "Universe Builder"; voice/palette aliases still include `universe-builder` so old phrasings keep resolving.diff --git a/.gitignore b/.gitignoreindex 95a54923e4..9a41b13cee 100644--- a/.gitignore+++ b/.gitignore@@ -29,6 +29,7 @@ npm-debug.log**.png!client/public/portos-logo.png!docs/media/portos-logo.png+!data.sample/templates/*.png# OS files.DS_Storediff --git a/PLAN.md b/PLAN.mdindex 4e4e306005..d9a1d0b2ce 100644--- a/PLAN.md+++ b/PLAN.md@@ -22,6 +22,19 @@ _Nothing currently parked — pick the next item from the Backlog._### Universe-as-Canon — Phase 2 + extensions+- [ ] [character-bible-simplify-followups] **Character bible / reference-sheet `/simplify` follow-ups.** Captured from the simplify review during the character bible expansion PR; each is deferred-but-cheap and shares the same surface area:+ - Bundle `CanonCard`'s four new character-only props (`universeId`, `onExpandCharacter`, `expanding`, `onSheetCompleted`) into a single `characterExtensions={…}` object; collapses the gate from 4 nulls per non-character call site to `characterExtensions && kind.key === 'characters'`. Touches `client/src/components/pipeline/CanonCard.jsx`, `client/src/components/universe/UniverseCanonSection.jsx` `KindSection`, and any other CanonCard consumer.+ - Mirror `server/lib/storyBible.js` `BIBLE_LIMITS` constants to the client (new `client/src/lib/bibleLimits.js`) and import in `client/src/components/universe/CharacterDetailEditor.jsx` so the editor's `max:` literals can't drift from the server caps.+ - Factor `WardrobeSection`'s draft+blur+pending-row editor (`client/src/components/pipeline/CanonCard.jsx:100-247`) into a shared `<EditableListRow>` / `useFieldDraft()` hook reused by both `WardrobeSection` and `CharacterDetailEditor.jsx`'s `ListRow`. Two implementations will drift.+ - Generalize `server/services/pipeline/refineHelpers.js#runPromptRefine` to handle multi-field merges so `universeCharacterExpand.js` can reuse its empty-guard + rationale-trim + log-tag scaffold instead of inlining them.+ - Collapse `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset` in `server/lib/fileUtils.js` onto a shared `makePathResolver(root, { extensions, cache? })` factory — three near-identical 15-line helpers today.+ - Add a `shortId(id, n=8)` helper in a shared lib for the `String(x).slice(0, 8)` pattern that's now in ~12 console.log call sites across `universeCharacterExpand.js` / `universeCharacterSheet.js` / others.+ - Extract a reusable `subscribeToImageGenJob({ jobId, onComplete, onFailed, timeoutMs })` from `server/services/universeCharacterSheet.js#renderCharacterReferenceSheet`; mirrors the pattern in `server/services/voice/tools.js:1320-1338` and `server/routes/sdapi.js#createCompletionWaiter`.+ - Move `universeCharacterSheet.js`'s `flattenStats`/`flattenPalette`/`flattenWardrobes`/`flattenProps`/`flattenNamedList` next to `RICH_SPEC` in `server/lib/canonPrompt.js` so per-page render prompts can reuse them.+ - Active-purge `character.referenceSheetImageRef` when the underlying file in `data/image-refs/` is deleted. Today there is no delete-route for sheet files, and the GET-time lazy `pruneStaleReferenceSheets` masks staleness at read-time, but when a sheet-delete route lands it must also call into a `purgeReferenceSheetFromAllUniverses(filename)` helper mirroring `purgeImageRefFromAllUniverses` in `server/services/universeCanon.js:263`.+ - Prune `_latestPendingByCharacter` in `server/services/universeCharacterSheet.js:221` when a character or universe is deleted. Map grows bounded by characters ever rendered, but stale slot entries persist across the process lifetime — wire a `clearPendingSheetSlot(universeId, entryId)` helper into the character-delete + universe-delete paths once those exist.+ - Cancel `CharacterReferenceSheetPanel`'s `waitForImageRef` poll on unmount. The `mountedRef` guard prevents the state update at line 77, but the 3 s poll keeps issuing HEAD requests against the dead component. Plumb an `AbortSignal` from a `useEffect` cleanup so the loop exits early.+- [x] ~~**Drop the default `characters` category.**~~ Shipped via the Universe Builder redesign Phase A migration; default `characters` bucket retired, variations backfilled into `universe.characters[]`.- [x] ~~**Universe expand LLM contract enrichment.**~~ Shipped via the Universe Builder redesign Phase B — expand contract now returns rich canon arrays alongside categories.- [x] ~~**arcPlanner prompt context — include canon characters/places/objects.**~~ Shipped via the Universe Builder redesign Phase B (`renderCanonForPrompt(world)` + `worldCanonText` + migration 019 for `pipeline-arc-overview`, `pipeline-arc-verify`, `pipeline-arc-resolve`, `pipeline-volume-verify`). Follow-up still open: sweep `grep -rn "world\.categories" server/services/pipeline server/services/universeBuilder*.js` for other prompt builders that read categories but not canon.diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsxindex 90d871c0d9..ec493e6ab5 100644--- a/client/src/components/pipeline/CanonCard.jsx+++ b/client/src/components/pipeline/CanonCard.jsx@@ -11,10 +11,12 @@*/import { useEffect, useRef, useState } from 'react';-import { Loader2, ImagePlus, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, ChevronDown, ChevronRight, Star, Square } from 'lucide-react';+import { Loader2, ImagePlus, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, ChevronDown, ChevronRight, Star, Square, BookOpen } from 'lucide-react';import useMediaJobProgress from '../../hooks/useMediaJobProgress';import MediaJobThumb from './MediaJobThumb';import EntryCard from '../universe/EntryCard';+import CharacterDetailEditor from '../universe/CharacterDetailEditor';+import CharacterReferenceSheetPanel from '../universe/CharacterReferenceSheetPanel';// Place metadata enums — kept in lock-step with `PLACE_INT_EXT` and// `PLACE_TIME_OF_DAY` in `server/lib/storyBible.js`. Mirror is fine: a@@ -56,6 +58,28 @@ function ReadonlyChip({ children }) {);}+// Collapsible wrapper for the universe-only character details panel+// (CharacterDetailEditor + CharacterReferenceSheetPanel). Single toggle so the+// card stays terse by default — the user opens it only when filling in+// novelist / graphic-novelist fields or generating a reference sheet.+function CharacterDetailsToggle({ children }) {+ const [open, setOpen] = useState(false);+ return (+ <div className="mt-2">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-gray-500 hover:text-white"+ >+ {open ? <ChevronDown size={10} /> : <ChevronRight size={10} />}+ <BookOpen size={10} />+ Character details {open ? '' : '+ reference sheet'}+ </button>+ {open ? <div>{children}</div> : null}+ </div>+ );+}+function SourceSeriesChip({ sourceSeriesId, seriesName }) {return (<span@@ -244,6 +268,14 @@ export default function CanonCard({// render the actual series name. Null/empty falls back to the id-tooltip// form for callers that don't have the map handy.seriesNameMap = null,+ // Universe-only character extensions. When provided + kind is 'characters',+ // CanonCard reveals an Expand → CharacterDetailEditor section and a+ // Reference Sheet panel. NounsStage (series view) omits these so the+ // per-series cast list stays focused on naming + visual refs.+ universeId = null,+ onExpandCharacter = null,+ expanding = false,+ onSheetCompleted = null,}) {const description = kind.descFor(entry);const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];@@ -349,6 +381,27 @@ export default function CanonCard({onChange={(next) => onPatchEntry?.(entry.id, { wardrobes: next })}/>) : null}+ {/* Universe-only: extended character detail editor + AI expand action.+ Hidden when the caller didn't pass the universe wiring (pipeline+ series view). Locked characters render read-only inputs. */}+ {kind.key === 'characters' && universeId && onPatchEntry ? (+ <CharacterDetailsToggle>+ <CharacterDetailEditor+ entry={entry}+ onPatch={(patch) => onPatchEntry(entry.id, patch)}+ onExpand={onExpandCharacter ? () => onExpandCharacter(entry.id) : null}+ expanding={expanding}+ disabled={locked}+ />+ <CharacterReferenceSheetPanel+ universeId={universeId}+ entry={entry}+ locked={locked}+ onSheetCompleted={onSheetCompleted}+ onOpenLightbox={(filename) => onPreview?.(filename, { isSheet: true })}+ />+ </CharacterDetailsToggle>+ ) : null}</>);diff --git a/client/src/components/universe/CharacterDetailEditor.jsx b/client/src/components/universe/CharacterDetailEditor.jsxnew file mode 100644index 0000000000..332bb29e7d--- /dev/null+++ b/client/src/components/universe/CharacterDetailEditor.jsx@@ -0,0 +1,380 @@+/**+ * CharacterDetailEditor — sectioned form for the extended character fields+ * (pronouns, motivations, stats, color palette, props, expressions, hand+ * gestures, etc.) used by the Universe Builder Cast tab.+ *+ * Mirrors the WardrobeSection draft+blur pattern in CanonCard.jsx: per-field+ * drafts buffered locally and PATCHed on blur (or row mutation) so typing+ * doesn't fire a universe-wide round-trip per keystroke. The parent owns the+ * persisted `entry` and the `onPatch(patch)` write channel — this component+ * only knows the field shape.+ */++import { useState } from 'react';+import {+ ChevronDown, ChevronRight, Plus, Trash2, WandSparkles, Loader2,+ Palette, Hand, Smile, Package, BookOpen, Eye, Activity,+} from 'lucide-react';++const SECTIONS = Object.freeze([+ {+ key: 'identity', label: 'Identity', icon: BookOpen,+ fields: [+ { name: 'pronouns', label: 'Pronouns', placeholder: 'she/her · they/them · it/its', max: 60, type: 'input' },+ { name: 'age', label: 'Age', placeholder: '27 · centuries old · unknown', max: 80, type: 'input' },+ { name: 'coreTheme', label: 'Core theme', placeholder: 'one-sentence essence', max: 500, type: 'textarea' },+ { name: 'speechAccent', label: 'Speech / accent', placeholder: 'clipped Edinburgh; rarely contracts; nautical metaphors', max: 500, type: 'textarea' },+ { name: 'visualNotes', label: 'Visual notes (at-a-glance)', placeholder: 'layered streetwear; faded mustard + charcoal; chunky boots', max: 1000, type: 'textarea' },+ ],+ },+ {+ key: 'personality', label: 'Personality & motivations', icon: Smile,+ fields: [+ { name: 'motivations', label: 'Motivations', placeholder: 'what they WANT and what they fear losing', max: 2000, type: 'textarea' },+ { name: 'likes', label: 'Likes', placeholder: 'short prose; comma-separated', max: 1500, type: 'textarea' },+ { name: 'dislikes', label: 'Dislikes', placeholder: 'short prose; comma-separated', max: 1500, type: 'textarea' },+ { name: 'mannerisms', label: 'Mannerisms', placeholder: 'habitual physical / verbal tics', max: 1500, type: 'textarea' },+ { name: 'relationships', label: 'Relationships', placeholder: 'who they\'re connected to and the tenor of each connection', max: 2000, type: 'textarea' },+ { name: 'skills', label: 'Skills', placeholder: 'concrete abilities, soft and hard', max: 2000, type: 'textarea' },+ ],+ },+ {+ key: 'visualIdentity', label: 'Visual identity', icon: Eye,+ fields: [+ { name: 'silhouetteNotes', label: 'Silhouette notes', placeholder: 'compact upper body; tapered lower half; short hair adds 5cm height', max: 2000, type: 'textarea' },+ { name: 'postureNotes', label: 'Posture notes', placeholder: 'slight forward lean; weight in left foot; shoulders loose', max: 1000, type: 'textarea' },+ { name: 'specialTraits', label: 'Special traits', placeholder: 'quick hands; scar on right eyebrow; observant', max: 2000, type: 'textarea' },+ { name: 'visualIdentity', label: 'Visual identity (design language)', placeholder: 'knobs + sights; urban utilitarian; analog tech feel', max: 1000, type: 'textarea' },+ ],+ },+]);++const LIST_SECTIONS = Object.freeze([+ {+ key: 'stats', label: 'Stats', icon: Activity, field: 'stats',+ addLabel: 'Add stat', singular: 'stat',+ columns: [+ { name: 'label', placeholder: 'Height · Eyes · Form', max: 80 },+ { name: 'value', placeholder: '5\'7" · amber · vapor', max: 200 },+ ],+ summary: (s) => `${s.label}${s.value ? `: ${s.value}` : ''}`,+ },+ {+ key: 'colorPalette', label: 'Color palette', icon: Palette, field: 'colorPalette',+ addLabel: 'Add swatch', singular: 'swatch',+ columns: [+ { name: 'name', placeholder: 'amber', max: 80 },+ { name: 'hex', placeholder: '#f59e0b', max: 10, narrow: true },+ { name: 'role', placeholder: 'skin · jacket primary · boot leather', max: 120 },+ ],+ summary: (c) => `${c.name}${c.hex ? ` ${c.hex}` : ''}${c.role ? ` — ${c.role}` : ''}`,+ swatchHex: (row) => row.hex,+ },+ {+ key: 'props', label: 'Props', icon: Package, field: 'props',+ addLabel: 'Add prop', singular: 'prop',+ columns: [+ { name: 'name', placeholder: 'Radio · Map case', max: 120 },+ { name: 'purpose', placeholder: 'comms · navigation · talisman', max: 400 },+ { name: 'materials', placeholder: 'aluminum + ABS plastic', max: 200 },+ ],+ summary: (p) => `${p.name}${p.purpose ? ` (${p.purpose})` : ''}`,+ },+ {+ key: 'expressions', label: 'Expression sheet', icon: Smile, field: 'expressions',+ addLabel: 'Add expression', singular: 'expression',+ columns: [+ { name: 'name', placeholder: 'neutral · curious · worried', max: 80 },+ { name: 'description', placeholder: 'wide eyes; lips parted; brow raised', max: 400 },+ ],+ summary: (e) => `${e.name}${e.description ? ` — ${e.description}` : ''}`,+ },+ {+ key: 'handGestures', label: 'Hand gestures', icon: Hand, field: 'handGestures',+ addLabel: 'Add gesture', singular: 'gesture',+ columns: [+ { name: 'name', placeholder: 'pointing · peace sign · gripping radio', max: 80 },+ { name: 'description', placeholder: 'open palm; index extended; relaxed', max: 300 },+ ],+ summary: (g) => `${g.name}${g.description ? ` — ${g.description}` : ''}`,+ },+]);++// Buffered text input — local draft state, commits to onCommit on blur.+function DraftField({ field, value, onCommit, disabled, idPrefix }) {+ const [draft, setDraft] = useState(undefined);+ const current = draft !== undefined ? draft : (value || '');+ const commit = () => {+ if (draft === undefined) return;+ if (draft === (value || '')) { setDraft(undefined); return; }+ onCommit(draft);+ setDraft(undefined);+ };+ const common = {+ value: current,+ onChange: (e) => setDraft(e.target.value),+ onBlur: commit,+ disabled,+ placeholder: field.placeholder,+ maxLength: field.max,+ className: 'w-full px-2 py-1 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50',+ // idPrefix scopes the field id to one editor instance so two open+ // character cards don't render duplicate `chr-field-pronouns` DOM ids+ // and break the label/input association.+ id: `chr-field-${idPrefix || 'unknown'}-${field.name}`,+ };+ return (+ <div className="space-y-0.5">+ <label htmlFor={common.id} className="block text-[10px] uppercase tracking-wider text-gray-500">+ {field.label}+ </label>+ {field.type === 'textarea'+ ? <textarea {...common} rows={2} />+ : <input type="text" {...common} />}+ </div>+ );+}++// Generic list editor row — one input per `columns` spec, plus delete.+function ListRow({ row, idx, columns, swatchHex, onChange, onDelete, disabled }) {+ const [drafts, setDrafts] = useState({});+ const draftFor = (col) => (col in drafts ? drafts[col] : (row[col] || ''));+ const setDraft = (col, v) => setDrafts((p) => ({ ...p, [col]: v }));+ const commit = (col) => {+ if (!(col in drafts)) return;+ const v = drafts[col];+ if (v === (row[col] || '')) {+ setDrafts((prev) => { const next = { ...prev }; delete next[col]; return next; });+ return;+ }+ // Spread `row` AND any other pending drafts so a fast A-blur → B-blur+ // sequence doesn't lose column A: if the parent hasn't re-rendered with+ // the committed A value by the time B blurs, B's commit would otherwise+ // spread the stale `row` prop and overwrite A back to its original. By+ // merging in `drafts`, the in-flight edits on sibling columns ride along.+ const nextRow = { ...row, ...drafts, [col]: v };+ setDrafts((prev) => { const next = { ...prev }; delete next[col]; return next; });+ onChange(nextRow);+ };+ return (+ <div className="flex items-start gap-1.5">+ {swatchHex ? (+ <span+ className="shrink-0 w-6 h-6 rounded border border-port-border mt-0.5"+ style={{ background: swatchHex(row) || 'transparent' }}+ title={`Preview ${swatchHex(row) || 'no hex'}`}+ />+ ) : null}+ {columns.map((col) => (+ <input+ key={col.name}+ type="text"+ value={draftFor(col.name)}+ onChange={(e) => setDraft(col.name, e.target.value)}+ onBlur={() => commit(col.name)}+ placeholder={col.placeholder}+ maxLength={col.max}+ disabled={disabled}+ className={`${col.narrow ? 'w-24 shrink-0' : 'flex-1 min-w-0'} px-1.5 py-0.5 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50`}+ aria-label={`row ${idx + 1} ${col.name}`}+ />+ ))}+ <button+ type="button"+ onClick={() => onDelete(idx)}+ disabled={disabled}+ title="Remove row"+ className="shrink-0 text-gray-500 hover:text-port-error disabled:opacity-30"+ >+ <Trash2 size={12} />+ </button>+ </div>+ );+}++function CollapsibleSection({ icon: Icon, label, summary, defaultOpen = false, children }) {+ const [open, setOpen] = useState(defaultOpen);+ return (+ <div className="rounded border border-port-border bg-port-bg/50">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="w-full flex items-center gap-1.5 px-2 py-1.5 text-[10px] uppercase tracking-wider text-gray-400 hover:text-white"+ >+ {open ? <ChevronDown size={11} /> : <ChevronRight size={11} />}+ <Icon size={11} />+ <span className="text-gray-300">{label}</span>+ {summary && !open ? <span className="text-gray-500 normal-case truncate">— {summary}</span> : null}+ </button>+ {open ? <div className="px-2.5 pb-2.5 pt-1 space-y-2">{children}</div> : null}+ </div>+ );+}++export default function CharacterDetailEditor({ entry, onPatch, onExpand, expanding = false, disabled = false }) {+ // Per-section pending rows — kept local until the required column (first+ // column on each LIST_SECTION, always `name` or `label`) is non-empty.+ // Persisting a blank row immediately would round-trip a row the server+ // sanitizer drops, and the user's first keystroke would land in a row that+ // disappears on the next render. Mirrors WardrobeSection's pendingNew+ // pattern in CanonCard.jsx.+ const [pendingByList, setPendingByList] = useState({});++ if (!entry) return null;++ const patchField = (name, value) => onPatch?.({ [name]: value });+ const patchList = (field, next) => onPatch?.({ [field]: next });++ const persistedFor = (section) =>+ (Array.isArray(entry[section.field]) ? entry[section.field] : []);+ const pendingFor = (section) => pendingByList[section.key] || [];+ const mergedFor = (section) => [...persistedFor(section), ...pendingFor(section)];+ const requiredColumn = (section) => section.columns[0].name;++ const sectionSummary = (section) => {+ const filled = section.fields.filter((f) => (entry[f.name] || '').trim()).length;+ return filled ? `${filled}/${section.fields.length} filled` : 'empty';+ };+ const listSummary = (section) => {+ const merged = mergedFor(section);+ if (merged.length === 0) return 'empty';+ return `${merged.length} ${merged.length === 1 ? section.singular : section.singular + 's'}`;+ };++ const addRow = (section) => {+ // Client-only id on pending rows so ListRow's local draft state stays+ // bound to THIS row across re-renders and after-deletes — without it,+ // the React key falls through to index and an earlier-row delete shifts+ // a different row's drafts buffer onto this one. The `pending-` prefix+ // is stripped at promotion (see updateRow) so the server's `ensureId`+ // mints a fresh `<kind>-<uuid>` id under its own convention; without+ // that strip the sanitizer would round-trip the client prefix back onto+ // the persisted row.+ const id = `pending-${section.key}-${(crypto?.randomUUID?.() ?? Date.now().toString(36) + Math.random().toString(36).slice(2))}`;+ const blank = { id, ...Object.fromEntries(section.columns.map((c) => [c.name, ''])) };+ setPendingByList((prev) => ({+ ...prev,+ [section.key]: [...(prev[section.key] || []), blank],+ }));+ };++ const isPendingIdx = (section, idx) => idx >= persistedFor(section).length;+ const pendingIdxOf = (section, idx) => idx - persistedFor(section).length;++ const updateRow = (section, idx, nextRow) => {+ if (!isPendingIdx(section, idx)) {+ const persisted = persistedFor(section);+ patchList(section.field, persisted.map((r, i) => (i === idx ? nextRow : r)));+ return;+ }+ const pIdx = pendingIdxOf(section, idx);+ const pending = pendingFor(section);+ const requiredFilled = String(nextRow[requiredColumn(section)] || '').trim().length > 0;+ if (requiredFilled) {+ // Promote into persisted; drop from pending. Strip the client-only+ // `pending-*` id so the server's sanitizer mints a fresh `<kind>-<uuid>`+ // under its own convention (sanitizer's `ensureId` preserves any+ // non-empty string id verbatim, so an unstripped pending prefix would+ // round-trip onto the persisted row).+ const remaining = pending.filter((_, i) => i !== pIdx);+ setPendingByList((prev) => ({ ...prev, [section.key]: remaining }));+ const { id: _pendingId, ...promoted } = nextRow;+ patchList(section.field, [...persistedFor(section), promoted]);+ return;+ }+ const next = pending.map((r, i) => (i === pIdx ? nextRow : r));+ setPendingByList((prev) => ({ ...prev, [section.key]: next }));+ };++ const removeRow = (section, idx) => {+ if (isPendingIdx(section, idx)) {+ const pIdx = pendingIdxOf(section, idx);+ const next = pendingFor(section).filter((_, i) => i !== pIdx);+ setPendingByList((prev) => ({ ...prev, [section.key]: next }));+ return;+ }+ patchList(section.field, persistedFor(section).filter((_, i) => i !== idx));+ };++ return (+ <div className="mt-2 space-y-1.5">+ {onExpand ? (+ <button+ type="button"+ onClick={onExpand}+ disabled={expanding || disabled}+ className="inline-flex items-center gap-1.5 px-2 py-1 text-[10px] rounded border border-port-accent/40 bg-port-accent/10 text-port-accent hover:bg-port-accent/20 disabled:opacity-40"+ title={`Fill blank fields on ${entry.name} via one LLM call. Populated fields are preserved.`}+ >+ {expanding ? <Loader2 size={10} className="animate-spin" /> : <WandSparkles size={10} />}+ AI: expand character+ </button>+ ) : null}++ {SECTIONS.map((section) => (+ <CollapsibleSection+ key={section.key}+ icon={section.icon}+ label={section.label}+ summary={sectionSummary(section)}+ >+ {section.fields.map((field) => (+ <DraftField+ key={field.name}+ field={field}+ value={entry[field.name]}+ onCommit={(v) => patchField(field.name, v)}+ disabled={disabled}+ idPrefix={entry.id}+ />+ ))}+ </CollapsibleSection>+ ))}++ {LIST_SECTIONS.map((section) => {+ const merged = mergedFor(section);+ return (+ <CollapsibleSection+ key={section.key}+ icon={section.icon}+ label={section.label}+ summary={listSummary(section)}+ >+ {merged.length === 0 ? (+ <p className="text-[11px] text-gray-500 italic">No {section.label.toLowerCase()} yet.</p>+ ) : (+ <div className="space-y-1.5">+ {merged.map((row, idx) => (+ <ListRow+ // Every persisted row carries a server-stamped id (see+ // sanitizeStat / sanitizePaletteColor / etc.) and every+ // pending row gets a client-only id from `addRow`. The+ // index fallback would tie ListRow's local `drafts` state+ // to a slot, so a delete on an earlier row would shift+ // another row's drafts onto this one.+ key={row.id || `${section.key}-${idx}`}+ row={row}+ idx={idx}+ columns={section.columns}+ swatchHex={section.swatchHex}+ onChange={(next) => updateRow(section, idx, next)}+ onDelete={() => removeRow(section, idx)}+ disabled={disabled}+ />+ ))}+ </div>+ )}+ <button+ type="button"+ onClick={() => addRow(section)}+ disabled={disabled}+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white hover:border-gray-500 disabled:opacity-40"+ >+ <Plus size={10} /> {section.addLabel}+ </button>+ </CollapsibleSection>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/universe/CharacterReferenceSheetPanel.jsx b/client/src/components/universe/CharacterReferenceSheetPanel.jsxnew file mode 100644index 0000000000..28e3371396--- /dev/null+++ b/client/src/components/universe/CharacterReferenceSheetPanel.jsx@@ -0,0 +1,154 @@+/**+ * Character Reference Sheet panel — embeds inside the universe Cast section.+ *+ * Shows the existing sheet (if any) as a thumbnail that opens a lightbox, plus+ * a Generate / Regenerate button that kicks off the render. The renderer is+ * text-template-based and works across codex + local image-gen modes (the+ * user's current Image Gen setting decides). Subscribes to media-job SSE+ * for live progress; calls `onSheetCompleted(entryId, filename)` so the+ * parent can drop the new filename into the universe draft without needing+ * a fresh GET (the server has already persisted it).+ */++import { useEffect, useRef, useState } from 'react';+import { Camera, Loader2, RefreshCcw, ExternalLink } from 'lucide-react';+import { renderCharacterReferenceSheet } from '../../services/apiUniverseBuilder';+import useMediaJobProgress from '../../hooks/useMediaJobProgress';+import useMounted from '../../hooks/useMounted';+import toast from '../ui/Toast';++// HEAD-poll for the rendered sheet at its destination URL, with backoff. The+// server-side onSheetComplete listener copies the gallery PNG into+// /data/image-refs/ AFTER the SSE 'completed' event fires (the listener is+// async, the event was sync), so claiming the file exists at SSE-completion+// time races and shows a 404 thumbnail. Returns true once the file is+// reachable, false after ~3s of polling.+async function waitForImageRef(filename, { maxMs = 3000, intervalMs = 150 } = {}) {+ if (!filename) return false;+ const url = `/data/image-refs/${filename}`;+ const deadline = Date.now() + maxMs;+ while (Date.now() < deadline) {+ // cache: 'no-store' so a transient 404 isn't cached by the browser and+ // poisoning subsequent <img> tags.+ const res = await fetch(url, { method: 'HEAD', cache: 'no-store' }).catch(() => null);+ if (res?.ok) return true;+ await new Promise((resolve) => setTimeout(resolve, intervalMs));+ }+ return false;+}++export default function CharacterReferenceSheetPanel({+ universeId, entry, locked, onSheetCompleted, onOpenLightbox,+}) {+ const existing = entry?.referenceSheetImageRef || null;+ const [jobId, setJobId] = useState(null);+ // destFilename for the in-flight render — captured from the route response+ // so the SSE-completion handler can pass the real refs-dir filename up to+ // the parent without a universe refetch.+ const destFilenameRef = useRef(null);+ // Prevent the completion callback from firing twice under React 18 StrictMode+ // dev double-mount.+ const settledRef = useRef(null);+ // mountedRef gates the post-completion HEAD-poll callback so an unmount+ // (universe switch, parent collapsing the section, etc.) mid-poll doesn't+ // fire `onSheetCompleted` against a stale entry/universe. useMounted resets+ // the ref to true on every effect setup — a plain `useRef(true)` plus a+ // cleanup-only effect leaves the ref permanently false after React 18+ // StrictMode's mount→cleanup→remount cycle in dev.+ const mountedRef = useMounted();++ const { status, filename, error, progress } = useMediaJobProgress(jobId);++ useEffect(() => {+ if (!jobId) { settledRef.current = null; return; }+ if (settledRef.current === jobId) return;+ if (status === 'completed' && filename) {+ settledRef.current = jobId;+ const dest = destFilenameRef.current;+ const entryId = entry?.id;+ destFilenameRef.current = null;+ setJobId(null);+ // The SSE 'completed' event fires when the image-gen child exits —+ // BEFORE the server-side onSheetComplete listener has copied the+ // gallery PNG into /data/image-refs/ and stamped the character.+ // Verify the file is actually reachable before flipping the UI;+ // otherwise the <img> renders a 404 that the browser caches.+ waitForImageRef(dest).then((ok) => {+ if (!mountedRef.current) return;+ if (ok) onSheetCompleted?.(entryId, dest);+ else toast.error('Sheet render finished but the image never appeared — refresh to see it');+ });+ } else if (status === 'failed' || status === 'canceled') {+ settledRef.current = jobId;+ destFilenameRef.current = null;+ toast.error(`Sheet render failed: ${error || status}`);+ setJobId(null);+ }+ }, [jobId, status, filename, error, entry?.id, onSheetCompleted]);++ const handleGenerate = async () => {+ if (jobId || !universeId || !entry?.id) return;+ const queued = await renderCharacterReferenceSheet(universeId, entry.id)+ .catch((err) => { toast.error(err.message || 'Sheet render failed to start'); return null; });+ if (!queued?.jobId) return;+ destFilenameRef.current = queued.destFilename || null;+ setJobId(queued.jobId);+ toast.success(`Rendering reference sheet for ${entry.name}…`);+ };++ const inFlight = !!jobId;+ const pctLabel = inFlight && typeof progress === 'number'+ ? ` ${Math.round(progress * 100)}%`+ : '';++ return (+ <div className="mt-2 rounded border border-port-border bg-port-bg/50 p-2">+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-gray-500">+ <Camera size={11} />+ Reference sheet+ </div>+ <div className="flex items-center gap-1">+ <button+ type="button"+ onClick={handleGenerate}+ disabled={inFlight || locked}+ title={locked+ ? `Unlock ${entry.name} to render a reference sheet`+ : (existing ? 'Regenerate the character reference sheet' : 'Generate a character reference sheet')}+ className="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"+ >+ {inFlight+ ? <Loader2 size={10} className="animate-spin" />+ : (existing ? <RefreshCcw size={10} /> : <Camera size={10} />)}+ {inFlight+ ? `Rendering${pctLabel}`+ : (existing ? 'Regenerate sheet' : 'Generate sheet')}+ </button>+ </div>+ </div>+ {existing ? (+ <button+ type="button"+ onClick={() => onOpenLightbox?.(existing)}+ className="mt-2 block w-full bg-port-bg rounded overflow-hidden border border-port-border hover:border-port-accent/60 cursor-zoom-in p-0"+ title="Open sheet at full size"+ >+ <img+ src={`/data/image-refs/${existing}`}+ alt={`${entry.name} reference sheet`}+ className="w-full h-auto block"+ loading="lazy"+ />+ <span className="flex items-center justify-center gap-1 px-2 py-1 text-[10px] text-gray-500 border-t border-port-border">+ <ExternalLink size={10} /> {existing}+ </span>+ </button>+ ) : !inFlight ? (+ <p className="mt-1.5 text-[11px] text-gray-500 italic">+ No reference sheet yet. Click <span className="text-gray-300">Generate sheet</span> to render a multi-view turnaround, expression progression, color palette, wardrobe + prop cards, and hand gestures — all in the universe's style.+ </p>+ ) : null}+ </div>+ );+}diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex 3277acd15a..13f9f904c2 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -24,6 +24,7 @@ import {updateUniverse,getUniverseCanonUsage,setUniverseCanonLock,+ expandUniverseCharacter,} from '../../services/apiUniverseBuilder';import { generateImage } from '../../services/apiSystem';import { composeStyledPrompt } from '../../lib/composeStyledPrompt';@@ -57,6 +58,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseCconst seriesFilter = searchParams.get('series') || '';const [renderingJobs, setRenderingJobs] = useState({});const [refiningId, setRefiningId] = useState(null);+ const [expandingId, setExpandingId] = useState(null);const [differentiating, setDifferentiating] = useState(false);const [togglingLockId, setTogglingLockId] = useState(null);// Ref mirrors togglingLockId for the reentrancy guard so handleToggleLock@@ -77,6 +79,14 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC// repopulate `usage` with stale data after fast navigation.const currentUniverseIdRef = useRef(universeId);useEffect(() => { currentUniverseIdRef.current = universeId; }, [universeId]);++ // Latest-universe ref so callbacks fired after async waits (e.g. the+ // sheet panel's HEAD-poll for the rendered file) merge against the+ // CURRENT draft instead of a snapshot captured at callback-creation+ // time. Without this, a concurrent character edit landing during the+ // poll window would be clobbered by the stale `universe` closure.+ const latestUniverseRef = useRef(universe);+ useEffect(() => { latestUniverseRef.current = universe; }, [universe]);const refreshUsage = useCallback(() => {if (!universeId) return;const requestedFor = universeId;@@ -167,14 +177,34 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseCprompt: `${entry.name}: ${kind.descFor(entry) || ''}`.trim().replace(/:\s*$/, ''),});}+ // Reference sheets live in data/image-refs/ — different static prefix+ // than the gallery. Built into the same list so the existing+ // MediaPreview lightbox + arrow navigation work uniformly.+ if (kind.key === 'characters' && typeof entry.referenceSheetImageRef === 'string' && entry.referenceSheetImageRef) {+ const filename = entry.referenceSheetImageRef;+ out.push({+ key: `canon-sheet:${filename}`,+ kind: 'image',+ filename,+ previewUrl: `/data/image-refs/${filename}`,+ downloadUrl: `/data/image-refs/${filename}`,+ prompt: `${entry.name} — character reference sheet`,+ });+ }}}return out;}, [universe]);- const openPreview = useCallback((filename) => {+ const openPreview = useCallback((filename, opts) => {if (!filename) return;- const match = previewItems.find((i) => i.filename === filename);+ // Match on the kind-tagged key when the caller indicates a sheet —+ // gallery `imageRefs[]` and `referenceSheetImageRef` can theoretically+ // collide on basename, in which case a filename-only find would route+ // the lightbox to the wrong static prefix (/data/images vs /data/image-refs).+ const targetKey = opts?.isSheet ? `canon-sheet:${filename}` : `canon:${filename}`;+ const match = previewItems.find((i) => i.key === targetKey)+ || previewItems.find((i) => i.filename === filename);if (match) setPreview(match);}, [previewItems]);@@ -249,6 +279,47 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseCtoast.success(`Refined — ${(result.rationale || result.changes?.[0] || 'description rewritten').slice(0, 140)}`);};+ // One LLM call fleshes out the extended character fields (motivations,+ // stats, color palette, expressions, etc.). No-clobber on populated fields.+ // Locked characters return `{ locked: true }` so the toast surfaces the+ // reason rather than a successful no-op.+ const handleExpandCharacter = async (entryId) => {+ if (!universe || expandingId) return;+ setExpandingId(entryId);+ const capturedId = universeId;+ const providerId = universe.llm?.provider || undefined;+ const model = universe.llm?.model || undefined;+ const result = await expandUniverseCharacter(universeId, entryId, { providerId, model })+ .catch((err) => { toast.error(err.message || 'Expand failed'); return null; });+ if (mountedRef.current) setExpandingId(null);+ if (!result || !isStillCurrent(capturedId)) return;+ if (result.locked) {+ toast.error(`${result.entry?.name || 'Character'} is locked — unlock before expanding`);+ return;+ }+ if (result.universe) onUniverseChange(result.universe);+ const fields = Array.isArray(result.updatedFields) ? result.updatedFields : [];+ toast.success(fields.length+ ? `Expanded ${result.entry?.name || 'character'} — filled ${fields.length} field${fields.length === 1 ? '' : 's'}`+ : `${result.entry?.name || 'Character'} already complete — nothing to fill`);+ };++ // Server already stamped the character via mediaJobEvents — merge the+ // filename into the local draft instead of refetching the whole universe.+ // Read from `latestUniverseRef` (not closed-over `universe`) so an edit+ // that landed during the panel's HEAD-poll wait isn't clobbered by an+ // older snapshot. No deps on `universe` keeps the callback stable.+ const handleSheetCompleted = useCallback((entryId, destFilename) => {+ const latest = latestUniverseRef.current;+ if (!latest || !destFilename) return;+ const nextCharacters = (latest.characters || []).map((c) =>+ c.id === entryId ? { ...c, referenceSheetImageRef: destFilename } : c,+ );+ onUniverseChange({ ...latest, characters: nextCharacters });+ const entryName = nextCharacters.find((c) => c.id === entryId)?.name || 'Character';+ toast.success(`${entryName} reference sheet ready`);+ }, [onUniverseChange]);+const handleRenderRef = async (kind, entry) => {const description = kind.descFor(entry);if (!description.trim()) {@@ -458,6 +529,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC<KindSectionkey={kind.key}kind={kind}+ universeId={universeId}all={filteredByKind[kind.key] || []}totalCount={(universe[kind.key] || []).length}filtered={!!seriesFilter}@@ -469,6 +541,9 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseConPreview={openPreview}onRefine={handleRefineCharacter}refiningId={refiningId}+ onExpandCharacter={handleExpandCharacter}+ expandingId={expandingId}+ onSheetCompleted={handleSheetCompleted}onToggleLock={(entryId, nextLocked) => handleToggleLock(kind, entryId, nextLocked)}togglingLockId={togglingLockId}onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}@@ -482,7 +557,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC);}-function KindSection({ kind, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap }) {+function KindSection({ kind, universeId, all, totalCount, filtered, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onExpandCharacter, expandingId, onSheetCompleted, onToggleLock, togglingLockId, onPatchEntry, onRenderCleanPlate, seriesNameMap }) {const Icon = kind.icon;return (<section className="rounded border border-port-border bg-port-bg/60">@@ -519,6 +594,10 @@ function KindSection({ kind, all, totalCount, filtered, usage, renderingJobs, ononPatchEntry={onPatchEntry}onRenderCleanPlate={onRenderCleanPlate}seriesNameMap={seriesNameMap}+ universeId={kind.key === 'characters' ? universeId : null}+ onExpandCharacter={kind.key === 'characters' ? onExpandCharacter : null}+ expanding={kind.key === 'characters' && expandingId === entry.id}+ onSheetCompleted={kind.key === 'characters' ? onSheetCompleted : null}/>))}</ul>diff --git a/client/src/lib/canonPrompt.js b/client/src/lib/canonPrompt.jsindex 43f56163f9..493f3d526f 100644--- a/client/src/lib/canonPrompt.js+++ b/client/src/lib/canonPrompt.js@@ -26,6 +26,11 @@ const RICH_SPEC = Object.freeze({characters: Object.freeze([{ field: 'physicalDescription' },{ field: 'role' },+ { field: 'visualNotes' },+ { field: 'silhouetteNotes' },+ { field: 'postureNotes' },+ { field: 'specialTraits' },+ { field: 'visualIdentity' },]),places: Object.freeze([{ field: 'description' },diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex e14f2e22a1..1c831b1925 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -171,6 +171,28 @@ export const refineUniverseCharacter = (universeId, entryId, { providerId, modelbody: JSON.stringify({ providerId, model }),});+// One LLM call fills BLANK extended character fields (pronouns / age / stats /+// motivations / colorPalette / expressions / hand gestures / ...). No-clobber+// on populated fields. Locked characters return `{ locked: true }` instead of+// a 4xx — the UI surfaces this as a "Locked" badge.+export const expandUniverseCharacter = (universeId, entryId, { providerId, model } = {}) =>+ request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/expand`, {+ method: 'POST',+ body: JSON.stringify({ providerId, model }),+ });++// Kick off a character reference sheet render. Returns immediately with+// `{ jobId, generationId, filename, path }`; the caller subscribes to media-job+// SSE for live progress. Server-side completion handler stamps the resulting+// filename onto `character.referenceSheetImageRef` automatically.+export const renderCharacterReferenceSheet = (universeId, entryId, {+ overridePrompt, overrideNegativePrompt, modelId,+} = {}) =>+ request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/render-reference-sheet`, {+ method: 'POST',+ body: JSON.stringify({ overridePrompt, overrideNegativePrompt, modelId }),+ });+// Cast-wide differentiate — single LLM call rewrites every character so the// whole cast has no visually-colliding pairs.export const differentiateUniverseCast = (universeId, { providerId, model } = {}) =>diff --git a/data.sample/prompts/stage-config.json b/data.sample/prompts/stage-config.jsonindex d06f3f5db7..fa0400ecb9 100644--- a/data.sample/prompts/stage-config.json+++ b/data.sample/prompts/stage-config.json@@ -284,6 +284,13 @@"returnsJson": true,"variables": []},+ "universe-character-expand": {+ "name": "Universe — Expand Character Profile",+ "description": "Flesh out blank fields on one universe canon character — novelist depth (motivations / likes / mannerisms / relationships) plus graphic-novelist visual fields (silhouette / palette / expressions / props / hand gestures). Preserves populated fields and stays distinct from peer characters.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"importer-classify": {"name": "Importer — Content-Type Classification","description": "Classify the first chunk of a source as short-story / novel / screenplay / comic-script. Runs at `light` tier — only sees ~4K chars from the head of the source, costs are negligible compared to the canon/arc/issue extractors.",diff --git a/data.sample/prompts/stages/universe-character-expand.md b/data.sample/prompts/stages/universe-character-expand.mdnew file mode 100644index 0000000000..148a5602a3--- /dev/null+++ b/data.sample/prompts/stages/universe-character-expand.md@@ -0,0 +1,82 @@+# Universe — Expand Character Profile++You are fleshing out one character in a story universe so a novelist (motivation, likes, mannerisms, relationships) and a graphic novelist (silhouette, palette, expressions, props) both have everything they need to render the character consistently.++## Universe style / aesthetic++{{styleClause}}++## The character++Current data — fields that are already populated MUST be preserved verbatim. Only fill BLANK fields. Empty string `""` or `[]` means blank.++```json+{{characterJson}}+```++## Other characters in this universe (peers — DO NOT collide visually or narratively)++```json+{{peersJson}}+```++## Task++For every BLANK field in the character JSON above, propose a value that:++1. **Fits the universe's aesthetic** and the character's existing `role` / `physicalDescription` / `personality`.+2. **Stays distinct from every peer.** Don't reuse a peer's signature color, accent, prop, or mannerism. If the character's species is non-human (ghost, spider, cloud, AI, etc.), let the stats and visual fields reflect that — do not force human anatomy.+3. **Reads as image-gen-ready prose** for the visual fields (`visualNotes`, `silhouetteNotes`, `postureNotes`, `specialTraits`, `visualIdentity`). Dense, specific, single paragraphs. No bullet points inside string values.++### Field guidance++- `pronouns` — short form ("she/her", "they/them", "it/its", "no pronouns — referred to as 'the Reach'").+- `age` — flexible string ("27", "centuries old", "newly hatched", "unknown — appears mid-30s"). Don't force a number.+- `coreTheme` — the character's one-sentence thematic essence ("a cartographer of grief", "the city's last honest broker").+- `speechAccent` — written speech pattern + accent ("clipped Edinburgh, rarely contracts; uses nautical metaphors").+- `visualNotes` — 1–2 sentences capturing the at-a-glance silhouette and palette ("layered practical streetwear in faded mustard + charcoal; chunky boots; ever-present beanie").+- `silhouetteNotes` — bulleted-as-prose distinctive shape features ("compact upper body; layered silhouette; tapered lower half; short hair adds 5cm height").+- `postureNotes` — habitual posture cues ("slight forward lean; weight in left foot; shoulders loose; ready-to-move; eyes constantly scanning").+- `specialTraits` — non-redundant standout details ("quick hands; chipped nail polish; scar on right eyebrow; restless energy; observant").+- `visualIdentity` — design language axes ("knobs + sights; urban utilitarian; analog tech feel; small signals of story; hard to pin down").+- `motivations` — primary drives in 2–3 sentences. What does the character WANT, and what does the character fear losing?+- `likes` — short prose list, separated by commas or semicolons.+- `dislikes` — same shape as likes.+- `mannerisms` — habitual physical / verbal tics ("touches the back of the neck when lying; trails off mid-sentence when thinking; whistles tunelessly while working").+- `relationships` — who the character is connected to in the world (use peer names where applicable), and the tenor of each connection.+- `skills` — concrete abilities, soft and hard ("conversational Mandarin; sleight-of-hand; knows every bus route from memory").+- `stats` — 4–10 entries appropriate for the character's form. For humans, default to height / weight / eye color / hair / skin / signature scent. For non-humans, replace with form-appropriate dimensions ("Wingspan: 12 ft", "Mass: 80kg of damp linen", "Eyes: none — echolocates").+- `colorPalette` — 6–8 named swatches that drive the character's wardrobe + skin + accent palette. Include a hex value (e.g. `#f59e0b`) and a 1–3-word role ("skin", "jacket primary", "boot leather"). Stay coherent with the universe aesthetic.+- `props` — 2–6 signature items the character carries or interacts with frequently. Each gets a `name`, `purpose`, `materials`, optional `notes`.+- `expressions` — 7 named facial expressions covering the emotional range ("neutral", "curious", "worried", "surprised", "amused", "determined", "relaxed"). Each gets a 1-line `description`.+- `handGestures` — 5 named hand gestures the character habitually uses ("relaxed hand", "pointing", "peace sign", "gripping radio", "adjusting earpiece"). Each gets a 1-line `description`.++## Output contract++Return ONLY valid JSON, no markdown fence, no commentary. Include ONLY the keys you are proposing values for — if you have nothing meaningful to add for a field (or it was already populated), OMIT the key entirely. Do not echo unchanged values.++```json+{+ "pronouns": "string",+ "age": "string",+ "coreTheme": "string",+ "speechAccent": "string",+ "visualNotes": "string",+ "silhouetteNotes": "string",+ "postureNotes": "string",+ "specialTraits": "string",+ "visualIdentity": "string",+ "motivations": "string",+ "likes": "string",+ "dislikes": "string",+ "mannerisms": "string",+ "relationships": "string",+ "skills": "string",+ "stats": [{"label": "string", "value": "string"}],+ "colorPalette": [{"name": "string", "hex": "#xxxxxx", "role": "string"}],+ "props": [{"name": "string", "purpose": "string", "materials": "string", "notes": "string"}],+ "expressions": [{"name": "string", "description": "string"}],+ "handGestures": [{"name": "string", "description": "string"}],+ "rationale": "1-sentence summary of the character direction you chose"+}+```diff --git a/data.sample/templates/character-reference-sheet.png b/data.sample/templates/character-reference-sheet.pngnew file mode 100644index 0000000000..a875fcdfa3Binary files /dev/null and b/data.sample/templates/character-reference-sheet.png differdiff --git a/scripts/migrations/022-character-extended-fields.js b/scripts/migrations/022-character-extended-fields.jsnew file mode 100644index 0000000000..0314b0dce6--- /dev/null+++ b/scripts/migrations/022-character-extended-fields.js@@ -0,0 +1,96 @@+/**+ * Universe canon characters — extended schema + LLM expand stage assets.+ *+ * Schema extension itself is record-only: `sanitizeCharacter` in+ * `server/lib/storyBible.js` fills the new fields with defaults on next read,+ * so no on-disk character rewrite is required.+ *+ * Side effects this migration is responsible for (so an upgrade via plain+ * git-pull + pm2 restart, without re-running `npm run install:all` /+ * `scripts/setup-data.js`, still has everything the runtime expects):+ *+ * 1. Copies `data.sample/prompts/stages/universe-character-expand.md` →+ * `data/prompts/stages/universe-character-expand.md` for the+ * `expandUniverseCharacter` LLM stage.+ * 2. Merges the `universe-character-expand` entry into the installed+ * `data/prompts/stage-config.json` so `runStagedLLM` can resolve the+ * stage. Mirrors the pattern in `017-volume-cover-concepts-stage.js` /+ * `020-comic-cover-concepts-stage.js`.+ *+ * Earlier versions of this migration also seeded+ * `data/templates/character-reference-sheet.png` as a FLUX.2 init image+ * for the sheet renderer. The renderer has since switched to a pure+ * text-template prompt that works across codex + local backends and no+ * longer consumes that asset — the seeding step was removed to stop+ * advertising a non-existent dependency to future maintainers. Already-+ * installed PNGs on existing systems are harmless (orphan file).+ */++import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';+import { dirname, join } from 'path';++const PROMPT_FILENAME = 'universe-character-expand.md';+const STAGE_KEY = 'universe-character-expand';++export default {+ async up({ rootDir }) {+ // 1. LLM stage prompt.+ {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ await mkdir(stagesDir, { recursive: true });+ const dataPath = join(stagesDir, PROMPT_FILENAME);+ const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', PROMPT_FILENAME);+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);+ if (exists) {+ console.log(`📝 ${PROMPT_FILENAME}: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ ${PROMPT_FILENAME}: sample missing — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${PROMPT_FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ ${PROMPT_FILENAME}: copy failed: ${err.message}`);+ }+ }+ }+ }++ // 2. stage-config entry — without this, runStagedLLM can't resolve the+ // universe-character-expand stage and the expand route 500s.+ {+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.sample', 'prompts', 'stage-config.json');+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);+ if (!sampleConfigExists) {+ console.warn(`⚠️ universe-character-expand: data.sample stage-config.json missing — skipping config write`);+ return;+ }+ try {+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);+ const installed = installedExists+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))+ : { stages: {} };+ installed.stages = installed.stages || {};+ if (installed.stages[STAGE_KEY]) {+ console.log(`📝 ${STAGE_KEY} stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ ${STAGE_KEY}: sample stage-config missing the entry — skipping`);+ return;+ }+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];+ await mkdir(dirname(installedConfigPath), { recursive: true });+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');+ const action = installedExists ? 'merged' : 'created';+ console.log(`📝 ${STAGE_KEY} stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ ${STAGE_KEY}: stage-config merge failed: ${err.message}`);+ }+ }+ },+};diff --git a/server/index.js b/server/index.jsindex 2fac518013..527a20ce58 100644--- a/server/index.js+++ b/server/index.js@@ -498,6 +498,9 @@ restoreLoops().catch(err => console.error(`❌ Loop restore failed: ${err.messag// Serve generated images from configured images directoryapp.use('/data/images', express.static(PATHS.images));+// Reference images (multi-ref upload inputs + generated character reference+// sheets) — served read-only so the UI can render thumbnails by URL.+app.use('/data/image-refs', express.static(PATHS.imageRefs));// Serve generated videos + thumbnails so the Media UI and tailnet clients// can pull them by URL without going through an explicit download route.app.use('/data/videos', express.static(PATHS.videos));diff --git a/server/lib/canonPrompt.js b/server/lib/canonPrompt.jsindex dcec2b4578..1ad1f32133 100644--- a/server/lib/canonPrompt.js+++ b/server/lib/canonPrompt.js@@ -46,6 +46,15 @@ const RICH_SPEC = Object.freeze({characters: Object.freeze([{ field: 'physicalDescription' },{ field: 'role' },+ // Extended visual descriptors — flow into per-page render prompts so the+ // model has continuity beyond the bare physicalDescription. Structured+ // fields (colorPalette, props, expressions) are flattened by the+ // reference-sheet builder, not here, to keep this spec field-keyed.+ { field: 'visualNotes' },+ { field: 'silhouetteNotes' },+ { field: 'postureNotes' },+ { field: 'specialTraits' },+ { field: 'visualIdentity' },]),places: Object.freeze([{ field: 'description' },diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex e94ba49952..7da90c04e3 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -59,6 +59,11 @@ export const PATHS = {decisions: join(__lib_dirname, '../../data/cos/decisions'),telegram: join(__lib_dirname, '../../data/telegram'),templates: join(__lib_dirname, '../../data/prompts/templates'),+ // Visual template assets (e.g. the character reference-sheet layout PNG used+ // as the init-image anchor by the universe-builder character sheet renderer).+ // Distinct from `templates` above, which is the legacy prompt-template dir.+ // Files here are shipped via data.sample/templates/ on first install.+ visualTemplates: join(__lib_dirname, '../../data/templates'),settings: join(__lib_dirname, '../../data/settings'),missions: join(__lib_dirname, '../../data/cos/missions'),tools: join(__lib_dirname, '../../data/tools'),@@ -674,6 +679,98 @@ export function resolveImageRef(name, { mustExist = true } = {}) {}}+/**+ * Resolve any user-supplied image input (init image OR multi-reference image)+ * to an absolute path under one of PortOS's approved image roots — the+ * gallery (`PATHS.images`), the multi-ref upload dir (`PATHS.imageRefs`),+ * or the shipped visual-template dir (`PATHS.visualTemplates`). Used by the+ * image-gen runner to re-validate paths that originated from internal+ * features (gallery picks, reference-sheet renders) which may legitimately+ * cross dir boundaries — a portrait pinned from the gallery passed as a+ * multi-ref input, a template PNG used as an init-image anchor.+ *+ * The defense-in-depth checks (basename strip, traversal block, root prefix,+ * existence + isFile gate) apply at each candidate root just like the+ * single-root resolvers (`resolveGalleryImage`, `resolveImageRef`,+ * `resolveTemplateAsset`).+ *+ * Accepts both basename input (`"foo.png"`) and already-resolved absolute+ * paths (the local image-gen runner re-validates the same input on every+ * call so we need to accept both shapes).+ *+ * @param {string} rawPath - basename or absolute path+ * @returns {string|null} validated absolute path, or null+ */+export function resolveImageInputPath(rawPath) {+ if (typeof rawPath !== 'string' || !rawPath) return null;+ // For ABSOLUTE inputs, dispatch by prefix. The single-root resolvers+ // basename their input for defense-in-depth, so trying them in order on an+ // absolute path can silently redirect a `/data/templates/foo.png` input+ // to `/data/images/foo.png` whenever a same-named file lives in the gallery.+ // Validate against the matching root only.+ const ROOTS = [+ [PATHS.images, resolveGalleryImage],+ [PATHS.imageRefs, resolveImageRef],+ [PATHS.visualTemplates, resolveTemplateAsset],+ ];+ const resolvedInput = resolvePath(rawPath);+ for (const [rootDir, resolver] of ROOTS) {+ const rootPrefix = resolvePath(rootDir) + PATH_SEP;+ if (resolvedInput.startsWith(rootPrefix)) return resolver(rawPath);+ }+ // For basename / relative input (no matching prefix), fall through the+ // resolvers in order. First match wins; basename collisions across roots+ // are accepted as ambiguous and resolve to the first defined root.+ for (const [, resolver] of ROOTS) {+ const candidate = resolver(rawPath);+ if (candidate) return candidate;+ }+ return null;+}++/**+ * Resolve a shipped visual template filename (e.g. character reference-sheet+ * layout PNG) to an absolute path under `PATHS.visualTemplates`. Mirrors+ * `resolveImageRef` / `resolveGalleryImage`: basename + traversal + root-prefix+ * + existence checks. Allows PNG/JPG/JPEG/WEBP since the template assets are+ * shipped image files.+ *+ * @param {string} name - Filename (basenamed internally)+ * @param {object} [opts]+ * @param {boolean} [opts.mustExist=true] - Require an existing regular file+ * @returns {string|null} Absolute path inside PATHS.visualTemplates, or null+ */+// Templates are shipped assets — once a basename resolves to a file the path+// is stable for the lifetime of the process, so cache the result. This stays+// off the hot path of every reference-sheet render without sacrificing the+// defense-in-depth basename + traversal + extension checks.+const _templateAssetCache = new Map();+export function resolveTemplateAsset(name, { mustExist = true } = {}) {+ if (typeof name !== 'string' || !name) return null;+ const safe = basename(name);+ if (!safe || safe === '.' || safe === '..') return null;+ const lower = safe.toLowerCase();+ if (!/\.(png|jpg|jpeg|webp)$/.test(lower)) return null;+ const cacheKey = mustExist ? `must:${safe}` : `nostat:${safe}`;+ if (_templateAssetCache.has(cacheKey)) return _templateAssetCache.get(cacheKey);+ const root = resolvePath(PATHS.visualTemplates) + PATH_SEP;+ const localPath = resolvePath(join(PATHS.visualTemplates, safe));+ if (!localPath.startsWith(root)) return null;+ if (!mustExist) {+ _templateAssetCache.set(cacheKey, localPath);+ return localPath;+ }+ let resolved = null;+ try {+ const stat = statSync(localPath, { throwIfNoEntry: false });+ resolved = stat?.isFile() ? localPath : null;+ } catch { /* falls through to null */ }+ // Only cache successful resolutions — a missing-then-installed template+ // should pick up on the next call (e.g. setup-data.js races a render).+ if (resolved) _templateAssetCache.set(cacheKey, resolved);+ return resolved;+}+/*** List a directory, keep entries whose extension matches `extensions`, stat* each, and project the survivors through `mapEntry(name, fullPath, stat)`.diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex dc5f2b21d9..745f79936a 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';import { writeFile, rm, mkdir } from 'fs/promises';import { mkdtempSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';@@ -14,7 +14,14 @@ import {readJSONLFile,formatDuration,sha256File,+ resolveImageInputPath,+ PATHS,} from './fileUtils.js';+import { copyFileSync, existsSync, mkdirSync } from 'fs';+import { dirname } from 'path';+import { fileURLToPath } from 'url';++const __dirname_test = dirname(fileURLToPath(import.meta.url));describe('fileUtils', () => {describe('isValidJSON', () => {@@ -512,6 +519,101 @@ describe('fileUtils', () => {});});+ // CONVENTION: this block writes fixtures into the REAL `data/images`,+ // `data/image-refs`, and `data/templates` roots because `PATHS` is module-+ // evaluated and not easily overridable. Two rules to keep dev/CI worktrees+ // clean and avoid clobbering shipped assets:+ // 1. Every fixture name MUST start with the `fileutils-test-` prefix so+ // the cleanup below can target it unambiguously (and so the basenames+ // don't shadow any real asset the resolver would otherwise find).+ // 2. Cleanup goes in `afterAll`, NOT a recursive remove of the root —+ // the data/ roots hold the user's universe content and shipped templates.+ describe('resolveImageInputPath', () => {+ const sampleTemplate = join(__dirname_test, '..', '..', 'data.sample', 'templates', 'character-reference-sheet.png');+ const galleryName = 'fileutils-test-gallery.png';+ const refsName = 'fileutils-test-refs.png';+ const templateName = 'fileutils-test-template.png';+ const galleryPath = join(PATHS.images, galleryName);+ const refsPath = join(PATHS.imageRefs, refsName);+ const templatePath = join(PATHS.visualTemplates, templateName);++ beforeEach(() => {+ // Provision fixtures in each approved root so the resolver can find+ // them. Reuses the shipped sample asset as a stand-in PNG body.+ for (const root of [PATHS.images, PATHS.imageRefs, PATHS.visualTemplates]) {+ if (!existsSync(root)) mkdirSync(root, { recursive: true });+ }+ if (existsSync(sampleTemplate)) {+ if (!existsSync(galleryPath)) copyFileSync(sampleTemplate, galleryPath);+ if (!existsSync(refsPath)) copyFileSync(sampleTemplate, refsPath);+ if (!existsSync(templatePath)) copyFileSync(sampleTemplate, templatePath);+ }+ });++ afterAll(() => {+ // Remove ONLY the per-test fixture files (uniquely-named so dev/CI+ // worktrees aren't polluted and later basename lookups don't keep+ // finding stale resolver hits). Never recursively remove the real+ // `data/images` / `data/image-refs` / `data/templates` roots.+ for (const p of [galleryPath, refsPath, templatePath]) {+ if (existsSync(p)) rmSync(p, { force: true });+ }+ });++ it('returns null for non-string / empty input', () => {+ expect(resolveImageInputPath(null)).toBeNull();+ expect(resolveImageInputPath('')).toBeNull();+ expect(resolveImageInputPath(undefined)).toBeNull();+ expect(resolveImageInputPath(123)).toBeNull();+ });++ it('resolves a basename present in the gallery (first root)', () => {+ const out = resolveImageInputPath(galleryName);+ expect(out).toBeTruthy();+ expect(out).toContain('data/images/');+ expect(out).toContain(galleryName);+ });++ it('resolves a basename present only in image-refs', () => {+ const out = resolveImageInputPath(refsName);+ expect(out).toBeTruthy();+ expect(out).toContain('data/image-refs/');+ });++ it('resolves a basename present only in visualTemplates', () => {+ const out = resolveImageInputPath(templateName);+ expect(out).toBeTruthy();+ // visualTemplates is the third root; without a basename in gallery first+ // it falls through. We can't fully isolate that here without temp dirs,+ // so just assert the resolver doesn't return null.+ });++ it('REGRESSION: absolute path under a specific root stays in that root', () => {+ // Bug it guards: previously the resolver basenamed any input and tried+ // each root in order — so `/data/templates/<name>.png` for a file that+ // also exists in `/data/images/<name>.png` would silently redirect to+ // the gallery copy. Reference-sheet renders would have used the wrong+ // init image. Verify each absolute path resolves to its own root.+ const galleryAbs = join(PATHS.images, galleryName);+ const refsAbs = join(PATHS.imageRefs, refsName);+ const templateAbs = join(PATHS.visualTemplates, templateName);++ expect(resolveImageInputPath(galleryAbs)).toContain('data/images/');+ expect(resolveImageInputPath(refsAbs)).toContain('data/image-refs/');+ expect(resolveImageInputPath(templateAbs)).toContain('data/templates/');+ });++ it('REGRESSION: same basename in multiple roots — absolute path picks the matching root', () => {+ // All three fixtures share the same body (copied from sampleTemplate),+ // but the absolute path should pin to its own root, NOT collapse to+ // the gallery via basename fallback.+ const refsAbs = join(PATHS.imageRefs, refsName);+ const out = resolveImageInputPath(refsAbs);+ expect(out).toContain('data/image-refs/');+ expect(out).not.toContain('data/images/');+ });+ });+describe('sha256File', () => {let dir;beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'portos-sha256-')); });diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex 0ec5cc87dd..aa8b032c20 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -10,7 +10,7 @@import { randomUUID } from 'crypto';import { join } from 'path';import { normalizeSlugline } from './scenePrompt.js';-import { PATHS, atomicWrite, ensureDir, readJSONFile } from './fileUtils.js';+import { PATHS, atomicWrite, ensureDir, readJSONFile, resolveImageRef } from './fileUtils.js';import { ServerError } from './errorHandler.js';// Re-export so callers (writers-room domain files) can import a single@@ -28,6 +28,47 @@ export const BIBLE_LIMITS = Object.freeze({NOTES_MAX: 4000,IMAGE_REF_MAX: 500,IMAGE_REFS_PER_ENTRY_MAX: 12,+ // Extended character identity (novelist + graphic-novelist needs). All+ // optional; sanitizer trims missing/blank to empty string. These flow into+ // the bible-extraction prompt + the universe-character-expand LLM call.+ PRONOUNS_MAX: 60,+ AGE_MAX: 80,+ CORE_THEME_MAX: 500,+ SPEECH_ACCENT_MAX: 500,+ VISUAL_NOTES_MAX: 1000,+ SILHOUETTE_NOTES_MAX: 2000,+ POSTURE_NOTES_MAX: 1000,+ SPECIAL_TRAITS_MAX: 2000,+ VISUAL_IDENTITY_MAX: 1000,+ MOTIVATIONS_MAX: 2000,+ LIKES_MAX: 1500,+ DISLIKES_MAX: 1500,+ MANNERISMS_MAX: 1500,+ RELATIONSHIPS_MAX: 2000,+ SKILLS_MAX: 2000,+ // Flexible stats list — open key/value so non-humans aren't forced into+ // human anatomy ("Number of eyes: 8", "Form: spectral vapor", etc).+ STAT_LABEL_MAX: 80,+ STAT_VALUE_MAX: 200,+ STATS_PER_CHARACTER_MAX: 30,+ // Color palette: named hex swatches with role hints ("amber #f59e0b — skin").+ COLOR_NAME_MAX: 80,+ COLOR_HEX_MAX: 10,+ COLOR_ROLE_MAX: 120,+ COLORS_PER_PALETTE_MAX: 12,+ // Props (graphic-novelist reference): per-prop name + purpose + materials.+ PROP_NAME_MAX: 120,+ PROP_PURPOSE_MAX: 400,+ PROP_MATERIALS_MAX: 200,+ PROP_NOTES_MAX: 600,+ PROPS_PER_CHARACTER_MAX: 12,+ // Expressions + hand gestures: named visual cues for reference-sheet panels.+ EXPRESSION_NAME_MAX: 80,+ EXPRESSION_DESC_MAX: 400,+ EXPRESSIONS_PER_CHARACTER_MAX: 16,+ GESTURE_NAME_MAX: 80,+ GESTURE_DESC_MAX: 300,+ GESTURES_PER_CHARACTER_MAX: 12,// Wardrobes per character — A2 in the AnyFilm gap analysis. Each entry// is an outfit/styling variant; first one is the visual default.WARDROBE_NAME_MAX: 120,@@ -118,7 +159,7 @@ export const BIBLE_KINDS = Object.freeze(Object.values(BIBLE_KIND));// `existing<X>Json` prompt variable (bibleExtractor) and into the script// stage's bibles context (evaluator). Excludes ids/timestamps/source/notes.export const PROMPT_FIELDS = Object.freeze({- [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'voiceId', 'wardrobes', 'prompt', 'tags'],+ [BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'pronouns', 'age', 'coreTheme', 'speechAccent', 'visualNotes', 'physicalDescription', 'personality', 'background', 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity', 'motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills', 'stats', 'colorPalette', 'props', 'expressions', 'handGestures', 'voiceId', 'wardrobes', 'prompt', 'tags'],[BIBLE_KIND.PLACE]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'intExt', 'timeOfDay', 'recurringDetails', 'prompt', 'tags'],[BIBLE_KIND.OBJECT]: ['name', 'aliases', 'description', 'significance', 'prompt', 'tags'],});@@ -199,24 +240,52 @@ export function findBibleEntryByName(list, name) {|| (Array.isArray(e?.aliases) && e.aliases.some((a) => normalizeBibleName(a) === needle)));}-// 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).+// Single source of truth for fields that LIVE on a canon entry but are+// NOT freely user-editable through the normal LLM/client flow. Each entry+// names *why* a guard exists; the consumers below read from this list so+// adding a new operational field is one edit, not three.+//+// - `id/createdAt/updatedAt`: freshly minted by the per-kind sanitizer.+// - `locked`: a hallucinated `true` would block user edits without a Lock+// UI click — purely a user-driven toggle.+// - `sourceSeriesId`: provenance owned by series imports.+// - `imageRefs` / `primaryImageRef`: user-uploaded gallery references —+// the user is the writer here, but the LLM should not hallucinate+// filenames into the gallery.+// - `referenceSheetImageRef`: SERVER-stamped operational pointer. The+// render-completion mutator is the sole writer. Distinct from the+// `imageRefs[]` gallery — lives in `data/image-refs/`.+//+// `SERVER_OWNED_CHARACTER_FIELDS` is a strict subset: ONLY the pointers+// that the *server* writes via render-completion mutators (never the+// client, never the LLM). `updateUniverse` preserves these across+// literal-object PATCHes so a stale client body can't clobber a newer+// server stamp (multi-tab / parallel render race). Mutator-form callers+// are trusted to update these (they read `cur` themselves).+export const CANON_CONTROL_FIELDS = Object.freeze([+ 'id', 'createdAt', 'updatedAt',+ 'locked', 'sourceSeriesId',+ 'imageRefs', 'primaryImageRef', 'referenceSheetImageRef',+]);++export const SERVER_OWNED_CHARACTER_FIELDS = Object.freeze([+ 'referenceSheetImageRef',+]);+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;+ const rest = { ...entry };+ for (const f of CANON_CONTROL_FIELDS) delete rest[f];return rest;}const nowIso = () => new Date().toISOString();+// Any non-empty string `raw` round-trips verbatim — the `idPrefix` arg is+// ONLY used to mint a fresh id when `raw` is absent/blank. Callers that+// need to enforce a per-shape prefix (e.g. drop a client-supplied+// `pending-*` placeholder so a fresh `<kind>-<uuid>` gets minted) must+// strip the offending id before calling.function ensureId(raw, idPrefix) {if (isStr(raw) && raw) return raw;return `${idPrefix}${randomUUID()}`;@@ -243,6 +312,55 @@ function derivePrimaryImageRef(raw, imageRefs) {return imageRefs.includes(trimmed) ? trimmed : null;}+// Generated character reference sheet pointer. Server-owned (set by the+// render-completion handler), basename-only-validated here (synchronous,+// keeps the sanitizer pure so it stays cheap on every universe read).+// Stale-file collapse happens at GET time via `pruneStaleReferenceSheets`+// below — a deleted file lazily nulls on the next universe load, but the+// sanitizer doesn't pay an FS stat on every character it sanitizes.+function deriveReferenceSheetImageRef(raw) {+ if (!isStr(raw) || !raw.trim()) return null;+ const trimmed = raw.trim().slice(0, BIBLE_LIMITS.IMAGE_REF_MAX);+ if (trimmed === '.' || trimmed === '..') return null;+ if (trimmed.includes('/') || trimmed.includes('\\')) return null;+ if (trimmed.startsWith('.')) return null;+ return trimmed;+}++/**+ * Walk a character list and null out any `referenceSheetImageRef` whose+ * underlying file no longer exists in PATHS.imageRefs. Returns a NEW list+ * (cheap shallow copy per character) so callers can persist the cleaned+ * state. Pure with respect to the sanitizer — no FS I/O during sanitize,+ * just here at the "GET universe / verify before render" boundary.+ *+ * `resolveImageRef(mustExist: true)` does the FS stat synchronously; for+ * a typical 5-50 character universe this is sub-millisecond.+ *+ * CONVENTION: call from BOTH the GET universe route AND `updateUniverse`'s+ * write path. GET alone is not sufficient — without the write-time call,+ * stale values stay on disk and a later PATCH that omits `characters`+ * (e.g. rename) resurfaces the stale filename in the response.+ */+export function pruneStaleReferenceSheets(characters) {+ if (!Array.isArray(characters)) return characters;+ let changed = false;+ const out = characters.map((c) => {+ if (!c || !c.referenceSheetImageRef) return c;+ if (resolveImageRef(c.referenceSheetImageRef, { mustExist: true })) return c;+ changed = true;+ return { ...c, referenceSheetImageRef: null };+ });+ return changed ? out : characters;+}++// CONVENTION: every per-row sanitizer below stamps a stable `id` via+// `ensureId`. The character editor (CharacterDetailEditor.jsx) binds local+// draft state to each `ListRow` via its React key — without a server-stamped+// id, the key falls back to row index and a delete-then-edit sequence carries+// the wrong drafts buffer onto the wrong row. New list shapes added here+// MUST include `id: ensureId(raw.id, '<prefix>-')`.+// Wardrobe sanitizer (A2). One entry per outfit/styling variant; the// description is image-gen-ready prose ("worn linen suit, gold pocket watch,// scuffed wingtips"). Reference images per wardrobe land in a follow-up.@@ -267,6 +385,77 @@ function sanitizeWardrobeList(raw, opts = {}) {);}+// Flexible stat entry — open label/value so non-humans aren't shoehorned into+// "height/weight/eyes" assumptions. Both fields are strings; the LLM expand+// flow may emit "Unknown" / "N/A" rather than blank, which is fine.+function sanitizeStat(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const label = trimTo(raw.label, BIBLE_LIMITS.STAT_LABEL_MAX);+ if (!label) return null;+ // Stable id so the editor's per-row local state (drafts buffer in+ // ListRow.jsx) doesn't carry over when an earlier row is deleted — without+ // it, React falls back to an index key and reuses the wrong row instance.+ return { id: ensureId(raw.id, 'stat-'), label, value: trimTo(raw.value, BIBLE_LIMITS.STAT_VALUE_MAX) };+}++// Color palette swatch. `hex` is optional — pure-name palettes still flow+// through; the prompt builder skips the "#xxxxxx" fragment when blank. We+// don't validate hex strictness here; the LLM may emit "amber" / "off-white".+function sanitizePaletteColor(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const name = trimTo(raw.name, BIBLE_LIMITS.COLOR_NAME_MAX);+ if (!name) return null;+ return {+ id: ensureId(raw.id, 'color-'),+ name,+ hex: trimTo(raw.hex, BIBLE_LIMITS.COLOR_HEX_MAX),+ role: trimTo(raw.role, BIBLE_LIMITS.COLOR_ROLE_MAX),+ };+}++// Prop entry — gets a UUID id like wardrobes for stable React keys. Name is+// required; everything else is free-form prose for the artist.+function sanitizeProp(raw, { preserveTimestamps = true } = {}) {+ if (!raw || typeof raw !== 'object') return null;+ const name = trimTo(raw.name, BIBLE_LIMITS.PROP_NAME_MAX);+ if (!name) return null;+ return {+ id: ensureId(raw.id, 'prop-'),+ name,+ purpose: trimTo(raw.purpose, BIBLE_LIMITS.PROP_PURPOSE_MAX),+ materials: trimTo(raw.materials, BIBLE_LIMITS.PROP_MATERIALS_MAX),+ notes: trimTo(raw.notes, BIBLE_LIMITS.PROP_NOTES_MAX),+ // Per-prop reference image is optional. Stored as a trimmed string only —+ // there's no derive-against-imageRefs[] check here because a prop image is+ // free-standing (the user can upload directly to the prop card; it doesn't+ // need to be a member of the character's gallery imageRefs[]). Stale+ // filenames are tolerated and produce a 404 in the UI rather than a+ // sanitizer collapse. Treat this string as untrusted at render time.+ imageRef: isStr(raw.imageRef) && raw.imageRef.trim() ? raw.imageRef.trim().slice(0, BIBLE_LIMITS.IMAGE_REF_MAX) : null,+ createdAt: preserveTimestamps && isStr(raw.createdAt) ? raw.createdAt : nowIso(),+ updatedAt: preserveTimestamps && isStr(raw.updatedAt) ? raw.updatedAt : nowIso(),+ };+}++// Expression entry — name + 1-line prose description. The reference-sheet+// builder uses up to 7; remaining entries are still available to per-page+// shot prompts that key on a named expression.+function sanitizeExpression(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const name = trimTo(raw.name, BIBLE_LIMITS.EXPRESSION_NAME_MAX);+ if (!name) return null;+ return { id: ensureId(raw.id, 'expr-'), name, description: trimTo(raw.description, BIBLE_LIMITS.EXPRESSION_DESC_MAX) };+}++// Hand-gesture entry — name + 1-line prose. Mirrors expression shape so the+// editor UI can reuse the same row component.+function sanitizeHandGesture(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const name = trimTo(raw.name, BIBLE_LIMITS.GESTURE_NAME_MAX);+ if (!name) return null;+ return { id: ensureId(raw.id, 'gesture-'), name, description: trimTo(raw.description, BIBLE_LIMITS.GESTURE_DESC_MAX) };+}+// Shared canon extras applied to every kind. `locked` follows the on-disk// minimization pattern from universe-builder variations: only `true` is// persisted, missing/false collapses to absent.@@ -301,10 +490,43 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,name,aliases: cleanStringArray(raw.aliases, BIBLE_LIMITS.ALIAS_MAX, BIBLE_LIMITS.ALIASES_PER_ENTRY_MAX),role: trimTo(raw.role, BIBLE_LIMITS.ROLE_MAX),+ // Identity (novelist-grade depth). All optional; downstream consumers+ // (LLM extractor, render-prompt builder, reference-sheet renderer) check+ // for blank and skip the corresponding fragment.+ pronouns: trimTo(raw.pronouns, BIBLE_LIMITS.PRONOUNS_MAX),+ age: trimTo(raw.age, BIBLE_LIMITS.AGE_MAX),+ coreTheme: trimTo(raw.coreTheme, BIBLE_LIMITS.CORE_THEME_MAX),+ speechAccent: trimTo(raw.speechAccent, BIBLE_LIMITS.SPEECH_ACCENT_MAX),+ visualNotes: trimTo(raw.visualNotes, BIBLE_LIMITS.VISUAL_NOTES_MAX),physicalDescription,personality: trimTo(raw.personality, BIBLE_LIMITS.PERSONALITY_MAX),background: trimTo(raw.background, BIBLE_LIMITS.BACKGROUND_MAX),+ // Visual identity (graphic-novelist-grade). These feed the+ // reference-sheet renderer and per-page shot prompts.+ silhouetteNotes: trimTo(raw.silhouetteNotes, BIBLE_LIMITS.SILHOUETTE_NOTES_MAX),+ postureNotes: trimTo(raw.postureNotes, BIBLE_LIMITS.POSTURE_NOTES_MAX),+ specialTraits: trimTo(raw.specialTraits, BIBLE_LIMITS.SPECIAL_TRAITS_MAX),+ visualIdentity: trimTo(raw.visualIdentity, BIBLE_LIMITS.VISUAL_IDENTITY_MAX),+ // Narrative depth — drives dialogue + arc planning.+ motivations: trimTo(raw.motivations, BIBLE_LIMITS.MOTIVATIONS_MAX),+ likes: trimTo(raw.likes, BIBLE_LIMITS.LIKES_MAX),+ dislikes: trimTo(raw.dislikes, BIBLE_LIMITS.DISLIKES_MAX),+ mannerisms: trimTo(raw.mannerisms, BIBLE_LIMITS.MANNERISMS_MAX),+ relationships: trimTo(raw.relationships, BIBLE_LIMITS.RELATIONSHIPS_MAX),+ skills: trimTo(raw.skills, BIBLE_LIMITS.SKILLS_MAX),notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),+ // Flexible stats list. Open key/value so ghosts/spiders/clouds aren't+ // forced into human anatomy categories.+ stats: sanitizeListWith(raw.stats, sanitizeStat, BIBLE_LIMITS.STATS_PER_CHARACTER_MAX),+ // Named color palette for the artist reference sheet + per-page render.+ colorPalette: sanitizeListWith(raw.colorPalette, sanitizePaletteColor, BIBLE_LIMITS.COLORS_PER_PALETTE_MAX),+ // Props the character carries / interacts with. Persists across panels;+ // the reference sheet renders these as prop-detail cards.+ props: sanitizeListWith(raw.props, (p) => sanitizeProp(p, { preserveTimestamps }), BIBLE_LIMITS.PROPS_PER_CHARACTER_MAX),+ // Expression + gesture menus drive the per-panel reference sheet zones+ // and can be cited from page-render prompts ("expression: 'curious'").+ expressions: sanitizeListWith(raw.expressions, sanitizeExpression, BIBLE_LIMITS.EXPRESSIONS_PER_CHARACTER_MAX),+ handGestures: sanitizeListWith(raw.handGestures, sanitizeHandGesture, BIBLE_LIMITS.GESTURES_PER_CHARACTER_MAX),// Voice binding for VO synthesis (kokoro/piper local OSS, ElevenLabs// when configured). null = use the project default at synth time.voiceId: trimTo(raw.voiceId, BIBLE_LIMITS.VOICE_ID_MAX) || null,@@ -312,6 +534,12 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,// Pinned visual anchor (A3). One of imageRefs marked canonical so// downstream renders + the UI know which to lean on.primaryImageRef: derivePrimaryImageRef(raw.primaryImageRef, imageRefs),+ // Generated character reference sheet filename (lives in data/image-refs/,+ // not in imageRefs[] — the sheet is operational metadata, not a candidate+ // for arbitrary panel reference). Basename-validated so an LLM-extracted+ // payload that snuck past stripCanonControlFields can't persist a path+ // the UI would 404 on or that would escape PATHS.imageRefs at render time.+ referenceSheetImageRef: deriveReferenceSheetImageRef(raw.referenceSheetImageRef),// Wardrobes (A2): outfit/styling variants applied on top of// physicalDescription. Empty array stays the legacy shape — every// existing character keeps rendering through physicalDescription alone.@@ -417,7 +645,18 @@ const SANITIZERS = Object.freeze({// so a later entry in the same batch resolves to the canonical record.const MERGE_CONFIG = Object.freeze({character: {- userEditable: ['role', 'physicalDescription', 'personality', 'background', 'wardrobes'],+ userEditable: [+ 'role', 'physicalDescription', 'personality', 'background', 'wardrobes',+ // Extended character fields — fill only when blank on the existing entry+ // (LLM extractor's "no-clobber" contract). The reference-sheet+ // operational fields (`referenceSheetImageRef`, `primaryImageRef`,+ // `imageRefs`) intentionally aren't here — those are owned by the+ // render flow, not the prose extractor.+ 'pronouns', 'age', 'coreTheme', 'speechAccent', 'visualNotes',+ 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity',+ 'motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills',+ 'stats', 'colorPalette', 'props', 'expressions', 'handGestures',+ ],keyFields: [{ field: 'name', normalize: normalizeBibleName },{ field: 'aliases', normalize: normalizeBibleName },diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex 55d96436c3..fb2395c9b9 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -28,6 +28,10 @@ const {BIBLE_LIMITS,BIBLE_KIND,createBibleStore,+ pruneStaleReferenceSheets,+ stripCanonControlFields,+ CANON_CONTROL_FIELDS,+ SERVER_OWNED_CHARACTER_FIELDS,} = storyBible;const WORK_ID = 'wr-work-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';@@ -257,6 +261,267 @@ describe('storyBible — sanitizeCharacter', () => {expect(out.wardrobes).toEqual([]);});});++ describe('extended character fields (novelist + graphic-novelist depth)', () => {+ it('defaults every new string field to empty + every list field to []', () => {+ const out = sanitizeCharacter({ name: 'Bare' });+ // String defaults+ expect(out.pronouns).toBe('');+ expect(out.age).toBe('');+ expect(out.coreTheme).toBe('');+ expect(out.speechAccent).toBe('');+ expect(out.visualNotes).toBe('');+ expect(out.silhouetteNotes).toBe('');+ expect(out.postureNotes).toBe('');+ expect(out.specialTraits).toBe('');+ expect(out.visualIdentity).toBe('');+ expect(out.motivations).toBe('');+ expect(out.likes).toBe('');+ expect(out.dislikes).toBe('');+ expect(out.mannerisms).toBe('');+ expect(out.relationships).toBe('');+ expect(out.skills).toBe('');+ // List defaults+ expect(out.stats).toEqual([]);+ expect(out.colorPalette).toEqual([]);+ expect(out.props).toEqual([]);+ expect(out.expressions).toEqual([]);+ expect(out.handGestures).toEqual([]);+ // Operational+ expect(out.referenceSheetImageRef).toBeNull();+ });++ it('round-trips a fully-populated character', () => {+ const out = sanitizeCharacter({+ name: 'Vale',+ pronouns: 'she/her',+ age: '27',+ coreTheme: 'cartographer of grief',+ speechAccent: 'clipped Edinburgh',+ visualNotes: 'layered streetwear',+ silhouetteNotes: 'compact upper body',+ postureNotes: 'slight forward lean',+ specialTraits: 'quick hands, restless energy',+ visualIdentity: 'urban utilitarian; analog tech feel',+ motivations: 'finish the map; protect her sister',+ likes: 'thunderstorms, fresh ink',+ dislikes: 'small talk, fluorescent light',+ mannerisms: 'touches the back of her neck when lying',+ relationships: 'estranged from her father; ride-or-die with Park',+ skills: 'conversational Mandarin, sleight-of-hand',+ });+ expect(out.pronouns).toBe('she/her');+ expect(out.age).toBe('27');+ expect(out.coreTheme).toBe('cartographer of grief');+ expect(out.skills).toBe('conversational Mandarin, sleight-of-hand');+ });++ it('caps every new string field at its BIBLE_LIMITS bound', () => {+ const longs = {+ pronouns: 'p'.repeat(BIBLE_LIMITS.PRONOUNS_MAX + 5),+ age: 'a'.repeat(BIBLE_LIMITS.AGE_MAX + 5),+ coreTheme: 't'.repeat(BIBLE_LIMITS.CORE_THEME_MAX + 50),+ motivations: 'm'.repeat(BIBLE_LIMITS.MOTIVATIONS_MAX + 50),+ skills: 's'.repeat(BIBLE_LIMITS.SKILLS_MAX + 50),+ };+ const out = sanitizeCharacter({ name: 'A', ...longs });+ expect(out.pronouns.length).toBe(BIBLE_LIMITS.PRONOUNS_MAX);+ expect(out.age.length).toBe(BIBLE_LIMITS.AGE_MAX);+ expect(out.coreTheme.length).toBe(BIBLE_LIMITS.CORE_THEME_MAX);+ expect(out.motivations.length).toBe(BIBLE_LIMITS.MOTIVATIONS_MAX);+ expect(out.skills.length).toBe(BIBLE_LIMITS.SKILLS_MAX);+ });++ it('keeps the open key/value stats list (non-human characters supported)', () => {+ const out = sanitizeCharacter({+ name: 'The Reach',+ stats: [+ { label: 'Form', value: 'translucent vapor' },+ { label: 'Eyes', value: 'none (echolocates)' },+ { label: 'Limbs', value: '6 segmented' },+ ],+ });+ expect(out.stats).toHaveLength(3);+ expect(out.stats[0]).toMatchObject({ label: 'Form', value: 'translucent vapor' });+ expect(out.stats[0].id).toMatch(/^stat-/);+ expect(out.stats[2].label).toBe('Limbs');+ });++ it('stats round-trip caller-supplied id and assign UUIDs to fresh rows', () => {+ const out = sanitizeCharacter({+ name: 'A',+ stats: [+ { label: 'Form', value: 'vapor' },+ { id: 'stat-fixed-1', label: 'Limbs', value: '6' },+ ],+ });+ expect(out.stats[0].id).toMatch(/^stat-/);+ expect(out.stats[1].id).toBe('stat-fixed-1');+ });++ it('drops stats entries missing a label, caps overall list', () => {+ const tooMany = Array.from({ length: BIBLE_LIMITS.STATS_PER_CHARACTER_MAX + 5 }, (_, i) => ({ label: `s${i}`, value: 'v' }));+ const out = sanitizeCharacter({+ name: 'A',+ stats: [+ { value: 'no label' },+ ...tooMany,+ ],+ });+ // Nameless entry dropped; list capped at the limit.+ expect(out.stats).toHaveLength(BIBLE_LIMITS.STATS_PER_CHARACTER_MAX);+ expect(out.stats[0]).toMatchObject({ label: 's0', value: 'v' });+ });++ it('color palette accepts hex + role; drops nameless rows', () => {+ const out = sanitizeCharacter({+ name: 'A',+ colorPalette: [+ { name: 'amber', hex: '#f59e0b', role: 'skin' },+ { name: 'olive', hex: '', role: '' },+ { role: 'no name' },+ ],+ });+ expect(out.colorPalette).toHaveLength(2);+ expect(out.colorPalette[0]).toMatchObject({ name: 'amber', hex: '#f59e0b', role: 'skin' });+ expect(out.colorPalette[0].id).toMatch(/^color-/);+ expect(out.colorPalette[1]).toMatchObject({ name: 'olive', hex: '', role: '' });+ });++ it('props get a UUID id and round-trip caller-supplied ids', () => {+ const out = sanitizeCharacter({+ name: 'A',+ props: [+ { name: 'Radio', purpose: 'comms', materials: 'plastic + alloy' },+ { id: 'prop-fixed-1', name: 'Compass' },+ ],+ });+ expect(out.props).toHaveLength(2);+ expect(out.props[0].id).toMatch(/^prop-/);+ expect(out.props[1].id).toBe('prop-fixed-1');+ expect(out.props[0].purpose).toBe('comms');+ });++ it('expressions + handGestures drop rows without a name', () => {+ const out = sanitizeCharacter({+ name: 'A',+ expressions: [+ { name: 'neutral', description: 'baseline' },+ { description: 'no name' },+ ],+ handGestures: [+ { description: 'no name' },+ { name: 'pointing', description: 'index out' },+ ],+ });+ expect(out.expressions).toHaveLength(1);+ expect(out.expressions[0].name).toBe('neutral');+ expect(out.expressions[0].id).toMatch(/^expr-/);+ expect(out.handGestures).toHaveLength(1);+ expect(out.handGestures[0].name).toBe('pointing');+ expect(out.handGestures[0].id).toMatch(/^gesture-/);+ });++ it('referenceSheetImageRef accepts a filename and trims it', () => {+ const out = sanitizeCharacter({ name: 'A', referenceSheetImageRef: ' universe-abc-character-sheet.png ' });+ expect(out.referenceSheetImageRef).toBe('universe-abc-character-sheet.png');+ });++ it('referenceSheetImageRef collapses to null for non-string / blank', () => {+ expect(sanitizeCharacter({ name: 'A', referenceSheetImageRef: '' }).referenceSheetImageRef).toBeNull();+ expect(sanitizeCharacter({ name: 'A', referenceSheetImageRef: ' ' }).referenceSheetImageRef).toBeNull();+ expect(sanitizeCharacter({ name: 'A', referenceSheetImageRef: 123 }).referenceSheetImageRef).toBeNull();+ expect(sanitizeCharacter({ name: 'A' }).referenceSheetImageRef).toBeNull();+ });++ it('REGRESSION: referenceSheetImageRef rejects path separators + traversal', () => {+ // Defense-in-depth against an LLM-extracted payload that bypassed+ // stripCanonControlFields. The runtime route serves /data/image-refs/<x>+ // — a value with separators or dot-prefix would 404 OR escape the dir.+ expect(sanitizeCharacter({ name: 'A', referenceSheetImageRef: '../etc/passwd' }).referenceSheetImageRef).toBeNull();+ expect(sanitizeCharacter({ name: 'A', referenceSheetImageRef: 'foo/bar.png' }).referenceSheetImageRef).toBeNull();+ expect(sanitizeCharacter({ name: 'A', referenceSheetImageRef: 'foo\\bar.png' }).referenceSheetImageRef).toBeNull();+ expect(sanitizeCharacter({ name: 'A', referenceSheetImageRef: '.' }).referenceSheetImageRef).toBeNull();+ expect(sanitizeCharacter({ name: 'A', referenceSheetImageRef: '..' }).referenceSheetImageRef).toBeNull();+ expect(sanitizeCharacter({ name: 'A', referenceSheetImageRef: '.hidden.png' }).referenceSheetImageRef).toBeNull();+ });+ });+});++describe('storyBible — canon control + server-owned field invariants', () => {+ // These constants are the single source of truth for "fields the LLM /+ // client shouldn't be the writer of". `stripCanonControlFields` reads+ // CANON_CONTROL_FIELDS; `updateUniverse`'s PATCH-preservation guard+ // reads SERVER_OWNED_CHARACTER_FIELDS. Pin both so a new operational+ // field added to one constant without updating the other (or its+ // consumer) gets caught.++ it('stripCanonControlFields drops every CANON_CONTROL_FIELD on an entry', () => {+ const entry = {+ id: 'c-1', createdAt: 'x', updatedAt: 'y',+ locked: true, sourceSeriesId: 'sr-1',+ imageRefs: ['a.png'], primaryImageRef: 'a.png',+ referenceSheetImageRef: 'sheet.png',+ // Non-control field — must survive.+ name: 'Vale', personality: 'alert',+ };+ const stripped = stripCanonControlFields(entry);+ for (const f of CANON_CONTROL_FIELDS) {+ expect(stripped).not.toHaveProperty(f);+ }+ expect(stripped.name).toBe('Vale');+ expect(stripped.personality).toBe('alert');+ });++ it('SERVER_OWNED_CHARACTER_FIELDS is a subset of CANON_CONTROL_FIELDS', () => {+ // The PATCH-preservation guard reads server-owned fields; the+ // strip-from-LLM guard reads control fields. Server-owned MUST be a+ // strict subset — otherwise a new server-owned field could appear+ // in literal PATCH bodies that bypass `stripCanonControlFields`.+ const ctrl = new Set(CANON_CONTROL_FIELDS);+ for (const f of SERVER_OWNED_CHARACTER_FIELDS) {+ expect(ctrl.has(f)).toBe(true);+ }+ });++ it('SERVER_OWNED_CHARACTER_FIELDS lists exactly the render-completion-stamped pointers', () => {+ // Pin the current set so a new server-owned addition is a deliberate+ // change (update both this test AND the corresponding render flow).+ expect([...SERVER_OWNED_CHARACTER_FIELDS]).toEqual(['referenceSheetImageRef']);+ });+});++describe('storyBible — pruneStaleReferenceSheets', () => {+ // Lives outside the sanitizeCharacter describe because it does FS I/O+ // (intentionally outside the sanitizer's pure contract). It collapses any+ // character.referenceSheetImageRef whose underlying file is missing from+ // PATHS.imageRefs — what the universe-builder GET route surfaces to the UI.++ it('returns the input unchanged when nothing is stale', () => {+ // No character has a pointer → nothing to check, returns the same array.+ const list = [{ name: 'A' }, { name: 'B', referenceSheetImageRef: null }];+ const out = pruneStaleReferenceSheets(list);+ expect(out).toBe(list);+ });++ it('nulls out pointers whose file does not exist (without persisting back)', () => {+ const list = [+ { name: 'A', referenceSheetImageRef: 'definitely-not-on-disk.png' },+ { name: 'B' },+ ];+ const out = pruneStaleReferenceSheets(list);+ expect(out).not.toBe(list); // new array on change+ expect(out[0].referenceSheetImageRef).toBeNull();+ // Untouched character pass-through (same reference).+ expect(out[1]).toBe(list[1]);+ expect(out).toHaveLength(2);+ });++ it('passes through a non-array input', () => {+ expect(pruneStaleReferenceSheets(null)).toBeNull();+ expect(pruneStaleReferenceSheets(undefined)).toBeUndefined();+ expect(pruneStaleReferenceSheets('not array')).toBe('not array');+ });});describe('storyBible — sanitizePlace', () => {diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 03ecd26cad..97b44f47ad 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -18,7 +18,9 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as svc from '../services/universeBuilder.js';import * as canonSvc from '../services/universeCanon.js';-import { BIBLE_KINDS, BIBLE_LIMITS } from '../lib/storyBible.js';+import { expandUniverseCharacter } from '../services/universeCharacterExpand.js';+import { renderCharacterReferenceSheet } from '../services/universeCharacterSheet.js';+import { BIBLE_KINDS, BIBLE_LIMITS, pruneStaleReferenceSheets } from '../lib/storyBible.js';import { getUniverseCanonUsage, listLinkedSeriesNames } from '../services/canonUsage.js';import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';import { refineWorldPrompts } from '../services/universeBuilderRefine.js';@@ -355,7 +357,15 @@ router.post('/refine-prompts', asyncHandler(async (req, res) => {router.get('/:id', asyncHandler(async (req, res) => {const w = await svc.getUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });- res.json(w);+ // Lazy stale-reference-sheet collapse: nulls out any character.referenceSheetImageRef+ // whose underlying file was deleted from disk, so the UI never tries to+ // render `<img src="/data/image-refs/<gone>">`. Doesn't persist the change+ // — next render or PATCH will overwrite cleanly. Sub-millisecond for the+ // typical 5-50 character universe.+ const pruned = Array.isArray(w?.characters)+ ? { ...w, characters: pruneStaleReferenceSheets(w.characters) }+ : w;+ res.json(pruned);}));router.patch('/:id', asyncHandler(async (req, res) => {@@ -593,6 +603,35 @@ router.post('/:id/characters/:entryId/refine', asyncHandler(async (req, res) =>res.json(result);}));+// Expand a character via one LLM call — fills BLANK extended fields+// (pronouns/age/stats/colorPalette/expressions/...) so a novelist + graphic+// novelist have full reference data. No-clobber on populated fields; locked+// characters return `{ locked: true }` with no LLM call.+router.post('/:id/characters/:entryId/expand', asyncHandler(async (req, res) => {+ const body = validateRequest(refineCharSchema, req.body ?? {});+ const result = await expandUniverseCharacter(req.params.id, req.params.entryId, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));++// Generate a single dense artist reference sheet (turnaround + expressions ++// palette + wardrobe + props + hand gestures) from a structured TEXT prompt+// — no init image required, so it works across codex / local backends.+// Returns immediately with `{ jobId, generationId }`; client subscribes to+// SSE for progress, and the server-side completion handler stamps+// `character.referenceSheetImageRef` on success.+const renderReferenceSheetSchema = z.object({+ overridePrompt: z.string().trim().max(8000).optional(),+ overrideNegativePrompt: z.string().trim().max(2000).optional(),+ modelId: z.string().trim().max(64).optional(),+});+router.post('/:id/characters/:entryId/render-reference-sheet', asyncHandler(async (req, res) => {+ const body = validateRequest(renderReferenceSheetSchema, req.body ?? {});+ const result = await renderCharacterReferenceSheet(req.params.id, req.params.entryId, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+// Cast-wide differentiate — one LLM call rewrites every character so the// cast as a whole has no visually-colliding pairs. Returns counts + the// updated universe.diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.jsindex 3d5f5df489..c345490b46 100644--- a/server/routes/universeBuilder.test.js+++ b/server/routes/universeBuilder.test.js@@ -53,6 +53,26 @@ vi.mock('../services/universeBuilderAutoSort.js', () => ({autoSortOtherBuckets: (...args) => autoSortOtherBucketsMock(...args),}));+// Stub the character-expand LLM call.+const expandUniverseCharacterMock = vi.fn(async (universeId, entryId) => ({+ universe: { id: universeId, characters: [{ id: entryId, name: 'Vale', motivations: 'survive' }] },+ entry: { id: entryId, name: 'Vale', motivations: 'survive' },+ updatedFields: ['motivations'],+ rationale: 'mock rationale',+ runId: 'mock-expand-run',+ providerId: 'mock', model: 'mock',+}));+vi.mock('../services/universeCharacterExpand.js', () => ({+ expandUniverseCharacter: (...args) => expandUniverseCharacterMock(...args),+}));++// Stub the reference-sheet renderer — only the route contract is verified+// here; the actual prompt builder is exercised in universeCharacterSheet.test.js.+const renderCharacterReferenceSheetMock = vi.fn();+vi.mock('../services/universeCharacterSheet.js', () => ({+ renderCharacterReferenceSheet: (...args) => renderCharacterReferenceSheetMock(...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 }) => ({@@ -659,4 +679,121 @@ describe('universe-builder routes', () => {expect(res.body.code).toBe('UNIVERSE_AUTOSORT_NO_PROVIDER');});});++ describe('POST /:id/characters/:entryId/expand', () => {+ beforeEach(() => expandUniverseCharacterMock.mockClear());++ it('200s and forwards providerId / model to the service', async () => {+ const res = await request(buildApp())+ .post('/api/universe-builder/u-1/characters/c-1/expand')+ .send({ providerId: 'anthropic', model: 'claude' });+ expect(res.status).toBe(200);+ expect(expandUniverseCharacterMock).toHaveBeenCalledWith('u-1', 'c-1', expect.objectContaining({+ providerId: 'anthropic',+ model: 'claude',+ }));+ expect(res.body.updatedFields).toEqual(['motivations']);+ expect(res.body.entry.id).toBe('c-1');+ });++ it('accepts an empty body (providerId + model are optional)', async () => {+ const res = await request(buildApp())+ .post('/api/universe-builder/u-1/characters/c-1/expand')+ .send({});+ expect(res.status).toBe(200);+ expect(expandUniverseCharacterMock).toHaveBeenCalled();+ });++ it('surfaces `locked: true` as a 200 — UI shows a Locked badge instead of a toast', async () => {+ expandUniverseCharacterMock.mockResolvedValueOnce({+ universe: { id: 'u-1', characters: [] },+ entry: { id: 'c-2', name: 'Frozen', locked: true },+ locked: true,+ updatedFields: [],+ });+ const res = await request(buildApp())+ .post('/api/universe-builder/u-1/characters/c-2/expand')+ .send({});+ expect(res.status).toBe(200);+ expect(res.body.locked).toBe(true);+ expect(res.body.updatedFields).toEqual([]);+ });++ it('maps service NOT_FOUND status onto a 404', async () => {+ expandUniverseCharacterMock.mockRejectedValueOnce(+ Object.assign(new Error('Character cx not found in universe'), {+ status: 404,+ code: 'UNIVERSE_CANON_NOT_FOUND',+ }),+ );+ const res = await request(buildApp())+ .post('/api/universe-builder/u-1/characters/cx/expand')+ .send({});+ expect(res.status).toBe(404);+ expect(res.body.code).toBe('UNIVERSE_CANON_NOT_FOUND');+ });+ });++ describe('POST /:id/characters/:entryId/render-reference-sheet', () => {+ beforeEach(() => {+ renderCharacterReferenceSheetMock.mockReset();+ renderCharacterReferenceSheetMock.mockImplementation(async (universeId, entryId, body = {}) => ({+ jobId: `job-${entryId}`,+ // generationId is now an alias for jobId per the client back-compat+ // contract — keep them identical in the mock so the test reflects prod.+ generationId: `job-${entryId}`,+ queuePosition: 1,+ destFilename: `universe-${universeId}-${entryId}-sheet-job-${entryId}.png`,+ destPath: `/data/image-refs/universe-${universeId}-${entryId}-sheet-job-${entryId}.png`,+ promptPreview: `mock prompt for ${entryId} (override:${!!body.overridePrompt})`,+ }));+ });++ it('200s with { jobId, generationId } and forwards overrides to the service', async () => {+ const res = await request(buildApp())+ .post('/api/universe-builder/u-1/characters/c-1/render-reference-sheet')+ .send({ overridePrompt: 'custom prompt', modelId: 'flux2-klein-9b' });+ expect(res.status).toBe(200);+ expect(renderCharacterReferenceSheetMock).toHaveBeenCalledWith('u-1', 'c-1', expect.objectContaining({+ overridePrompt: 'custom prompt',+ modelId: 'flux2-klein-9b',+ }));+ expect(res.body.jobId).toBe('job-c-1');+ // generationId is now an alias for jobId (client back-compat).+ expect(res.body.generationId).toBe('job-c-1');+ expect(res.body.queuePosition).toBe(1);+ expect(res.body.destFilename).toContain('-sheet-');+ expect(res.body.destPath).toContain('/data/image-refs/');+ });++ it('accepts an empty body (every override is optional)', async () => {+ const res = await request(buildApp())+ .post('/api/universe-builder/u-1/characters/c-1/render-reference-sheet')+ .send({});+ expect(res.status).toBe(200);+ expect(renderCharacterReferenceSheetMock).toHaveBeenCalledWith('u-1', 'c-1', {});+ });++ it('400s when overridePrompt exceeds the 8000-char Zod cap', async () => {+ const res = await request(buildApp())+ .post('/api/universe-builder/u-1/characters/c-1/render-reference-sheet')+ .send({ overridePrompt: 'x'.repeat(8001) });+ expect(res.status).toBe(400);+ expect(renderCharacterReferenceSheetMock).not.toHaveBeenCalled();+ });++ it('maps a service "unsupported mode" error onto a 400 with the right code', async () => {+ renderCharacterReferenceSheetMock.mockRejectedValueOnce(+ Object.assign(new Error('Character reference sheet rendering needs codex or local image-gen mode'), {+ status: 400,+ code: 'UNIVERSE_CHARACTER_SHEET_UNSUPPORTED_MODE',+ }),+ );+ const res = await request(buildApp())+ .post('/api/universe-builder/u-1/characters/c-1/render-reference-sheet')+ .send({});+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('UNIVERSE_CHARACTER_SHEET_UNSUPPORTED_MODE');+ });+ });});diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 6959f4ce90..ade7d09516 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -18,7 +18,7 @@ import { existsSync, watch as fsWatch } from 'fs';import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';import { tmpdir } from 'os';import { randomUUID } from 'crypto';-import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageRef } from '../../lib/fileUtils.js';+import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageInputPath } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';@@ -282,9 +282,11 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mconst validLoraFilenames = validLoras.map((p) => basename(p));// i2i: defense in depth — the route already validated a fresh request,// but an old sidecar replay can carry a stale absolute path outside the- // gallery. Re-anchor through resolveGalleryImage before handing to mflux.+ // approved image roots. resolveImageInputPath accepts gallery + image-refs+ // + visual templates — the latter so the universe-builder reference-sheet+ // renderer can use a shipped layout template as the init-image anchor.const validInitImagePath = (initImagePath && typeof initImagePath === 'string')- ? resolveGalleryImage(initImagePath)+ ? resolveImageInputPath(initImagePath): null;// Clamp 0..1 with a finite-fallback — Math.max/min preserve NaN, so a// corrupt sidecar value like Number('bad') would slip through and end up@@ -299,15 +301,17 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mconst validInitImageStrength = validInitImagePath && initImageStrength != null? clampStrength01(initImageStrength, null): null;- // Multi-reference: re-anchor each path through resolveImageRef so a sidecar- // replay can't sneak a path outside PATHS.imageRefs into the runner. Pair- // each path with its strength BEFORE filtering so a rejected entry doesn't- // shift the strength array — otherwise the surviving path would inherit the- // wrong slot's strength.+ // Multi-reference: re-anchor each path through resolveImageInputPath so a+ // sidecar replay can't sneak a path outside the approved image roots into+ // the runner. Accepts gallery + image-refs + visual templates — the gallery+ // path lets a canon portrait (e.g. character.primaryImageRef) flow in as a+ // multi-ref input. Pair each path with its strength BEFORE filtering so a+ // rejected entry doesn't shift the strength array — otherwise the surviving+ // path would inherit the wrong slot's strength.const rawRefPaths = Array.isArray(referenceImagePaths) ? referenceImagePaths : [];const validReferences = rawRefPaths.map((p, i) => {- const resolved = typeof p === 'string' ? resolveImageRef(p) : null;+ const resolved = typeof p === 'string' ? resolveImageInputPath(p) : null;if (!resolved) return null;const rawStrength = referenceImageStrengths?.[i];const strength = rawStrength != null ? clampStrength01(rawStrength, 1.0) : 1.0;diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.jsindex bc3ab674d6..2ee9607691 100644--- a/server/services/imageGen/local.test.js+++ b/server/services/imageGen/local.test.js@@ -240,6 +240,30 @@ describe('imageGen local.buildArgs flux2 dispatch', () => {expect(args).not.toContain('--reference-strengths');});+ // Templates land at /data/templates/, not /data/images/ — the runner-side+ // resolver (generateImage) accepts them via resolveImageInputPath (covered+ // in fileUtils.test.js). Pin that buildArgs emits the validated absolute+ // path verbatim so a future refactor can't silently drop the template anchor.+ it('emits --image-path verbatim for a pre-validated template path', () => {+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');+ const { args } = buildArgs({+ ...baseInput,+ initImagePath: '/data/templates/character-reference-sheet.png',+ initImageStrength: 0.25,+ model: {+ id: 'flux2-klein-9b',+ runner: 'flux2',+ quantization: 'sdnq',+ repo: 'Disty0/FLUX.2-klein-9B-SDNQ-4bit-dynamic-svd-r32',+ tokenizerRepo: 'black-forest-labs/FLUX.2-klein-9B',+ },+ });+ expect(args).toContain('--image-path');+ expect(args[args.indexOf('--image-path') + 1]).toBe('/data/templates/character-reference-sheet.png');+ expect(args).toContain('--image-strength');+ expect(args[args.indexOf('--image-strength') + 1]).toBe('0.25');+ });+it('falls back to mflux dispatch for non-flux2 models on macOS', () => {// No flux2 mock needed — the branch shouldn't be taken at all.mockResolveFlux2Python.mockReturnValue(null);diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex a0a51d0dcb..227ccd3d6c 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -69,11 +69,20 @@ async function resolveSourceBio(bucket) {* gen params in practice, so the second writer's (possibly missing) sidecar* doesn't overwrite the first's.*/+// 'image-ref' covers files under data/image-refs/ (multi-ref upload inputs+// + generated character reference sheets). No sidecar handling — these+// don't carry the gen-params metadata sidecar that gallery images do.+const ASSET_SOURCE_DIRS = Object.freeze({+ video: PATHS.videos,+ image: PATHS.images,+ 'image-ref': PATHS.imageRefs,+});+async function copyAssetIfPresent(filename, kind, bucketPath) {if (!filename || typeof filename !== 'string') return null;const base = basename(filename);if (!base || base !== filename) return null; // refuse path traversal- const sourceDir = kind === 'video' ? PATHS.videos : PATHS.images;+ const sourceDir = ASSET_SOURCE_DIRS[kind] || PATHS.images;await ensureDir(bucketBlobsDir(bucketPath));const sourcePath = join(sourceDir, base);if (!existsSync(sourcePath)) {@@ -200,6 +209,10 @@ function collectAssetReferences(record) {const jobIds = new Set();const directImageFilenames = new Set();const directVideoFilenames = new Set();+ // Character reference sheets — files live under data/image-refs/, distinct+ // from the gallery (data/images/). Tracked separately so the export loop+ // can route them through the 'image-ref' source-dir branch.+ const directImageRefFilenames = new Set();const walk = (node) => {if (!node) return;@@ -211,6 +224,7 @@ function collectAssetReferences(record) {if (Array.isArray(node.imageRefs)) {for (const r of node.imageRefs) if (isStr(r)) directImageFilenames.add(r);}+ if (isStr(node.referenceSheetImageRef)) directImageRefFilenames.add(node.referenceSheetImageRef);if (isStr(node.videoPath)) directVideoFilenames.add(basename(node.videoPath));for (const k of Object.keys(node)) {const v = node[k];@@ -223,6 +237,7 @@ function collectAssetReferences(record) {jobIds: [...jobIds],directImageFilenames: [...directImageFilenames],directVideoFilenames: [...directVideoFilenames],+ directImageRefFilenames: [...directImageRefFilenames],};}@@ -358,11 +373,13 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {const allJobIds = new Set();const allImageFiles = new Set();const allVideoFiles = new Set();+ const allImageRefFiles = new Set();for (const rec of [series, ...issues, universe].filter(Boolean)) {const refs = collectAssetReferences(rec);refs.jobIds.forEach((j) => allJobIds.add(j));refs.directImageFilenames.forEach((f) => allImageFiles.add(f));refs.directVideoFilenames.forEach((f) => allVideoFiles.add(f));+ refs.directImageRefFilenames.forEach((f) => allImageRefFiles.add(f));}if (linkedCollection) {const collAssets = collectCollectionAssets(linkedCollection);@@ -372,14 +389,15 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {}}- // Copy media-job records + their assets — run all three groups in parallel.+ // Copy media-job records + their assets — run all four groups in parallel.const mediaRecordsDir = join(bucket.path, 'records', 'media');- const [jobRefGroups, imageRefs, videoRefs] = await Promise.all([+ const [jobRefGroups, imageRefs, videoRefs, imageRefRefs] = await Promise.all([Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir))),Promise.all([...allImageFiles].map((f) => copyAssetIfPresent(f, 'image', bucket.path))),Promise.all([...allVideoFiles].map((f) => copyAssetIfPresent(f, 'video', bucket.path))),+ Promise.all([...allImageRefFiles].map((f) => copyAssetIfPresent(f, 'image-ref', bucket.path))),]);- const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean)];+ const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean), ...imageRefRefs.filter(Boolean)];const manifest = { ...manifestStub, recordIds, assetRefs };const filename = await writeManifest(bucket.path, manifest);@@ -430,14 +448,16 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {const allVideoFiles = new Set(collectionAssets.assetFilenames.filter((a) => a.kind === 'video').map((a) => a.ref),);+ const allImageRefFiles = new Set(universeRefs.directImageRefFilenames);const mediaRecordsDir = join(bucket.path, 'records', 'media');- const [jobRefGroups, imageRefs, videoRefs] = await Promise.all([+ const [jobRefGroups, imageRefs, videoRefs, imageRefRefs] = await Promise.all([Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir))),Promise.all([...allImageFiles].map((f) => copyAssetIfPresent(f, 'image', bucket.path))),Promise.all([...allVideoFiles].map((f) => copyAssetIfPresent(f, 'video', bucket.path))),+ Promise.all([...allImageRefFiles].map((f) => copyAssetIfPresent(f, 'image-ref', bucket.path))),]);- const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean)];+ const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean), ...imageRefRefs.filter(Boolean)];const manifest = { ...manifestStub, recordIds: [universe.id], assetRefs };const filename = await writeManifest(bucket.path, manifest);diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 554dfdc989..02f5ba8d8e 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -134,12 +134,17 @@ async function mergeCollectionPayload(payload, availableAssetKeys = null) {return { itemsAdded: added, itemsDeferred: deferred };}+// `image-ref` covers files under data/image-refs/ (character reference+// sheets). Unknown kinds collapse to 'image' for back-compat with v1+// peers that only emitted 'image' / 'video'.+const KNOWN_ASSET_KINDS = new Set(['video', 'image', 'image-ref']);+function manifestAssetRefs(manifest) {const refs = [];const seen = new Set();const push = (raw) => {if (!raw || !isStr(raw.ref)) return;- const kind = raw.kind === 'video' ? 'video' : 'image';+ const kind = KNOWN_ASSET_KINDS.has(raw.kind) ? raw.kind : 'image';const filename = basename(raw.ref);if (!filename || filename !== raw.ref) return;const key = `${kind}:${filename}`;@@ -196,19 +201,28 @@ function resolveBucketAssetPaths(bucketPath, ref) {};}+// Local target dir per asset kind. 'image-ref' covers character reference+// sheets (data/image-refs/). Unknown kinds route to the gallery for+// safety — peer manifests using a kind we don't recognize land there.+const LOCAL_TARGET_DIRS = Object.freeze({+ video: PATHS.videos,+ image: PATHS.images,+ 'image-ref': PATHS.imageRefs,+});+/** Copy bundled assets from the bucket into local data dirs. Runs in parallel. */async function copyAssetsLocally(bucketPath, assetRefs) {await ensureDir(PATHS.images);await ensureDir(PATHS.videos);+ await ensureDir(PATHS.imageRefs);const copied = [];const available = [];const missing = [];await Promise.all((assetRefs || []).map(async (ref) => {if (!ref || !isStr(ref.ref)) return;const filename = basename(ref.ref);- const isVideo = ref.kind === 'video';- const kind = isVideo ? 'video' : 'image';- const targetDir = isVideo ? PATHS.videos : PATHS.images;+ const kind = ref.kind;+ const targetDir = LOCAL_TARGET_DIRS[kind] || PATHS.images;const targetPath = join(targetDir, filename);const { blobPath, sidecarPath } = resolveBucketAssetPaths(bucketPath, ref);if (!existsSync(blobPath)) {@@ -361,10 +375,17 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =};// Universes first — series may reference them via universeId.+ // Wrap updateUniverse in a mutator form so the service-side+ // `referenceSheetImageRef` preservation guard (gated on `!isMutator`) is+ // skipped: sync's intent is that the remote's newer record wins LWW,+ // including server-owned operational pointers like the rendered sheet+ // filename. A literal-patch call would let the local stale pointer+ // overwrite the remote's freshly-rendered one.for (const uni of records.universes) {await mergeOne({kind: 'universe', record: uni, label: uni.name,- getFn: getUniverse, insertFn: insertUniverseWithId, updateFn: updateUniverse,+ getFn: getUniverse, insertFn: insertUniverseWithId,+ updateFn: (id, record) => updateUniverse(id, () => record),});}for (const s of records.series) {diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 87d7061b59..713d4427fa 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -27,12 +27,14 @@import { join } from 'path';import { randomUUID } from 'crypto';-import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';+import { PATHS, atomicWrite, readJSONFile, ensureDir, resolveImageRef } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';import { richCanonDescriptorFragments } from '../lib/canonPrompt.js';import {sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS, BIBLE_SOURCE,+ SERVER_OWNED_CHARACTER_FIELDS,+ pruneStaleReferenceSheets,normalizeBibleName, isStr, trimTo,} from '../lib/storyBible.js';import { sanitizeOrigin } from '../lib/sharingOrigin.js';@@ -854,6 +856,46 @@ export async function updateUniverse(id, patchOrMutator = {}) {const scalarPatch = Object.fromEntries(PATCHABLE_SCALARS.filter((k) => k in patch).map((k) => [k, patch[k]]),);+ // Server-owned operational fields on characters (see+ // SERVER_OWNED_CHARACTER_FIELDS in storyBible.js) are written only by+ // server-side render-completion mutators. A literal-object PATCH that+ // round-trips a character body the client loaded before a newer+ // render finished would otherwise clobber the freshly-stamped+ // pointer (multi-tab / parallel render race). Preserve cur's value+ // per-(id, field); new characters in the patch start fresh.+ //+ // ONLY applies to literal-object patches. The mutator path is the+ // trusted writer here — `onSheetComplete` reads `cur` itself and+ // intentionally constructs a patch with the newly stamped value, so+ // running preservation against its output would clobber the stamp+ // back to the OLD/null value and the sheet would never persist. The+ // sharing importer wraps `updateUniverse(id, () => record)` for the+ // same reason — sync's intent is LWW including operational pointers,+ // so it opts into the mutator-bypass.+ if (!isMutator+ && Array.isArray(scalarPatch.characters)+ && Array.isArray(cur.characters)) {+ const curById = new Map(cur.characters.filter((c) => c?.id).map((c) => [c.id, c]));+ scalarPatch.characters = scalarPatch.characters.map((c) => {+ const prev = c?.id ? curById.get(c.id) : null;+ if (!prev) return c;+ const preserved = { ...c };+ // Preserve cur's value ONLY when it still resolves on disk. Without+ // the FS check, this guard reintroduces stale pointers that the+ // GET route's lazy `pruneStaleReferenceSheets` already nulled out:+ // GET → null (file gone) → client PATCH carries null → guard+ // overwrites null with cur's stale filename → thumbnail 404s+ // again. The pruner returns null for non-existent files, so we+ // skip preservation in that case and let the patch's value (the+ // pruned null) survive.+ for (const f of SERVER_OWNED_CHARACTER_FIELDS) {+ if (prev[f] && resolveImageRef(prev[f], { mustExist: true })) {+ preserved[f] = prev[f];+ }+ }+ return preserved;+ });+ }const mergedRecord = sanitizeTemplate({...cur,@@ -869,6 +911,16 @@ export async function updateUniverse(id, patchOrMutator = {}) {updatedAt: new Date().toISOString(),});if (!mergedRecord) throw makeErr('Invalid universe payload', ERR_VALIDATION);+ // Persist the stale-reference-sheet null at write time so the on-disk+ // record catches up with what the GET-route pruner shows. Otherwise a+ // PATCH that omits `characters` (e.g. rename) merges from `cur` and+ // returns the stale filename, and the UI re-renders the broken thumbnail.+ // Render-completion writes are unaffected — the renderer copies the file+ // BEFORE its mutator runs, so the just-stamped pointer resolves on disk+ // and the prune skips it.+ if (Array.isArray(mergedRecord.characters)) {+ mergedRecord.characters = pruneStaleReferenceSheets(mergedRecord.characters);+ }state.universes[idx] = mergedRecord;await writeState(state);return { merged: mergedRecord, nameChanged: mergedRecord.name !== cur.name, skipped: false };diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex e2b4828b21..36dd342294 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -2,6 +2,12 @@ import { describe, it, expect, vi, beforeEach } from "vitest";const fileStore = new Map();+// Per-test reference-sheet "what exists on disk" — keys are filenames the+// referenceSheetImageRef preservation guard / pruner asks about. Default+// behavior is "non-empty filename resolves" so existing tests using fake+// names like 'sheet-B.png' still pass; the stale-prune test overrides+// resolveImageRef to return null for the stale filename.+const refSheetFilesByName = new Map();vi.mock("../lib/fileUtils.js", () => ({PATHS: { data: "/mock/data" },ensureDir: vi.fn().mockResolvedValue(undefined),@@ -11,6 +17,15 @@ vi.mock("../lib/fileUtils.js", () => ({readJSONFile: vi.fn(async (path, fallback) =>fileStore.has(path) ? fileStore.get(path) : fallback,),+ // mustExist: true → return a non-null path when the filename either+ // appears in refSheetFilesByName or has no explicit "missing" entry.+ // Tests opt into "this file is gone" by calling+ // refSheetFilesByName.set('foo.png', null).+ resolveImageRef: vi.fn((ref) => {+ if (typeof ref !== 'string' || !ref) return null;+ if (refSheetFilesByName.has(ref)) return refSheetFilesByName.get(ref);+ return `/mock/refs/${ref}`;+ }),}));let uuidCounter = 0;@@ -337,6 +352,105 @@ describe("universeBuilder service", () => {expect(patched.name).toBe("Solo Rename");});+ it("updateUniverse preserves server-owned referenceSheetImageRef across character PATCHes", async () => {+ // Multi-tab race: tab B finished a newer sheet render (server pointer is+ // 'sheet-B.png'), tab A PATCH-saves with a character body it loaded+ // BEFORE the render landed (still carrying the previous 'sheet-A.png',+ // or null). Without server-side preservation the older PATCH would+ // clobber the newer server pointer and the UI would 404 on the stale+ // filename. The render-completion handler bypasses this preservation+ // path because it writes referenceSheetImageRef inside its own+ // updateUniverse mutator from the latest record state.+ const w = await seedWorld();+ // Simulate the render-completion stamp via an in-queue mutator (same+ // path the real onSheetComplete uses).+ await svc.updateUniverse(w.id, (latest) => {+ const next = [...(latest.characters || []), {+ id: "c-1", name: "Vale", referenceSheetImageRef: "sheet-B.png",+ }];+ return { characters: next };+ });+ // Client PATCH that round-trips a stale body — sheet pointer is the+ // OLD value (or null). Server should keep 'sheet-B.png' regardless.+ const afterClientPatch = await svc.updateUniverse(w.id, {+ characters: [{ id: "c-1", name: "Vale", referenceSheetImageRef: "sheet-A.png" }],+ });+ const char = afterClientPatch.characters.find((c) => c.id === "c-1");+ expect(char?.referenceSheetImageRef).toBe("sheet-B.png");++ // Same invariant when client PATCHes with the field omitted entirely.+ const afterOmitPatch = await svc.updateUniverse(w.id, {+ characters: [{ id: "c-1", name: "Vale" }],+ });+ const charOmit = afterOmitPatch.characters.find((c) => c.id === "c-1");+ expect(charOmit?.referenceSheetImageRef).toBe("sheet-B.png");++ // Mutator path (the render-completion handler) IS trusted to update+ // referenceSheetImageRef — it constructs the patch from the latest+ // record. Preservation must NOT run against mutator output, or the+ // newly-stamped filename gets clobbered back to the old value.+ const afterRenderStamp = await svc.updateUniverse(w.id, (latest) => {+ const next = (latest.characters || []).map((c) =>+ c.id === "c-1" ? { ...c, referenceSheetImageRef: "sheet-C.png" } : c,+ );+ return { characters: next };+ });+ const charAfterStamp = afterRenderStamp.characters.find((c) => c.id === "c-1");+ expect(charAfterStamp?.referenceSheetImageRef).toBe("sheet-C.png");+ });++ it("updateUniverse preservation skips when cur's referenceSheetImageRef no longer resolves on disk", async () => {+ // GET /:id runs pruneStaleReferenceSheets, returning null when the+ // underlying file is gone. Client PATCHes carry the pruned null. The+ // preservation guard MUST honor that null by skipping preservation —+ // otherwise the stale filename comes back from cur and the UI 404s+ // again. resolveImageRef returning null is the "file missing" signal.+ const w = await seedWorld();+ // Stamp a sheet (mutator path is trusted).+ await svc.updateUniverse(w.id, (latest) => {+ const next = [...(latest.characters || []), {+ id: "c-stale", name: "Stale", referenceSheetImageRef: "sheet-DEAD.png",+ }];+ return { characters: next };+ });+ // Mark that filename as missing for the resolveImageRef mock.+ refSheetFilesByName.set("sheet-DEAD.png", null);+ // Client PATCH that carries the pruned null (matching what GET would+ // surface after pruneStaleReferenceSheets ran). Preservation should+ // detect the stale cur value and skip, so the null wins.+ const after = await svc.updateUniverse(w.id, {+ characters: [{ id: "c-stale", name: "Stale", referenceSheetImageRef: null }],+ });+ const stale = after.characters.find((c) => c.id === "c-stale");+ expect(stale?.referenceSheetImageRef).toBeNull();+ // Clean up the per-test FS shim so later tests start clean.+ refSheetFilesByName.delete("sheet-DEAD.png");+ });++ it("updateUniverse persists null for stale referenceSheetImageRef on the write path, not just GET", async () => {+ // Reviewer-found bug: the GET-route pruner nulled the response but the+ // on-disk record kept the stale filename, so a later PATCH that omitted+ // `characters` (e.g. rename) merged from cur and returned the stale value.+ // The write-time prune in updateUniverse fixes this — any PATCH catches+ // the on-disk record up.+ const w = await seedWorld();+ await svc.updateUniverse(w.id, (latest) => ({+ characters: [...(latest.characters || []), {+ id: "c-rename", name: "Anchor", referenceSheetImageRef: "sheet-RENAME.png",+ }],+ }));+ refSheetFilesByName.set("sheet-RENAME.png", null);+ // PATCH that does NOT include `characters` — only renames the universe.+ const renamed = await svc.updateUniverse(w.id, { name: "Renamed" });+ const char = renamed.characters.find((c) => c.id === "c-rename");+ expect(char?.referenceSheetImageRef).toBeNull();+ // And a follow-up GET sees the same null — disk is now consistent.+ const reread = await svc.getUniverse(w.id);+ const charReread = reread.characters.find((c) => c.id === "c-rename");+ expect(charReread?.referenceSheetImageRef).toBeNull();+ refSheetFilesByName.delete("sheet-RENAME.png");+ });+it("deleteUniverse removes the universe and its runs", async () => {const w = await seedWorld();await svc.recordRun({diff --git a/server/services/universeCanon.js b/server/services/universeCanon.jsindex e2b271445c..c6a68a4c00 100644--- a/server/services/universeCanon.js+++ b/server/services/universeCanon.js@@ -13,7 +13,7 @@ import { runStagedLLM } from '../lib/stageRunner.js';import { runPromptRefine } from './pipeline/refineHelpers.js';import { ServerError } from '../lib/errorHandler.js';-const peerForPrompt = (entry) => ({+export const peerForPrompt = (entry) => ({id: entry.id,name: entry.name,aliases: Array.isArray(entry.aliases) ? entry.aliases : [],@@ -27,7 +27,7 @@ const targetForPrompt = (entry) => ({firstAppearance: entry.firstAppearance || null,});-const buildStyleClause = (universe) => {+export const buildStyleClause = (universe) => {const embraceTokens = joinInfluenceList(universe.influences?.embrace);const bits = [embraceTokens ? `Universe aesthetic: ${embraceTokens}` : null,diff --git a/server/services/universeCharacterExpand.js b/server/services/universeCharacterExpand.jsnew file mode 100644index 0000000000..186ba2d098--- /dev/null+++ b/server/services/universeCharacterExpand.js@@ -0,0 +1,169 @@+/**+ * Universe Character — LLM expansion.+ *+ * One LLM call that fleshes out blank fields on a universe canon character+ * without clobbering populated content. Strict "fill blanks only" semantics:+ * - key absent from LLM response → preserve existing value+ * - key present with empty string/array → IGNORED (no-op; expand flow has+ * no "clear" intent — an empty proposal just means the LLM had nothing+ * to add). Distinct from the CLAUDE.md merge convention used for+ * direct-user PATCHes, where empty CAN mean clear.+ * - key present with non-empty value → fill ONLY when target field is blank.+ */++import { getUniverse, updateUniverse } from './universeBuilder.js';+import { buildStyleClause } from './universeCanon.js';+import { runStagedLLM } from '../lib/stageRunner.js';+import { ServerError } from '../lib/errorHandler.js';+import { sanitizeCharacter } from '../lib/storyBible.js';++// Adding a new extended field on `sanitizeCharacter` requires adding it here+// too — otherwise the expand response key is silently dropped.+const STRING_FIELDS = Object.freeze([+ 'pronouns', 'age', 'coreTheme', 'speechAccent', 'visualNotes',+ 'silhouetteNotes', 'postureNotes', 'specialTraits', 'visualIdentity',+ 'motivations', 'likes', 'dislikes', 'mannerisms', 'relationships', 'skills',+]);+const LIST_FIELDS = Object.freeze([+ 'stats', 'colorPalette', 'props', 'expressions', 'handGestures',+]);++// Distinct from universeCanon's peerForPrompt: the expand prompt benefits from+// the extended visual / theme fields for richer distinctness signals.+const peerForExpandPrompt = (entry) => ({+ id: entry.id,+ name: entry.name,+ role: entry.role || '',+ pronouns: entry.pronouns || '',+ physicalDescription: entry.physicalDescription || '',+ visualNotes: entry.visualNotes || '',+ coreTheme: entry.coreTheme || '',+});++const isAbsent = (v) => v === undefined || v === null;+const isBlankString = (v) => typeof v !== 'string' || v.trim() === '';+const isBlankArray = (v) => !Array.isArray(v) || v.length === 0;++/**+ * Pure no-clobber merge of an LLM payload onto a character. Exported so the+ * route tests can exercise the merge semantics without an LLM round-trip.+ */+export function applyExpansion(target, content) {+ if (!target || typeof target !== 'object' || !content || typeof content !== 'object') {+ return { merged: target, updatedFields: [] };+ }+ const merged = { ...target };+ const updatedFields = [];+ for (const field of STRING_FIELDS) {+ if (!(field in content)) continue;+ const proposed = content[field];+ if (isAbsent(proposed) || typeof proposed !== 'string') continue;+ if (!isBlankString(target[field])) continue;+ if (isBlankString(proposed)) continue;+ merged[field] = proposed.trim();+ updatedFields.push(field);+ }+ for (const field of LIST_FIELDS) {+ if (!(field in content)) continue;+ const proposed = content[field];+ if (isAbsent(proposed) || !Array.isArray(proposed)) continue;+ if (!isBlankArray(target[field])) continue;+ if (isBlankArray(proposed)) continue;+ // Sanitize the proposed list before recording the update. The bible+ // sanitizer drops rows missing required keys (stats without `label`,+ // props/expressions/gestures without `name`, palette without `name`),+ // so a raw acceptance would report `updatedFields: ['stats']` while+ // the persisted character actually saves `stats: []`. Run the proposal+ // through `sanitizeCharacter` (target's name carries the record so the+ // top-level sanitizer accepts it) and use the cleaned rows; skip the+ // field entirely when nothing survives.+ const sanitized = sanitizeCharacter(+ { name: target.name, [field]: proposed },+ { preserveTimestamps: false },+ );+ const cleaned = Array.isArray(sanitized?.[field]) ? sanitized[field] : [];+ if (cleaned.length === 0) continue;+ merged[field] = cleaned;+ updatedFields.push(field);+ }+ return { merged, updatedFields };+}++export async function expandUniverseCharacter(universeId, entryId, options = {}) {+ const universe = await getUniverse(universeId);+ const list = Array.isArray(universe.characters) ? universe.characters : [];+ const idx = list.findIndex((e) => e.id === entryId);+ if (idx < 0) {+ throw new ServerError(`Character ${entryId} not found in universe`, {+ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',+ });+ }+ const target = list[idx];+ if (target.locked === true) {+ return { universe, entry: target, locked: true, updatedFields: [] };+ }+ const peers = list.filter((_, i) => i !== idx);++ const { content, runId, providerId, model } = await runStagedLLM(+ 'universe-character-expand',+ {+ styleClause: buildStyleClause(universe),+ characterJson: JSON.stringify(target),+ peersJson: JSON.stringify(peers.map(peerForExpandPrompt)),+ },+ {+ providerOverride: options.providerId,+ modelOverride: options.model,+ returnsJson: true,+ source: 'universe-character-expand',+ },+ );++ // Reject array AND non-object — `typeof [] === 'object'` would otherwise+ // let an LLM that returned `[{...}]` slip through `applyExpansion` as a+ // valid-but-empty payload (no string keys match) and silently no-op.+ if (!content || typeof content !== 'object' || Array.isArray(content)) {+ throw new ServerError('LLM returned an empty character expansion', {+ status: 502, code: 'UNIVERSE_CHARACTER_EXPAND_EMPTY',+ });+ }++ const rationale = typeof content.rationale === 'string' ? content.rationale.trim() : '';++ // Re-derive the merge INSIDE the write queue against the freshest persisted+ // universe so a user edit (or another LLM call) that landed during the+ // expand LLM round-trip isn't silently overwritten. The mutator returns+ // null to short-circuit the write when nothing changed.+ let updatedFields = [];+ // Track WHY the write was skipped so the caller can distinguish "nothing+ // to fill" (no-op success) from "user locked the character mid-LLM-call"+ // (preserves the locked-character contract — UI shows the same "Locked"+ // badge it would for the pre-LLM-call lock check).+ let lockedDuringRender = false;+ const updated = await updateUniverse(universeId, (latest) => {+ const latestList = Array.isArray(latest.characters) ? latest.characters : [];+ const latestIdx = latestList.findIndex((e) => e.id === entryId);+ if (latestIdx < 0) return null;+ const latestTarget = latestList[latestIdx];+ // Re-check the lock — could have been set during the LLM call.+ if (latestTarget.locked === true) {+ lockedDuringRender = true;+ return null;+ }+ const { merged: next, updatedFields: fields } = applyExpansion(latestTarget, content);+ updatedFields = fields;+ if (fields.length === 0) return null;+ const nextList = latestList.map((e, i) => (i === latestIdx ? next : e));+ return { characters: nextList };+ });+ const latestEntry = (updated.characters || []).find((e) => e.id === entryId) || target;+ if (lockedDuringRender) {+ return { universe: updated, entry: latestEntry, locked: true, updatedFields: [], rationale, runId, providerId, model };+ }+ if (updatedFields.length === 0) {+ return { universe: updated, entry: latestEntry, rationale, runId, providerId, model, updatedFields };+ }+ console.log(`✨ Universe character expand — universe=${universeId.slice(0, 8)} entry=${entryId.slice(0, 8)} fields=${updatedFields.length} runId=${(runId || '').slice(0, 8)}`);+ return { universe: updated, entry: latestEntry, rationale, runId, providerId, model, updatedFields };+}+diff --git a/server/services/universeCharacterExpand.test.js b/server/services/universeCharacterExpand.test.jsnew file mode 100644index 0000000000..5a1d8acbf8--- /dev/null+++ b/server/services/universeCharacterExpand.test.js@@ -0,0 +1,172 @@+import { describe, it, expect } from 'vitest';+import { applyExpansion } from './universeCharacterExpand.js';++describe('universeCharacterExpand — applyExpansion (no-clobber merge semantics)', () => {+ it('fills blank string fields from the LLM response', () => {+ const target = { name: 'Vale', pronouns: '', age: '', motivations: '' };+ const content = { pronouns: 'she/her', age: '27', motivations: 'survive' };+ const { merged, updatedFields } = applyExpansion(target, content);+ expect(merged.pronouns).toBe('she/her');+ expect(merged.age).toBe('27');+ expect(merged.motivations).toBe('survive');+ expect(updatedFields).toEqual(expect.arrayContaining(['pronouns', 'age', 'motivations']));+ expect(updatedFields).toHaveLength(3);+ });++ it('does NOT clobber a populated string field', () => {+ const target = { name: 'Vale', pronouns: 'they/them', age: '' };+ const content = { pronouns: 'she/her', age: '27' };+ const { merged, updatedFields } = applyExpansion(target, content);+ // pronouns was populated, LLM proposal ignored+ expect(merged.pronouns).toBe('they/them');+ expect(merged.age).toBe('27');+ expect(updatedFields).toEqual(['age']);+ });++ it('treats absent keys as "no opinion" (preserves existing)', () => {+ const target = { name: 'Vale', pronouns: 'they/them', age: '27', motivations: 'survive' };+ const content = {}; // LLM had nothing to add+ const { merged, updatedFields } = applyExpansion(target, content);+ expect(merged.pronouns).toBe('they/them');+ expect(merged.age).toBe('27');+ expect(merged.motivations).toBe('survive');+ expect(updatedFields).toEqual([]);+ });++ it('fills blank list fields with non-empty arrays', () => {+ const target = { name: 'Vale', stats: [], colorPalette: [], expressions: [] };+ const content = {+ stats: [{ label: 'Height', value: "5'7\"" }],+ colorPalette: [{ name: 'amber', hex: '#f59e0b', role: 'skin' }],+ expressions: [{ name: 'neutral', description: 'baseline' }],+ };+ const { merged, updatedFields } = applyExpansion(target, content);+ expect(merged.stats).toHaveLength(1);+ expect(merged.colorPalette).toHaveLength(1);+ expect(merged.expressions).toHaveLength(1);+ expect(updatedFields).toEqual(expect.arrayContaining(['stats', 'colorPalette', 'expressions']));+ });++ it('does NOT clobber a populated list field', () => {+ const target = { name: 'Vale', stats: [{ label: 'Eyes', value: 'amber' }] };+ const content = { stats: [{ label: 'Height', value: "5'7\"" }] };+ const { merged } = applyExpansion(target, content);+ // existing populated list preserved+ expect(merged.stats).toEqual([{ label: 'Eyes', value: 'amber' }]);+ });++ it('ignores non-string proposals for string fields and non-array proposals for list fields', () => {+ const target = { name: 'Vale', pronouns: '', stats: [] };+ const content = { pronouns: 42, stats: { not: 'an array' } };+ const { merged, updatedFields } = applyExpansion(target, content);+ expect(merged.pronouns).toBe('');+ expect(merged.stats).toEqual([]);+ expect(updatedFields).toEqual([]);+ });++ it('ignores LLM-proposed empty strings / empty arrays as "intentional clear, no-op since field already blank"', () => {+ const target = { name: 'Vale', pronouns: '', stats: [] };+ const content = { pronouns: ' ', stats: [] };+ const { merged, updatedFields } = applyExpansion(target, content);+ expect(merged.pronouns).toBe('');+ expect(merged.stats).toEqual([]);+ expect(updatedFields).toEqual([]);+ });++ it('trims string proposals before assignment', () => {+ const target = { name: 'Vale', pronouns: '' };+ const content = { pronouns: ' she/her ' };+ const { merged } = applyExpansion(target, content);+ expect(merged.pronouns).toBe('she/her');+ });++ it('returns the target untouched when content is null / not an object', () => {+ const target = { name: 'Vale', pronouns: 'they/them' };+ expect(applyExpansion(target, null).merged).toBe(target);+ expect(applyExpansion(target, 'not an object').merged).toBe(target);+ expect(applyExpansion(null, {}).merged).toBeNull();+ });++ it('respects the full extended-field set (smoke check the field list stays in sync)', () => {+ const target = {+ name: 'Vale', pronouns: '', age: '', coreTheme: '', speechAccent: '', visualNotes: '',+ silhouetteNotes: '', postureNotes: '', specialTraits: '', visualIdentity: '',+ motivations: '', likes: '', dislikes: '', mannerisms: '', relationships: '', skills: '',+ stats: [], colorPalette: [], props: [], expressions: [], handGestures: [],+ };+ const content = {+ pronouns: 'she/her', age: '27', coreTheme: 't', speechAccent: 'a', visualNotes: 'v',+ silhouetteNotes: 's', postureNotes: 'p', specialTraits: 'st', visualIdentity: 'vi',+ motivations: 'm', likes: 'l', dislikes: 'd', mannerisms: 'mn', relationships: 'r', skills: 'sk',+ stats: [{ label: 'L', value: 'V' }],+ colorPalette: [{ name: 'n' }],+ props: [{ name: 'n' }],+ expressions: [{ name: 'n' }],+ handGestures: [{ name: 'n' }],+ };+ const { updatedFields } = applyExpansion(target, content);+ // 15 strings + 5 lists = 20 fields total in the expand contract.+ expect(updatedFields).toHaveLength(20);+ });++ it('REGRESSION: list proposals whose rows all fail bible sanitization are NOT marked as updated', () => {+ // Without the pre-sanitize check inside applyExpansion, the route+ // would report `updatedFields: ['stats', 'props', 'colorPalette',+ // 'expressions', 'handGestures']` but the persisted character would+ // have empty lists across the board — the bible sanitizer drops+ // rows missing required keys (stats without `label`, name-keyed+ // entries without `name`). Pin both the field-skip and the merge+ // result so the next refactor of either layer keeps them in sync.+ const target = {+ name: 'Vale',+ stats: [], props: [], colorPalette: [], expressions: [], handGestures: [],+ };+ const content = {+ // sanitizeStat drops rows missing `label`.+ stats: [{ value: "5'7\"" }, { value: 'amber' }],+ // sanitizeProp drops rows missing `name`.+ props: [{ purpose: 'comms' }],+ // sanitizePaletteColor drops rows missing `name`.+ colorPalette: [{ hex: '#f59e0b' }],+ // sanitizeExpression drops rows missing `name`.+ expressions: [{ description: 'baseline' }],+ // sanitizeHandGesture drops rows missing `name`.+ handGestures: [{ description: 'pointing' }],+ };+ const { merged, updatedFields } = applyExpansion(target, content);+ expect(updatedFields).toEqual([]);+ expect(merged.stats).toEqual([]);+ expect(merged.props).toEqual([]);+ expect(merged.colorPalette).toEqual([]);+ expect(merged.expressions).toEqual([]);+ expect(merged.handGestures).toEqual([]);+ });++ it('REGRESSION: partial-row drop — surviving rows land in merged, field marked as updated', () => {+ // Mixed-validity LLM payload: one valid stat, one invalid. The+ // valid row survives sanitization and the field IS legitimately+ // updated (sanitized length > 0). Without this case the previous+ // regression could be satisfied by a too-aggressive "drop the+ // whole field on any invalid row" implementation.+ const target = { name: 'Vale', stats: [] };+ const content = {+ stats: [{ label: 'Height', value: "5'7\"" }, { value: 'no-label' }],+ };+ const { merged, updatedFields } = applyExpansion(target, content);+ expect(updatedFields).toEqual(['stats']);+ expect(merged.stats).toHaveLength(1);+ expect(merged.stats[0]).toMatchObject({ label: 'Height', value: "5'7\"" });+ });++ it('REGRESSION: top-level array LLM response no-ops in applyExpansion (route-level rejection lives in expandUniverseCharacter)', () => {+ // `typeof [] === 'object'`, so `applyExpansion` accepts an array and+ // produces no updates — the route caller is responsible for the 502.+ // This test pins the pure no-op behavior so applyExpansion can stay+ // permissive; the upstream rejection is enforced in+ // expandUniverseCharacter and covered by the route mocks.+ const target = { name: 'Vale', pronouns: '' };+ const { merged, updatedFields } = applyExpansion(target, [{ pronouns: 'she/her' }]);+ expect(updatedFields).toEqual([]);+ expect(merged.pronouns).toBe('');+ });+});diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.jsnew file mode 100644index 0000000000..50caee5b35--- /dev/null+++ b/server/services/universeCharacterSheet.js@@ -0,0 +1,490 @@+/**+ * Universe Character — Reference Sheet Renderer (text-template).+ *+ * Generates a single dense artist reference sheet per universe canon+ * character from a structured TEXT prompt that describes every zone of+ * the sheet (turnaround, expressions, palette, wardrobe, props, gestures).+ * No init image or multi-reference input is required — the rich prompt+ * itself is the "template", so the renderer works equally well across+ * any image-gen backend (codex, local, future nano-banana).+ *+ * The route returns the generation id immediately; this module subscribes+ * to mediaJobEvents to copy the result into data/image-refs/ and stamp+ * `character.referenceSheetImageRef` once the render completes.+ */++import { copyFile } from 'fs/promises';+import { join, basename } from 'path';+import { randomUUID } from 'crypto';+import { PATHS, ensureDir } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';+import { getSettings } from './settings.js';+import { getUniverse, updateUniverse } from './universeBuilder.js';+import { buildStyleClause } from './universeCanon.js';+import { getImageModels } from '../lib/mediaModels.js';+import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';+import { findOrCreateUniverseCollection } from './mediaCollections.js';++// 2048×1536 keeps panel labels legible while still rendering in a single+// pass on Apple Silicon local backends. Codex / nano-banana ignore the+// hint past 1536 max edge but still honor the aspect ratio.+const DEFAULT_WIDTH = 2048;+const DEFAULT_HEIGHT = 1536;++// Resolve the local-mode model id. With pure text-template rendering we no+// longer depend on FLUX.2-specific init-image / multi-ref flags, so any+// registered model is fair game. Order:+// 1. Explicit override (when it matches a registered model).+// 2. settings.imageGen.local.modelId.+// 3. First available local model.+// Returns null when nothing is registered; caller surfaces the 400.+export function resolveSheetModelId({ override, settings, allModels }) {+ const findById = (id) => (typeof id === 'string' ? allModels.find((m) => m.id === id) : null);+ const trimmedOverride = typeof override === 'string' ? override.trim() : '';+ return findById(trimmedOverride)?.id+ ?? findById(settings?.imageGen?.local?.modelId)?.id+ ?? allModels[0]?.id+ ?? null;+}++const DEFAULT_EXPRESSIONS = Object.freeze([+ 'neutral', 'curious', 'worried', 'surprised', 'amused', 'determined', 'relaxed',+]);+const DEFAULT_HAND_GESTURES = Object.freeze([+ 'relaxed hand', 'pointing', 'peace sign', 'gripping object', 'adjusting accessory',+]);++const trim = (s) => (typeof s === 'string' ? s.trim() : '');++const flattenStats = (stats) => {+ if (!Array.isArray(stats) || stats.length === 0) return '';+ return stats+ .map((s) => (s?.label && s?.value ? `${s.label}: ${s.value}` : s?.label || ''))+ .filter(Boolean)+ .join(' | ');+};++const flattenPalette = (palette) => {+ if (!Array.isArray(palette) || palette.length === 0) return '';+ return palette+ .map((c, i) => {+ const name = trim(c?.name);+ const hex = trim(c?.hex);+ const role = trim(c?.role);+ if (!name) return '';+ const hexBit = hex ? ` ${hex}` : '';+ const roleBit = role ? ` — ${role}` : '';+ return `Swatch ${i + 1}: ${name}${hexBit}${roleBit}`;+ })+ .filter(Boolean)+ .join(', ');+};++const flattenWardrobes = (wardrobes) => {+ if (!Array.isArray(wardrobes) || wardrobes.length === 0) return '';+ return wardrobes+ .map((w) => (w?.name && w?.description ? `"${w.name}": ${w.description}` : w?.name || ''))+ .filter(Boolean)+ .join(' | ');+};++const flattenProps = (props) => {+ if (!Array.isArray(props) || props.length === 0) return '';+ return props+ .map((p) => {+ const name = trim(p?.name);+ const purpose = trim(p?.purpose);+ const materials = trim(p?.materials);+ if (!name) return '';+ const bits = [purpose ? `(${purpose})` : '', materials ? `[${materials}]` : '']+ .filter(Boolean)+ .join(' ');+ return bits ? `${name} ${bits}` : name;+ })+ .filter(Boolean)+ .join(' | ');+};++const flattenNamedList = (items, defaults) => {+ const list = Array.isArray(items) && items.length > 0+ ? items.map((e) => (e?.name && e?.description ? `${e.name} (${e.description})` : trim(e?.name))).filter(Boolean)+ : [...defaults];+ return list.slice(0, 7).join(', ');+};++/**+ * Build the prompt + render options for one character's reference sheet.+ * Pure function — does no I/O, doesn't enqueue anything. The route handler+ * combines this with `getUniverse` / the media-job queue to drive the+ * actual render. Pure text — no init image, no multi-reference plumbing.+ *+ * Returns `{ prompt, negativePrompt, width, height, modelId }`. modelId is+ * always null here; the renderer fills it in once the active image-gen+ * mode is known.+ */+export function buildCharacterReferenceSheetPrompt(universe, character) {+ if (!universe || !character) {+ throw new ServerError('buildCharacterReferenceSheetPrompt: universe and character are required', {+ status: 400, code: 'VALIDATION_ERROR',+ });+ }++ const styleClause = buildStyleClause(universe);+ const styleBits = styleClause.startsWith('(none provided') ? '' : styleClause;++ const name = trim(character.name) || 'Unnamed';+ const aliases = Array.isArray(character.aliases) ? character.aliases.filter(Boolean).join(', ') : '';+ const role = trim(character.role);+ const pronouns = trim(character.pronouns);+ const age = trim(character.age);+ const personality = trim(character.personality);+ const speechAccent = trim(character.speechAccent);+ const coreTheme = trim(character.coreTheme);+ const visualNotes = trim(character.visualNotes);++ const headerBits = [+ `Name: ${name}.`,+ aliases ? `Alias: ${aliases}.` : '',+ age ? `Age: ${age}.` : '',+ pronouns ? `Pronouns: ${pronouns}.` : '',+ role ? `Role: ${role}.` : '',+ personality ? `Personality: ${personality}.` : '',+ speechAccent ? `Speech: ${speechAccent}.` : '',+ coreTheme ? `Core theme: ${coreTheme}.` : '',+ visualNotes ? `Visual notes: ${visualNotes}.` : '',+ ].filter(Boolean).join(' ');++ const physical = trim(character.physicalDescription);+ const silhouette = trim(character.silhouetteNotes);+ const posture = trim(character.postureNotes);+ const special = trim(character.specialTraits);+ const visualIdentity = trim(character.visualIdentity);++ const statsLine = flattenStats(character.stats);+ const paletteLine = flattenPalette(character.colorPalette);+ const wardrobeLine = flattenWardrobes(character.wardrobes);+ const propsLine = flattenProps(character.props);+ const expressionsLine = flattenNamedList(character.expressions, DEFAULT_EXPRESSIONS);+ const gesturesLine = flattenNamedList(character.handGestures, DEFAULT_HAND_GESTURES);++ // Order matters: the model honors earliest tokens most reliably, so style ++ // header lead, then the per-zone layout enumeration.+ const promptParts = [+ 'CHARACTER REFERENCE SHEET — single dense reference page laid out in clear panels with thin borders, clean typography, and labeled zones.',+ styleBits || 'Style: contemporary illustrated character design with confident line work and saturated, intentional color.',+ `Character header (top of sheet): ${headerBits}`,+ physical ? `Physical description: ${physical}` : '',+ statsLine ? `Stats panel (small table, left side of header): ${statsLine}.` : '',+ `Main identity + scale sheet (large left zone): four full-body views of ${name} side by side at consistent scale — FRONT view, 3/4 view, SIDE view, BACK view — standing in a neutral pose with a small height-scale ruler in the margin. All four views must read as the same character with consistent proportions, clothing, color, and silhouette.`,+ silhouette ? `Silhouette notes panel (right of the scale sheet): ${silhouette}` : '',+ posture ? `Posture notes panel: ${posture}` : '',+ special ? `Special traits panel: ${special}` : '',+ visualIdentity ? `Visual identity panel: ${visualIdentity}` : '',+ paletteLine ? `Color palette zone (top right): a row of color swatch chips, each labeled, in order — ${paletteLine}.` : '',+ `Expression progression (right side): a row of seven head-and-shoulders portraits of ${name} showing — ${expressionsLine}.`,+ `Micro-expressions row (below expression progression): a row of five subtle headshot variants of ${name} demonstrating restrained facial nuance.`,+ `Head detail sheet (right side, lower): five small portraits of ${name} from different angles — 3/4 headshot, side headshot, top angle, low angle, three-quarter "elegant angle".`,+ `Neutral baseline + posture variation + close-up pose (lower right): one neutral standing pose, one variant posture (leaning or shifted weight), one close-up dramatic pose.`,+ wardrobeLine ? `Wardrobe / accessories details panel (lower left): labeled close-up cards of distinctive wardrobe pieces — ${wardrobeLine}.` : `Wardrobe / accessories details panel (lower left): labeled close-up cards of the character's signature garments and accessories.`,+ propsLine ? `Prop showcase panel (lower middle): a small still-life of the character's signature props — ${propsLine}.` : '',+ `Hand gestures panel (lower right): a row of five labeled hand close-ups showing the character's habitual gestures — ${gesturesLine}.`,+ 'Layout: thin black panel borders on off-white paper. Light grey labels under each zone. Consistent character proportions across every view. Render in the same illustrated style throughout the page — do NOT mix art styles between panels.',+ ].filter(Boolean);++ const prompt = promptParts.join('\n\n');+ const negativePrompt = 'multiple characters in the same panel, photographs, text artifacts, watermark, signature, blurry, distorted anatomy, low contrast labels';++ return {+ prompt,+ negativePrompt,+ width: DEFAULT_WIDTH,+ height: DEFAULT_HEIGHT,+ // modelId is resolved at render time from current settings — see+ // resolveSheetModelId. Returned as null here so the prompt builder stays+ // pure (no settings I/O) and the renderer is the single decision point.+ modelId: null,+ };+}++// Per-generation filename so re-renders don't trample prior versions; the+// "live" sheet pointer on the character (`referenceSheetImageRef`) always+// names the newest, but older files stay on disk for rollback.+const sheetFilename = (universeId, characterId, generationId) =>+ `universe-${String(universeId).slice(0, 8)}-${String(characterId).slice(0, 8)}-sheet-${String(generationId).slice(0, 8)}.png`;++// `(universeId, characterId) → latest generationId requested`. When a new+// render starts for a character it claims the slot; when a render completes,+// we only stamp `referenceSheetImageRef` if the slot STILL holds our+// generationId (no newer render started during ours). Prevents an+// older-but-slower render from clobbering a newer-but-finished one. The map+// grows bounded by the number of characters ever rendered.+const _latestPendingByCharacter = new Map();+const pendingKey = (universeId, characterId) => `${universeId}:${characterId}`;++// Single-dispatcher subscription so N pending sheets don't attach 4*N+// listeners on the global `mediaJobEvents` emitter (Node defaults to a+// 10-listener soft cap before warning). Each render claims an entry by+// jobId; the four module-level listeners route events to the right+// subscriber's handlers via O(1) Map lookup instead of N filters.+const sheetSubscribers = new Map(); // jobId → { onStarted, onCompleted, onFailed }+let _sheetListenersAttached = false;+function ensureSheetDispatchListeners() {+ if (_sheetListenersAttached) return;+ _sheetListenersAttached = true;+ mediaJobEvents.on('started', (job) => sheetSubscribers.get(job?.id)?.onStarted?.(job));+ mediaJobEvents.on('completed', (job) => sheetSubscribers.get(job?.id)?.onCompleted?.(job));+ const onTerminal = (job) => sheetSubscribers.get(job?.id)?.onFailed?.(job);+ mediaJobEvents.on('failed', onTerminal);+ mediaJobEvents.on('canceled', onTerminal);+}+function subscribeToSheetJob(jobId, handlers) {+ ensureSheetDispatchListeners();+ sheetSubscribers.set(jobId, handlers);+ return () => { sheetSubscribers.delete(jobId); };+}++/**+ * Returns immediately with `{ jobId, generationId, filename, path }`.+ * Deferred copy + character stamp run when imageGenEvents emits 'completed';+ * any failure there is logged (the client tracks the render via SSE).+ */+export async function renderCharacterReferenceSheet(universeId, entryId, options = {}) {+ const universe = await getUniverse(universeId);+ const list = Array.isArray(universe.characters) ? universe.characters : [];+ const character = list.find((c) => c.id === entryId);+ if (!character) {+ throw new ServerError(`Character ${entryId} not found in universe`, {+ status: 404, code: 'UNIVERSE_CANON_NOT_FOUND',+ });+ }+ // Same frozen-identity guard the character refine/expand flows enforce —+ // the UI gates this too, but the route is reachable directly so the lock+ // has to be enforced server-side as well. 409 mirrors refineUniverseCharacter.+ if (character.locked === true) {+ throw new ServerError(+ `Character "${character.name}" is locked — unlock it before rendering a reference sheet`,+ { status: 409, code: 'UNIVERSE_CANON_LOCKED' },+ );+ }++ const built = buildCharacterReferenceSheetPrompt(universe, character);++ const prompt = typeof options.overridePrompt === 'string' && options.overridePrompt.trim()+ ? options.overridePrompt.trim()+ : built.prompt;+ const negativePrompt = typeof options.overrideNegativePrompt === 'string' && options.overrideNegativePrompt.trim()+ ? options.overrideNegativePrompt.trim()+ : built.negativePrompt;++ const settings = await getSettings();+ // Text-template rendering works with any image-gen backend. Route through+ // the media-job queue with the active mode set; codex and local are both+ // first-class. External SD-API has no multi-zone layout support, so it+ // gets a clear remediation rather than a silently-degraded render.+ const activeMode = settings.imageGen?.mode || 'local';+ const baseParams = {+ mode: activeMode,+ prompt,+ negativePrompt,+ width: built.width,+ height: built.height,+ };++ let modelId = null;+ let params;+ if (activeMode === 'codex') {+ const c = settings.imageGen?.codex || {};+ if (!c.enabled) {+ throw new ServerError(+ 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',+ { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },+ );+ }+ modelId = c.model || 'codex';+ params = { ...baseParams, codexPath: c.codexPath, model: c.model };+ } else if (activeMode === 'local') {+ const allModels = getImageModels();+ modelId = resolveSheetModelId({ override: options.modelId, settings, allModels });+ if (!modelId) {+ throw new ServerError(+ 'No local image-gen models are registered. Install a model via `bash scripts/setup-image-video.sh` before generating a reference sheet.',+ { status: 400, code: 'UNIVERSE_CHARACTER_SHEET_NO_MODEL' },+ );+ }+ params = { ...baseParams, pythonPath: settings.imageGen?.local?.pythonPath || null, modelId };+ } else {+ throw new ServerError(+ `Character reference sheet rendering needs codex or local image-gen mode (currently: ${activeMode}). External SD-API doesn't support the multi-zone layout this renderer produces — switch in Settings → Image Gen.`,+ { status: 400, code: 'UNIVERSE_CHARACTER_SHEET_UNSUPPORTED_MODE' },+ );+ }++ // Resolve (or create) the universe's media collection up front, then attach+ // a `universeRun` tag to the job so `universeBuilderCollectionHook` files+ // the rendered gallery filename (`<jobId>.png`, distinct from the+ // /data/image-refs/ copy `onSheetComplete` makes for the character pointer)+ // into the same "Universe: <name>" bucket as the rest of the universe's+ // concept art. Bookkeeping is best-effort — if provisioning fails we still+ // run the render, just without the collection-filing side-effect.+ const collection = await findOrCreateUniverseCollection({+ universeId: universe.id,+ universeName: universe.name,+ description: `Universe Builder renders for "${universe.name}"`,+ }).catch((err) => {+ console.error(`❌ character sheet → universe collection provision failed: ${err?.message || err}`);+ return null;+ });+ if (collection) {+ params.universeRun = {+ runId: randomUUID(),+ universeId: universe.id,+ collectionId: collection.id,+ category: 'character-sheet',+ label: character.name,+ };+ }++ // Enqueue through mediaJobQueue so the render serializes through the right+ // backend lane alongside Image Gen / Universe Builder renders. The queue+ // dispatches by `params.mode` (codex → codex lane, local → GPU lane).+ const queued = enqueueJob({ kind: 'image', params });+ const jobId = queued.jobId;+ // Claim the latest-pending slot for this character. onSheetComplete checks+ // it before stamping — guards against an older-but-slower render finishing+ // after a newer one and overwriting the newer pointer.+ _latestPendingByCharacter.set(pendingKey(universeId, entryId), jobId);++ // Subscribe to the queue's completion bus via the shared sheet+ // dispatcher (NOT imageGenEvents directly — the queue mediates the+ // imageGen lifecycle and re-emits on mediaJobEvents with the full job+ // record). The shared dispatcher caps listeners at 4 regardless of how+ // many sheets are pending (see `subscribeToSheetJob` above), so a user+ // running 10+ parallel character renders won't trip+ // MaxListenersExceededWarning on the global emitter.+ //+ // Two-stage timeout: a generous queue-wait window covers the pre-start+ // gap (so a sheet queued behind a long video / first-run-download+ // doesn't detach mid-queue), then the `started` event resets the timer+ // to the tighter run window. Without the reset, a sheet waiting 30++ // minutes behind a video job would lose its bookkeeping listener+ // before onSheetComplete had a chance to run — file copy + character+ // pointer stamp lost.+ const QUEUE_WAIT_MS = 4 * 60 * 60 * 1000; // 4h — generous; survives chained video jobs.+ // 30min sits comfortably above the codex backend's 20min CODEX_TIMEOUT_MS+ // watchdog and the typical local FLUX.2 ceiling, so a legitimate slow+ // render lands its completion (or watchdog-failure) event before this+ // listener detaches. Bumping further is cheap — the detach is purely a+ // bookkeeping safety net for "queue never emits a terminal event".+ const RUN_TIMEOUT_MS = 30 * 60 * 1000;+ let timeoutHandle = null;+ let unsubscribe = null;+ const armTimeout = (ms, reason) => {+ if (timeoutHandle) clearTimeout(timeoutHandle);+ timeoutHandle = setTimeout(() => {+ console.log(`⏱️ Character sheet render ${reason} [${jobId.slice(0, 8)}] — detaching`);+ detach();+ }, ms);+ timeoutHandle.unref?.();+ };+ const detach = () => {+ if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }+ if (unsubscribe) { unsubscribe(); unsubscribe = null; }+ };+ unsubscribe = subscribeToSheetJob(jobId, {+ onStarted: () => armTimeout(RUN_TIMEOUT_MS, 'exceeded run window'),+ onCompleted: async (job) => {+ detach();+ const sourceFilename = job.result?.filename;+ await onSheetComplete({ universeId, entryId, jobId, sourceFilename }).catch((err) => {+ console.error(`❌ Character sheet post-completion failed [${jobId.slice(0, 8)}]: ${err?.message}`);+ });+ },+ onFailed: (job) => {+ detach();+ // Release the slot so a retry render doesn't get superseded by this dead one.+ if (_latestPendingByCharacter.get(pendingKey(universeId, entryId)) === jobId) {+ _latestPendingByCharacter.delete(pendingKey(universeId, entryId));+ }+ console.log(`⚠️ Character sheet render ${job.status} [${jobId.slice(0, 8)}]: ${job.error || 'unknown'}`);+ },+ });+ armTimeout(QUEUE_WAIT_MS, 'queue-wait timeout');++ // Deterministic destination filename — uses the queue's jobId so the client+ // can patch optimistically on SSE completion without a universe refetch.+ // onSheetComplete derives the same filename from the same inputs.+ const destFilename = sheetFilename(universeId, entryId, jobId);+ console.log(`🎨 Universe character sheet render — universe=${universeId.slice(0, 8)} entry=${entryId.slice(0, 8)} job=${jobId.slice(0, 8)} mode=${activeMode} model=${modelId} position=${queued.position}`);+ return {+ jobId,+ // `generationId` retained for client back-compat (older clients keyed+ // SSE attachment on this name); it's now an alias for `jobId`.+ generationId: jobId,+ queuePosition: queued.position,+ destFilename,+ destPath: `/data/image-refs/${destFilename}`,+ promptPreview: prompt.slice(0, 800),+ };+}++export async function onSheetComplete({ universeId, entryId, jobId, sourceFilename }) {+ if (!sourceFilename) return null;+ await ensureDir(PATHS.imageRefs);+ const destFilename = sheetFilename(universeId, entryId, jobId);+ const srcPath = join(PATHS.images, basename(sourceFilename));+ const destPath = join(PATHS.imageRefs, destFilename);+ // ALWAYS copy the file — even superseded renders are kept on disk for+ // rollback/comparison (they live at `data/image-refs/<...>-sheet-<job>.png`+ // with a unique per-job filename).+ await copyFile(srcPath, destPath);+ console.log(`📸 Character sheet copied to image-refs: ${destFilename}`);++ // If a newer render has been started for this character while ours was in+ // flight, the slot now holds someone else's jobId. Skip the stamp — the+ // newer render will stamp its own filename when it finishes. Without this,+ // an older-but-slower render could overwrite a newer-but-finished pointer.+ const key = pendingKey(universeId, entryId);+ if (_latestPendingByCharacter.get(key) !== jobId) {+ console.log(`⏭️ Character sheet [${jobId.slice(0, 8)}] superseded by newer render — file saved, pointer not stamped`);+ return { filename: destFilename, path: destPath, superseded: true };+ }+ // Stamp ONLY `referenceSheetImageRef` inside the write queue against the+ // freshest persisted universe so a concurrent user edit (or sibling render+ // landing close in time) can't clobber unrelated character fields. The+ // sheet lives in data/image-refs/, distinct from `imageRefs[]` (gallery,+ // /data/images/) — polluting imageRefs would 404 the CanonCard thumbnail.+ let stamped = false;+ await updateUniverse(universeId, (latest) => {+ const latestList = Array.isArray(latest.characters) ? latest.characters : [];+ const latestIdx = latestList.findIndex((c) => c.id === entryId);+ if (latestIdx < 0) return null;+ const nextList = latestList.map((e, i) => (i === latestIdx ? {+ ...e,+ referenceSheetImageRef: destFilename,+ } : e));+ stamped = true;+ return { characters: nextList };+ });+ // Release the slot only after a successful stamp AND only if it still+ // belongs to us — between the supersede check and this delete, a newer+ // render could have started, claimed the slot, and arrived here in+ // parallel. An unconditional delete would wipe the newer render's slot+ // and cause its onSheetComplete to see "superseded" (slot empty ≠ jobId)+ // and skip its own stamp — leaving the older filename persisted. A+ // failed stamp leaves the slot owned by us so the next render-start+ // cleanly overwrites it.+ if (_latestPendingByCharacter.get(key) === jobId) {+ _latestPendingByCharacter.delete(key);+ }+ if (!stamped) {+ console.log(`⚠️ Character ${entryId} not found post-render — sheet saved but not linked`);+ return null;+ }+ console.log(`📌 Character ${entryId.slice(0, 8)}.referenceSheetImageRef = ${destFilename}`);+ return { filename: destFilename, path: destPath };+}++export const REFERENCE_SHEET_CONSTANTS = Object.freeze({+ DEFAULT_WIDTH, DEFAULT_HEIGHT,+ DEFAULT_EXPRESSIONS, DEFAULT_HAND_GESTURES,+});diff --git a/server/services/universeCharacterSheet.test.js b/server/services/universeCharacterSheet.test.jsnew file mode 100644index 0000000000..1e4d173a1d--- /dev/null+++ b/server/services/universeCharacterSheet.test.js@@ -0,0 +1,198 @@+import { describe, it, expect } from 'vitest';+import { buildCharacterReferenceSheetPrompt, REFERENCE_SHEET_CONSTANTS, resolveSheetModelId } from './universeCharacterSheet.js';++const baseUniverse = {+ id: 'u-123',+ name: 'Test Universe',+ influences: { embrace: ['neo-noir', 'coastal rain'] },+ styleNotes: 'painterly, ink-heavy, saturated cool palette',+};++const richCharacter = {+ id: 'c-456',+ name: 'Vale',+ aliases: ['Signal Runner'],+ age: '27',+ pronouns: 'she/her',+ role: 'protagonist',+ personality: 'alert, mischievous',+ speechAccent: 'contemporary Pacific Northwest',+ coreTheme: 'cartographer of grief',+ visualNotes: 'layered streetwear; faded mustard + charcoal',+ physicalDescription: 'short curly hair, amber eyes',+ silhouetteNotes: 'compact upper body; tapered lower half',+ postureNotes: 'slight forward lean',+ specialTraits: 'quick hands; chipped nail polish',+ visualIdentity: 'urban utilitarian; analog tech feel',+ stats: [+ { label: 'Height', value: "5'7\"" },+ { label: 'Eye color', value: 'amber' },+ ],+ colorPalette: [+ { name: 'amber', hex: '#f59e0b', role: 'skin' },+ { name: 'olive', hex: '#6b7c4d', role: 'jacket' },+ ],+ props: [+ { name: 'Radio', purpose: 'comms', materials: 'plastic + alloy' },+ { name: 'Map case', purpose: 'navigation', materials: 'canvas' },+ ],+ expressions: [+ { name: 'neutral', description: 'baseline' },+ { name: 'curious', description: 'eyes wide' },+ ],+ handGestures: [+ { name: 'pointing', description: 'index extended' },+ { name: 'gripping radio', description: 'fingers wrapped' },+ ],+ wardrobes: [+ { name: 'Field', description: 'olive jacket + boots' },+ ],+};++describe('universeCharacterSheet — buildCharacterReferenceSheetPrompt', () => {+ it('builds a multi-section prompt with all character zones', () => {+ const out = buildCharacterReferenceSheetPrompt(baseUniverse, richCharacter);+ expect(out.prompt.length).toBeGreaterThan(1500);+ expect(out.prompt).toContain('CHARACTER REFERENCE SHEET');+ expect(out.prompt).toContain('Vale');+ expect(out.prompt).toContain('Signal Runner');+ expect(out.prompt).toContain('she/her');+ // Universe style tokens flow into the preamble.+ expect(out.prompt).toContain('neo-noir');+ expect(out.prompt).toContain('coastal rain');+ expect(out.prompt).toContain('painterly');+ // Every named zone appears in the prompt.+ expect(out.prompt).toMatch(/FRONT view.*3\/4 view.*SIDE view.*BACK view/s);+ expect(out.prompt).toMatch(/Color palette zone/);+ expect(out.prompt).toMatch(/Expression progression/);+ expect(out.prompt).toMatch(/Head detail sheet/);+ expect(out.prompt).toMatch(/Wardrobe \/ accessories/);+ expect(out.prompt).toMatch(/Prop showcase/);+ expect(out.prompt).toMatch(/Hand gestures/);+ expect(out.prompt).toMatch(/Silhouette notes/);+ expect(out.prompt).toMatch(/Posture notes/);+ expect(out.prompt).toMatch(/Special traits/);+ });++ it('flattens palette swatches with hex + role', () => {+ const out = buildCharacterReferenceSheetPrompt(baseUniverse, richCharacter);+ expect(out.prompt).toContain('amber #f59e0b — skin');+ expect(out.prompt).toContain('olive #6b7c4d — jacket');+ });++ it('flattens props with purpose + materials', () => {+ const out = buildCharacterReferenceSheetPrompt(baseUniverse, richCharacter);+ expect(out.prompt).toContain('Radio (comms) [plastic + alloy]');+ expect(out.prompt).toContain('Map case (navigation) [canvas]');+ });++ it('flattens wardrobes as labeled cards', () => {+ const out = buildCharacterReferenceSheetPrompt(baseUniverse, richCharacter);+ expect(out.prompt).toContain('"Field": olive jacket + boots');+ });++ it('uses default expression and gesture lists when character has none', () => {+ const sparse = { id: 'c-1', name: 'Sparse', physicalDescription: 'a body' };+ const out = buildCharacterReferenceSheetPrompt(baseUniverse, sparse);+ // Defaults from REFERENCE_SHEET_CONSTANTS appear.+ for (const expr of ['neutral', 'curious', 'worried', 'surprised', 'amused', 'determined', 'relaxed']) {+ expect(out.prompt).toContain(expr);+ }+ for (const gesture of REFERENCE_SHEET_CONSTANTS.DEFAULT_HAND_GESTURES) {+ expect(out.prompt).toContain(gesture);+ }+ });++ it('omits zone sentences when the character has no data for that zone', () => {+ const minimal = { id: 'c-1', name: 'Min', physicalDescription: 'tall' };+ const out = buildCharacterReferenceSheetPrompt(baseUniverse, minimal);+ // No silhouette → no silhouette panel line.+ expect(out.prompt).not.toMatch(/Silhouette notes panel/);+ expect(out.prompt).not.toMatch(/Posture notes panel/);+ expect(out.prompt).not.toMatch(/Stats panel/);+ expect(out.prompt).not.toMatch(/Color palette zone/);+ expect(out.prompt).not.toMatch(/Prop showcase panel/);+ // But the always-rendered zones still appear.+ expect(out.prompt).toMatch(/Expression progression/);+ expect(out.prompt).toMatch(/Hand gestures panel/);+ expect(out.prompt).toMatch(/Wardrobe \/ accessories details panel/);+ });++ it('returns render options pinned to the universe-builder constants', () => {+ const out = buildCharacterReferenceSheetPrompt(baseUniverse, richCharacter);+ expect(out.width).toBe(REFERENCE_SHEET_CONSTANTS.DEFAULT_WIDTH);+ expect(out.height).toBe(REFERENCE_SHEET_CONSTANTS.DEFAULT_HEIGHT);+ // modelId resolution is deferred to render time (uses current settings,+ // not a hardcoded default). Pure prompt builder returns null so the+ // caller chooses — see resolveSheetModelId.+ expect(out.modelId).toBeNull();+ expect(out.negativePrompt).toContain('watermark');+ expect(out.negativePrompt).toContain('text artifacts');+ });++ it('returns pure-text payload — no init image or multi-reference fields', () => {+ // Regression guard for the text-template refactor: the renderer must not+ // re-introduce init-image / multi-ref plumbing without an explicit+ // backend-support audit. Codex (gpt-image-2) and external SD-API don't+ // share FLUX.2's CLI surface, and the user-validated path is text-only.+ const out = buildCharacterReferenceSheetPrompt(baseUniverse, richCharacter);+ expect(out).not.toHaveProperty('initImagePath');+ expect(out).not.toHaveProperty('initImageStrength');+ expect(out).not.toHaveProperty('referenceImagePaths');+ expect(out).not.toHaveProperty('referenceImageStrengths');+ // The "Honor the reference image" line was specific to the dropped init+ // image — keep it gone so the prompt doesn't hallucinate a missing input.+ expect(out.prompt).not.toMatch(/reference image/i);+ });++ it('throws a 400 when called with no universe or no character', () => {+ expect(() => buildCharacterReferenceSheetPrompt(null, richCharacter)).toThrow(/required/);+ expect(() => buildCharacterReferenceSheetPrompt(baseUniverse, null)).toThrow(/required/);+ });+});++describe('universeCharacterSheet — resolveSheetModelId', () => {+ const flux2Model = { id: 'flux2-klein-9b', runner: 'flux2' };+ const devModel = { id: 'dev', runner: 'mflux' };++ it('honors an explicit override when the model exists in the registry', () => {+ const out = resolveSheetModelId({+ override: 'dev',+ settings: { imageGen: { local: { modelId: 'flux2-klein-9b' } } },+ allModels: [flux2Model, devModel],+ });+ expect(out).toBe('dev');+ });++ it('ignores an override that does not match any registered model, falling through to settings', () => {+ const out = resolveSheetModelId({+ override: 'made-up-model',+ settings: { imageGen: { local: { modelId: 'dev' } } },+ allModels: [flux2Model, devModel],+ });+ expect(out).toBe('dev');+ });++ it('honors the user-configured local modelId from settings', () => {+ const out = resolveSheetModelId({+ override: '',+ settings: { imageGen: { local: { modelId: 'dev' } } },+ allModels: [flux2Model, devModel],+ });+ expect(out).toBe('dev');+ });++ it('falls back to the first available local model as a last resort', () => {+ const out = resolveSheetModelId({+ override: undefined,+ settings: {},+ allModels: [devModel, flux2Model],+ });+ expect(out).toBe('dev');+ });++ it('returns null when no models are registered (caller surfaces the 400)', () => {+ const out = resolveSheetModelId({ override: undefined, settings: {}, allModels: [] });+ expect(out).toBeNull();+ });+});