Skip to content

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

feat(world-builder): structured Influences, per-field + per-item locks, deep routing, bible-aware refine

[._.]/ Adam Eivy38b75801ea75
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8eb476b7fc..d618eb0510 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,12 +4,23 @@ Released: TBD
## Overview
-In-tree `portos-ai-toolkit` and auto-migration of legacy codex provider configs.
+In-tree `portos-ai-toolkit`, auto-migration of legacy codex provider configs, and a major World Builder upgrade: structured Influences chips, full per-field locking, per-item locks on variations + composite boards, deep routing for selected world, and bible-aware prompt refinement.
+
+## Added
+
+- **World Builder — structured Influences (embrace + avoid).** Each world now carries a top-level `influences: { embrace: string[], avoid: string[] }` field — short canonical reference labels (e.g. "Moebius", "cel-shading", "Ghibli painterly") that the renderer prepends *deterministically* to `stylePrompt` and `negativePrompt` at compile time, with case-insensitive dedupe. Inline chip editor in the Story bible section + chip preview/editor in the Refine modal. Capped at 30 entries × 120 chars per list. The structured field replaces the prior "Style direction:" prose clause inside `starterPrompt` — the user's pinned references now survive every re-expansion deterministically instead of relying on the LLM to remember them.
+- **World Builder — per-field locks on the bible + prompts.** Lock toggles on Starter idea, Style prompt, Negative prompt, Logline, Premise, Style notes, and Influences. Locked fields are echoed back unchanged by the refine LLM (server-enforced) AND preserved by the expand merge (client-enforced). Persisted on the world template; toggle saves immediately when the world is already on disk. Locks are AI-only — the human can still edit a locked field directly.
+- **World Builder — per-item locks on variations + composite boards.** Each variation row in `CategoryEditor` and each board in `CompositeSheetsEditor` now has a Lock/Unlock icon. On re-expand, the client extracts locked items, sends them to the server as `preservedVariations` / `preservedCompositeSheets` so the LLM is told not to regenerate those labels, then merges locked-first + LLM additions with case-insensitive label dedupe per category. Locked rows render with an accent-colored border.
+- **World Builder — deep routing.** The selected world id now lives in the URL: `/media/world-builder/:worldId` and `/world-builder/:worldId`. Back/forward buttons, refresh, and direct deep-links all work. Sidebar selection, post-create, and post-delete navigations go through `useNavigate`.
+- **World Builder — bible context in refine.** The Refine modal now sends `logline`, `premise`, `styleNotes`, and `influences` to the LLM alongside the existing prompts; the LLM rewrites all seven fields together so the bible stays narratively coherent with the prompts. Locked fields are excluded from the rewrite client- and server-side.
## Changed
- **`portos-ai-toolkit` is now vendored in-tree at `server/lib/aiToolkit/`** instead of being pulled from npm. PortOS no longer ships an external `portos-ai-toolkit` dependency in `server/package.json` — `createAIToolkit`, `createProviderStatusService`, and the four toolkit Router factories now live next to the rest of the server code. The toolkit's `uuid` dep was dropped (swapped for built-in `crypto.randomUUID()`), so this removes two transitive packages from `node_modules/`. The scaffold-generated app templates (`server/routes/scaffoldPortOS.js`) still emit `portos-ai-toolkit` imports — those are independent apps that can keep consuming the published npm package; PortOS itself does not.
+- **World Builder — "Expand starter → variations" button renamed to "Generate From Idea"** so the action's destructive nature is less ambiguous. (The lock UI is the long-term answer to "I don't want this regenerated.")
+- **World Builder — refine prompt no longer asks the LLM to maintain a `Style direction:` clause inside `starterPrompt`.** The structured `influences` field is now the canonical "where the world is heading" record. Legacy starter prompts containing `Style direction:` paragraphs are still cleaned up via `collapseStyleDirectionDupes` (defense in depth — keeps the seed from growing unboundedly across iterations on worlds upgraded from the prior schema).
## Fixed
- **Legacy codex provider configs auto-migrate to the `codex-configured-default` sentinel on boot.** PortOS now treats Codex CLI as "no `--model` flag — let `~/.codex/config.toml` decide" via the sentinel, but existing `data/providers.json` files from before that change still pinned real model ids (`gpt-5`, `gpt-5-codex`, `gpt-5.2`) and would pass `--model gpt-5.2` to a Codex CLI that's since renamed those models. The provider loader (`server/lib/aiToolkit/providers.js`) now rewrites any codex entry's `models[]`, `defaultModel`, `lightModel`, `mediumModel`, and `heavyModel` to the sentinel on the first read after upgrade. Idempotent — already-migrated configs are untouched. Triggered explicitly at startup so the migration runs before the first inbound request consults the file.
+- **World Builder — expand merge no longer clobbers legitimate empty-string LLM responses.** The `pick` helper in `handleExpand` previously used `(llmValue || draft[key])`, which silently restored a stale `negativePrompt` when the LLM intentionally returned `""`. Now distinguishes `null/undefined` (keep draft) from `""` (apply).
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 35fdb028ca..92969087d2 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -207,6 +207,7 @@ export default function App() {
<Route path="models" element={<MediaModels />} />
<Route path="loras" element={<Loras />} />
<Route path="world-builder" element={<WorldBuilder />} />
+ <Route path="world-builder/:worldId" element={<WorldBuilder />} />
</Route>
<Route path="image-gen" element={<RedirectWithSearch to="/media/image" />} />
<Route path="video-gen" element={<RedirectWithSearch to="/media/video" />} />
@@ -216,6 +217,7 @@ export default function App() {
<Route path="wiki/:tab" element={<Wiki />} />
<Route path="rapid-reader" element={<RapidReaderPage />} />
<Route path="world-builder" element={<WorldBuilder />} />
+ <Route path="world-builder/:worldId" element={<WorldBuilder />} />
<Route path="writers-room" element={<WritersRoom />} />
<Route path="pipeline" element={<Pipeline />} />
<Route path="pipeline/series/:seriesId" element={<PipelineSeries />} />
diff --git a/client/src/components/worldBuilder/InfluenceChipsInput.jsx b/client/src/components/worldBuilder/InfluenceChipsInput.jsx
new file mode 100644
index 0000000000..7c08172caf
--- /dev/null
+++ b/client/src/components/worldBuilder/InfluenceChipsInput.jsx
@@ -0,0 +1,109 @@
+import { useState } from 'react';
+import { X } from 'lucide-react';
+import { WORLD_INFLUENCE_ENTRY_MAX, WORLD_INFLUENCES_PER_LIST_MAX } from '../../services/api';
+
+const TONE_CLASS = {
+ success: 'bg-port-success/15 text-port-success border-port-success/40',
+ error: 'bg-port-error/15 text-port-error border-port-error/40',
+ accent: 'bg-port-accent/20 text-port-accent border-port-accent/40',
+};
+
+/**
+ * Chip input for an influence list (embrace or avoid). Used by both the
+ * inline World Builder editor and the Refine modal — extracting one
+ * implementation keeps Enter/comma/paste/Backspace behavior, dedupe rules,
+ * and per-entry caps in lockstep across both surfaces.
+ *
+ * `readOnly` collapses the editor to a plain chip preview (no input, no X
+ * buttons) so locked influences render with the same chrome.
+ */
+export default function InfluenceChipsInput({
+ tokens,
+ onChange,
+ tone = 'accent',
+ placeholder = 'Add reference, press Enter',
+ readOnly = false,
+ emptyLabel = '(none)',
+}) {
+ const [input, setInput] = useState('');
+ const safe = Array.isArray(tokens) ? tokens : [];
+ const toneClass = TONE_CLASS[tone] || TONE_CLASS.accent;
+
+ if (readOnly && safe.length === 0) {
+ return <div className="text-[11px] text-gray-600">{emptyLabel}</div>;
+ }
+
+ const commit = (raw) => {
+ const incoming = (raw || '')
+ .split(/[,\n]/)
+ .map((t) => t.trim())
+ .filter(Boolean)
+ .map((t) => t.slice(0, WORLD_INFLUENCE_ENTRY_MAX));
+ if (!incoming.length) return;
+ const seen = new Set(safe.map((v) => v.toLowerCase()));
+ const next = [...safe];
+ for (const t of incoming) {
+ const key = t.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ next.push(t);
+ if (next.length >= WORLD_INFLUENCES_PER_LIST_MAX) break;
+ }
+ onChange(next);
+ setInput('');
+ };
+
+ const removeAt = (idx) => onChange(safe.filter((_, i) => i !== idx));
+
+ return (
+ <div className={`flex flex-wrap items-center gap-1.5 p-2 bg-port-bg border border-port-border rounded ${readOnly ? 'opacity-70' : ''}`}>
+ {safe.map((v, idx) => (
+ <span
+ key={`${v}-${idx}`}
+ className={`inline-flex items-center gap-1 px-2 py-0.5 text-xs rounded-full border ${toneClass}`}
+ >
+ {v}
+ {!readOnly && (
+ <button
+ type="button"
+ onClick={() => removeAt(idx)}
+ className="text-current/70 hover:text-current"
+ aria-label={`Remove ${v}`}
+ >
+ <X size={11} />
+ </button>
+ )}
+ </span>
+ ))}
+ {!readOnly && safe.length < WORLD_INFLUENCES_PER_LIST_MAX && (
+ <input
+ type="text"
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ',') {
+ e.preventDefault();
+ commit(input);
+ } else if (e.key === 'Backspace' && !input && safe.length) {
+ onChange(safe.slice(0, -1));
+ }
+ }}
+ onBlur={() => commit(input)}
+ onPaste={(e) => {
+ const text = e.clipboardData.getData('text');
+ if (text && /[,\n]/.test(text)) {
+ e.preventDefault();
+ commit(text);
+ }
+ }}
+ placeholder={placeholder}
+ maxLength={WORLD_INFLUENCE_ENTRY_MAX}
+ className="flex-1 min-w-[120px] bg-transparent text-sm text-white placeholder-gray-500 focus:outline-none"
+ />
+ )}
+ {!readOnly && safe.length >= WORLD_INFLUENCES_PER_LIST_MAX && (
+ <span className="text-[11px] text-gray-500">Max {WORLD_INFLUENCES_PER_LIST_MAX} reached</span>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/worldBuilder/WorldPromptRefineModal.jsx b/client/src/components/worldBuilder/WorldPromptRefineModal.jsx
index ee3e8114e5..aa12d9f5f3 100644
--- a/client/src/components/worldBuilder/WorldPromptRefineModal.jsx
+++ b/client/src/components/worldBuilder/WorldPromptRefineModal.jsx
@@ -1,20 +1,47 @@
import { useEffect, useState } from 'react';
-import { Check, Sparkles, Wand2, X } from 'lucide-react';
+import { Check, Lock, Sparkles, Wand2, X } from 'lucide-react';
import ProviderModelSelector from '../ProviderModelSelector';
import toast from '../ui/Toast';
import useProviderModels from '../../hooks/useProviderModels';
-import { refineWorldPrompts } from '../../services/api';
+import { refineWorldPrompts, WORLD_LOCKABLE_FIELDS, ensureInfluences } from '../../services/api';
+import InfluenceChipsInput from './InfluenceChipsInput';
/**
- * Refines the three top-level world prompts (Starter Idea, Style Prompt,
- * Negative Prompt) based on user feedback. Mirrors PromptRefineModal's
- * shape — feedback box, provider/model selector, refined-fields review,
- * then apply.
+ * Refines all six top-level world fields (Starter Idea, Style Prompt, Negative
+ * Prompt, Logline, Premise, Style Notes) based on user feedback. Mirrors
+ * PromptRefineModal's shape — feedback box, provider/model selector,
+ * refined-fields review, then apply.
*
- * The modal is stateless from the server's perspective: applying the
- * refinement writes back to the page-level draft, and saving the world
- * is the user's choice (matches existing expansion-flow behavior).
+ * Locked fields (passed via the `locked` prop) are read-only in both the
+ * originals preview and the refined section, and are NEVER applied back to
+ * the parent draft — defense-in-depth on top of the server-side lock honoring.
*/
+
+const FIELD_LABELS = {
+ starterPrompt: 'Starter idea',
+ stylePrompt: 'Style prompt',
+ negativePrompt: 'Negative prompt',
+ logline: 'Logline',
+ premise: 'Premise',
+ styleNotes: 'Style notes',
+ influences: 'Influences',
+};
+
+// Single-line fields render as text inputs; multi-line as textareas with
+// per-field row counts so the modal scales sensibly without scroll-traps.
+// `influences` is handled by a dedicated chips renderer, not the textarea
+// path, so it has no row count entry.
+const FIELD_ROWS = {
+ starterPrompt: 4,
+ stylePrompt: 4,
+ negativePrompt: 3,
+ logline: 0,
+ premise: 6,
+ styleNotes: 6,
+};
+
+const emptyInfluences = () => ({ embrace: [], avoid: [] });
+
export default function WorldPromptRefineModal({
open,
onClose,
@@ -22,6 +49,11 @@ export default function WorldPromptRefineModal({
starterPrompt = '',
stylePrompt = '',
negativePrompt = '',
+ logline = '',
+ premise = '',
+ styleNotes = '',
+ influences = emptyInfluences(),
+ locked = {},
// Optional pre-selected provider/model — when a world already pins an LLM
// for expansion, default the refiner to the same combo so the user doesn't
// have to re-pick.
@@ -38,10 +70,13 @@ export default function WorldPromptRefineModal({
loading: providersLoading,
} = useProviderModels();
+ const originals = {
+ starterPrompt, stylePrompt, negativePrompt, logline, premise, styleNotes,
+ influences: ensureInfluences(influences),
+ };
+
const [feedback, setFeedback] = useState('');
- const [refinedStarter, setRefinedStarter] = useState('');
- const [refinedStyle, setRefinedStyle] = useState('');
- const [refinedNegative, setRefinedNegative] = useState('');
+ const [refined, setRefined] = useState({});
const [rationale, setRationale] = useState('');
const [changes, setChanges] = useState([]);
const [refining, setRefining] = useState(false);
@@ -51,9 +86,7 @@ export default function WorldPromptRefineModal({
useEffect(() => {
if (!open) return;
setFeedback('');
- setRefinedStarter('');
- setRefinedStyle('');
- setRefinedNegative('');
+ setRefined({});
setRationale('');
setChanges([]);
}, [open]);
@@ -72,43 +105,51 @@ export default function WorldPromptRefineModal({
if (!open) return null;
- const hasResult = refinedStarter !== '' || rationale !== '';
- const canRefine = feedback.trim() && starterPrompt.trim() && selectedProviderId && !refining;
- const canApply = hasResult && refinedStarter.trim();
+ const allLocked = WORLD_LOCKABLE_FIELDS.every((k) => locked[k]);
+ const hasResult = Object.keys(refined).length > 0 || rationale !== '';
+ const canRefine = feedback.trim() && starterPrompt.trim() && selectedProviderId && !refining && !allLocked;
+ const canApply = hasResult && (refined.starterPrompt || '').trim();
const runRefine = async () => {
if (!canRefine) return;
setRefining(true);
- setRefinedStarter('');
- setRefinedStyle('');
- setRefinedNegative('');
+ setRefined({});
setRationale('');
setChanges([]);
const result = await refineWorldPrompts({
- starterPrompt,
- stylePrompt,
- negativePrompt,
+ ...originals,
+ locked,
feedback: feedback.trim(),
providerId: selectedProviderId,
model: selectedModel || undefined,
}).catch(() => null); // services/apiCore#request already toasts on errors.
setRefining(false);
if (!result) return;
- setRefinedStarter(result.starterPrompt || '');
- setRefinedStyle(result.stylePrompt || '');
- setRefinedNegative(result.negativePrompt || '');
+ const next = {};
+ for (const key of WORLD_LOCKABLE_FIELDS) {
+ if (key === 'influences') next[key] = ensureInfluences(result[key]);
+ else next[key] = result[key] ?? '';
+ }
+ setRefined(next);
setRationale(result.rationale || '');
setChanges(Array.isArray(result.changes) ? result.changes : []);
};
+ const setRefinedField = (key, value) => setRefined((prev) => ({ ...prev, [key]: value }));
+
const handleApply = () => {
if (!canApply) return;
- onApply({
- starterPrompt: refinedStarter.trim(),
- stylePrompt: refinedStyle.trim(),
- negativePrompt: refinedNegative.trim(),
- });
- toast.success('Refined prompts applied');
+ // Only emit unlocked fields — the server already enforces this, but
+ // belt-and-suspenders prevents a stale lock-toggle race from clobbering
+ // a pinned value.
+ const patch = {};
+ for (const key of WORLD_LOCKABLE_FIELDS) {
+ if (locked[key]) continue;
+ if (key === 'influences') patch[key] = ensureInfluences(refined[key]);
+ else patch[key] = (refined[key] ?? '').trim();
+ }
+ onApply(patch);
+ toast.success('Refined fields applied');
onClose();
};
@@ -145,18 +186,34 @@ export default function WorldPromptRefineModal({
<div className="flex-1 overflow-y-auto p-4 space-y-4">
<p className="text-xs text-gray-400">
Describe what you want the world to feel like — story tone, era, art-direction
- references, what to avoid. The LLM rewrites your Starter Idea, Style Prompt, and
- Negative Prompt to match. Review the result before applying.
+ references, what to avoid. The LLM rewrites your starter, prompts, and bible
+ fields to match. Locked fields stay untouched. Review the result before applying.
</p>
- {/* Originals — collapsed-ish read-only preview so the user remembers
- what's about to change. */}
- <div className="grid grid-cols-1 sm:grid-cols-3 gap-2 text-xs">
- <ReadOnlyField label="Starter idea" value={starterPrompt} />
- <ReadOnlyField label="Style prompt" value={stylePrompt} />
- <ReadOnlyField label="Negative prompt" value={negativePrompt} />
+ {/* Originals — read-only preview so the user remembers what's about
+ to change. Lock indicator surfaces which fields the LLM will skip. */}
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
+ {WORLD_LOCKABLE_FIELDS.filter((k) => k !== 'influences').map((key) => (
+ <ReadOnlyField
+ key={key}
+ label={FIELD_LABELS[key]}
+ value={originals[key]}
+ locked={!!locked[key]}
+ />
+ ))}
+ <ReadOnlyInfluences
+ label={FIELD_LABELS.influences}
+ value={originals.influences}
+ locked={!!locked.influences}
+ />
</div>
+ {allLocked && (
+ <p className="text-xs text-port-warning">
+ All fields are locked — unlock at least one to enable refinement.
+ </p>
+ )}
+
<div>
<label htmlFor="world-refine-feedback" className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">
Feedback
@@ -218,23 +275,21 @@ export default function WorldPromptRefineModal({
</ul>
)}
- <RefinedTextarea
- label="New starter idea"
- value={refinedStarter}
- onChange={setRefinedStarter}
- rows={3}
- />
- <RefinedTextarea
- label="New style prompt"
- value={refinedStyle}
- onChange={setRefinedStyle}
- rows={4}
- />
- <RefinedTextarea
- label="New negative prompt"
- value={refinedNegative}
- onChange={setRefinedNegative}
- rows={3}
+ {WORLD_LOCKABLE_FIELDS.filter((k) => k !== 'influences').map((key) => (
+ <RefinedField
+ key={key}
+ label={`New ${FIELD_LABELS[key].toLowerCase()}`}
+ value={refined[key] ?? ''}
+ onChange={(v) => setRefinedField(key, v)}
+ rows={FIELD_ROWS[key]}
+ locked={!!locked[key]}
+ />
+ ))}
+ <RefinedInfluences
+ label={`New ${FIELD_LABELS.influences.toLowerCase()}`}
+ value={ensureInfluences(refined.influences)}
+ onChange={(v) => setRefinedField('influences', v)}
+ locked={!!locked.influences}
/>
</div>
)}
@@ -263,10 +318,17 @@ export default function WorldPromptRefineModal({
);
}
-function ReadOnlyField({ label, value }) {
+function ReadOnlyField({ label, value, locked }) {
return (
- <div className="bg-port-bg border border-port-border rounded p-2">
- <div className="text-[10px] uppercase tracking-wide text-gray-500 mb-1">{label}</div>
+ <div className={`bg-port-bg border rounded p-2 ${locked ? 'border-port-accent/40' : 'border-port-border'}`}>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="text-[10px] uppercase tracking-wide text-gray-500">{label}</div>
+ {locked && (
+ <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-accent">
+ <Lock className="w-3 h-3" /> Locked
+ </span>
+ )}
+ </div>
<div className="text-[11px] text-gray-300 line-clamp-4 whitespace-pre-wrap">
{value?.trim() ? value : <span className="text-gray-600">(empty)</span>}
</div>
@@ -274,7 +336,108 @@ function ReadOnlyField({ label, value }) {
);
}
-function RefinedTextarea({ label, value, onChange, rows }) {
+function ReadOnlyInfluences({ label, value, locked }) {
+ const hasAny = value.embrace.length || value.avoid.length;
+ return (
+ <div className={`bg-port-bg border rounded p-2 sm:col-span-2 ${locked ? 'border-port-accent/40' : 'border-port-border'}`}>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="text-[10px] uppercase tracking-wide text-gray-500">{label}</div>
+ {locked && (
+ <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-accent">
+ <Lock className="w-3 h-3" /> Locked
+ </span>
+ )}
+ </div>
+ {hasAny ? (
+ <div className="grid grid-cols-2 gap-2">
+ <InfluenceChipsInput tokens={value.embrace} onChange={() => {}} tone="success" readOnly />
+ <InfluenceChipsInput tokens={value.avoid} onChange={() => {}} tone="error" readOnly />
+ </div>
+ ) : (
+ <div className="text-[11px] text-gray-600">(empty)</div>
+ )}
+ </div>
+ );
+}
+
+function RefinedInfluences({ label, value, onChange, locked }) {
+ if (locked) {
+ return (
+ <div>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <label className="block text-[11px] uppercase tracking-wide text-gray-500">{label}</label>
+ <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-accent">
+ <Lock className="w-3 h-3" /> Locked — kept as-is
+ </span>
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ <InfluenceChipsInput tokens={value.embrace} onChange={() => {}} tone="success" readOnly />
+ <InfluenceChipsInput tokens={value.avoid} onChange={() => {}} tone="error" readOnly />
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div>
+ <label className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">{label}</label>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
+ <div>
+ <div className="text-[10px] uppercase tracking-wide text-port-success/80 mb-1">Embrace</div>
+ <InfluenceChipsInput
+ tokens={value.embrace}
+ onChange={(next) => onChange({ ...value, embrace: next })}
+ tone="success"
+ />
+ </div>
+ <div>
+ <div className="text-[10px] uppercase tracking-wide text-port-error/80 mb-1">Avoid</div>
+ <InfluenceChipsInput
+ tokens={value.avoid}
+ onChange={(next) => onChange({ ...value, avoid: next })}
+ tone="error"
+ placeholder="Add avoid token, press Enter"
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function RefinedField({ label, value, onChange, rows, locked }) {
+ // Locked fields render as a disabled read-only preview — a visible reminder
+ // that the LLM was told to skip them and the value the user pinned is
+ // intact. We hide them when there's no value rather than showing "(empty)"
+ // because there's nothing to confirm.
+ if (locked) {
+ return (
+ <div>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <label className="block text-[11px] uppercase tracking-wide text-gray-500">{label}</label>
+ <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-accent">
+ <Lock className="w-3 h-3" /> Locked — kept as-is
+ </span>
+ </div>
+ <div className="w-full bg-port-bg/60 border border-port-accent/40 rounded-lg p-3 text-sm text-gray-400 whitespace-pre-wrap">
+ {value?.trim() ? value : <span className="text-gray-600">(empty)</span>}
+ </div>
+ </div>
+ );
+ }
+ // Single-line fields (rows = 0) render as inputs so logline doesn't get a
+ // multi-line textarea for one sentence.
+ if (!rows || rows < 2) {
+ return (
+ <div>
+ <label className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">{label}</label>
+ <input
+ type="text"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded-lg p-3 text-sm text-white focus:outline-none focus:border-port-accent"
+ />
+ </div>
+ );
+ }
return (
<div>
<label className="block text-[11px] uppercase tracking-wide text-gray-500 mb-1">{label}</label>
diff --git a/client/src/pages/WorldBuilder.jsx b/client/src/pages/WorldBuilder.jsx
index e694d8e3be..d0f731e8d4 100644
--- a/client/src/pages/WorldBuilder.jsx
+++ b/client/src/pages/WorldBuilder.jsx
@@ -8,18 +8,22 @@
*/
import { useEffect, useMemo, useState } from 'react';
-import { Link } from 'react-router-dom';
+import { Link, useLocation, useNavigate, useParams } from 'react-router-dom';
import {
Globe2, Plus, Trash2, Sparkles, Wand2, Loader2, Save, FolderOpen,
- Edit3, X, MessageSquarePlus, Play,
+ Edit3, X, MessageSquarePlus, Play, Lock, Unlock,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import {
listWorlds, getWorld, createWorld, updateWorld, deleteWorld, expandWorld,
renderWorld, listWorldRuns, getProviders, WORLD_CATEGORIES,
WORLD_CATEGORY_KEY_MAX, COMPOSITE_PROMPT_MAX, WORLD_LOGLINE_MAX,
- WORLD_PREMISE_MAX, WORLD_STYLE_NOTES_MAX, listImageModels, getSettings,
+ WORLD_PREMISE_MAX, WORLD_STYLE_NOTES_MAX, WORLD_LOCKABLE_FIELDS,
+ WORLD_INFLUENCE_ENTRY_MAX, WORLD_INFLUENCES_PER_LIST_MAX,
+ ensureInfluences,
+ listImageModels, getSettings,
} from '../services/api';
+import InfluenceChipsInput from '../components/worldBuilder/InfluenceChipsInput';
import BackendChipStrip from '../components/media/BackendChipStrip';
import ImageGenControls from '../components/imageGen/ImageGenControls';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
@@ -95,12 +99,101 @@ const emptyTemplate = () => ({
styleNotes: '',
categories: ensureDraftCategories(),
compositeSheets: [],
+ influences: { embrace: [], avoid: [] },
+ locked: {},
llm: { provider: null, model: null },
});
+
+// Renders a small lock-toggle button to the right of a field label. The user
+// clicks it to pin a field against AI refinement/expansion. The icon flips
+// between locked (filled) and unlocked (outline) to make state obvious.
+function LockButton({ field, locked, onToggle, label }) {
+ const isLocked = !!locked?.[field];
+ const Icon = isLocked ? Lock : Unlock;
+ return (
+ <button
+ type="button"
+ onClick={() => onToggle(field)}
+ className={`p-1 rounded -mr-1 ${
+ isLocked
+ ? 'text-port-accent hover:bg-port-accent/20'
+ : 'text-gray-500 hover:text-gray-300 hover:bg-port-border/40'
+ }`}
+ title={isLocked ? `${label} locked — AI refine/expand will skip it` : `Lock ${label} against AI refine/expand`}
+ aria-label={isLocked ? `Unlock ${label}` : `Lock ${label}`}
+ aria-pressed={isLocked}
+ >
+ <Icon size={13} />
+ </button>
+ );
+}
+
+// Render a label row with the field name + lock toggle. Used by every
+// lockable bible/prompt field so the lock UI stays consistent.
+function FieldLabel({ htmlFor, children, field, locked, onToggleLock }) {
+ return (
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <label htmlFor={htmlFor} className="text-xs text-gray-400">{children}</label>
+ <LockButton field={field} locked={locked} onToggle={onToggleLock} label={typeof children === 'string' ? children : field} />
+ </div>
+ );
+}
+
+// Two-column embrace + avoid editor with a single shared lock toggle.
+// Sits in the Story bible section so the writers + creative directors can
+// pin canonical references that the renderer then prepends deterministically
+// to stylePrompt / negativePrompt.
+function InfluencesEditor({ influences, onChange, locked, onToggleLock }) {
+ const safe = ensureInfluences(influences);
+ const isLocked = !!locked?.influences;
+ return (
+ <div>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <label className="text-xs text-gray-400">
+ Influences <span className="text-gray-600">— prepended to render prompts deterministically</span>
+ </label>
+ <LockButton field="influences" locked={locked} onToggle={onToggleLock} label="Influences" />
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ <div>
+ <div className="text-[11px] uppercase tracking-wide text-port-success/80 mb-1">Embrace</div>
+ <InfluenceChipsInput
+ tokens={safe.embrace}
+ onChange={(next) => onChange({ ...safe, embrace: next })}
+ placeholder="Moebius, cel-shading…"
+ tone="success"
+ readOnly={isLocked}
+ />
+ </div>
+ <div>
+ <div className="text-[11px] uppercase tracking-wide text-port-error/80 mb-1">Avoid</div>
+ <InfluenceChipsInput
+ tokens={safe.avoid}
+ onChange={(next) => onChange({ ...safe, avoid: next })}
+ placeholder="Ghibli painterly, neon cyberpunk…"
+ tone="error"
+ readOnly={isLocked}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
+
export default function WorldBuilder() {
+ // The selected world id lives in the URL so deep-linking + back/forward
+ // work. The page is mounted at /world-builder, /world-builder/:worldId,
+ // and /media/world-builder(/:worldId) — strip any trailing /<id> off the
+ // current pathname to derive the base for navigation back to the list.
+ const params = useParams();
+ const navigate = useNavigate();
+ const location = useLocation();
+ const selectedId = params.worldId || null;
+ const basePath = location.pathname.replace(/\/world-builder(?:\/.*)?$/, '/world-builder');
+ const goToWorld = (id) => navigate(id ? `${basePath}/${encodeURIComponent(id)}` : basePath);
+
const [worlds, setWorlds] = useState([]);
- const [selectedId, setSelectedId] = useState(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [expanding, setExpanding] = useState(false);
@@ -188,6 +281,8 @@ export default function WorldBuilder() {
logline: w.logline || '',
premise: w.premise || '',
styleNotes: w.styleNotes || '',
+ influences: ensureInfluences(w.influences),
+ locked: w.locked || {},
llm: w.llm || { provider: null, model: null },
});
}
@@ -197,7 +292,7 @@ export default function WorldBuilder() {
}, [selectedId]);
const handleNew = () => {
- setSelectedId(null);
+ goToWorld(null);
setDraft(emptyTemplate());
setRuns([]);
};
@@ -218,6 +313,8 @@ export default function WorldBuilder() {
styleNotes: draft.styleNotes || '',
categories: draft.categories,
compositeSheets: draft.compositeSheets || [],
+ influences: ensureInfluences(draft.influences),
+ locked: draft.locked || {},
llm: draft.llm || {},
};
const result = selectedId
@@ -230,7 +327,10 @@ export default function WorldBuilder() {
const without = prev.filter((w) => w.id !== result.id);
return [result, ...without];
});
- setSelectedId(result.id);
+ // After Create: jump to the new id's URL so back-button / refresh
+ // returns to the same world. After Update: id is unchanged, but
+ // navigating is harmless (replace-style).
+ if (result.id !== selectedId) goToWorld(result.id);
}
};
@@ -251,7 +351,7 @@ export default function WorldBuilder() {
.catch((e) => { toast.error(`Delete failed: ${e.message}`); return false; });
if (!ok) return;
setWorlds((prev) => prev.filter((w) => w.id !== id));
- setSelectedId(null);
+ goToWorld(null);
setDraft(emptyTemplate());
setPendingDeleteId(null);
toast.success('World deleted');
@@ -262,29 +362,112 @@ export default function WorldBuilder() {
toast.error('Add a starter prompt to expand');
return;
}
+ // Extract per-item locks so the server can include them in the LLM
+ // prompt (avoid duplicate generation) AND we can merge them back in
+ // after the result returns. Only LOCKED entries are forwarded — the
+ // unlocked items get fully replaced.
+ const preservedVariations = {};
+ for (const [cat, bucket] of Object.entries(draft.categories || {})) {
+ const locked = (bucket?.variations || []).filter((v) => v?.locked === true);
+ if (locked.length) preservedVariations[cat] = locked;
+ }
+ const preservedCompositeSheets = (draft.compositeSheets || []).filter((s) => s?.locked === true);
+
setExpanding(true);
const result = await expandWorld({
starterPrompt: draft.starterPrompt,
+ // Pass current influences so re-expansions stay on-direction —
+ // without this, the LLM regenerates from the bare starter idea and
+ // any prior refinement is lost.
+ influences: ensureInfluences(draft.influences),
+ preservedVariations,
+ preservedCompositeSheets,
providerId: draft.llm?.provider || undefined,
model: draft.llm?.model || undefined,
}).catch((e) => { toast.error(`Expansion failed: ${e.message}`); return null; });
setExpanding(false);
if (!result) return;
+ // For each lockable field: pick the LLM's value when unlocked (falling
+ // back to the draft if the LLM produced empty); pick the draft's value
+ // verbatim when locked. Categories + compositeSheets aren't lockable
+ // (the lock UI scopes to the bible/prompt scalars), so they always
+ // come from the LLM. `starterPrompt` is normally untouched by expand
+ // (the LLM doesn't return one), but if it ever did, lock honoring
+ // protects the user's edits.
+ const locks = draft.locked || {};
+ // Distinguish "LLM omitted the field" (null/undefined → keep draft) from
+ // "LLM returned empty string" (negativePrompt is a legitimate "" — the
+ // user's `||` would silently restore a stale value they wanted gone).
+ const pick = (key, llmValue) => {
+ if (locks[key]) return draft[key];
+ return llmValue == null ? draft[key] : llmValue;
+ };
+ // Influences: preserve the draft's lists when locked OR when the LLM
+ // returned empty (defensive — sanitizeInfluences server-side already
+ // falls back, but the client's own lock state must dominate too).
+ const llmInf = ensureInfluences(result.influences);
+ const refinedInfluences = locks.influences
+ ? ensureInfluences(draft.influences)
+ : ((llmInf.embrace.length || llmInf.avoid.length) ? llmInf : ensureInfluences(draft.influences));
+ // Per-item lock merge: for each category, locked items survive at the
+ // top of the list; LLM-generated items follow, deduped case-insensitively
+ // by label so the LLM can't accidentally regenerate a pinned label.
+ // Categories that exist in the draft but not in the LLM result are
+ // preserved when they still hold locked variations.
+ const mergeVariations = (locked, fresh) => {
+ const seen = new Set(locked.map((v) => v.label.toLowerCase()));
+ const merged = [...locked];
+ for (const v of fresh || []) {
+ const key = v.label?.toLowerCase();
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ merged.push(v);
+ }
+ return merged;
+ };
+ const llmCategories = result.categories || {};
+ const mergedCategories = {};
+ const allCatKeys = new Set([
+ ...Object.keys(preservedVariations),
+ ...Object.keys(llmCategories),
+ ]);
+ for (const cat of allCatKeys) {
+ const locked = preservedVariations[cat] || [];
+ const fresh = (llmCategories[cat]?.variations || []);
+ mergedCategories[cat] = { variations: mergeVariations(locked, fresh) };
+ }
+ // Composite sheets merge follows the same locked-first + dedupe pattern.
+ const mergedSheets = (() => {
+ const llmSheets = result.compositeSheets || [];
+ const seen = new Set(preservedCompositeSheets.map((s) => s.label.toLowerCase()));
+ const out = [...preservedCompositeSheets];
+ for (const s of llmSheets) {
+ const key = s.label?.toLowerCase();
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ out.push(s);
+ }
+ return out;
+ })();
+
const expandedDraft = {
...draft,
- stylePrompt: result.stylePrompt || draft.stylePrompt,
- negativePrompt: result.negativePrompt || draft.negativePrompt,
- // Only overwrite the narrative bible fields when the LLM actually
- // produced one — preserves any prose the user has already hand-edited
- // when they re-run /expand to refresh just the image categories.
- logline: result.logline || draft.logline,
- premise: result.premise || draft.premise,
- styleNotes: result.styleNotes || draft.styleNotes,
- categories: ensureDraftCategories(result.categories),
- compositeSheets: result.compositeSheets || draft.compositeSheets || [],
+ starterPrompt: pick('starterPrompt', result.starterPrompt),
+ stylePrompt: pick('stylePrompt', result.stylePrompt),
+ negativePrompt: pick('negativePrompt', result.negativePrompt),
+ logline: pick('logline', result.logline),
+ premise: pick('premise', result.premise),
+ styleNotes: pick('styleNotes', result.styleNotes),
+ influences: refinedInfluences,
+ categories: ensureDraftCategories(mergedCategories),
+ compositeSheets: mergedSheets,
llm: result.llm || draft.llm,
};
setDraft(expandedDraft);
+ const lockedKeys = Object.keys(locks).filter((k) => locks[k]);
+ if (lockedKeys.length) {
+ console.log(`🔒 World Builder expand preserved ${lockedKeys.length} locked field(s): ${lockedKeys.join(', ')}`);
+ }
const total = totalVariationCount(expandedDraft);
if (expandedDraft.compositeSheets?.length) {
setRenderOpts((r) => ({ ...r, promptMode: 'sheets' }));
@@ -304,6 +487,8 @@ export default function WorldBuilder() {
styleNotes: expandedDraft.styleNotes || '',
categories: expandedDraft.categories,
compositeSheets: expandedDraft.compositeSheets || [],
+ influences: ensureInfluences(expandedDraft.influences),
+ locked: expandedDraft.locked || {},
llm: expandedDraft.llm || {},
}).catch((e) => { toast.error(`Auto-save after expand failed: ${e.message}`); return null; });
if (updated) {
@@ -318,16 +503,18 @@ export default function WorldBuilder() {
toast.success(`Expanded into ${total} variations and ${expandedDraft.compositeSheets?.length || 0} boards — review then Save`);
};
- // Writes the LLM-refined starter/style/negative back to the draft. Mirrors
- // handleExpand's auto-save: if the world is already persisted, persist the
- // refinement immediately so subsequent renders/expansions see it on disk.
- const applyRefinement = async ({ starterPrompt, stylePrompt, negativePrompt }) => {
- const next = {
- ...draft,
- starterPrompt: starterPrompt ?? draft.starterPrompt,
- stylePrompt: stylePrompt ?? draft.stylePrompt,
- negativePrompt: negativePrompt ?? draft.negativePrompt,
- };
+ // Writes the LLM-refined fields back to the draft. The modal only emits
+ // unlocked fields (server enforces this too), so we apply every key that
+ // shows up in the patch and leave everything else on the draft as-is.
+ // Mirrors handleExpand's auto-save: if the world is already persisted,
+ // persist the refinement immediately so subsequent renders/expansions see
+ // it on disk.
+ const applyRefinement = async (patch = {}) => {
+ const next = { ...draft };
+ for (const key of WORLD_LOCKABLE_FIELDS) {
+ if (!(key in patch) || patch[key] == null) continue;
+ next[key] = key === 'influences' ? ensureInfluences(patch[key]) : patch[key];
+ }
setDraft(next);
if (selectedId && next.name?.trim()) {
const updated = await updateWorld(selectedId, {
@@ -340,6 +527,8 @@ export default function WorldBuilder() {
styleNotes: next.styleNotes || '',
categories: next.categories,
compositeSheets: next.compositeSheets || [],
+ influences: ensureInfluences(next.influences),
+ locked: next.locked || {},
llm: next.llm || {},
}).catch((e) => { toast.error(`Auto-save after refine failed: ${e.message}`); return null; });
if (updated) {
@@ -404,6 +593,26 @@ export default function WorldBuilder() {
const canRender = !!selectedId && availableBackends.length > 0 && !rendering;
const updateDraft = (patch) => setDraft((d) => ({ ...d, ...patch }));
+ // Toggle a single field's lock state and (when the world is already saved)
+ // persist immediately — locks are part of the world template, so a stale
+ // disk copy would let a later refine/expand silently overwrite a "locked"
+ // field after a refresh.
+ const toggleLock = (field) => {
+ if (!WORLD_LOCKABLE_FIELDS.includes(field)) return;
+ setDraft((d) => {
+ const nextLocked = { ...(d.locked || {}) };
+ if (nextLocked[field]) delete nextLocked[field];
+ else nextLocked[field] = true;
+ const next = { ...d, locked: nextLocked };
+ if (selectedId && next.name?.trim()) {
+ // Fire-and-forget — the in-memory state already reflects the toggle;
+ // on failure we toast and the next manual Save still recovers.
+ updateWorld(selectedId, { locked: nextLocked })
+ .catch((e) => toast.error(`Lock save failed: ${e.message}`));
+ }
+ return next;
+ });
+ };
const updateCategory = (cat, variations) => setDraft((d) => ({
...d,
categories: { ...d.categories, [cat]: { variations } },
@@ -469,7 +678,7 @@ export default function WorldBuilder() {
return (
<li key={w.id}>
<button
- onClick={() => setSelectedId(w.id)}
+ onClick={() => goToWorld(w.id)}
className={`w-full text-left px-2 py-2 rounded text-sm transition-colors min-h-[40px] ${
active
? 'bg-port-accent/15 text-port-accent border border-port-accent/40'
@@ -524,7 +733,9 @@ export default function WorldBuilder() {
{/* Starter prompt + LLM picker */}
<div className="grid grid-cols-1 md:grid-cols-[1fr_220px] gap-3">
<div>
- <label className="text-xs text-gray-400 mb-1 block">Starter idea</label>
+ <FieldLabel field="starterPrompt" locked={draft.locked} onToggleLock={toggleLock}>
+ Starter idea
+ </FieldLabel>
<textarea
value={draft.starterPrompt}
onChange={(e) => updateDraft({ starterPrompt: e.target.value })}
@@ -573,7 +784,7 @@ export default function WorldBuilder() {
className="px-3 py-2 bg-purple-600/30 hover:bg-purple-600/50 disabled:opacity-50 text-purple-200 border border-purple-600/40 rounded flex items-center gap-2 min-h-[40px]"
>
{expanding ? <Loader2 size={16} className="animate-spin" /> : <Wand2 size={16} />}
- Expand starter → variations
+ Generate From Idea
</button>
<button
onClick={() => setRefineOpen(true)}
@@ -597,6 +808,11 @@ export default function WorldBuilder() {
starterPrompt={draft.starterPrompt || ''}
stylePrompt={draft.stylePrompt || ''}
negativePrompt={draft.negativePrompt || ''}
+ logline={draft.logline || ''}
+ premise={draft.premise || ''}
+ styleNotes={draft.styleNotes || ''}
+ influences={ensureInfluences(draft.influences)}
+ locked={draft.locked || {}}
defaultProviderId={draft.llm?.provider || activeProviderId || null}
defaultModel={draft.llm?.model || null}
/>
@@ -609,7 +825,9 @@ export default function WorldBuilder() {
</p>
</div>
<div>
- <label htmlFor="world-logline" className="text-xs text-gray-400 mb-1 block">Logline</label>
+ <FieldLabel htmlFor="world-logline" field="logline" locked={draft.locked} onToggleLock={toggleLock}>
+ Logline
+ </FieldLabel>
<input
id="world-logline"
type="text"
@@ -622,7 +840,9 @@ export default function WorldBuilder() {
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
- <label htmlFor="world-premise" className="text-xs text-gray-400 mb-1 block">Premise</label>
+ <FieldLabel htmlFor="world-premise" field="premise" locked={draft.locked} onToggleLock={toggleLock}>
+ Premise
+ </FieldLabel>
<textarea
id="world-premise"
value={draft.premise || ''}
@@ -634,7 +854,9 @@ export default function WorldBuilder() {
/>
</div>
<div>
- <label htmlFor="world-style-notes" className="text-xs text-gray-400 mb-1 block">Style notes</label>
+ <FieldLabel htmlFor="world-style-notes" field="styleNotes" locked={draft.locked} onToggleLock={toggleLock}>
+ Style notes
+ </FieldLabel>
<textarea
id="world-style-notes"
value={draft.styleNotes || ''}
@@ -646,14 +868,23 @@ export default function WorldBuilder() {
/>
</div>
</div>
+ <InfluencesEditor
+ influences={draft.influences}
+ onChange={(next) => updateDraft({ influences: next })}
+ locked={draft.locked}
+ onToggleLock={toggleLock}
+ />
</section>
{/* Style template */}
<section className="bg-port-card border border-port-border rounded p-4 grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
- <label className="text-xs text-gray-400 mb-1 block flex items-center gap-1">
- <Sparkles size={12} /> Style prompt (prepended to every variation)
- </label>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <label className="text-xs text-gray-400 flex items-center gap-1">
+ <Sparkles size={12} /> Style prompt (prepended to every variation)
+ </label>
+ <LockButton field="stylePrompt" locked={draft.locked} onToggle={toggleLock} label="Style prompt" />
+ </div>
<textarea
value={draft.stylePrompt}
onChange={(e) => updateDraft({ stylePrompt: e.target.value })}
@@ -664,7 +895,9 @@ export default function WorldBuilder() {
/>
</div>
<div>
- <label className="text-xs text-gray-400 mb-1 block">Negative prompt</label>
+ <FieldLabel field="negativePrompt" locked={draft.locked} onToggleLock={toggleLock}>
+ Negative prompt
+ </FieldLabel>
<textarea
value={draft.negativePrompt}
onChange={(e) => updateDraft({ negativePrompt: e.target.value })}
@@ -891,6 +1124,14 @@ function CompositeSheetsEditor({ sheets, onChange, canRender = false, onRender =
const removeAt = (idx) => onChange(sheets.filter((_, i) => i !== idx));
+ const toggleLockAt = (idx) => onChange(sheets.map((s, i) => {
+ if (i !== idx) return s;
+ const next = { ...s };
+ if (next.locked) delete next.locked;
+ else next.locked = true;
+ return next;
+ }));
+
const startEdit = (idx, sheet) => {
setEditIdx(idx);
setEditKind(sheet.kind || 'reference_sheet');
@@ -977,7 +1218,7 @@ function CompositeSheetsEditor({ sheets, onChange, canRender = false, onRender =
) : (
<ul className="flex flex-col gap-1.5 max-h-96 overflow-y-auto">
{sheets.map((sheet, idx) => (
- <li key={`${sheet.label}-${idx}`} className="bg-port-bg border border-port-border rounded p-2 text-sm">
+ <li key={`${sheet.label}-${idx}`} className={`bg-port-bg border rounded p-2 text-sm ${sheet.locked ? 'border-port-accent/50' : 'border-port-border'}`}>
{editIdx === idx ? (
<div className="flex flex-col gap-1">
<select
@@ -1029,6 +1270,14 @@ function CompositeSheetsEditor({ sheets, onChange, canRender = false, onRender =
<Play size={14} />
</button>
)}
+ <button
+ onClick={() => toggleLockAt(idx)}
+ className={`p-1 rounded ${sheet.locked ? 'text-port-accent hover:bg-port-accent/20' : 'text-gray-500 hover:text-gray-300'}`}
+ title={sheet.locked ? 'Locked — AI expand will preserve this board' : 'Lock this board against AI expand'}
+ aria-pressed={!!sheet.locked}
+ >
+ {sheet.locked ? <Lock size={14} /> : <Unlock size={14} />}
+ </button>
<button
onClick={() => startEdit(idx, sheet)}
className="p-1 text-gray-400 hover:text-port-accent rounded"
@@ -1077,6 +1326,14 @@ function CategoryEditor({
const removeAt = (idx) => onChange(variations.filter((_, i) => i !== idx));
+ const toggleLockAt = (idx) => onChange(variations.map((v, i) => {
+ if (i !== idx) return v;
+ const next = { ...v };
+ if (next.locked) delete next.locked;
+ else next.locked = true;
+ return next;
+ }));
+
const startEdit = (idx, v) => {
setEditIdx(idx);
setEditLabel(v.label);
@@ -1170,7 +1427,7 @@ function CategoryEditor({
) : (
<ul className="flex flex-col gap-1.5 max-h-72 overflow-y-auto">
{variations.map((v, idx) => (
- <li key={`${v.label}-${idx}`} className="bg-port-bg border border-port-border rounded p-2 text-sm">
+ <li key={`${v.label}-${idx}`} className={`bg-port-bg border rounded p-2 text-sm ${v.locked ? 'border-port-accent/50' : 'border-port-border'}`}>
{editIdx === idx ? (
<div className="flex flex-col gap-1">
<input
@@ -1208,6 +1465,14 @@ function CategoryEditor({
<Play size={14} />
</button>
)}
+ <button
+ onClick={() => toggleLockAt(idx)}
+ className={`p-1 rounded ${v.locked ? 'text-port-accent hover:bg-port-accent/20' : 'text-gray-500 hover:text-gray-300'}`}
+ title={v.locked ? 'Locked — AI expand will preserve this variation' : 'Lock this variation against AI expand'}
+ aria-pressed={!!v.locked}
+ >
+ {v.locked ? <Lock size={14} /> : <Unlock size={14} />}
+ </button>
<button
onClick={() => startEdit(idx, v)}
className="p-1 text-gray-400 hover:text-port-accent rounded"
diff --git a/client/src/services/apiWorldBuilder.js b/client/src/services/apiWorldBuilder.js
index d623c649d3..29bd3ed3b5 100644
--- a/client/src/services/apiWorldBuilder.js
+++ b/client/src/services/apiWorldBuilder.js
@@ -8,6 +8,11 @@ export const COMPOSITE_PROMPT_MAX = 4000;
export const WORLD_LOGLINE_MAX = 500;
export const WORLD_PREMISE_MAX = 4000;
export const WORLD_STYLE_NOTES_MAX = 4000;
+// Mirror of INFLUENCE_ENTRY_MAX + INFLUENCES_PER_LIST_MAX in
+// server/services/worldBuilder.js — used by the chip editor for maxLength
+// enforcement and to bound paste-floods of refs.
+export const WORLD_INFLUENCE_ENTRY_MAX = 120;
+export const WORLD_INFLUENCES_PER_LIST_MAX = 30;
export const listWorlds = () => request('/world-builder');
export const getWorld = (id) => request(`/world-builder/${encodeURIComponent(id)}`);
@@ -26,16 +31,55 @@ export const deleteWorld = (id) => request(`/world-builder/${encodeURIComponent(
method: 'DELETE',
});
-export const expandWorld = ({ starterPrompt, providerId, model } = {}) => request('/world-builder/expand', {
+export const expandWorld = ({
+ starterPrompt, influences,
+ preservedVariations, preservedCompositeSheets,
+ providerId, model,
+} = {}) => request('/world-builder/expand', {
method: 'POST',
- body: JSON.stringify({ starterPrompt, providerId, model }),
+ body: JSON.stringify({
+ starterPrompt, influences,
+ preservedVariations, preservedCompositeSheets,
+ providerId, model,
+ }),
});
export const refineWorldPrompts = ({
- starterPrompt, stylePrompt, negativePrompt, feedback, providerId, model,
+ starterPrompt, stylePrompt, negativePrompt,
+ logline, premise, styleNotes,
+ influences,
+ locked,
+ feedback, providerId, model,
} = {}) => request('/world-builder/refine-prompts', {
method: 'POST',
- body: JSON.stringify({ starterPrompt, stylePrompt, negativePrompt, feedback, providerId, model }),
+ body: JSON.stringify({
+ starterPrompt, stylePrompt, negativePrompt,
+ logline, premise, styleNotes,
+ influences,
+ locked,
+ feedback, providerId, model,
+ }),
+});
+
+// Mirror of LOCKABLE_FIELDS in server/services/worldBuilder.js — the lock UI
+// iterates this so a new lockable field only needs adding in two places.
+export const WORLD_LOCKABLE_FIELDS = [
+ 'starterPrompt',
+ 'stylePrompt',
+ 'negativePrompt',
+ 'logline',
+ 'premise',
+ 'styleNotes',
+ 'influences',
+];
+
+// Coerce whatever shape the server / draft / patch hands us into a strict
+// `{ embrace: [], avoid: [] }` so consumers never have to guard undefined.
+// The server has its own sanitizer (sanitizeInfluences) — this one just
+// normalizes shape on the client side.
+export const ensureInfluences = (raw) => ({
+ embrace: Array.isArray(raw?.embrace) ? raw.embrace : [],
+ avoid: Array.isArray(raw?.avoid) ? raw.avoid : [],
});
export const renderWorld = (id, options) => request(`/world-builder/${encodeURIComponent(id)}/render`, {
diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.js
index c9b7352b09..823056c2a0 100644
--- a/server/routes/worldBuilder.js
+++ b/server/routes/worldBuilder.js
@@ -41,11 +41,16 @@ const mapServiceError = (err) => {
const variationSchema = z.object({
label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),
prompt: z.string().trim().min(1).max(svc.PROMPT_FRAGMENT_MAX),
+ // Per-item lock — when true, expand preserves this variation across
+ // re-runs instead of letting the LLM regenerate it.
+ locked: z.boolean().optional(),
});
const compositeSheetSchema = z.object({
kind: z.enum(svc.COMPOSITE_SHEET_KINDS).optional(),
label: z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX),
prompt: z.string().trim().min(1).max(svc.COMPOSITE_PROMPT_MAX),
+ // Per-item lock for composite boards (same semantics as variations).
+ locked: z.boolean().optional(),
});
const categoryShape = z.object({
variations: z.array(variationSchema).max(svc.VARIATIONS_PER_CATEGORY_MAX),
@@ -62,6 +67,19 @@ const llmSchema = z.object({
model: z.string().trim().max(200).nullable().optional(),
}).optional();
+// `locked` is a sparse map of `{ field: true }` for the LOCKABLE_FIELDS list.
+// `false` is treated the same as omitted — only `true` records a lock so the
+// stored shape stays minimal and additive.
+const lockedSchema = z.object(
+ Object.fromEntries(svc.LOCKABLE_FIELDS.map((k) => [k, z.boolean().optional()])),
+).strict();
+
+const influenceEntrySchema = z.string().trim().min(1).max(svc.INFLUENCE_ENTRY_MAX);
+const influencesSchema = z.object({
+ embrace: z.array(influenceEntrySchema).max(svc.INFLUENCES_PER_LIST_MAX).optional().default([]),
+ avoid: z.array(influenceEntrySchema).max(svc.INFLUENCES_PER_LIST_MAX).optional().default([]),
+}).strict();
+
const createSchema = z.object({
name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH),
starterPrompt: z.string().trim().max(svc.STARTER_PROMPT_MAX).optional().default(''),
@@ -72,6 +90,8 @@ const createSchema = z.object({
styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),
categories: categoriesSchema.optional(),
compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
+ influences: influencesSchema.optional(),
+ locked: lockedSchema.optional(),
llm: llmSchema,
});
@@ -85,11 +105,25 @@ const patchSchema = z.object({
styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional(),
categories: categoriesSchema.optional(),
compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
+ influences: influencesSchema.optional(),
+ locked: lockedSchema.optional(),
llm: llmSchema,
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
const expandSchema = z.object({
starterPrompt: z.string().trim().min(1).max(svc.STARTER_PROMPT_MAX),
+ // Optional structured influences from a prior refinement — passed in so
+ // the LLM keeps re-expansions on-direction instead of regenerating from
+ // the bare starter idea.
+ influences: influencesSchema.optional(),
+ // Per-item locks the user has set on individual variations / composite
+ // boards. Listed in the LLM prompt so it doesn't waste tokens regenerating
+ // them; the client merges them back in after the result returns.
+ preservedVariations: z.record(
+ z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),
+ z.array(variationSchema).max(svc.VARIATIONS_PER_CATEGORY_MAX),
+ ).optional(),
+ preservedCompositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
providerId: z.string().trim().max(80).optional(),
model: z.string().trim().max(200).optional(),
});
@@ -98,6 +132,17 @@ const refinePromptsSchema = z.object({
starterPrompt: z.string().trim().min(1).max(svc.STARTER_PROMPT_MAX),
stylePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),
negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),
+ // Bible context: passed in so the refiner sees the full seed, refines them
+ // alongside the prompts, and stays consistent with the world's narrative.
+ logline: z.string().trim().max(svc.LOGLINE_MAX).optional().default(''),
+ premise: z.string().trim().max(svc.PREMISE_MAX).optional().default(''),
+ styleNotes: z.string().trim().max(svc.STYLE_NOTES_MAX).optional().default(''),
+ // Structured influences (embrace + avoid) — refined alongside the prompts
+ // and used as the canonical reference list for renderer-token composition.
+ influences: influencesSchema.optional(),
+ // Per-field lock map — locked fields are echoed back unchanged regardless
+ // of what the LLM tries to write.
+ locked: lockedSchema.optional().default({}),
feedback: z.string().trim().min(1).max(3000),
providerId: z.string().trim().max(80).optional(),
// Whitespace-only model → undefined so the refiner's defaultModel /
diff --git a/server/services/worldBuilder.js b/server/services/worldBuilder.js
index 9455ddb886..7a5c9a3e1e 100644
--- a/server/services/worldBuilder.js
+++ b/server/services/worldBuilder.js
@@ -55,6 +55,27 @@ export const COMPOSITE_SHEET_KINDS = Object.freeze([
export const WORLD_CATEGORY_KEY_MAX = 64;
export const WORLD_CATEGORY_COUNT_MAX = 30;
+// Influences — structured reference lists that deterministically inform
+// stylePrompt (embrace) and negativePrompt (avoid) at render-compile time.
+// They are the canonical record of the world's direction so re-expansions
+// inherit it; the LLM still authors the prose stylePrompt around them.
+export const INFLUENCE_ENTRY_MAX = 120;
+export const INFLUENCES_PER_LIST_MAX = 30;
+
+// Top-level fields the user can lock against AI-driven changes (refine /
+// expand). When a field is locked, both the refiner and the expansion-merge
+// must preserve the user's value verbatim. Categories + composite sheets are
+// not lockable yet — start with the bible/prompt scalars the user owns.
+export const LOCKABLE_FIELDS = Object.freeze([
+ 'starterPrompt',
+ 'stylePrompt',
+ 'negativePrompt',
+ 'logline',
+ 'premise',
+ 'styleNotes',
+ 'influences',
+]);
+
// Starter buckets the UI surfaces for a fresh world. They remain for
// compatibility, but saved templates may carry any additional sanitized
// category keys the LLM or user creates.
@@ -88,7 +109,12 @@ const sanitizeVariation = (raw) => {
const label = trimTo(raw.label, VARIATION_LABEL_MAX);
const prompt = trimTo(raw.prompt, PROMPT_FRAGMENT_MAX);
if (!label || !prompt) return null;
- return { label, prompt };
+ // Per-item lock — when true, expand merges preserve this entry instead of
+ // letting the LLM regenerate it. Only `true` is recorded; missing/false
+ // collapses to undefined so the on-disk shape stays minimal.
+ const out = { label, prompt };
+ if (raw.locked === true) out.locked = true;
+ return out;
};
const sanitizeCompositeSheet = (raw) => {
@@ -97,7 +123,9 @@ const sanitizeCompositeSheet = (raw) => {
const prompt = trimTo(raw.prompt, COMPOSITE_PROMPT_MAX);
if (!label || !prompt) return null;
const kind = COMPOSITE_SHEET_KINDS.includes(raw.kind) ? raw.kind : 'reference_sheet';
- return { kind, label, prompt };
+ const out = { kind, label, prompt };
+ if (raw.locked === true) out.locked = true;
+ return out;
};
const sanitizeCategory = (raw) => {
@@ -153,6 +181,44 @@ export const getWorldCategoryKeys = (categories = {}) => {
return keys;
};
+// Sanitize one influence list (embrace OR avoid):
+// - drop non-strings, trim, slice to per-entry cap
+// - drop empties + case-insensitive duplicates within the list
+// - cap list length
+const sanitizeInfluenceList = (raw) => {
+ if (!Array.isArray(raw)) return [];
+ const out = [];
+ const seen = new Set();
+ for (const v of raw) {
+ if (!isStr(v)) continue;
+ const trimmed = v.trim().slice(0, INFLUENCE_ENTRY_MAX);
+ if (!trimmed) continue;
+ const key = trimmed.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(trimmed);
+ if (out.length >= INFLUENCES_PER_LIST_MAX) break;
+ }
+ return out;
+};
+
+export const sanitizeInfluences = (raw = {}) => {
+ if (!raw || typeof raw !== 'object') return { embrace: [], avoid: [] };
+ return {
+ embrace: sanitizeInfluenceList(raw.embrace),
+ avoid: sanitizeInfluenceList(raw.avoid),
+ };
+};
+
+export const sanitizeLocked = (raw = {}) => {
+ if (!raw || typeof raw !== 'object') return {};
+ const out = {};
+ for (const key of LOCKABLE_FIELDS) {
+ if (raw[key] === true) out[key] = true;
+ }
+ return out;
+};
+
export const sanitizeCompositeSheets = (raw = []) => {
if (!Array.isArray(raw)) return [];
const sheets = [];
@@ -178,6 +244,8 @@ const sanitizeTemplate = (raw) => {
const styleNotes = trimTo(raw.styleNotes, STYLE_NOTES_MAX);
const categories = sanitizeCategories(raw.categories || {});
const compositeSheets = sanitizeCompositeSheets(raw.compositeSheets || []);
+ const influences = sanitizeInfluences(raw.influences);
+ const locked = sanitizeLocked(raw.locked);
const llm = raw.llm && typeof raw.llm === 'object'
? {
provider: trimTo(raw.llm.provider, 80) || null,
@@ -197,6 +265,8 @@ const sanitizeTemplate = (raw) => {
styleNotes,
categories,
compositeSheets,
+ influences,
+ locked,
llm,
createdAt,
updatedAt,
@@ -258,6 +328,8 @@ export async function createWorld(input = {}) {
styleNotes: input.styleNotes || '',
categories: input.categories || {},
compositeSheets: input.compositeSheets || [],
+ influences: input.influences || {},
+ locked: input.locked || {},
llm: input.llm || {},
createdAt: now,
updatedAt: now,
@@ -286,9 +358,19 @@ export async function updateWorld(id, patch = {}) {
? { ...(cur.llm || {}), ...(patch.llm || {}) }
: cur.llm;
+ // `locked` replaces wholesale when the patch sends it (so unticking a lock
+ // actually unlocks). Skipped when the patch omits it.
+ const mergedLocked = 'locked' in patch ? (patch.locked || {}) : (cur.locked || {});
+
+ // `influences` also replaces wholesale (each list is the user's full
+ // intended state — partial merging would leave stale entries the user
+ // thought they removed).
+ const mergedInfluences = 'influences' in patch ? (patch.influences || {}) : (cur.influences || {});
+
// Scalar fields: only apply what the patch actually carries, so a partial
// PATCH never clobbers a field the caller didn't send. `categories` + `llm`
- // are handled above (they need per-key merging, not replacement).
+ // + `locked` are handled above (they need per-key merging or wholesale
+ // replacement, not the simple scalar copy).
const PATCHABLE_SCALARS = [
'name', 'starterPrompt', 'stylePrompt', 'negativePrompt',
'logline', 'premise', 'styleNotes', 'compositeSheets',
@@ -301,6 +383,8 @@ export async function updateWorld(id, patch = {}) {
...cur,
...scalarPatch,
categories: mergedCategories,
+ influences: mergedInfluences,
+ locked: mergedLocked,
llm: mergedLlm,
updatedAt: new Date().toISOString(),
});
@@ -338,6 +422,31 @@ export async function listRuns(worldId = null) {
return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
}
+/**
+ * Compose a token string by prepending an influence list (embrace or avoid)
+ * to a free-form comma-separated prose tokens string, with case-insensitive
+ * dedupe so the LLM-authored prompt never repeats an entry the user already
+ * pinned. Used by compilePrompts so structured influences ALWAYS land in the
+ * rendered prompt regardless of whether the LLM remembered them.
+ */
+export function composeInfluenceTokens(structured = [], prose = '') {
+ const all = [];
+ if (Array.isArray(structured)) all.push(...structured);
+ if (typeof prose === 'string' && prose.trim()) {
+ all.push(...prose.split(',').map((s) => s.trim()).filter(Boolean));
+ }
+ const seen = new Set();
+ const out = [];
+ for (const token of all) {
+ if (!token) continue;
+ const key = token.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(token);
+ }
+ return out.join(', ');
+}
+
/**
* Compile the world template into an ordered list of full image-gen
* prompts. Each entry combines the world's style prompt with one
@@ -366,8 +475,8 @@ export function compilePrompts(world, options = {}) {
const batchPerVariation = Math.max(1, Math.min(20, Number(options.batchPerVariation) || 1));
const stylePreset = {
- prompt: world.stylePrompt?.trim() || '',
- negativePrompt: world.negativePrompt?.trim() || '',
+ prompt: composeInfluenceTokens(world.influences?.embrace, world.stylePrompt),
+ negativePrompt: composeInfluenceTokens(world.influences?.avoid, world.negativePrompt),
};
const compiled = [];
diff --git a/server/services/worldBuilder.test.js b/server/services/worldBuilder.test.js
index 15198e16b2..6df0eeac6e 100644
--- a/server/services/worldBuilder.test.js
+++ b/server/services/worldBuilder.test.js
@@ -1,53 +1,65 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach } from "vitest";
const fileStore = new Map();
-vi.mock('../lib/fileUtils.js', () => ({
- PATHS: { data: '/mock/data' },
+vi.mock("../lib/fileUtils.js", () => ({
+ PATHS: { data: "/mock/data" },
ensureDir: vi.fn().mockResolvedValue(undefined),
- atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),
- readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),
+ atomicWrite: vi.fn(async (path, data) => {
+ fileStore.set(path, data);
+ }),
+ readJSONFile: vi.fn(async (path, fallback) =>
+ fileStore.has(path) ? fileStore.get(path) : fallback,
+ ),
}));
let uuidCounter = 0;
-vi.mock('crypto', async () => {
- const actual = await vi.importActual('crypto');
+vi.mock("crypto", async () => {
+ const actual = await vi.importActual("crypto");
return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };
});
-const svc = await import('./worldBuilder.js');
-
-const seedWorld = async (overrides = {}) => svc.createWorld({
- name: 'Moebius SciFi',
- starterPrompt: 'moebius and scavengers reign meets prophet',
- stylePrompt: 'moebius linework, scavengers reign palette',
- negativePrompt: 'blurry, lowres',
- categories: {
- landscapes: { variations: [
- { label: 'Crystal Canyon', prompt: 'crystalline canyon, alien sun' },
- { label: 'Sand Sea', prompt: 'endless sand sea, dunes' },
- ] },
- characters: { variations: [
- { label: 'Scavenger', prompt: 'lone scavenger figure, weathered cloak' },
- ] },
- },
- ...overrides,
-});
+const svc = await import("./worldBuilder.js");
+
+const seedWorld = async (overrides = {}) =>
+ svc.createWorld({
+ name: "Moebius SciFi",
+ starterPrompt: "moebius and scavengers reign meets prophet",
+ stylePrompt: "moebius linework, scavengers reign palette",
+ negativePrompt: "blurry, lowres",
+ categories: {
+ landscapes: {
+ variations: [
+ { label: "Crystal Canyon", prompt: "crystalline canyon, alien sun" },
+ { label: "Sand Sea", prompt: "endless sand sea, dunes" },
+ ],
+ },
+ characters: {
+ variations: [
+ {
+ label: "Scavenger",
+ prompt: "lone scavenger figure, weathered cloak",
+ },
+ ],
+ },
+ },
+ ...overrides,
+ });
-describe('worldBuilder service', () => {
+describe("worldBuilder service", () => {
beforeEach(() => {
fileStore.clear();
uuidCounter = 0;
});
- it('listWorlds returns [] for fresh state', async () => {
+ it("listWorlds returns [] for fresh state", async () => {
expect(await svc.listWorlds()).toEqual([]);
});
- it('createWorld persists with sanitized categories', async () => {
+ it("createWorld persists with sanitized categories", async () => {
const w = await seedWorld();
- expect(w.id).toBe('uuid-1');
- expect(w.name).toBe('Moebius SciFi');
+ expect(w.id).toBe("uuid-1");
+ expect(w.name).toBe("Moebius SciFi");
// All five categories materialized even when only two were provided.
for (const c of svc.WORLD_CATEGORIES) {
expect(w.categories[c]).toBeDefined();
@@ -58,175 +70,257 @@ describe('worldBuilder service', () => {
expect(w.categories.environments.variations).toHaveLength(0);
});
- it('createWorld preserves custom world-building categories', async () => {
+ it("createWorld preserves custom world-building categories", async () => {
const w = await seedWorld({
categories: {
- 'Clothing Styles': { variations: [{ label: 'Rib-Cage Nomads', prompt: 'reference sheet, layered sailcloth, bone toggles' }] },
- factions: { variations: [{ label: 'Wake Jackals', prompt: 'spare raider kit, patched pressure masks' }] },
+ "Clothing Styles": {
+ variations: [
+ {
+ label: "Rib-Cage Nomads",
+ prompt: "reference sheet, layered sailcloth, bone toggles",
+ },
+ ],
+ },
+ factions: {
+ variations: [
+ {
+ label: "Wake Jackals",
+ prompt: "spare raider kit, patched pressure masks",
+ },
+ ],
+ },
},
});
expect(w.categories.clothing_styles.variations).toEqual([
- { label: 'Rib-Cage Nomads', prompt: 'reference sheet, layered sailcloth, bone toggles' },
+ {
+ label: "Rib-Cage Nomads",
+ prompt: "reference sheet, layered sailcloth, bone toggles",
+ },
]);
expect(w.categories.factions.variations).toHaveLength(1);
expect(w.categories.landscapes.variations).toHaveLength(0);
});
- it('createWorld persists composite sheet prompts separately from categories', async () => {
+ it("createWorld persists composite sheet prompts separately from categories", async () => {
const w = await seedWorld({
compositeSheets: [
- { label: 'Gas-Giant Drifters costume sheet', prompt: 'Create a clean illustrated costume reference sheet with five figures, materials swatches, fasteners, accessories, and color palette strip.' },
+ {
+ label: "Gas-Giant Drifters costume sheet",
+ prompt:
+ "Create a clean illustrated costume reference sheet with five figures, materials swatches, fasteners, accessories, and color palette strip.",
+ },
],
});
expect(w.compositeSheets).toEqual([
- { kind: 'reference_sheet', label: 'Gas-Giant Drifters costume sheet', prompt: 'Create a clean illustrated costume reference sheet with five figures, materials swatches, fasteners, accessories, and color palette strip.' },
+ {
+ kind: "reference_sheet",
+ label: "Gas-Giant Drifters costume sheet",
+ prompt:
+ "Create a clean illustrated costume reference sheet with five figures, materials swatches, fasteners, accessories, and color palette strip.",
+ },
]);
});
- it('createWorld persists world pitch poster prompts separately from categories', async () => {
+ it("createWorld persists world pitch poster prompts separately from categories", async () => {
const w = await seedWorld({
compositeSheets: [
- { kind: 'world_pitch_poster', label: 'World summary concept pitch poster', prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.' },
+ {
+ kind: "world_pitch_poster",
+ label: "World summary concept pitch poster",
+ prompt:
+ "Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.",
+ },
],
});
expect(w.compositeSheets).toEqual([
- { kind: 'world_pitch_poster', label: 'World summary concept pitch poster', prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.' },
+ {
+ kind: "world_pitch_poster",
+ label: "World summary concept pitch poster",
+ prompt:
+ "Create a cinematic world summary concept pitch poster with hero panorama, inset environments, cultures, creatures, visual language, color palette, materials, light atmosphere, and theme icons.",
+ },
]);
});
- it('createWorld rejects empty name', async () => {
- await expect(svc.createWorld({ name: '' })).rejects.toThrow(/name is required/);
+ it("createWorld rejects empty name", async () => {
+ await expect(svc.createWorld({ name: "" })).rejects.toThrow(
+ /name is required/,
+ );
});
- it('createWorld persists narrative bible fields (logline / premise / styleNotes)', async () => {
+ it("createWorld persists narrative bible fields (logline / premise / styleNotes)", async () => {
const w = await seedWorld({
- logline: 'A foundry city goes silent, and the only survivor is a child.',
- premise: 'Long-form premise paragraph about the setting, conflict, stakes, and tone.',
- styleNotes: 'Moebius linework, oil-on-canvas grain, contemplative pacing, sparse dialogue.',
+ logline: "A foundry city goes silent, and the only survivor is a child.",
+ premise:
+ "Long-form premise paragraph about the setting, conflict, stakes, and tone.",
+ styleNotes:
+ "Moebius linework, oil-on-canvas grain, contemplative pacing, sparse dialogue.",
});
- expect(w.logline).toBe('A foundry city goes silent, and the only survivor is a child.');
- expect(w.premise).toBe('Long-form premise paragraph about the setting, conflict, stakes, and tone.');
- expect(w.styleNotes).toBe('Moebius linework, oil-on-canvas grain, contemplative pacing, sparse dialogue.');
+ expect(w.logline).toBe(
+ "A foundry city goes silent, and the only survivor is a child.",
+ );
+ expect(w.premise).toBe(
+ "Long-form premise paragraph about the setting, conflict, stakes, and tone.",
+ );
+ expect(w.styleNotes).toBe(
+ "Moebius linework, oil-on-canvas grain, contemplative pacing, sparse dialogue.",
+ );
});
- it('updateWorld patches narrative bible fields independently of categories', async () => {
- const w = await seedWorld({ logline: 'original logline' });
+ it("updateWorld patches narrative bible fields independently of categories", async () => {
+ const w = await seedWorld({ logline: "original logline" });
const patched = await svc.updateWorld(w.id, {
- logline: 'new logline',
- premise: 'new premise',
- styleNotes: 'new style notes',
+ logline: "new logline",
+ premise: "new premise",
+ styleNotes: "new style notes",
});
- expect(patched.logline).toBe('new logline');
- expect(patched.premise).toBe('new premise');
- expect(patched.styleNotes).toBe('new style notes');
+ expect(patched.logline).toBe("new logline");
+ expect(patched.premise).toBe("new premise");
+ expect(patched.styleNotes).toBe("new style notes");
// Untouched (existing) data preserved.
expect(patched.categories.landscapes.variations).toHaveLength(2);
expect(patched.stylePrompt).toBe(w.stylePrompt);
});
- it('createWorld trims bible fields to their max length', async () => {
+ it("createWorld trims bible fields to their max length", async () => {
const w = await seedWorld({
- logline: 'x'.repeat(svc.LOGLINE_MAX + 50),
- premise: 'y'.repeat(svc.PREMISE_MAX + 50),
- styleNotes: 'z'.repeat(svc.STYLE_NOTES_MAX + 50),
+ logline: "x".repeat(svc.LOGLINE_MAX + 50),
+ premise: "y".repeat(svc.PREMISE_MAX + 50),
+ styleNotes: "z".repeat(svc.STYLE_NOTES_MAX + 50),
});
expect(w.logline).toHaveLength(svc.LOGLINE_MAX);
expect(w.premise).toHaveLength(svc.PREMISE_MAX);
expect(w.styleNotes).toHaveLength(svc.STYLE_NOTES_MAX);
});
- it('updateWorld merges partial patches', async () => {
+ it("updateWorld merges partial patches", async () => {
const w = await seedWorld();
- const patched = await svc.updateWorld(w.id, { name: 'Renamed', stylePrompt: 'new style' });
- expect(patched.name).toBe('Renamed');
- expect(patched.stylePrompt).toBe('new style');
+ const patched = await svc.updateWorld(w.id, {
+ name: "Renamed",
+ stylePrompt: "new style",
+ });
+ expect(patched.name).toBe("Renamed");
+ expect(patched.stylePrompt).toBe("new style");
// Untouched fields preserved.
expect(patched.starterPrompt).toBe(w.starterPrompt);
expect(patched.categories.landscapes.variations).toHaveLength(2);
});
- it('updateWorld throws NOT_FOUND for unknown id', async () => {
- await expect(svc.updateWorld('no-such', { name: 'X' })).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ it("updateWorld throws NOT_FOUND for unknown id", async () => {
+ await expect(
+ svc.updateWorld("no-such", { name: "X" }),
+ ).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
- it('deleteWorld removes the world and its runs', async () => {
+ it("deleteWorld removes the world and its runs", async () => {
const w = await seedWorld();
await svc.recordRun({
- id: 'run-1', worldId: w.id, collectionId: 'col-1', jobIds: ['j1'], promptCount: 3,
+ id: "run-1",
+ worldId: w.id,
+ collectionId: "col-1",
+ jobIds: ["j1"],
+ promptCount: 3,
});
- expect((await svc.listRuns(w.id))).toHaveLength(1);
+ expect(await svc.listRuns(w.id)).toHaveLength(1);
await svc.deleteWorld(w.id);
expect(await svc.listWorlds()).toEqual([]);
expect(await svc.listRuns(w.id)).toEqual([]);
});
- describe('compilePrompts', () => {
- it('returns one prompt per variation across selected categories with style prefix', async () => {
+ describe("compilePrompts", () => {
+ it("returns one prompt per variation across selected categories with style prefix", async () => {
const w = await seedWorld();
const compiled = svc.compilePrompts(w);
// 2 landscapes + 1 character = 3 (other categories empty)
expect(compiled).toHaveLength(3);
// Style prefix uses `. ` separator (composeStyledPrompt convention,
// shared with the scenePrompt composer in the client).
- expect(compiled[0].prompt).toBe('moebius linework, scavengers reign palette. crystalline canyon, alien sun');
- expect(compiled[0].category).toBe('landscapes');
- expect(compiled[0].label).toBe('Crystal Canyon');
- expect(compiled[0].negativePrompt).toBe('blurry, lowres');
+ expect(compiled[0].prompt).toBe(
+ "moebius linework, scavengers reign palette. crystalline canyon, alien sun",
+ );
+ expect(compiled[0].category).toBe("landscapes");
+ expect(compiled[0].label).toBe("Crystal Canyon");
+ expect(compiled[0].negativePrompt).toBe("blurry, lowres");
});
- it('includes custom categories by default', async () => {
+ it("includes custom categories by default", async () => {
const w = await seedWorld({
categories: {
- colonies: { variations: [{ label: 'Canopy Symbiotes', prompt: 'leaf-fiber clothing reference sheet, sap resin closures' }] },
+ colonies: {
+ variations: [
+ {
+ label: "Canopy Symbiotes",
+ prompt:
+ "leaf-fiber clothing reference sheet, sap resin closures",
+ },
+ ],
+ },
},
});
const compiled = svc.compilePrompts(w);
expect(compiled).toHaveLength(1);
expect(compiled[0]).toMatchObject({
- category: 'colonies',
- label: 'Canopy Symbiotes',
+ category: "colonies",
+ label: "Canopy Symbiotes",
});
});
- it('respects batchPerVariation', async () => {
+ it("respects batchPerVariation", async () => {
const w = await seedWorld();
const compiled = svc.compilePrompts(w, { batchPerVariation: 3 });
expect(compiled).toHaveLength(9); // 3 variations × 3 batch
- expect(compiled.filter((c) => c.label === 'Crystal Canyon')).toHaveLength(3);
+ expect(compiled.filter((c) => c.label === "Crystal Canyon")).toHaveLength(
+ 3,
+ );
});
- it('selection: array filters by label (case-insensitive)', async () => {
+ it("selection: array filters by label (case-insensitive)", async () => {
const w = await seedWorld();
const compiled = svc.compilePrompts(w, {
- selection: { landscapes: ['crystal canyon'], characters: 'all' },
+ selection: { landscapes: ["crystal canyon"], characters: "all" },
});
// 1 landscape (filtered) + 1 character (all) = 2
expect(compiled).toHaveLength(2);
- expect(compiled.map((c) => c.label).sort()).toEqual(['Crystal Canyon', 'Scavenger']);
+ expect(compiled.map((c) => c.label).sort()).toEqual([
+ "Crystal Canyon",
+ "Scavenger",
+ ]);
});
- it('selection: missing key skips category', async () => {
+ it("selection: missing key skips category", async () => {
const w = await seedWorld();
- const compiled = svc.compilePrompts(w, { selection: { landscapes: 'all' } });
+ const compiled = svc.compilePrompts(w, {
+ selection: { landscapes: "all" },
+ });
expect(compiled).toHaveLength(2);
- expect(compiled.every((c) => c.category === 'landscapes')).toBe(true);
+ expect(compiled.every((c) => c.category === "landscapes")).toBe(true);
});
- it('selection supports custom category keys', async () => {
+ it("selection supports custom category keys", async () => {
const w = await seedWorld({
categories: {
- raider_clans: { variations: [
- { label: 'Wake Jackals', prompt: 'clean scavenger raider outfit board' },
- { label: 'Hull Vultures', prompt: 'pressure-ring pirate boarding gear' },
- ] },
+ raider_clans: {
+ variations: [
+ {
+ label: "Wake Jackals",
+ prompt: "clean scavenger raider outfit board",
+ },
+ {
+ label: "Hull Vultures",
+ prompt: "pressure-ring pirate boarding gear",
+ },
+ ],
+ },
},
});
- const compiled = svc.compilePrompts(w, { selection: { raider_clans: ['wake jackals'] } });
+ const compiled = svc.compilePrompts(w, {
+ selection: { raider_clans: ["wake jackals"] },
+ });
expect(compiled).toHaveLength(1);
- expect(compiled[0].label).toBe('Wake Jackals');
+ expect(compiled[0].label).toBe("Wake Jackals");
});
- it('clamps batchPerVariation to 1..20', async () => {
+ it("clamps batchPerVariation to 1..20", async () => {
const w = await seedWorld();
// 0 → 1
expect(svc.compilePrompts(w, { batchPerVariation: 0 })).toHaveLength(3);
@@ -235,75 +329,271 @@ describe('worldBuilder service', () => {
expect(big).toHaveLength(60); // 3 × 20
});
- it('can compile composite sheets without atomic variations', async () => {
+ it("can compile composite sheets without atomic variations", async () => {
const w = await seedWorld({
categories: {},
compositeSheets: [
- { label: 'Canopy Symbiotes sheet', prompt: 'clean costume reference sheet, lineup, materials, fasteners, palette' },
- { label: 'Gas-Giant Drifters sheet', prompt: 'clean costume reference sheet, pressure collars, clips, palette' },
+ {
+ label: "Canopy Symbiotes sheet",
+ prompt:
+ "clean costume reference sheet, lineup, materials, fasteners, palette",
+ },
+ {
+ label: "Gas-Giant Drifters sheet",
+ prompt:
+ "clean costume reference sheet, pressure collars, clips, palette",
+ },
],
});
- const compiled = svc.compilePrompts(w, { promptMode: 'sheets' });
+ const compiled = svc.compilePrompts(w, { promptMode: "sheets" });
expect(compiled).toHaveLength(2);
expect(compiled[0]).toMatchObject({
- category: 'composite_sheets',
- label: 'Canopy Symbiotes sheet',
- prompt: 'moebius linework, scavengers reign palette. clean costume reference sheet, lineup, materials, fasteners, palette',
+ category: "composite_sheets",
+ label: "Canopy Symbiotes sheet",
+ prompt:
+ "moebius linework, scavengers reign palette. clean costume reference sheet, lineup, materials, fasteners, palette",
});
});
- it('tags world pitch poster prompts separately from reference sheets', async () => {
+ it("tags world pitch poster prompts separately from reference sheets", async () => {
const w = await seedWorld({
categories: {},
compositeSheets: [
- { kind: 'world_pitch_poster', label: 'World pitch poster', prompt: 'cinematic world summary pitch poster, hero panorama, inset cultures, palette, themes' },
+ {
+ kind: "world_pitch_poster",
+ label: "World pitch poster",
+ prompt:
+ "cinematic world summary pitch poster, hero panorama, inset cultures, palette, themes",
+ },
],
});
- const compiled = svc.compilePrompts(w, { promptMode: 'sheets' });
+ const compiled = svc.compilePrompts(w, { promptMode: "sheets" });
expect(compiled).toHaveLength(1);
expect(compiled[0]).toMatchObject({
- category: 'world_pitch_posters',
- label: 'World pitch poster',
+ category: "world_pitch_posters",
+ label: "World pitch poster",
});
});
- it('can compile atomic variations and composite sheets together', async () => {
+ it("can compile atomic variations and composite sheets together", async () => {
const w = await seedWorld({
compositeSheets: [
- { label: 'Gas-Giant Drifters sheet', prompt: 'clean costume reference sheet, pressure collars, clips, palette' },
+ {
+ label: "Gas-Giant Drifters sheet",
+ prompt:
+ "clean costume reference sheet, pressure collars, clips, palette",
+ },
],
});
- const compiled = svc.compilePrompts(w, { promptMode: 'all' });
+ const compiled = svc.compilePrompts(w, { promptMode: "all" });
expect(compiled).toHaveLength(4); // 3 atomic variations + 1 composite
- expect(compiled.map((p) => p.category)).toContain('composite_sheets');
+ expect(compiled.map((p) => p.category)).toContain("composite_sheets");
});
});
- describe('sanitizers', () => {
- it('drops malformed variations on read', async () => {
+ describe("influences", () => {
+ it("round-trips embrace + avoid lists through createWorld", async () => {
+ const w = await seedWorld({
+ influences: {
+ embrace: ["Moebius", "cel-shading"],
+ avoid: ["Ghibli painterly", "neon cyberpunk"],
+ },
+ });
+ expect(w.influences.embrace).toEqual(["Moebius", "cel-shading"]);
+ expect(w.influences.avoid).toEqual([
+ "Ghibli painterly",
+ "neon cyberpunk",
+ ]);
+ });
+
+ it("dedupes influences case-insensitively, trims, drops empties + invalid types", async () => {
+ const w = await seedWorld({
+ influences: {
+ embrace: ["Moebius", "moebius", " cel-shading ", "", 42, null],
+ avoid: ["Ghibli", "ghibli"],
+ },
+ });
+ expect(w.influences.embrace).toEqual(["Moebius", "cel-shading"]);
+ expect(w.influences.avoid).toEqual(["Ghibli"]);
+ });
+
+ it("defaults to empty lists when influences is missing or invalid", async () => {
+ const w = await seedWorld({ influences: undefined });
+ expect(w.influences).toEqual({ embrace: [], avoid: [] });
+ const w2 = await seedWorld({
+ name: "second",
+ influences: "not-an-object",
+ });
+ expect(w2.influences).toEqual({ embrace: [], avoid: [] });
+ });
+
+ it("caps influence lists at INFLUENCES_PER_LIST_MAX", async () => {
+ const tooMany = Array.from(
+ { length: svc.INFLUENCES_PER_LIST_MAX + 12 },
+ (_, i) => `ref-${i}`,
+ );
+ const w = await seedWorld({
+ influences: { embrace: tooMany, avoid: [] },
+ });
+ expect(w.influences.embrace).toHaveLength(svc.INFLUENCES_PER_LIST_MAX);
+ });
+
+ it("updateWorld replaces influence lists wholesale (does not merge)", async () => {
+ const w = await seedWorld({
+ influences: { embrace: ["A", "B"], avoid: ["X"] },
+ });
+ const patched = await svc.updateWorld(w.id, {
+ influences: { embrace: ["C"] },
+ });
+ // Wholesale replace: avoid is gone because the patch didn't carry it.
+ expect(patched.influences.embrace).toEqual(["C"]);
+ expect(patched.influences.avoid).toEqual([]);
+ });
+
+ it("compilePrompts deterministically prepends embrace to prompt + avoid to negative, deduped", async () => {
+ const w = await seedWorld({
+ // stylePrompt already mentions one of the embraces — dedupe should
+ // ensure it doesn't appear twice in the rendered prompt.
+ stylePrompt: "cel-shading, ink, dust palette",
+ negativePrompt: "lowres",
+ influences: {
+ embrace: ["Moebius", "cel-shading"],
+ avoid: ["ghibli painterly", "lowres"],
+ },
+ });
+ const compiled = svc.compilePrompts(w, {
+ selection: { landscapes: ["Crystal Canyon"] },
+ });
+ expect(compiled).toHaveLength(1);
+ // Embrace tokens prefix the existing style tokens; the duplicate
+ // "cel-shading" only appears once.
+ expect(
+ compiled[0].prompt.startsWith(
+ "Moebius, cel-shading, ink, dust palette",
+ ),
+ ).toBe(true);
+ expect((compiled[0].prompt.match(/cel-shading/g) || []).length).toBe(1);
+ // Negative: avoid tokens prefix existing negatives, deduped against "lowres".
+ expect(
+ compiled[0].negativePrompt.startsWith("ghibli painterly, lowres"),
+ ).toBe(true);
+ expect((compiled[0].negativePrompt.match(/lowres/g) || []).length).toBe(
+ 1,
+ );
+ });
+ });
+
+ describe("per-item locks", () => {
+ it("round-trips a `locked: true` flag on variations", async () => {
+ const w = await seedWorld({
+ categories: {
+ landscapes: {
+ variations: [
+ {
+ label: "Pinned canyon",
+ prompt: "pinned canyon prompt",
+ locked: true,
+ },
+ { label: "Open canyon", prompt: "open canyon prompt" },
+ ],
+ },
+ },
+ });
+ const vs = w.categories.landscapes.variations;
+ expect(vs.find((v) => v.label === "Pinned canyon").locked).toBe(true);
+ expect(vs.find((v) => v.label === "Open canyon").locked).toBeUndefined();
+ });
+
+ it("drops non-true `locked` values rather than recording them", async () => {
+ const w = await seedWorld({
+ categories: {
+ landscapes: {
+ variations: [
+ { label: "A", prompt: "a", locked: false },
+ { label: "B", prompt: "b", locked: "yes" },
+ { label: "C", prompt: "c", locked: 1 },
+ ],
+ },
+ },
+ });
+ const labels = Object.fromEntries(
+ w.categories.landscapes.variations.map((v) => [v.label, v.locked]),
+ );
+ expect(labels.A).toBeUndefined();
+ expect(labels.B).toBeUndefined();
+ expect(labels.C).toBeUndefined();
+ });
+
+ it("round-trips a `locked: true` flag on composite sheets", async () => {
+ const w = await seedWorld({
+ compositeSheets: [
+ {
+ label: "Pinned poster",
+ prompt: "pinned poster prompt long enough",
+ kind: "world_pitch_poster",
+ locked: true,
+ },
+ { label: "Open sheet", prompt: "open sheet prompt long enough" },
+ ],
+ });
+ expect(
+ w.compositeSheets.find((s) => s.label === "Pinned poster").locked,
+ ).toBe(true);
+ expect(
+ w.compositeSheets.find((s) => s.label === "Open sheet").locked,
+ ).toBeUndefined();
+ });
+ });
+
+ describe("locked", () => {
+ it("round-trips a sparse lock map and replaces wholesale on patch", async () => {
+ const w = await seedWorld({
+ locked: { logline: true, influences: true },
+ });
+ expect(w.locked).toEqual({ logline: true, influences: true });
+ const patched = await svc.updateWorld(w.id, {
+ locked: { styleNotes: true },
+ });
+ expect(patched.locked).toEqual({ styleNotes: true });
+ });
+
+ it("ignores non-true / unknown lock keys", async () => {
+ const w = await seedWorld({
+ locked: { logline: false, bogus: true, premise: true },
+ });
+ expect(w.locked).toEqual({ premise: true });
+ });
+ });
+
+ describe("sanitizers", () => {
+ it("drops malformed variations on read", async () => {
// Manually plant invalid state — sanitizeTemplate strips it on read.
- fileStore.set('/mock/data/world-builder.json', {
- worlds: [{
- id: 'w1',
- name: 'X',
- starterPrompt: '',
- stylePrompt: '',
- negativePrompt: '',
- categories: {
- landscapes: { variations: [
- { label: 'Good', prompt: 'good prompt' },
- { label: '', prompt: 'no label' },
- { label: 'No prompt', prompt: '' },
- null,
- ] },
+ fileStore.set("/mock/data/world-builder.json", {
+ worlds: [
+ {
+ id: "w1",
+ name: "X",
+ starterPrompt: "",
+ stylePrompt: "",
+ negativePrompt: "",
+ categories: {
+ landscapes: {
+ variations: [
+ { label: "Good", prompt: "good prompt" },
+ { label: "", prompt: "no label" },
+ { label: "No prompt", prompt: "" },
+ null,
+ ],
+ },
+ },
+ createdAt: "2024-01-01T00:00:00Z",
},
- createdAt: '2024-01-01T00:00:00Z',
- }],
+ ],
runs: [],
});
const list = await svc.listWorlds();
expect(list[0].categories.landscapes.variations).toHaveLength(1);
- expect(list[0].categories.landscapes.variations[0].label).toBe('Good');
+ expect(list[0].categories.landscapes.variations[0].label).toBe("Good");
});
});
});
diff --git a/server/services/worldBuilderExpand.js b/server/services/worldBuilderExpand.js
index 2ab950097e..204fef7ff0 100644
--- a/server/services/worldBuilderExpand.js
+++ b/server/services/worldBuilderExpand.js
@@ -11,7 +11,7 @@
* model so the UI still works for users who haven't configured a stage.
*/
-import { getActiveProvider, getProviderById } from './providers.js';
+import { getActiveProvider, getProviderById } from "./providers.js";
import {
WORLD_CATEGORIES,
PROMPT_FRAGMENT_MAX,
@@ -22,28 +22,76 @@ import {
STYLE_NOTES_MAX,
sanitizeCategories,
sanitizeCompositeSheets,
-} from './worldBuilder.js';
-import { ServerError } from '../lib/errorHandler.js';
-import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';
-import { resolveEffectiveModel, runPromptThroughProvider } from '../lib/promptRunner.js';
+ sanitizeInfluences,
+} from "./worldBuilder.js";
+import { ServerError } from "../lib/errorHandler.js";
+import { extractJson as extractJsonShared } from "../lib/jsonExtract.js";
+import {
+ resolveEffectiveModel,
+ runPromptThroughProvider,
+} from "../lib/promptRunner.js";
const LABEL_MAX = 80;
-const EXPANSION_PROMPT = `You are a world-building prompt engineer for a Stable-Diffusion-style image generation pipeline AND a story-bible drafter for a comic/TV production pipeline. You will turn the user's starter idea into (a) a structured prompt set that produces a visually consistent universe across many renders, and (b) a short narrative bible that downstream writing stages can ingest.
+function buildExpansionPrompt({
+ starterPrompt,
+ influences,
+ preservedVariations,
+ preservedCompositeSheets,
+}) {
+ const embrace = Array.isArray(influences?.embrace)
+ ? influences.embrace.filter(Boolean)
+ : [];
+ const avoid = Array.isArray(influences?.avoid)
+ ? influences.avoid.filter(Boolean)
+ : [];
+ const influencesSection =
+ embrace.length || avoid.length
+ ? `\n# Influences (canonical reference list — these MUST inform stylePrompt + styleNotes for embraces and negativePrompt for avoids)\nEmbrace: ${embrace.join(", ") || "(none)"}\nAvoid: ${avoid.join(", ") || "(none)"}\n`
+ : "";
-# Starter idea
-{starterPrompt}
+ // Preserved items: the client extracted user-pinned variations and
+ // composite boards. List them by category + label so the LLM can avoid
+ // generating duplicates, but tell it explicitly NOT to echo them in its
+ // output (the client merges them back in).
+ const preservedVariationLines = [];
+ if (preservedVariations && typeof preservedVariations === "object") {
+ for (const [cat, list] of Object.entries(preservedVariations)) {
+ if (!Array.isArray(list) || list.length === 0) continue;
+ for (const v of list) {
+ if (!v || !v.label) continue;
+ preservedVariationLines.push(`- ${cat}: "${v.label}"`);
+ }
+ }
+ }
+ const preservedSheetLines = Array.isArray(preservedCompositeSheets)
+ ? preservedCompositeSheets
+ .filter((s) => s && s.label)
+ .map((s) => `- ${s.kind || "reference_sheet"}: "${s.label}"`)
+ : [];
+
+ const preservedSection =
+ preservedVariationLines.length || preservedSheetLines.length
+ ? `\n# Preserved items — DO NOT regenerate these labels (the user has pinned them; the client preserves them on merge)
+${preservedVariationLines.length ? `Pinned variations:\n${preservedVariationLines.join("\n")}\n` : ""}${preservedSheetLines.length ? `Pinned composite boards:\n${preservedSheetLines.join("\n")}\n` : ""}`
+ : "";
+ return `You are a world-building prompt engineer for a Stable-Diffusion-style image generation pipeline AND a story-bible drafter for a comic/TV production pipeline. You will turn the user's starter idea into (a) a structured prompt set that produces a visually consistent universe across many renders, and (b) a short narrative bible that downstream writing stages can ingest.
+
+# Starter idea
+${starterPrompt}
+${influencesSection}${preservedSection}
# Output contract
Return a SINGLE JSON object. NO markdown, NO commentary. The object MUST have these top-level keys:
- logline: string. ONE sentence (≤500 chars) capturing the world's central tension/hook — protagonist-agnostic if no protagonist is implied. Example: "A foundry city goes silent — and the only survivor is a child."
- premise: string. 1-3 short paragraphs (≤4000 chars total) describing the setting, the central conflict or situation, the stakes, and the tone. Write it as the elevator pitch a showrunner would hand to a writers' room. No bullet points; prose only.
- styleNotes: string. A prose paragraph (≤4000 chars) describing the visual + tonal style for the story bible — references (artists, films, comics, games), mood, palette, pacing, narrative voice. This is read by writers + creative directors, not the image model, so use full sentences instead of comma-separated tokens.
-- stylePrompt: string. A single comma-separated style fragment (lighting, color palette, render quality, artist references) that will be PREFIXED to every variation prompt. Keep under 400 characters. No subject nouns — those go in variations.
-- negativePrompt: string. Comma-separated tokens to avoid (e.g. "blurry, lowres, watermark, extra fingers"). Tailor to the world's aesthetic.
+- influences: object { "embrace": [string], "avoid": [string] }. Short canonical reference labels (max 120 chars each, max 30 per list) — artists, comics, films, directors, palettes, materials, eras the world EMBRACES; styles, tropes, palettes the world AVOIDS. The renderer prepends these to stylePrompt/negativePrompt verbatim, so each entry should read as a clean prompt token (e.g. "Moebius", "cel-shading", "Ghibli painterly", "neon cyberpunk"). When influence input is provided above, preserve those entries unless the starter idea explicitly contradicts them.
+- stylePrompt: string. A single comma-separated style fragment (lighting, color palette, render quality, artist references) that will be PREFIXED to every variation prompt. Keep under 400 characters. No subject nouns — those go in variations. Echo the embrace influences here so the renderer-side prompt is self-contained even before the structured prepend kicks in.
+- negativePrompt: string. Comma-separated tokens to avoid (e.g. "blurry, lowres, watermark, extra fingers"). Tailor to the world's aesthetic. Echo the avoid influences here.
- categories: object. Atomic reusable buckets. Use snake_case keys. Start from these common buckets when useful:
-${WORLD_CATEGORIES.map((c) => ` - ${c}`).join('\n')}
+${WORLD_CATEGORIES.map((c) => ` - ${c}`).join("\n")}
Add, remove, or rename buckets to fit the user's actual world-building task. Do not force every project into the starter buckets.
Useful extra buckets include colonies, factions, tribes, species, cultures, clothing_styles, material_palettes, fasteners_and_closures, tools, rituals, raider_clans, vehicles, settlements, and artifacts.
- compositeSheets: array. Complete, ready-to-render composite board prompts. Each item has { "kind": "reference_sheet" | "world_pitch_poster", "label": string, "prompt": string up to 4000 chars }. These are NOT atomic fragments; each prompt must describe one complete board/poster that combines multiple buckets into a single image.
@@ -73,6 +121,7 @@ Concrete compositeSheets examples:
- World pitch poster prompts must include a clear editorial poster structure: world title/subtitle/logline area, dominant hero panorama, inset environment/culture/creature images, visual-language strip, color palette, materials/textures, light/atmosphere, themes/icons, and concise labeled blocks for world, feel, aesthetic, environments, cultures, and tone. Mention that body copy should be short, clean, and readable; avoid dense tiny text.
- If the world needs pitch posters, do not put "text" in the negativePrompt. Prefer "watermark, logo, unreadable tiny text, text artifacts" so title/section typography remains possible.
- Output JUST the JSON object. No prose before or after.`;
+}
// Prefer a block that *looks like* a world-expansion response (has any of
// stylePrompt / negativePrompt / categories / compositeSheets at the top
@@ -80,31 +129,39 @@ Concrete compositeSheets examples:
// { "label": "Crystalline canyon basin", "prompt": "…" }
// which parse cleanly but aren't the response. Without the shape preference
// we'd return that first valid-but-wrong object and end up with 0 variations.
-const isExpansionShape = (o) => o && typeof o === 'object'
- && (typeof o.stylePrompt === 'string'
- || typeof o.negativePrompt === 'string'
- || typeof o.logline === 'string'
- || typeof o.premise === 'string'
- || typeof o.styleNotes === 'string'
- || (o.categories && typeof o.categories === 'object')
- || Array.isArray(o.compositeSheets));
+const isExpansionShape = (o) =>
+ o &&
+ typeof o === "object" &&
+ (typeof o.stylePrompt === "string" ||
+ typeof o.negativePrompt === "string" ||
+ typeof o.logline === "string" ||
+ typeof o.premise === "string" ||
+ typeof o.styleNotes === "string" ||
+ (o.influences && typeof o.influences === "object") ||
+ (o.categories && typeof o.categories === "object") ||
+ Array.isArray(o.compositeSheets));
const extractJson = (raw) => {
// Empty input is a "client-side" oversight (no LLM output at all) — keep
// the original raw Error so callers / tests that key on the message
// continue to match. Down-stream JSON parse failures are wrapped in a
// typed 502 ServerError so the route layer surfaces a useful HTTP code.
- if (!raw || typeof raw !== 'string') throw new Error('Empty LLM response');
+ if (!raw || typeof raw !== "string") throw new Error("Empty LLM response");
const { value, lastError, lastPreview } = extractJsonShared(raw, {
shapePredicate: isExpansionShape,
});
if (value !== undefined) return value;
throw new ServerError(
- 'LLM returned invalid JSON for world expansion. Try a different model or rerun.',
+ "LLM returned invalid JSON for world expansion. Try a different model or rerun.",
{
status: 502,
- code: 'LLM_INVALID_JSON',
- context: { details: { reason: lastError?.message || 'no JSON object found', preview: lastPreview || '' } },
+ code: "LLM_INVALID_JSON",
+ context: {
+ details: {
+ reason: lastError?.message || "no JSON object found",
+ preview: lastPreview || "",
+ },
+ },
},
);
};
@@ -116,7 +173,7 @@ const normalizeCategories = (raw) => {
// (e.g. colonies, factions, clothing_styles) instead of forcing everything
// into the starter categories.
const out = {};
- const rawEntries = raw && typeof raw === 'object' ? Object.entries(raw) : [];
+ const rawEntries = raw && typeof raw === "object" ? Object.entries(raw) : [];
for (const [key, node] of rawEntries) {
let variations = [];
if (Array.isArray(node)) variations = node;
@@ -124,34 +181,47 @@ const normalizeCategories = (raw) => {
out[key] = {
// Clamp to the same per-category cap the route schema enforces (50)
// so a runaway LLM response can't bloat /expand output.
- variations: variations.slice(0, VARIATIONS_PER_CATEGORY_MAX).map((v) => {
- if (typeof v === 'string') {
- const trimmed = v.trim();
- return {
- label: trimmed.slice(0, LABEL_MAX),
- prompt: trimmed.slice(0, PROMPT_FRAGMENT_MAX),
- };
- }
- const label = typeof v?.label === 'string' ? v.label.trim().slice(0, LABEL_MAX) : '';
- const prompt = typeof v?.prompt === 'string' ? v.prompt.trim().slice(0, PROMPT_FRAGMENT_MAX) : '';
- return { label, prompt };
- }).filter((v) => v.label && v.prompt),
+ variations: variations
+ .slice(0, VARIATIONS_PER_CATEGORY_MAX)
+ .map((v) => {
+ if (typeof v === "string") {
+ const trimmed = v.trim();
+ return {
+ label: trimmed.slice(0, LABEL_MAX),
+ prompt: trimmed.slice(0, PROMPT_FRAGMENT_MAX),
+ };
+ }
+ const label =
+ typeof v?.label === "string"
+ ? v.label.trim().slice(0, LABEL_MAX)
+ : "";
+ const prompt =
+ typeof v?.prompt === "string"
+ ? v.prompt.trim().slice(0, PROMPT_FRAGMENT_MAX)
+ : "";
+ return { label, prompt };
+ })
+ .filter((v) => v.label && v.prompt),
};
}
return sanitizeCategories(out);
};
-const normalizeCompositeSheets = (raw) => sanitizeCompositeSheets(
- Array.isArray(raw)
- ? raw.map((sheet) => {
- if (typeof sheet === 'string') {
- const trimmed = sheet.trim();
- return { label: trimmed.slice(0, LABEL_MAX), prompt: trimmed.slice(0, COMPOSITE_PROMPT_MAX) };
- }
- return sheet;
- })
- : [],
-);
+const normalizeCompositeSheets = (raw) =>
+ sanitizeCompositeSheets(
+ Array.isArray(raw)
+ ? raw.map((sheet) => {
+ if (typeof sheet === "string") {
+ const trimmed = sheet.trim();
+ return {
+ label: trimmed.slice(0, LABEL_MAX),
+ prompt: trimmed.slice(0, COMPOSITE_PROMPT_MAX),
+ };
+ }
+ return sheet;
+ })
+ : [],
+ );
/**
* Expand a starter prompt into a structured world template draft.
@@ -162,14 +232,27 @@ const normalizeCompositeSheets = (raw) => sanitizeCompositeSheets(
* @param {string} [options.providerId] — optional override; falls back to active.
* @param {string} [options.model] — optional override; falls back to provider default.
*/
-export async function expandWorldTemplate({ starterPrompt, providerId, model } = {}) {
+export async function expandWorldTemplate({
+ starterPrompt,
+ influences,
+ preservedVariations = {},
+ preservedCompositeSheets = [],
+ providerId,
+ model,
+} = {}) {
if (!starterPrompt || !starterPrompt.trim()) {
- throw new Error('starterPrompt is required');
+ throw new Error("starterPrompt is required");
}
+ // Sanitize so a careless caller can't push out-of-cap influence labels into
+ // the LLM prompt or the returned result. Empty / missing → empty lists.
+ const safeInfluences = sanitizeInfluences(influences);
- let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;
+ let provider = providerId
+ ? await getProviderById(providerId).catch(() => null)
+ : null;
if (!provider) provider = await getActiveProvider();
- if (!provider) throw new Error('No AI provider available for world expansion');
+ if (!provider)
+ throw new Error("No AI provider available for world expansion");
// resolveEffectiveModel mirrors what promptRunner resolves internally
// so the log line below + the returned `llm.model` field reflect what
// actually executed. For CLI providers with a baked --model/-m flag
@@ -177,8 +260,23 @@ export async function expandWorldTemplate({ starterPrompt, providerId, model } =
// which can diverge).
const selectedModel = resolveEffectiveModel(provider, model);
- const fullPrompt = EXPANSION_PROMPT.replace('{starterPrompt}', starterPrompt.trim());
- console.log(`🌍 World Builder expanding via ${provider.name}/${selectedModel || 'default'}`);
+ const fullPrompt = buildExpansionPrompt({
+ starterPrompt: starterPrompt.trim(),
+ influences: safeInfluences,
+ preservedVariations,
+ preservedCompositeSheets,
+ });
+ const totalIn = safeInfluences.embrace.length + safeInfluences.avoid.length;
+ const preservedVarCount = Object.values(preservedVariations || {}).reduce(
+ (n, list) => n + (Array.isArray(list) ? list.length : 0),
+ 0,
+ );
+ const preservedSheetCount = Array.isArray(preservedCompositeSheets)
+ ? preservedCompositeSheets.length
+ : 0;
+ console.log(
+ `🌍 World Builder expanding via ${provider.name}/${selectedModel || "default"} — influences in: ${totalIn ? `embrace=${safeInfluences.embrace.length} avoid=${safeInfluences.avoid.length}` : "none"} preserved: variations=${preservedVarCount} sheets=${preservedSheetCount}`,
+ );
// runId is logged so a user debugging an empty expansion can find the
// raw stdout at data/runs/<runId>/output.txt.
@@ -186,28 +284,53 @@ export async function expandWorldTemplate({ starterPrompt, providerId, model } =
provider,
model: selectedModel,
prompt: fullPrompt,
- source: 'world-builder-expansion',
+ source: "world-builder-expansion",
});
// Log raw response shape so a "0 variations" outcome is debuggable from
// the server console alone — the runId points at data/runs/<id>/output.txt
// for the full transcript.
- console.log(`🌍 World Builder raw response — runId=${runId} length=${raw?.length || 0}`);
+ console.log(
+ `🌍 World Builder raw response — runId=${runId} length=${raw?.length || 0}`,
+ );
const parsed = extractJson(raw);
- console.log(`🌍 World Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(',')}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(',')}] compositeSheets=${Array.isArray(parsed?.compositeSheets) ? parsed.compositeSheets.length : 0}`);
+ console.log(
+ `🌍 World Builder parsed JSON — keys=[${Object.keys(parsed || {}).join(",")}] categoryKeys=[${Object.keys(parsed?.categories || {}).join(",")}] compositeSheets=${Array.isArray(parsed?.compositeSheets) ? parsed.compositeSheets.length : 0}`,
+ );
- const trimField = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
+ const trimField = (value, max) =>
+ typeof value === "string" ? value.trim().slice(0, max) : "";
const stylePrompt = trimField(parsed.stylePrompt, PROMPT_FRAGMENT_MAX);
const negativePrompt = trimField(parsed.negativePrompt, PROMPT_FRAGMENT_MAX);
const logline = trimField(parsed.logline, LOGLINE_MAX);
const premise = trimField(parsed.premise, PREMISE_MAX);
const styleNotes = trimField(parsed.styleNotes, STYLE_NOTES_MAX);
const categories = normalizeCategories(parsed.categories || {});
- const compositeSheets = normalizeCompositeSheets(parsed.compositeSheets || []);
- const perCat = Object.keys(categories).map((k) => `${k}=${categories[k]?.variations?.length || 0}`).join(' ');
- const totalVariations = Object.values(categories).reduce((n, c) => n + (c?.variations?.length || 0), 0);
- console.log(`🌍 World Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, bible=${logline ? 'yes' : 'no'} (${perCat})`);
+ const compositeSheets = normalizeCompositeSheets(
+ parsed.compositeSheets || [],
+ );
+ // sanitizeInfluences enforces the same per-entry cap, list cap, and
+ // case-insensitive dedupe used everywhere else; falls back to the input
+ // influences when the LLM omits them so the user's pinned references
+ // don't silently disappear on the first expansion that misses the field.
+ const llmInfluences = sanitizeInfluences(parsed.influences);
+ const influencesOut =
+ llmInfluences.embrace.length || llmInfluences.avoid.length
+ ? llmInfluences
+ : safeInfluences;
+ const perCat = Object.keys(categories)
+ .map((k) => `${k}=${categories[k]?.variations?.length || 0}`)
+ .join(" ");
+ const totalVariations = Object.values(categories).reduce(
+ (n, c) => n + (c?.variations?.length || 0),
+ 0,
+ );
+ console.log(
+ `🌍 World Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, bible=${logline ? "yes" : "no"} (${perCat})`,
+ );
if (totalVariations === 0 && compositeSheets.length === 0) {
- console.warn(`⚠️ World Builder expansion produced 0 variations — inspect data/runs/${runId}/output.txt for the raw LLM response`);
+ console.warn(
+ `⚠️ World Builder expansion produced 0 variations — inspect data/runs/${runId}/output.txt for the raw LLM response`,
+ );
}
return {
@@ -216,6 +339,7 @@ export async function expandWorldTemplate({ starterPrompt, providerId, model } =
styleNotes,
stylePrompt,
negativePrompt,
+ influences: influencesOut,
categories,
compositeSheets,
llm: { provider: provider.id, model: selectedModel || null },
@@ -223,4 +347,9 @@ export async function expandWorldTemplate({ starterPrompt, providerId, model } =
}
// Export for tests.
-export const __testing = { extractJson, normalizeCategories, normalizeCompositeSheets, EXPANSION_PROMPT };
+export const __testing = {
+ extractJson,
+ normalizeCategories,
+ normalizeCompositeSheets,
+ buildExpansionPrompt,
+};
diff --git a/server/services/worldBuilderExpand.test.js b/server/services/worldBuilderExpand.test.js
index 642de63df9..f27e74140d 100644
--- a/server/services/worldBuilderExpand.test.js
+++ b/server/services/worldBuilderExpand.test.js
@@ -1,251 +1,328 @@
-import { describe, it, expect } from 'vitest';
-import { __testing } from './worldBuilderExpand.js';
-import { WORLD_CATEGORIES } from './worldBuilder.js';
+import { describe, it, expect } from "vitest";
+import { __testing } from "./worldBuilderExpand.js";
+import { WORLD_CATEGORIES } from "./worldBuilder.js";
-const { extractJson, normalizeCategories, normalizeCompositeSheets, EXPANSION_PROMPT } = __testing;
+const {
+ extractJson,
+ normalizeCategories,
+ normalizeCompositeSheets,
+ buildExpansionPrompt,
+} = __testing;
+// Anchor the legacy assertions on the static body of the prompt — the only
+// dynamic substitutions are the starter idea + (optional) influences section.
+const EXPANSION_PROMPT = buildExpansionPrompt({
+ starterPrompt: "fixture starter",
+});
-describe('worldBuilderExpand.extractJson', () => {
- it('parses a raw JSON object', () => {
- const obj = { stylePrompt: 'a, b, c', negativePrompt: 'blur', categories: {} };
+describe("worldBuilderExpand.extractJson", () => {
+ it("parses a raw JSON object", () => {
+ const obj = {
+ stylePrompt: "a, b, c",
+ negativePrompt: "blur",
+ categories: {},
+ };
expect(extractJson(JSON.stringify(obj))).toEqual(obj);
});
- it('strips ```json fences', () => {
+ it("strips ```json fences", () => {
const fenced = '```json\n{"stylePrompt":"x","categories":{}}\n```';
- expect(extractJson(fenced)).toEqual({ stylePrompt: 'x', categories: {} });
+ expect(extractJson(fenced)).toEqual({ stylePrompt: "x", categories: {} });
});
- it('strips bare ``` fences', () => {
+ it("strips bare ``` fences", () => {
const fenced = '```\n{"stylePrompt":"x"}\n```';
- expect(extractJson(fenced)).toEqual({ stylePrompt: 'x' });
+ expect(extractJson(fenced)).toEqual({ stylePrompt: "x" });
});
- it('skips a preamble before the first { … } block', () => {
- const raw = 'Here is the JSON you asked for:\n{"stylePrompt":"x","negativePrompt":"y"}\nHope this helps!';
- expect(extractJson(raw)).toEqual({ stylePrompt: 'x', negativePrompt: 'y' });
+ it("skips a preamble before the first { … } block", () => {
+ const raw =
+ 'Here is the JSON you asked for:\n{"stylePrompt":"x","negativePrompt":"y"}\nHope this helps!';
+ expect(extractJson(raw)).toEqual({ stylePrompt: "x", negativePrompt: "y" });
});
- it('rejects empty / non-string input', () => {
- expect(() => extractJson('')).toThrow(/Empty LLM response/);
+ it("rejects empty / non-string input", () => {
+ expect(() => extractJson("")).toThrow(/Empty LLM response/);
expect(() => extractJson(null)).toThrow(/Empty LLM response/);
expect(() => extractJson(undefined)).toThrow(/Empty LLM response/);
});
- it('throws when no JSON object can be parsed', () => {
- expect(() => extractJson('totally bogus output, no braces')).toThrow();
- expect(() => extractJson('{ this is not valid json')).toThrow();
+ it("throws when no JSON object can be parsed", () => {
+ expect(() => extractJson("totally bogus output, no braces")).toThrow();
+ expect(() => extractJson("{ this is not valid json")).toThrow();
});
- it('replaces literal [...] placeholders with empty arrays so the rest parses', () => {
- const raw = '{"stylePrompt":"x","categories":{"vehicles":{"variations":[...]}}}';
+ it("replaces literal [...] placeholders with empty arrays so the rest parses", () => {
+ const raw =
+ '{"stylePrompt":"x","categories":{"vehicles":{"variations":[...]}}}';
const out = extractJson(raw);
- expect(out.stylePrompt).toBe('x');
+ expect(out.stylePrompt).toBe("x");
expect(out.categories.vehicles.variations).toEqual([]);
});
- it('skips a pseudo-JSON schema example in echoed prompt and parses the real response (Codex CLI)', () => {
+ it("skips a pseudo-JSON schema example in echoed prompt and parses the real response (Codex CLI)", () => {
// Codex CLI echoes the user prompt back to stdout before printing the model's
// response. The prompt contains a JSON-shaped schema example using bare
// identifiers as placeholder values — its braces balance but its contents
// are not valid JSON. Earlier extractJson grabbed the first balanced block
// and crashed; it should now fall through to the next block.
const raw = [
- 'OpenAI Codex v0.128.0 (research preview)',
- '--------',
- 'workdir: /tmp',
- '--------',
- 'user',
+ "OpenAI Codex v0.128.0 (research preview)",
+ "--------",
+ "workdir: /tmp",
+ "--------",
+ "user",
'Each variation has the shape { "label": string (max 80 chars), "prompt": string (max 400 chars, comma-separated tokens describing ONE specific subject) }.',
- 'codex',
+ "codex",
'{"stylePrompt":"x","negativePrompt":"y","categories":{"vehicles":{"variations":[{"label":"a","prompt":"b"}]}}}',
- 'tokens used',
- '2,787',
- ].join('\n');
+ "tokens used",
+ "2,787",
+ ].join("\n");
const out = extractJson(raw);
- expect(out.stylePrompt).toBe('x');
- expect(out.negativePrompt).toBe('y');
- expect(out.categories.vehicles.variations).toEqual([{ label: 'a', prompt: 'b' }]);
+ expect(out.stylePrompt).toBe("x");
+ expect(out.negativePrompt).toBe("y");
+ expect(out.categories.vehicles.variations).toEqual([
+ { label: "a", prompt: "b" },
+ ]);
});
- it('repairs Codex CLI orphan-brace corruption (`}}]` → `}]`) inside the response', () => {
+ it("repairs Codex CLI orphan-brace corruption (`}}]` → `}]`) inside the response", () => {
// Real-world: Codex produced `{"label":"...","prompt":"…blister"}}]}}}`
// — an extra `}` snuck in between the variation's close-brace and the
// array's `]`. extractJson must recover that to a parsed expansion shape.
- const badJson = '{"stylePrompt":"x","categories":{"vehicles":{"variations":[{"label":"a","prompt":"…blister"}}]}}}';
+ const badJson =
+ '{"stylePrompt":"x","categories":{"vehicles":{"variations":[{"label":"a","prompt":"…blister"}}]}}}';
const out = extractJson(badJson);
- expect(out.stylePrompt).toBe('x');
- expect(out.categories.vehicles.variations).toEqual([{ label: 'a', prompt: '…blister' }]);
+ expect(out.stylePrompt).toBe("x");
+ expect(out.categories.vehicles.variations).toEqual([
+ { label: "a", prompt: "…blister" },
+ ]);
});
- it('strips a trailing comma before `]` (common LLM mistake)', () => {
- const raw = '{"stylePrompt":"x","categories":{"landscapes":{"variations":[{"label":"a","prompt":"b"},]}}}';
+ it("strips a trailing comma before `]` (common LLM mistake)", () => {
+ const raw =
+ '{"stylePrompt":"x","categories":{"landscapes":{"variations":[{"label":"a","prompt":"b"},]}}}';
const out = extractJson(raw);
- expect(out.categories.landscapes.variations).toEqual([{ label: 'a', prompt: 'b' }]);
+ expect(out.categories.landscapes.variations).toEqual([
+ { label: "a", prompt: "b" },
+ ]);
});
- it('prefers a world-expansion-shaped object over an in-prompt JSON example', () => {
+ it("prefers a world-expansion-shaped object over an in-prompt JSON example", () => {
// The actual prompt template includes literal JSON example variations:
// { "label": "Crystalline canyon basin", "prompt": "…" }
// These are valid JSON and brace-balance cleanly, but they aren't the
// response. extractJson must skip them and return the larger object that
// has the world-expansion top-level keys.
const raw = [
- 'codex',
+ "codex",
'{ "label": "Crystalline canyon basin", "prompt": "vast crystalline canyon, salt flats" }',
'{ "label": "Scrap-iron dune sea", "prompt": "rolling dunes of rusted scrap" }',
- 'codex',
+ "codex",
'{"stylePrompt":"painterly","categories":{"landscapes":{"variations":[{"label":"Real","prompt":"real prompt"}]}}}',
- ].join('\n');
+ ].join("\n");
const out = extractJson(raw);
- expect(out.stylePrompt).toBe('painterly');
- expect(out.categories.landscapes.variations).toEqual([{ label: 'Real', prompt: 'real prompt' }]);
+ expect(out.stylePrompt).toBe("painterly");
+ expect(out.categories.landscapes.variations).toEqual([
+ { label: "Real", prompt: "real prompt" },
+ ]);
});
- it('wraps a JSON.parse failure in a 502 LLM_INVALID_JSON ServerError (no raw 500)', () => {
+ it("wraps a JSON.parse failure in a 502 LLM_INVALID_JSON ServerError (no raw 500)", () => {
let thrown;
- try { extractJson('{ "stylePrompt": "x", "broken'); } catch (e) { thrown = e; }
+ try {
+ extractJson('{ "stylePrompt": "x", "broken');
+ } catch (e) {
+ thrown = e;
+ }
expect(thrown).toBeDefined();
expect(thrown.status).toBe(502);
- expect(thrown.code).toBe('LLM_INVALID_JSON');
- expect(thrown.context?.details?.preview).toContain('broken');
+ expect(thrown.code).toBe("LLM_INVALID_JSON");
+ expect(thrown.context?.details?.preview).toContain("broken");
});
});
-describe('worldBuilderExpand.normalizeCategories', () => {
- it('returns all canonical categories with empty variations on empty input', () => {
+describe("worldBuilderExpand.normalizeCategories", () => {
+ it("returns all canonical categories with empty variations on empty input", () => {
const out = normalizeCategories({});
for (const key of WORLD_CATEGORIES) {
expect(out[key]).toEqual({ variations: [] });
}
});
- it('coerces a flat array of strings into label/prompt pairs', () => {
+ it("coerces a flat array of strings into label/prompt pairs", () => {
const out = normalizeCategories({
- landscapes: ['Crystalline canyon basin', 'Salt flat ruins'],
+ landscapes: ["Crystalline canyon basin", "Salt flat ruins"],
});
expect(out.landscapes.variations).toEqual([
- { label: 'Crystalline canyon basin', prompt: 'Crystalline canyon basin' },
- { label: 'Salt flat ruins', prompt: 'Salt flat ruins' },
+ { label: "Crystalline canyon basin", prompt: "Crystalline canyon basin" },
+ { label: "Salt flat ruins", prompt: "Salt flat ruins" },
]);
});
- it('truncates long string-shape labels at 80 chars', () => {
- const longText = 'x'.repeat(200);
+ it("truncates long string-shape labels at 80 chars", () => {
+ const longText = "x".repeat(200);
const out = normalizeCategories({ characters: [longText] });
expect(out.characters.variations[0].label).toHaveLength(80);
expect(out.characters.variations[0].prompt).toBe(longText);
});
- it('accepts the canonical { variations: [{label,prompt}] } shape', () => {
+ it("accepts the canonical { variations: [{label,prompt}] } shape", () => {
const out = normalizeCategories({
- vehicles: { variations: [{ label: 'Walker mech', prompt: 'rusted six-leg walker mech' }] },
+ vehicles: {
+ variations: [
+ { label: "Walker mech", prompt: "rusted six-leg walker mech" },
+ ],
+ },
});
expect(out.vehicles.variations).toEqual([
- { label: 'Walker mech', prompt: 'rusted six-leg walker mech' },
+ { label: "Walker mech", prompt: "rusted six-leg walker mech" },
]);
});
- it('drops malformed variations with missing label or prompt', () => {
+ it("drops malformed variations with missing label or prompt", () => {
const out = normalizeCategories({
structures: {
variations: [
- { label: 'Tower', prompt: 'spire of obsidian' }, // keep
- { label: '', prompt: 'no label' }, // drop
- { label: 'No prompt', prompt: '' }, // drop
- { label: 42, prompt: 'numeric label' }, // drop (label not string)
- null, // drop
+ { label: "Tower", prompt: "spire of obsidian" }, // keep
+ { label: "", prompt: "no label" }, // drop
+ { label: "No prompt", prompt: "" }, // drop
+ { label: 42, prompt: "numeric label" }, // drop (label not string)
+ null, // drop
],
},
});
expect(out.structures.variations).toEqual([
- { label: 'Tower', prompt: 'spire of obsidian' },
+ { label: "Tower", prompt: "spire of obsidian" },
]);
});
- it('preserves custom categories beyond WORLD_CATEGORIES', () => {
+ it("preserves custom categories beyond WORLD_CATEGORIES", () => {
const out = normalizeCategories({
- landscapes: { variations: [{ label: 'A', prompt: 'a' }] },
- 'Raider / Pirate Clans': { variations: [{ label: 'Wake Jackals', prompt: 'spare moebius scavenger raiders' }] },
+ landscapes: { variations: [{ label: "A", prompt: "a" }] },
+ "Raider / Pirate Clans": {
+ variations: [
+ { label: "Wake Jackals", prompt: "spare moebius scavenger raiders" },
+ ],
+ },
});
expect(out.landscapes.variations).toHaveLength(1);
expect(out.raider_pirate_clans.variations).toEqual([
- { label: 'Wake Jackals', prompt: 'spare moebius scavenger raiders' },
+ { label: "Wake Jackals", prompt: "spare moebius scavenger raiders" },
]);
});
- it('treats a non-object category as empty variations (not a crash)', () => {
- const out = normalizeCategories({ characters: 'not an object' });
+ it("treats a non-object category as empty variations (not a crash)", () => {
+ const out = normalizeCategories({ characters: "not an object" });
expect(out.characters).toEqual({ variations: [] });
});
});
-describe('worldBuilderExpand.normalizeCompositeSheets', () => {
- it('keeps complete composite reference-sheet prompts', () => {
+describe("worldBuilderExpand.normalizeCompositeSheets", () => {
+ it("keeps complete composite reference-sheet prompts", () => {
const out = normalizeCompositeSheets([
{
- label: 'Gas-Giant Drifters costume sheet',
- prompt: 'Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, color palette strip, and simple floating-platform background.',
+ label: "Gas-Giant Drifters costume sheet",
+ prompt:
+ "Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, color palette strip, and simple floating-platform background.",
},
]);
expect(out).toEqual([
{
- kind: 'reference_sheet',
- label: 'Gas-Giant Drifters costume sheet',
- prompt: 'Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, color palette strip, and simple floating-platform background.',
+ kind: "reference_sheet",
+ label: "Gas-Giant Drifters costume sheet",
+ prompt:
+ "Create a clean illustrated costume reference sheet with five figures, material swatches, fasteners, accessories, color palette strip, and simple floating-platform background.",
},
]);
});
- it('coerces string sheets into label/prompt pairs', () => {
- const out = normalizeCompositeSheets(['Canopy Symbiotes reference board']);
+ it("coerces string sheets into label/prompt pairs", () => {
+ const out = normalizeCompositeSheets(["Canopy Symbiotes reference board"]);
expect(out).toEqual([
- { kind: 'reference_sheet', label: 'Canopy Symbiotes reference board', prompt: 'Canopy Symbiotes reference board' },
+ {
+ kind: "reference_sheet",
+ label: "Canopy Symbiotes reference board",
+ prompt: "Canopy Symbiotes reference board",
+ },
]);
});
- it('preserves world pitch poster board kind', () => {
+ it("preserves world pitch poster board kind", () => {
const out = normalizeCompositeSheets([
{
- kind: 'world_pitch_poster',
- label: 'World summary concept pitch poster',
- prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.',
+ kind: "world_pitch_poster",
+ label: "World summary concept pitch poster",
+ prompt:
+ "Create a cinematic world summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.",
},
]);
expect(out).toEqual([
{
- kind: 'world_pitch_poster',
- label: 'World summary concept pitch poster',
- prompt: 'Create a cinematic world summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.',
+ kind: "world_pitch_poster",
+ label: "World summary concept pitch poster",
+ prompt:
+ "Create a cinematic world summary concept pitch poster with hero panorama, inset environments, culture callouts, palette, materials, light atmosphere, and theme icons.",
},
]);
});
- it('falls back to reference_sheet for unknown kinds', () => {
+ it("falls back to reference_sheet for unknown kinds", () => {
const out = normalizeCompositeSheets([
- { kind: 'bogus_kind', label: 'Mystery board', prompt: 'A board of unknown lineage with figures, palette, materials, and atmosphere.' },
+ {
+ kind: "bogus_kind",
+ label: "Mystery board",
+ prompt:
+ "A board of unknown lineage with figures, palette, materials, and atmosphere.",
+ },
]);
- expect(out[0].kind).toBe('reference_sheet');
+ expect(out[0].kind).toBe("reference_sheet");
});
});
-describe('worldBuilderExpand.EXPANSION_PROMPT', () => {
- it('allows dynamic world-building buckets and reference-sheet domains', () => {
- expect(EXPANSION_PROMPT).toContain('Add, remove, or rename buckets');
- expect(EXPANSION_PROMPT).toContain('colonies, factions, tribes, species');
- expect(EXPANSION_PROMPT).toContain('clothing guides');
- expect(EXPANSION_PROMPT).toContain('raider_clans');
- expect(EXPANSION_PROMPT).toContain('compositeSheets');
- expect(EXPANSION_PROMPT).toContain('world_pitch_poster');
- expect(EXPANSION_PROMPT).toContain('world summary concept pitch poster');
- expect(EXPANSION_PROMPT).toContain('materials swatches');
+describe("worldBuilderExpand.EXPANSION_PROMPT", () => {
+ it("allows dynamic world-building buckets and reference-sheet domains", () => {
+ expect(EXPANSION_PROMPT).toContain("Add, remove, or rename buckets");
+ expect(EXPANSION_PROMPT).toContain("colonies, factions, tribes, species");
+ expect(EXPANSION_PROMPT).toContain("clothing guides");
+ expect(EXPANSION_PROMPT).toContain("raider_clans");
+ expect(EXPANSION_PROMPT).toContain("compositeSheets");
+ expect(EXPANSION_PROMPT).toContain("world_pitch_poster");
+ expect(EXPANSION_PROMPT).toContain("world summary concept pitch poster");
+ expect(EXPANSION_PROMPT).toContain("materials swatches");
});
- it('asks the LLM to emit a narrative bible (logline / premise / styleNotes)', () => {
+ it("asks the LLM to emit a narrative bible (logline / premise / styleNotes)", () => {
// The pipeline pulls these straight into the New Series form, so the
// contract has to stay in the prompt. If this assertion fails, double-
// check that worldBuilderExpand.js still hydrates the three fields too.
- expect(EXPANSION_PROMPT).toContain('logline:');
- expect(EXPANSION_PROMPT).toContain('premise:');
- expect(EXPANSION_PROMPT).toContain('styleNotes:');
+ expect(EXPANSION_PROMPT).toContain("logline:");
+ expect(EXPANSION_PROMPT).toContain("premise:");
+ expect(EXPANSION_PROMPT).toContain("styleNotes:");
+ });
+
+ it("asks the LLM to emit structured influences alongside the prose prompts", () => {
+ // The renderer prepends embrace / avoid lists deterministically, so the
+ // schema contract must instruct the LLM to populate them.
+ expect(EXPANSION_PROMPT).toContain("influences:");
+ expect(EXPANSION_PROMPT).toContain('"embrace"');
+ expect(EXPANSION_PROMPT).toContain('"avoid"');
+ });
+
+ it("omits the Influences input section when no influences are provided", () => {
+ const out = buildExpansionPrompt({ starterPrompt: "seed" });
+ expect(out).not.toContain("# Influences");
+ });
+
+ it("embeds provided influences as starter context", () => {
+ const out = buildExpansionPrompt({
+ starterPrompt: "seed",
+ influences: {
+ embrace: ["Moebius", "cel-shading"],
+ avoid: ["Ghibli painterly"],
+ },
+ });
+ expect(out).toContain("# Influences");
+ expect(out).toContain("Embrace: Moebius, cel-shading");
+ expect(out).toContain("Avoid: Ghibli painterly");
});
});
diff --git a/server/services/worldBuilderRefine.js b/server/services/worldBuilderRefine.js
index 89598cf8a8..14df032c40 100644
--- a/server/services/worldBuilderRefine.js
+++ b/server/services/worldBuilderRefine.js
@@ -11,37 +11,46 @@
* overwrite the draft, so the LLM never silently mutates a saved world.
*/
-import { ServerError } from '../lib/errorHandler.js';
-import { getActiveProvider, getProviderById } from './providers.js';
-import { createRun, executeApiRun, executeCliRun } from './runner.js';
-import { resolveEffectiveModel } from '../lib/promptRunner.js';
+import { ServerError } from "../lib/errorHandler.js";
+import { getActiveProvider, getProviderById } from "./providers.js";
+import { createRun, executeApiRun, executeCliRun } from "./runner.js";
+import { resolveEffectiveModel } from "../lib/promptRunner.js";
import {
+ LOCKABLE_FIELDS,
+ LOGLINE_MAX,
+ PREMISE_MAX,
PROMPT_FRAGMENT_MAX,
STARTER_PROMPT_MAX,
-} from './worldBuilder.js';
+ STYLE_NOTES_MAX,
+ sanitizeInfluences,
+ sanitizeLocked,
+} from "./worldBuilder.js";
const MAX_FEEDBACK = 3000;
const MAX_RATIONALE = 1200;
const MAX_CHANGES = 8;
const trimTo = (value, max) =>
- typeof value === 'string' ? value.trim().slice(0, max) : '';
+ typeof value === "string" ? value.trim().slice(0, max) : "";
-const cleanChanges = (changes) => (
+const cleanChanges = (changes) =>
Array.isArray(changes)
- ? changes.map((c) => trimTo(c, 240)).filter(Boolean).slice(0, MAX_CHANGES)
- : []
-);
+ ? changes
+ .map((c) => trimTo(c, 240))
+ .filter(Boolean)
+ .slice(0, MAX_CHANGES)
+ : [];
// Same brace-walker as mediaPromptRefiner: Codex CLI echoes the prompt to
// stdout before the model response, and the prompt itself contains a JSON
// schema example whose braces balance but whose contents are placeholder
// text. Walk every brace-balanced block in order and return the first that
// looks like a refinement payload (object with a `starterPrompt` string).
-const isPlaceholder = (s) => typeof s === 'string' && /^\s*<.+>\s*$/.test(s);
+const isPlaceholder = (s) => typeof s === "string" && /^\s*<.+>\s*$/.test(s);
function extractRefinementJson(raw) {
- if (typeof raw !== 'string' || !raw.trim()) throw new Error('Empty AI response');
+ if (typeof raw !== "string" || !raw.trim())
+ throw new Error("Empty AI response");
let s = raw.trim();
const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
if (fence) s = fence[1].trim();
@@ -50,7 +59,7 @@ function extractRefinementJson(raw) {
let lastErr;
let placeholderSeen = false;
while (i < s.length) {
- const start = s.indexOf('{', i);
+ const start = s.indexOf("{", i);
if (start === -1) break;
let depth = 0;
let inString = false;
@@ -60,66 +69,166 @@ function extractRefinementJson(raw) {
const ch = s[j];
if (inString) {
if (escaped) escaped = false;
- else if (ch === '\\') escaped = true;
+ else if (ch === "\\") escaped = true;
else if (ch === '"') inString = false;
continue;
}
- if (ch === '"') { inString = true; continue; }
- if (ch === '{') depth += 1;
- else if (ch === '}') {
+ if (ch === '"') {
+ inString = true;
+ continue;
+ }
+ if (ch === "{") depth += 1;
+ else if (ch === "}") {
depth -= 1;
- if (depth === 0) { end = j; break; }
+ if (depth === 0) {
+ end = j;
+ break;
+ }
}
}
if (end === -1) break;
const block = s.slice(start, end + 1);
try {
const value = JSON.parse(block);
- if (value && typeof value === 'object' && typeof value.starterPrompt === 'string') {
- if (isPlaceholder(value.starterPrompt)) { placeholderSeen = true; }
- else return value;
+ if (
+ value &&
+ typeof value === "object" &&
+ typeof value.starterPrompt === "string"
+ ) {
+ if (isPlaceholder(value.starterPrompt)) {
+ placeholderSeen = true;
+ } else return value;
}
- } catch (e) { lastErr = e; }
+ } catch (e) {
+ lastErr = e;
+ }
i = end + 1;
}
if (placeholderSeen) {
- throw new Error('AI returned the schema placeholder instead of a real refinement — try a stronger model or rerun');
+ throw new Error(
+ "AI returned the schema placeholder instead of a real refinement — try a stronger model or rerun",
+ );
}
- throw new Error(`Invalid JSON in AI response${lastErr ? `: ${lastErr.message}` : ''}`);
+ throw new Error(
+ `Invalid JSON in AI response${lastErr ? `: ${lastErr.message}` : ""}`,
+ );
+}
+
+// Field labels surfaced to the LLM so the "DO NOT MODIFY" list reads naturally.
+const FIELD_LABELS = {
+ starterPrompt: "starter idea",
+ stylePrompt: "style prompt",
+ negativePrompt: "negative prompt",
+ logline: "logline",
+ premise: "premise",
+ styleNotes: "style notes",
+ influences: "influences (embrace + avoid)",
+};
+
+const lockedList = (locked) =>
+ LOCKABLE_FIELDS.filter((k) => locked && locked[k] === true).map(
+ (k) => `- ${FIELD_LABELS[k]} ("${k}")`,
+ );
+
+/**
+ * Collapse multiple `Style direction:` blocks within the starter prompt into
+ * one — keep the LAST occurrence (the latest refinement). We instruct the LLM
+ * to maintain a single trailing block, but defense-in-depth here ensures the
+ * starter never grows unboundedly across repeated refinements.
+ *
+ * Matches a heading-style line beginning with "Style direction:" (any case),
+ * including the body text that follows up to the next heading or end of input.
+ */
+export function collapseStyleDirectionDupes(starter) {
+ if (typeof starter !== "string" || !starter) return "";
+ const re =
+ /(?:^|\n)\s*Style direction:[\s\S]*?(?=(?:\n\s*Style direction:)|$)/gi;
+ const matches = starter.match(re);
+ if (!matches || matches.length <= 1) return starter;
+ const stripped = starter.replace(re, "").trim();
+ const last = matches[matches.length - 1].trim();
+ return `${stripped}\n\n${last}`.trim();
}
-export function buildWorldRefinePrompt({ starterPrompt, stylePrompt, negativePrompt, feedback }) {
- return `You are a senior world-building prompt editor for a Stable-Diffusion-style image-generation pipeline.
+export function buildWorldRefinePrompt({
+ starterPrompt,
+ stylePrompt,
+ negativePrompt,
+ logline = "",
+ premise = "",
+ styleNotes = "",
+ influences = { embrace: [], avoid: [] },
+ locked = {},
+ feedback,
+}) {
+ const lockedRules = lockedList(locked);
+ const lockedSection = lockedRules.length
+ ? `LOCKED FIELDS — DO NOT MODIFY (the user has pinned these; echo them back UNCHANGED in the JSON output, do not rewrite a single word):
+${lockedRules.join("\n")}
+
+`
+ : "";
+
+ const embrace = Array.isArray(influences?.embrace) ? influences.embrace : [];
+ const avoid = Array.isArray(influences?.avoid) ? influences.avoid : [];
-The user has three top-level prompts that define a "world": a STARTER IDEA (the high-concept seed), a STYLE PROMPT (visual style fragment prepended to every render — palette, lighting, render quality, artist references), and a NEGATIVE PROMPT (tokens to avoid). They have given feedback about the story concept, mood, style, design, or any aspect of the world they want refined.
+ return `You are a senior world-building editor for a Stable-Diffusion-style image-generation pipeline AND a story-bible drafter for a comic/TV production pipeline.
-Rewrite all three prompts so they more faithfully express the user's intention. Output the COMPLETE rewritten text for each — not a placeholder, not a summary, not a diff.
+The user has seven top-level fields that define a "world":
+- STARTER IDEA — the high-concept seed the world expander fans out into categories.
+- STYLE PROMPT — comma-separated visual style tokens prepended to every render (palette, lighting, render quality, artist references).
+- NEGATIVE PROMPT — comma-separated tokens to avoid in renders.
+- LOGLINE — one-sentence narrative hook.
+- PREMISE — 1-3 paragraph elevator pitch (setting, conflict, stakes, tone).
+- STYLE NOTES — narrative-side prose about references, mood, palette, pacing, voice.
+- INFLUENCES — structured { embrace: [string], avoid: [string] } reference list. The renderer prepends embrace verbatim to the style prompt and avoid verbatim to the negative prompt, so this is the canonical record of "what direction is this world pointing." Each entry is a short prompt-token-style label (e.g. "Moebius", "cel-shading", "Ghibli painterly"). Max 30 entries per list, max 120 chars each.
-Return ONLY valid JSON in this schema (replace every <…> with real content; do NOT output the literal angle-bracket text):
+The user has given feedback about the story, mood, style, or design they want refined. Rewrite ALL seven fields so they more faithfully express the user's intention and stay internally consistent. Output the COMPLETE rewritten text/values for each — not a placeholder, not a summary, not a diff.
+
+${lockedSection}Return ONLY valid JSON in this schema (replace every <…> with real content; do NOT output the literal angle-bracket text):
{
- "starterPrompt": "<full rewritten high-concept starter idea, 1-3 sentences, ready to feed back into the world expander>",
- "stylePrompt": "<full rewritten style fragment, comma-separated tokens, no subject nouns — palette, lighting, render quality, artist references>",
- "negativePrompt": "<full rewritten negative prompt, comma-separated tokens to avoid; empty string if none>",
+ "starterPrompt": "<full rewritten high-concept starter idea, 1-3 sentences. Stays a clean seed — do NOT append style direction prose here, that belongs in influences + styleNotes>",
+ "stylePrompt": "<full rewritten style fragment, comma-separated tokens, no subject nouns — palette, lighting, render quality, artist references; should echo the embrace influences>",
+ "negativePrompt": "<full rewritten negative prompt, comma-separated tokens to avoid; empty string if none; should echo the avoid influences>",
+ "logline": "<full rewritten one-sentence narrative hook>",
+ "premise": "<full rewritten 1-3 paragraph elevator pitch>",
+ "styleNotes": "<full rewritten narrative-style prose about references, mood, palette, pacing, voice>",
+ "influences": { "embrace": ["<short reference label>", "..."], "avoid": ["<short reference label>", "..."] },
"rationale": "<one concise sentence explaining the overall edit>",
"changes": ["<short bullet of what changed and why>"]
}
Rules:
- Preserve story/character/world DNA from the originals unless the user's feedback explicitly contradicts it.
-- The "starterPrompt" should remain a seed — the high-concept hook the world expander will fan out into categories. Do not list category content (landscapes, factions, etc.) here.
-- The "stylePrompt" must be comma-separated visual-style tokens only. No subject nouns. No camera/aspect tokens. Under 400 characters.
-- The "negativePrompt" must be comma-separated tokens. If the world relies on text/typography (e.g. pitch posters), avoid putting "text" in negatives — prefer "watermark, logo, unreadable tiny text, text artifacts".
-- Apply the user's feedback decisively. If they ask for a different style/mood/era, move toward it in the style prompt AND name the things to avoid in the negative prompt.
-- The "starterPrompt" field must NEVER equal the schema placeholder text — it must be the actual rewritten seed.
-
+- The "starterPrompt" stays a clean high-concept seed — no category content (landscapes, factions, etc.) and no style-direction prose. The structured "influences" field carries that direction so re-expansions inherit it deterministically.
+- The "stylePrompt" must be comma-separated visual-style tokens only. No subject nouns. No camera/aspect tokens. Under 400 characters. It SHOULD echo every "embrace" influence so the prompt is self-contained even before the structured prepend kicks in.
+- The "negativePrompt" must be comma-separated tokens. It SHOULD echo every "avoid" influence. If the world relies on text/typography (e.g. pitch posters), avoid putting "text" in negatives — prefer "watermark, logo, unreadable tiny text, text artifacts".
+- The "influences" lists are the canonical reference set. Add what the user's feedback embraces, drop what's no longer relevant, and add explicit avoids for things they're moving away from. Keep entries short (a name, a movement, a palette descriptor) — they're prepended verbatim to the renderer prompt.
+- The "logline", "premise", and "styleNotes" must stay narratively coherent with the refined influences and style prompts.
+- Apply the user's feedback decisively. If they ask for a different style/mood/era, move toward it in influences + style prompt + styleNotes, and name the things to avoid in negativePrompt + influences.avoid.
+- No field may equal the schema placeholder text — output real rewritten content for every key.
+${lockedRules.length ? "- Any field listed under LOCKED FIELDS above must be returned EXACTLY as the original — do not reword, expand, or trim it. The server will discard any change to a locked field, but echoing the original keeps the JSON consistent.\n" : ""}
ORIGINAL STARTER IDEA:
-${starterPrompt || '(empty)'}
+${starterPrompt || "(empty)"}
ORIGINAL STYLE PROMPT:
-${stylePrompt || '(empty)'}
+${stylePrompt || "(empty)"}
ORIGINAL NEGATIVE PROMPT:
-${negativePrompt || '(empty)'}
+${negativePrompt || "(empty)"}
+
+ORIGINAL LOGLINE:
+${logline || "(empty)"}
+
+ORIGINAL PREMISE:
+${premise || "(empty)"}
+
+ORIGINAL STYLE NOTES:
+${styleNotes || "(empty)"}
+
+ORIGINAL INFLUENCES:
+Embrace: ${embrace.length ? embrace.join(", ") : "(none)"}
+Avoid: ${avoid.length ? avoid.join(", ") : "(none)"}
USER FEEDBACK:
${feedback}`;
@@ -134,69 +243,124 @@ async function runRefine(provider, model, prompt) {
providerId: provider.id,
model,
prompt,
- source: 'world-builder-refine',
+ source: "world-builder-refine",
});
- let text = '';
+ let text = "";
return new Promise((resolve, reject) => {
- const onData = (chunk) => { text += typeof chunk === 'string' ? chunk : (chunk?.text || ''); };
+ const onData = (chunk) => {
+ text += typeof chunk === "string" ? chunk : chunk?.text || "";
+ };
const onComplete = (result) => {
if (result?.error || result?.success === false) {
- reject(new ServerError(result?.error || 'World refinement failed', { status: 502, code: 'WORLD_REFINE_FAILED' }));
+ reject(
+ new ServerError(result?.error || "World refinement failed", {
+ status: 502,
+ code: "WORLD_REFINE_FAILED",
+ }),
+ );
} else {
resolve({ text, runId });
}
};
- if (provider.type === 'cli') {
+ if (provider.type === "cli") {
// Mirror the media refiner: `buildCliArgs` now honors a per-call model
// override (via `provider.defaultModel`) for codex / claude-code /
// gemini-cli. Clone the provider with the overridden defaultModel
// whenever the caller picked something other than the saved default.
- const providerForCli = model && model !== provider.defaultModel
- ? { ...provider, defaultModel: model }
- : provider;
- executeCliRun(runId, providerForCli, prompt, process.cwd(), onData, onComplete, provider.timeout ?? 300000).catch(reject);
+ const providerForCli =
+ model && model !== provider.defaultModel
+ ? { ...provider, defaultModel: model }
+ : provider;
+ executeCliRun(
+ runId,
+ providerForCli,
+ prompt,
+ process.cwd(),
+ onData,
+ onComplete,
+ provider.timeout ?? 300000,
+ ).catch(reject);
} else {
- executeApiRun(runId, provider, model, prompt, process.cwd(), [], onData, onComplete).catch(reject);
+ executeApiRun(
+ runId,
+ provider,
+ model,
+ prompt,
+ process.cwd(),
+ [],
+ onData,
+ onComplete,
+ ).catch(reject);
}
});
}
/**
- * Refine the 3 top-level world prompts.
+ * Refine the 6 top-level world fields (starter, style, negative + bible).
*
* @param {object} args
* @param {string} args.starterPrompt — original
* @param {string} [args.stylePrompt] — original (may be empty)
* @param {string} [args.negativePrompt] — original (may be empty)
+ * @param {string} [args.logline] — original bible logline (may be empty)
+ * @param {string} [args.premise] — original bible premise (may be empty)
+ * @param {string} [args.styleNotes] — original bible style notes (may be empty)
+ * @param {object} [args.locked] — { field: true } for fields the user has pinned; locked fields are echoed back unchanged
* @param {string} args.feedback — required user feedback
* @param {string} [args.providerId] — overrides the active provider
* @param {string} [args.model] — overrides the provider's default model
*/
export async function refineWorldPrompts({
starterPrompt,
- stylePrompt = '',
- negativePrompt = '',
+ stylePrompt = "",
+ negativePrompt = "",
+ logline = "",
+ premise = "",
+ styleNotes = "",
+ influences,
+ locked = {},
feedback,
providerId,
model,
} = {}) {
if (!feedback || !feedback.trim()) {
- throw new ServerError('Feedback is required', { status: 400, code: 'FEEDBACK_REQUIRED' });
+ throw new ServerError("Feedback is required", {
+ status: 400,
+ code: "FEEDBACK_REQUIRED",
+ });
}
if (!starterPrompt || !starterPrompt.trim()) {
- throw new ServerError('Starter prompt is required to refine', { status: 400, code: 'STARTER_REQUIRED' });
+ throw new ServerError("Starter prompt is required to refine", {
+ status: 400,
+ code: "STARTER_REQUIRED",
+ });
+ }
+ const safeLocked = sanitizeLocked(locked);
+ // Refusing the run if everything is locked spares the user a confusing
+ // "nothing changed" outcome (the LLM would echo every field, then the
+ // server would overwrite with originals, then the modal would show no diff).
+ if (LOCKABLE_FIELDS.every((k) => safeLocked[k])) {
+ throw new ServerError(
+ "All fields are locked — unlock at least one before refining",
+ { status: 400, code: "ALL_FIELDS_LOCKED" },
+ );
}
- let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;
+ let provider = providerId
+ ? await getProviderById(providerId).catch(() => null)
+ : null;
if (!provider) provider = await getActiveProvider();
if (!provider) {
- throw new ServerError('No AI provider available for world refinement', { status: 400, code: 'NO_PROVIDER' });
+ throw new ServerError("No AI provider available for world refinement", {
+ status: 400,
+ code: "NO_PROVIDER",
+ });
}
if (provider.enabled === false) {
throw new ServerError(
`Provider "${provider.name || provider.id}" is disabled — enable it in Settings → Providers first`,
- { status: 400, code: 'PROVIDER_DISABLED' },
+ { status: 400, code: "PROVIDER_DISABLED" },
);
}
@@ -204,15 +368,29 @@ export async function refineWorldPrompts({
// run record / log line match the args-pinned id when a CLI provider's
// args have a baked --model/-m flag. Shared helper documents the
// decision table.
- const selectedModel = resolveEffectiveModel(provider, model) || '';
- if (!selectedModel && provider.type === 'api') {
- throw new ServerError('Model is required for world refinement', { status: 400, code: 'MODEL_REQUIRED' });
+ const selectedModel = resolveEffectiveModel(provider, model) || "";
+ if (!selectedModel && provider.type === "api") {
+ throw new ServerError("Model is required for world refinement", {
+ status: 400,
+ code: "MODEL_REQUIRED",
+ });
}
- const llmPrompt = buildWorldRefinePrompt({
+ // Trim originals up front so we can pass them to both the LLM AND use them
+ // verbatim as the lock fallback below.
+ const originals = {
starterPrompt: trimTo(starterPrompt, STARTER_PROMPT_MAX),
stylePrompt: trimTo(stylePrompt, PROMPT_FRAGMENT_MAX),
negativePrompt: trimTo(negativePrompt, PROMPT_FRAGMENT_MAX),
+ logline: trimTo(logline, LOGLINE_MAX),
+ premise: trimTo(premise, PREMISE_MAX),
+ styleNotes: trimTo(styleNotes, STYLE_NOTES_MAX),
+ influences: sanitizeInfluences(influences),
+ };
+
+ const llmPrompt = buildWorldRefinePrompt({
+ ...originals,
+ locked: safeLocked,
feedback: trimTo(feedback, MAX_FEEDBACK),
});
@@ -220,21 +398,73 @@ export async function refineWorldPrompts({
let parsed;
try {
- parsed = extractRefinementJson(text || '');
+ parsed = extractRefinementJson(text || "");
} catch (e) {
- console.warn(`⚠️ world-refine [${provider.id}/${selectedModel || 'default'} runId=${runId}] parse failed: ${e.message} (response size: ${(text || '').length} chars)`);
- throw new ServerError(e.message, { status: 502, code: 'WORLD_REFINE_BAD_JSON' });
+ console.warn(
+ `⚠️ world-refine [${provider.id}/${selectedModel || "default"} runId=${runId}] parse failed: ${e.message} (response size: ${(text || "").length} chars)`,
+ );
+ throw new ServerError(e.message, {
+ status: 502,
+ code: "WORLD_REFINE_BAD_JSON",
+ });
+ }
+
+ const FIELD_CAPS = {
+ starterPrompt: STARTER_PROMPT_MAX,
+ stylePrompt: PROMPT_FRAGMENT_MAX,
+ negativePrompt: PROMPT_FRAGMENT_MAX,
+ logline: LOGLINE_MAX,
+ premise: PREMISE_MAX,
+ styleNotes: STYLE_NOTES_MAX,
+ };
+
+ // For each lockable field: if locked, echo the original; otherwise take
+ // the LLM's value (or fall back to original when missing/empty so the
+ // modal never receives a blank where the user had content). Influences is
+ // an object — handle it after the scalar loop.
+ const refined = {};
+ for (const key of LOCKABLE_FIELDS) {
+ if (key === "influences") continue;
+ if (safeLocked[key]) {
+ refined[key] = originals[key];
+ continue;
+ }
+ const llmValue = trimTo(parsed[key], FIELD_CAPS[key]);
+ refined[key] = llmValue || originals[key];
+ }
+
+ // Influences: locked → echo originals; unlocked → take the LLM's lists
+ // (sanitized for caps + dedupe). When the LLM omits it entirely we keep
+ // the originals rather than wiping them.
+ if (safeLocked.influences) {
+ refined.influences = originals.influences;
+ } else {
+ const llmInfluences = sanitizeInfluences(parsed.influences);
+ refined.influences =
+ llmInfluences.embrace.length || llmInfluences.avoid.length
+ ? llmInfluences
+ : originals.influences;
+ }
+
+ // Legacy cleanup: prior refinements may have stuffed a "Style direction:"
+ // paragraph into the starter. Now that influences carries the direction
+ // structurally, collapse any leftover duplicates so the starter doesn't
+ // keep growing across iterations. The new refine prompt no longer asks
+ // for the clause, but the cleanup is cheap.
+ if (!safeLocked.starterPrompt) {
+ refined.starterPrompt = collapseStyleDirectionDupes(refined.starterPrompt);
}
- const refinedStarter = trimTo(parsed.starterPrompt, STARTER_PROMPT_MAX);
- if (!refinedStarter) {
- throw new ServerError('LLM returned an empty starter prompt', { status: 502, code: 'WORLD_REFINE_EMPTY_STARTER' });
+ if (!refined.starterPrompt) {
+ throw new ServerError("LLM returned an empty starter prompt", {
+ status: 502,
+ code: "WORLD_REFINE_EMPTY_STARTER",
+ });
}
return {
- starterPrompt: refinedStarter,
- stylePrompt: trimTo(parsed.stylePrompt, PROMPT_FRAGMENT_MAX),
- negativePrompt: trimTo(parsed.negativePrompt, PROMPT_FRAGMENT_MAX),
+ ...refined,
+ locked: safeLocked,
rationale: trimTo(parsed.rationale, MAX_RATIONALE),
changes: cleanChanges(parsed.changes),
providerId: provider.id,
@@ -242,4 +472,8 @@ export async function refineWorldPrompts({
};
}
-export const __testing = { extractRefinementJson, buildWorldRefinePrompt };
+export const __testing = {
+ extractRefinementJson,
+ buildWorldRefinePrompt,
+ collapseStyleDirectionDupes,
+};
diff --git a/server/services/worldBuilderRefine.test.js b/server/services/worldBuilderRefine.test.js
index c16a123995..86ead441cc 100644
--- a/server/services/worldBuilderRefine.test.js
+++ b/server/services/worldBuilderRefine.test.js
@@ -1,87 +1,245 @@
-import { describe, it, expect } from 'vitest';
-import { __testing } from './worldBuilderRefine.js';
+import { describe, it, expect } from "vitest";
+import { __testing } from "./worldBuilderRefine.js";
-const { extractRefinementJson, buildWorldRefinePrompt } = __testing;
+const {
+ extractRefinementJson,
+ buildWorldRefinePrompt,
+ collapseStyleDirectionDupes,
+} = __testing;
-describe('worldBuilderRefine.extractRefinementJson', () => {
- it('parses a raw refinement object', () => {
+describe("worldBuilderRefine.extractRefinementJson", () => {
+ it("parses a raw refinement object", () => {
const obj = {
- starterPrompt: 'a darker scavenger world',
- stylePrompt: 'gritty palette, deep shadows',
- negativePrompt: 'cute, neon',
- rationale: 'pushed mood toward grim',
+ starterPrompt: "a darker scavenger world",
+ stylePrompt: "gritty palette, deep shadows",
+ negativePrompt: "cute, neon",
+ rationale: "pushed mood toward grim",
};
expect(extractRefinementJson(JSON.stringify(obj))).toEqual(obj);
});
- it('strips ```json fences', () => {
- const fenced = '```json\n{"starterPrompt":"x","stylePrompt":"y","negativePrompt":""}\n```';
- expect(extractRefinementJson(fenced)).toMatchObject({ starterPrompt: 'x', stylePrompt: 'y' });
+ it("strips ```json fences", () => {
+ const fenced =
+ '```json\n{"starterPrompt":"x","stylePrompt":"y","negativePrompt":""}\n```';
+ expect(extractRefinementJson(fenced)).toMatchObject({
+ starterPrompt: "x",
+ stylePrompt: "y",
+ });
});
- it('skips preamble before the JSON', () => {
- const raw = 'Here is the refinement:\n{"starterPrompt":"x","stylePrompt":"y"}\nend';
- expect(extractRefinementJson(raw)).toMatchObject({ starterPrompt: 'x' });
+ it("skips preamble before the JSON", () => {
+ const raw =
+ 'Here is the refinement:\n{"starterPrompt":"x","stylePrompt":"y"}\nend';
+ expect(extractRefinementJson(raw)).toMatchObject({ starterPrompt: "x" });
});
- it('skips a schema-example block that has a <…> placeholder starterPrompt and parses the real block (Codex CLI prompt echo)', () => {
+ it("skips a schema-example block that has a <…> placeholder starterPrompt and parses the real block (Codex CLI prompt echo)", () => {
const raw = [
- 'codex banner',
+ "codex banner",
// The prompt template body — its first balanced { ... } block contains
// <…> placeholders that walked past extractRefinementJson by mistake
// would surface as "AI returned schema placeholder" instead of finding
// the real response below it.
'{"starterPrompt":"<full rewritten…>","stylePrompt":"<…>","negativePrompt":"<…>"}',
- 'codex response:',
+ "codex response:",
'{"starterPrompt":"a darker world","stylePrompt":"gritty","negativePrompt":""}',
- ].join('\n');
+ ].join("\n");
const out = extractRefinementJson(raw);
- expect(out.starterPrompt).toBe('a darker world');
- expect(out.stylePrompt).toBe('gritty');
+ expect(out.starterPrompt).toBe("a darker world");
+ expect(out.stylePrompt).toBe("gritty");
});
- it('throws when ONLY schema-placeholder blocks are present', () => {
+ it("throws when ONLY schema-placeholder blocks are present", () => {
const raw = '{"starterPrompt":"<placeholder>","stylePrompt":"<x>"}';
expect(() => extractRefinementJson(raw)).toThrow(/schema placeholder/);
});
- it('throws on empty / non-string input', () => {
- expect(() => extractRefinementJson('')).toThrow(/Empty AI response/);
+ it("throws on empty / non-string input", () => {
+ expect(() => extractRefinementJson("")).toThrow(/Empty AI response/);
expect(() => extractRefinementJson(null)).toThrow(/Empty AI response/);
});
- it('throws when no balanced JSON object with starterPrompt is present', () => {
- expect(() => extractRefinementJson('just prose, no json')).toThrow(/Invalid JSON/);
- expect(() => extractRefinementJson('{"prompt":"unrelated shape"}')).toThrow(/Invalid JSON/);
+ it("throws when no balanced JSON object with starterPrompt is present", () => {
+ expect(() => extractRefinementJson("just prose, no json")).toThrow(
+ /Invalid JSON/,
+ );
+ expect(() => extractRefinementJson('{"prompt":"unrelated shape"}')).toThrow(
+ /Invalid JSON/,
+ );
});
});
-describe('worldBuilderRefine.buildWorldRefinePrompt', () => {
- it('includes all three originals + feedback verbatim', () => {
+describe("worldBuilderRefine.buildWorldRefinePrompt", () => {
+ it("includes all three originals + feedback verbatim", () => {
const out = buildWorldRefinePrompt({
- starterPrompt: 'moebius scavengers',
- stylePrompt: 'comic ink, dust palette',
- negativePrompt: 'lowres',
- feedback: 'lean grimmer and more spiritual',
+ starterPrompt: "moebius scavengers",
+ stylePrompt: "comic ink, dust palette",
+ negativePrompt: "lowres",
+ feedback: "lean grimmer and more spiritual",
});
- expect(out).toContain('moebius scavengers');
- expect(out).toContain('comic ink, dust palette');
- expect(out).toContain('lowres');
- expect(out).toContain('lean grimmer and more spiritual');
+ expect(out).toContain("moebius scavengers");
+ expect(out).toContain("comic ink, dust palette");
+ expect(out).toContain("lowres");
+ expect(out).toContain("lean grimmer and more spiritual");
// Schema must mention the three output keys so the LLM can comply.
expect(out).toContain('"starterPrompt"');
expect(out).toContain('"stylePrompt"');
expect(out).toContain('"negativePrompt"');
});
- it('substitutes (empty) for missing originals so the LLM sees the slot', () => {
+ it("substitutes (empty) for missing originals so the LLM sees the slot", () => {
const out = buildWorldRefinePrompt({
- starterPrompt: 'seed',
- stylePrompt: '',
- negativePrompt: '',
- feedback: 'go dark',
+ starterPrompt: "seed",
+ stylePrompt: "",
+ negativePrompt: "",
+ feedback: "go dark",
});
expect(out).toMatch(/ORIGINAL STYLE PROMPT:\n\(empty\)/);
expect(out).toMatch(/ORIGINAL NEGATIVE PROMPT:\n\(empty\)/);
+ expect(out).toMatch(/ORIGINAL LOGLINE:\n\(empty\)/);
+ expect(out).toMatch(/ORIGINAL PREMISE:\n\(empty\)/);
+ expect(out).toMatch(/ORIGINAL STYLE NOTES:\n\(empty\)/);
+ });
+
+ it("includes bible context (logline / premise / styleNotes) when provided", () => {
+ const out = buildWorldRefinePrompt({
+ starterPrompt: "seed",
+ stylePrompt: "s",
+ negativePrompt: "",
+ logline: "A foundry city goes silent.",
+ premise: "Three families inherit the silence.",
+ styleNotes: "Tarkovsky pacing, Moebius palette.",
+ feedback: "go grimmer",
+ });
+ expect(out).toContain("A foundry city goes silent.");
+ expect(out).toContain("Three families inherit the silence.");
+ expect(out).toContain("Tarkovsky pacing, Moebius palette.");
+ // Schema must declare the new output keys so the LLM emits them.
+ expect(out).toContain('"logline"');
+ expect(out).toContain('"premise"');
+ expect(out).toContain('"styleNotes"');
+ });
+
+ it("emits a LOCKED FIELDS section when fields are pinned", () => {
+ const out = buildWorldRefinePrompt({
+ starterPrompt: "seed",
+ stylePrompt: "",
+ negativePrompt: "",
+ logline: "L",
+ premise: "",
+ styleNotes: "",
+ locked: { logline: true, styleNotes: true },
+ feedback: "go grimmer",
+ });
+ expect(out).toContain("LOCKED FIELDS");
+ expect(out).toContain("logline");
+ expect(out).toContain("style notes");
+ // The "echo unchanged" rule must appear so the LLM doesn't try to rewrite.
+ expect(out).toMatch(/echo them back UNCHANGED/);
+ });
+
+ it("omits the LOCKED FIELDS section entirely when nothing is locked", () => {
+ const out = buildWorldRefinePrompt({
+ starterPrompt: "seed",
+ stylePrompt: "",
+ negativePrompt: "",
+ feedback: "x",
+ });
+ expect(out).not.toContain("LOCKED FIELDS");
+ });
+
+ it("declares the structured influences schema in the output contract", () => {
+ const out = buildWorldRefinePrompt({
+ starterPrompt: "seed",
+ stylePrompt: "",
+ negativePrompt: "",
+ feedback: "x",
+ });
+ // Structured influences replaced the legacy "Style direction:" clause —
+ // the renderer prepends them deterministically so the LLM has to populate
+ // them for re-expansions to inherit direction.
+ expect(out).toContain('"influences"');
+ expect(out).toContain('"embrace"');
+ expect(out).toContain('"avoid"');
+ // And the starter idea should stay a clean seed (no style-direction prose).
+ expect(out).toMatch(/do NOT append style direction prose here/);
+ });
+
+ it("embeds prior influences as ORIGINAL INFLUENCES context", () => {
+ const out = buildWorldRefinePrompt({
+ starterPrompt: "seed",
+ stylePrompt: "",
+ negativePrompt: "",
+ influences: {
+ embrace: ["Moebius", "cel-shading"],
+ avoid: ["Ghibli painterly"],
+ },
+ feedback: "lean indie comic",
+ });
+ expect(out).toMatch(/ORIGINAL INFLUENCES:/);
+ expect(out).toContain("Embrace: Moebius, cel-shading");
+ expect(out).toContain("Avoid: Ghibli painterly");
+ });
+
+ it("renders ORIGINAL INFLUENCES with (none) when lists are empty", () => {
+ const out = buildWorldRefinePrompt({
+ starterPrompt: "seed",
+ stylePrompt: "",
+ negativePrompt: "",
+ feedback: "x",
+ });
+ expect(out).toMatch(/Embrace: \(none\)/);
+ expect(out).toMatch(/Avoid: \(none\)/);
+ });
+});
+
+describe("worldBuilderRefine.collapseStyleDirectionDupes", () => {
+ it("returns input untouched when no Style direction block is present", () => {
+ expect(collapseStyleDirectionDupes("a foundry city goes silent")).toBe(
+ "a foundry city goes silent",
+ );
+ });
+
+ it("returns input untouched when exactly one Style direction block is present", () => {
+ const input =
+ "A foundry city.\n\nStyle direction: Moebius palette, oil-on-canvas grain.";
+ expect(collapseStyleDirectionDupes(input)).toBe(input);
+ });
+
+ it("collapses two Style direction blocks, keeping the LATEST one", () => {
+ const input = [
+ "A foundry city.",
+ "",
+ "Style direction: painterly Ghibli palette.",
+ "",
+ "Style direction: indie comic Moebius, cel-shading, simple palette.",
+ ].join("\n");
+ const out = collapseStyleDirectionDupes(input);
+ expect(out).not.toContain("painterly Ghibli");
+ expect(out).toContain("indie comic Moebius");
+ // The seed core is preserved.
+ expect(out).toContain("A foundry city.");
+ // Exactly one Style direction occurrence remains.
+ expect((out.match(/Style direction:/gi) || []).length).toBe(1);
+ });
+
+ it("handles arbitrary numbers of stale Style direction blocks", () => {
+ const input = [
+ "core",
+ "Style direction: A",
+ "Style direction: B",
+ "Style direction: C",
+ ].join("\n");
+ const out = collapseStyleDirectionDupes(input);
+ expect(out).toContain("Style direction: C");
+ expect(out).not.toMatch(/Style direction: A/);
+ expect(out).not.toMatch(/Style direction: B/);
+ });
+
+ it("is case-insensitive on the heading", () => {
+ const input = "core\n\nstyle direction: lower\n\nStyle Direction: upper";
+ const out = collapseStyleDirectionDupes(input);
+ expect((out.match(/style direction:/gi) || []).length).toBe(1);
+ expect(out).toContain("Style Direction: upper");
});
});