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): holistic Refine — also edits categories + composites, append-only locked influences

[._.]/ Adam Eivyd8d338d0be97
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 642fef8926..21cfd3be2f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,6 +17,7 @@ In-tree `portos-ai-toolkit`, auto-migration of legacy codex provider configs, an
- **World Builder — independent locks for embrace + avoid influences.** The single influences lock split into `influencesEmbrace` and `influencesAvoid`. Each list has its own lock toggle in the UI; the embrace and avoid lines in the LLM prompt get `[LOCKED]` flags independently. Legacy `locked.influences: true` is migrated to both per-list locks on read (no data migration step needed).
- **World Builder — drag-to-reorder for influence chips.** Embrace and avoid chips now reorder via `@dnd-kit` (`rectSortingStrategy` since chips wrap). Each chip has a `GripVertical` handle; the renderer prepends them in the new order to `stylePrompt`/`negativePrompt`. 8px activation distance keeps the X remove button and the trailing input click-safe; keyboard sensor enables space-to-grab + arrow-key reordering.
- **World Builder — collapsible Worlds sidebar with deep routing + tight layout.** The Worlds list now collapses to a 32px rail via a localStorage-backed toggle (persists across visits). The page is full-width (no outer page padding) and the sidebar uses `border-r` + tinted bg matching the WritersRoom layout convention. Selected world id lives in the URL (`/world-builder/:worldId` and `/media/world-builder/:worldId`).
+- **World Builder — holistic Refine (bible + influences + categories + composites).** The Refine action now sees the *full* world after Expand: feedback can replace specific variations ("swap The Lollipop Bureau for something more Umbrella Academy"), retune composites to reference the new items, propose entirely new categories, and tune the bible — all in one pass. Locked variations and composites round-trip verbatim (server-enforced; the LLM can't override them even by re-using the same label). Locked influence lists become *append-only* in this path: existing tokens stay in order, but the model may add new ones — Expand still uses strict no-touch lock semantics. The modal now renders a diff section per category and for composite sheets, with Added / Removed / Changed / Locked / Unchanged badges so the user can see exactly what's about to land before clicking Apply. Pre-Expand drafts still get today's bible-only refine — the new structure pass kicks in only when `categories` or `compositeSheets` are non-empty.
## Changed
diff --git a/client/src/components/worldBuilder/WorldPromptRefineModal.jsx b/client/src/components/worldBuilder/WorldPromptRefineModal.jsx
index 135fd29016..034c938b44 100644
--- a/client/src/components/worldBuilder/WorldPromptRefineModal.jsx
+++ b/client/src/components/worldBuilder/WorldPromptRefineModal.jsx
@@ -1,22 +1,23 @@
import { useEffect, useMemo, useState } from 'react';
-import { Check, Lock, Sparkles, Wand2, X } from 'lucide-react';
+import { Check, Lock, Minus, Plus, Sparkles, Wand2, X } from 'lucide-react';
import ProviderModelSelector from '../ProviderModelSelector';
import toast from '../ui/Toast';
import useProviderModels from '../../hooks/useProviderModels';
import {
- refineWorldPrompts, WORLD_LOCKABLE_FIELDS, ensureInfluences, isInfluenceLockField,
+ refineWorldPrompts, WORLD_LOCKABLE_FIELDS, ensureInfluences, isInfluenceLockField, normalizeLabelKey,
} from '../../services/api';
import InfluenceChipsInput from './InfluenceChipsInput';
/**
- * 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.
+ * Refines world fields (bible + influences) and, when the world has been
+ * expanded, also the structure (categories + composite sheets) based on user
+ * feedback. Mirrors PromptRefineModal's shape — feedback box, provider/model
+ * selector, refined-fields review, then apply.
*
- * 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.
+ * Locked fields / locked variations / locked composites are preserved
+ * server-side; the modal renders them as read-only and never applies a change
+ * to a locked entity. Locked influence lists are append-only in this path
+ * (server may add new tokens; existing ones round-trip in order).
*/
const FIELD_LABELS = {
@@ -52,6 +53,11 @@ export default function WorldPromptRefineModal({
premise = '',
styleNotes = '',
influences = emptyInfluences(),
+ // Post-Expand world structure — when present, the refiner sees and may
+ // edit categories + composite sheets alongside the bible. Pre-Expand drafts
+ // pass null/empty and the modal degrades to bible-only mode.
+ categories = null,
+ compositeSheets = null,
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
@@ -75,7 +81,14 @@ export default function WorldPromptRefineModal({
const originals = useMemo(() => ({
starterPrompt, stylePrompt, negativePrompt, logline, premise, styleNotes,
influences: ensureInfluences(influences),
- }), [starterPrompt, stylePrompt, negativePrompt, logline, premise, styleNotes, influences]);
+ categories: categories && typeof categories === 'object' ? categories : {},
+ compositeSheets: Array.isArray(compositeSheets) ? compositeSheets : [],
+ }), [starterPrompt, stylePrompt, negativePrompt, logline, premise, styleNotes, influences, categories, compositeSheets]);
+
+ const hasStructure = useMemo(() => (
+ Object.keys(originals.categories).length > 0 ||
+ originals.compositeSheets.length > 0
+ ), [originals.categories, originals.compositeSheets]);
const [feedback, setFeedback] = useState('');
const [refined, setRefined] = useState({});
@@ -120,6 +133,9 @@ export default function WorldPromptRefineModal({
setChanges([]);
const result = await refineWorldPrompts({
...originals,
+ // Empty structure → server reverts to bible-only refine.
+ categories: hasStructure ? originals.categories : undefined,
+ compositeSheets: hasStructure ? originals.compositeSheets : undefined,
locked,
feedback: feedback.trim(),
providerId: selectedProviderId,
@@ -133,6 +149,12 @@ export default function WorldPromptRefineModal({
next[key] = result[key] ?? '';
}
next.influences = ensureInfluences(result.influences);
+ if (result.categories && typeof result.categories === 'object') {
+ next.categories = result.categories;
+ }
+ if (Array.isArray(result.compositeSheets)) {
+ next.compositeSheets = result.compositeSheets;
+ }
setRefined(next);
setRationale(result.rationale || '');
setChanges(Array.isArray(result.changes) ? result.changes : []);
@@ -154,12 +176,18 @@ export default function WorldPromptRefineModal({
}
const refinedInf = ensureInfluences(refined.influences);
const origInf = originals.influences;
+ // Influences in refine mode are append-only when locked, so the server's
+ // returned list is always safe to apply directly (locked tokens are
+ // preserved in order, new tokens appended).
patch.influences = {
- embrace: locked.influencesEmbrace ? origInf.embrace : refinedInf.embrace,
- avoid: locked.influencesAvoid ? origInf.avoid : refinedInf.avoid,
+ embrace: refinedInf.embrace.length ? refinedInf.embrace : origInf.embrace,
+ avoid: refinedInf.avoid.length ? refinedInf.avoid : origInf.avoid,
};
+ // Server already enforced per-item locks before returning these.
+ if (refined.categories) patch.categories = refined.categories;
+ if (refined.compositeSheets) patch.compositeSheets = refined.compositeSheets;
onApply(patch);
- toast.success('Refined fields applied');
+ toast.success('Refined world applied');
onClose();
};
@@ -180,7 +208,7 @@ export default function WorldPromptRefineModal({
<div className="flex items-center gap-2 min-w-0">
<Sparkles className="w-4 h-4 text-port-accent shrink-0" />
<h2 id="world-refine-title" className="text-sm font-semibold text-white">
- Refine world prompts
+ {hasStructure ? 'Refine world' : 'Refine world prompts'}
</h2>
</div>
<button
@@ -197,7 +225,9 @@ export default function WorldPromptRefineModal({
<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, prompts, and bible
- fields to match. Locked fields stay untouched. Review the result before applying.
+ fields{hasStructure ? ', plus categories + composite sheets,' : ''} to match.
+ Locked fields and locked items stay untouched (locked influence lists are
+ preserved in order but may gain new tokens). Review the result before applying.
</p>
{/* Originals — read-only preview so the user remembers what's about
@@ -303,6 +333,14 @@ export default function WorldPromptRefineModal({
lockedEmbrace={!!locked.influencesEmbrace}
lockedAvoid={!!locked.influencesAvoid}
/>
+ {(refined.categories || refined.compositeSheets) && (
+ <StructureDiff
+ originalCategories={originals.categories}
+ refinedCategories={refined.categories}
+ originalComposites={originals.compositeSheets}
+ refinedComposites={refined.compositeSheets}
+ />
+ )}
</div>
)}
</div>
@@ -412,6 +450,107 @@ function RefinedInfluences({ label, value, onChange, lockedEmbrace, lockedAvoid
);
}
+function diffItems(orig, fresh) {
+ const origByKey = new Map(orig.map((i) => [normalizeLabelKey(i.label), i]));
+ const freshByKey = new Map(fresh.map((i) => [normalizeLabelKey(i.label), i]));
+ const rows = [];
+ for (const item of fresh) {
+ const prev = origByKey.get(normalizeLabelKey(item.label));
+ if (!prev) {
+ rows.push({ status: 'added', current: item });
+ } else if (prev.locked) {
+ rows.push({ status: 'locked', current: prev });
+ } else if (prev.prompt === item.prompt) {
+ rows.push({ status: 'unchanged', current: item });
+ } else {
+ rows.push({ status: 'changed', current: item, previous: prev });
+ }
+ }
+ for (const item of orig) {
+ if (!freshByKey.has(normalizeLabelKey(item.label))) {
+ rows.push({ status: 'removed', current: item });
+ }
+ }
+ return rows;
+}
+
+function DiffRow({ status, current, previous }) {
+ const accents = {
+ added: 'border-port-success/40 bg-port-success/5',
+ removed: 'border-port-error/40 bg-port-error/5',
+ changed: 'border-port-accent/40 bg-port-accent/5',
+ locked: 'border-port-accent/20 bg-port-bg',
+ unchanged: 'border-port-border bg-port-bg',
+ };
+ const badges = {
+ added: <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-success"><Plus className="w-3 h-3" /> Added</span>,
+ removed: <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-error"><Minus className="w-3 h-3" /> Removed</span>,
+ changed: <span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-port-accent">Changed</span>,
+ 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>,
+ unchanged: <span className="text-[10px] uppercase tracking-wide text-gray-500">Unchanged</span>,
+ };
+ return (
+ <div className={`border rounded p-2 ${accents[status]}`}>
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <div className="text-xs font-medium text-white truncate">{current.label}</div>
+ {badges[status]}
+ </div>
+ {status === 'changed' && (
+ <div className="text-[11px] text-gray-500 whitespace-pre-wrap line-clamp-2 line-through">
+ {previous.prompt}
+ </div>
+ )}
+ <div className={`text-[11px] whitespace-pre-wrap ${status === 'removed' ? 'text-gray-500 line-through' : 'text-gray-300'}`}>
+ {current.prompt}
+ </div>
+ </div>
+ );
+}
+
+function StructureDiff({ originalCategories, refinedCategories, originalComposites, refinedComposites }) {
+ const catKeys = useMemo(() => {
+ const keys = new Set([
+ ...Object.keys(originalCategories || {}),
+ ...Object.keys(refinedCategories || {}),
+ ]);
+ return Array.from(keys).sort();
+ }, [originalCategories, refinedCategories]);
+
+ return (
+ <div className="space-y-3">
+ <div className="text-xs font-semibold uppercase tracking-wide text-gray-400">
+ Structure changes
+ </div>
+ {catKeys.map((key) => {
+ const orig = originalCategories?.[key]?.variations || [];
+ const fresh = refinedCategories?.[key]?.variations || [];
+ const rows = diffItems(orig, fresh);
+ if (!rows.length) return null;
+ return (
+ <div key={key} className="border border-port-border rounded-lg p-2 bg-port-bg/50">
+ <div className="text-[11px] uppercase tracking-wide text-gray-500 mb-2">{key}</div>
+ <div className="space-y-1.5">
+ {rows.map((r, i) => (
+ <DiffRow key={`${key}-${r.current.label}-${i}`} {...r} />
+ ))}
+ </div>
+ </div>
+ );
+ })}
+ {(originalComposites?.length || refinedComposites?.length) > 0 && (
+ <div className="border border-port-border rounded-lg p-2 bg-port-bg/50">
+ <div className="text-[11px] uppercase tracking-wide text-gray-500 mb-2">composite sheets</div>
+ <div className="space-y-1.5">
+ {diffItems(originalComposites || [], refinedComposites || []).map((r, i) => (
+ <DiffRow key={`comp-${r.current.label}-${i}`} {...r} />
+ ))}
+ </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
diff --git a/client/src/pages/WorldBuilder.jsx b/client/src/pages/WorldBuilder.jsx
index 863241e0c7..f27c43d796 100644
--- a/client/src/pages/WorldBuilder.jsx
+++ b/client/src/pages/WorldBuilder.jsx
@@ -537,6 +537,11 @@ export default function WorldBuilder() {
next[key] = patch[key];
}
if (patch.influences != null) next.influences = ensureInfluences(patch.influences);
+ // Holistic refine returns categories + composites when the world has
+ // been expanded; the server already enforced per-item locks before
+ // sending these back, so apply directly.
+ if (patch.categories) next.categories = ensureDraftCategories(patch.categories);
+ if (Array.isArray(patch.compositeSheets)) next.compositeSheets = patch.compositeSheets;
setDraft(next);
if (selectedId && next.name?.trim()) {
const updated = await updateWorld(selectedId, {
@@ -872,6 +877,8 @@ export default function WorldBuilder() {
premise={draft.premise || ''}
styleNotes={draft.styleNotes || ''}
influences={ensureInfluences(draft.influences)}
+ categories={draft.categories || {}}
+ compositeSheets={draft.compositeSheets || []}
locked={draft.locked || {}}
defaultProviderId={draft.llm?.provider || activeProviderId || null}
defaultModel={draft.llm?.model || null}
diff --git a/client/src/services/apiWorldBuilder.js b/client/src/services/apiWorldBuilder.js
index 3b0cf85e12..b270251fb9 100644
--- a/client/src/services/apiWorldBuilder.js
+++ b/client/src/services/apiWorldBuilder.js
@@ -52,6 +52,10 @@ export const refineWorldPrompts = ({
starterPrompt, stylePrompt, negativePrompt,
logline, premise, styleNotes,
influences,
+ // Post-Expand structure — when provided, the server sees the full world and
+ // may edit/replace/add categories + composites alongside the bible refine.
+ // Omit (or pass empty/falsy) to get the bible-only behavior.
+ categories, compositeSheets,
locked,
feedback, providerId, model,
} = {}) => request('/world-builder/refine-prompts', {
@@ -60,6 +64,8 @@ export const refineWorldPrompts = ({
starterPrompt, stylePrompt, negativePrompt,
logline, premise, styleNotes,
influences,
+ ...(categories && Object.keys(categories).length ? { categories } : {}),
+ ...(Array.isArray(compositeSheets) && compositeSheets.length ? { compositeSheets } : {}),
locked,
feedback, providerId, model,
}),
@@ -78,6 +84,11 @@ export const WORLD_LOCKABLE_FIELDS = [
'influencesAvoid',
];
+// Mirror of `normalizeLabelKey` in server/services/worldBuilder.js — used for
+// case-insensitive identity matching between original and refined items.
+export const normalizeLabelKey = (label) =>
+ typeof label === 'string' ? label.trim().toLowerCase() : '';
+
// Coerce whatever shape the server / draft / patch hands us into a strict
// `{ embrace: [], avoid: [] }` so consumers never have to guard undefined.
// Fast-path: if the input is already shape-correct, return it unchanged so
diff --git a/server/routes/worldBuilder.js b/server/routes/worldBuilder.js
index 45dcd4dbc0..1b16d113bf 100644
--- a/server/routes/worldBuilder.js
+++ b/server/routes/worldBuilder.js
@@ -148,6 +148,12 @@ const refinePromptsSchema = z.object({
// Structured influences (embrace + avoid) — refined alongside the prompts
// and used as the canonical reference list for renderer-token composition.
influences: influencesSchema.optional(),
+ // Post-Expand structure — when present, the refiner sees the full world
+ // (categories + composites with per-item locks) and may edit/replace/add
+ // items per the user's feedback. When omitted (pre-Expand iteration), the
+ // refiner falls back to the bible-only behavior.
+ categories: categoriesSchema.optional(),
+ compositeSheets: z.array(compositeSheetSchema).max(svc.COMPOSITE_SHEETS_MAX).optional(),
// Per-field lock map — locked fields are echoed back unchanged regardless
// of what the LLM tries to write.
locked: lockedSchema.optional().default({}),
diff --git a/server/services/worldBuilder.js b/server/services/worldBuilder.js
index d9ae9e864f..6c5d38efd1 100644
--- a/server/services/worldBuilder.js
+++ b/server/services/worldBuilder.js
@@ -115,6 +115,12 @@ const DEFAULT_STATE = { worlds: [], runs: [] };
const isStr = (v) => typeof v === 'string';
const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
+// Case-insensitive key for matching variation/composite labels across the
+// original + LLM-refined sets. Returning the same lowercase string ensures
+// "Lollipop Bureau" and "lollipop bureau" collapse to one identity.
+export const normalizeLabelKey = (label) =>
+ typeof label === "string" ? label.trim().toLowerCase() : "";
+
export const normalizeCategoryKey = (raw) => {
if (!isStr(raw)) return '';
return raw
@@ -250,6 +256,36 @@ export const mergeInfluencesWithLocks = (locked, fresh, fallback) => {
};
};
+// Refine-time variant: when a list is locked, preserve every existing token in
+// order but allow the LLM to APPEND new tokens (case-insensitive de-dup). The
+// user explicitly wants "lock = no rebuild, additions still welcome" in the
+// holistic refine flow; Expand should keep using the strict variant above.
+const appendUnique = (existing, additions) => {
+ const seen = new Set(existing.map((t) => normalizeLabelKey(t)));
+ const out = [...existing];
+ for (const t of additions) {
+ const key = normalizeLabelKey(t);
+ if (!key || seen.has(key)) continue;
+ seen.add(key);
+ out.push(t);
+ if (out.length >= INFLUENCES_PER_LIST_MAX) break;
+ }
+ return out;
+};
+
+export const mergeInfluencesWithLocksAdditive = (locked, fresh, fallback) => {
+ const freshSafe = sanitizeInfluences(fresh);
+ const fallbackSafe = sanitizeInfluences(fallback);
+ return {
+ embrace: locked?.influencesEmbrace
+ ? appendUnique(fallbackSafe.embrace, freshSafe.embrace)
+ : (freshSafe.embrace.length ? freshSafe.embrace : fallbackSafe.embrace),
+ avoid: locked?.influencesAvoid
+ ? appendUnique(fallbackSafe.avoid, freshSafe.avoid)
+ : (freshSafe.avoid.length ? freshSafe.avoid : fallbackSafe.avoid),
+ };
+};
+
export const sanitizeLocked = (raw = {}) => {
if (!raw || typeof raw !== 'object') return {};
const out = {};
diff --git a/server/services/worldBuilderRefine.js b/server/services/worldBuilderRefine.js
index f84239a6f5..25b76a92e2 100644
--- a/server/services/worldBuilderRefine.js
+++ b/server/services/worldBuilderRefine.js
@@ -16,6 +16,9 @@ import { getActiveProvider, getProviderById } from "./providers.js";
import { createRun, executeApiRun, executeCliRun } from "./runner.js";
import { resolveEffectiveModel } from "../lib/promptRunner.js";
import {
+ COMPOSITE_PROMPT_MAX,
+ COMPOSITE_SHEETS_MAX,
+ COMPOSITE_SHEET_KINDS,
LOCKABLE_FIELDS,
LOCKABLE_FIELD_LABELS,
LOGLINE_MAX,
@@ -23,8 +26,15 @@ import {
PROMPT_FRAGMENT_MAX,
STARTER_PROMPT_MAX,
STYLE_NOTES_MAX,
+ VARIATIONS_PER_CATEGORY_MAX,
+ VARIATION_LABEL_MAX,
+ WORLD_CATEGORY_COUNT_MAX,
isInfluenceLockField,
- mergeInfluencesWithLocks,
+ mergeInfluencesWithLocksAdditive,
+ normalizeCategoryKey,
+ normalizeLabelKey,
+ sanitizeCategories,
+ sanitizeCompositeSheets,
sanitizeInfluences,
sanitizeLocked,
} from "./worldBuilder.js";
@@ -142,6 +152,32 @@ export function collapseStyleDirectionDupes(starter) {
return `${stripped}\n\n${last}`.trim();
}
+const renderCategoriesForPrompt = (categories) => {
+ const entries = Object.entries(categories || {});
+ if (!entries.length) return "";
+ return entries
+ .map(([key, cat]) => {
+ const variations = (cat?.variations || [])
+ .map((v) => {
+ const flag = v.locked ? " [LOCKED]" : "";
+ return ` - "${v.label}"${flag}: ${v.prompt}`;
+ })
+ .join("\n");
+ return ` ${key}:\n${variations || " (no variations yet)"}`;
+ })
+ .join("\n");
+};
+
+const renderCompositesForPrompt = (composites) => {
+ if (!composites?.length) return "";
+ return composites
+ .map((c) => {
+ const flag = c.locked ? " [LOCKED]" : "";
+ return ` - (${c.kind || "reference_sheet"}) "${c.label}"${flag}: ${c.prompt}`;
+ })
+ .join("\n");
+};
+
export function buildWorldRefinePrompt({
starterPrompt,
stylePrompt,
@@ -150,6 +186,8 @@ export function buildWorldRefinePrompt({
premise = "",
styleNotes = "",
influences = { embrace: [], avoid: [] },
+ categories = null,
+ compositeSheets = null,
locked = {},
feedback,
}) {
@@ -164,6 +202,41 @@ ${lockedRules.join("\n")}
const embrace = Array.isArray(influences?.embrace) ? influences.embrace : [];
const avoid = Array.isArray(influences?.avoid) ? influences.avoid : [];
+ const hasStructure =
+ (categories && Object.keys(categories).length) ||
+ (Array.isArray(compositeSheets) && compositeSheets.length);
+
+ const structureRules = hasStructure
+ ? `
+STRUCTURE RULES (the world has been expanded — categories and composite sheets are part of this refinement):
+- Each category groups related prompt variations (factions, characters, vehicles, etc.). Each variation is { "label", "prompt" } and may be flagged [LOCKED].
+- Each composite sheet is a multi-subject board (kind "reference_sheet" or "world_pitch_poster") with { "label", "prompt" }, also [LOCKED]-flaggable.
+- Variations / composites flagged [LOCKED] must be returned with their EXACT original label + prompt — do not rephrase, expand, trim, or "lightly clean up" them. The server discards changes to locked items.
+- Unlocked variations / composites may be rewritten, replaced (same label, new prompt), or REMOVED if the user's feedback warrants it. Removing an item means omitting it from the response.
+- You MAY ADD new variations to any existing category, propose ENTIRELY NEW categories, and ADD new composite sheets when the feedback motivates it. Use snake_case keys for new category names (e.g. "secret_rituals").
+- Keep category counts manageable: at most ${WORLD_CATEGORY_COUNT_MAX} total categories, ${VARIATIONS_PER_CATEGORY_MAX} variations per category, ${COMPOSITE_SHEETS_MAX} composite sheets.
+- Variation prompts ≤${PROMPT_FRAGMENT_MAX} chars; composite prompts ≤${COMPOSITE_PROMPT_MAX} chars; labels ≤${VARIATION_LABEL_MAX} chars.
+- When updating an unlocked composite that references a renamed/removed variation, update the composite's prompt to match — keep the world internally consistent.
+- For LOCKED influence lists in this refine: preserve every existing token IN ORDER, but you MAY APPEND new tokens at the end. You may NOT remove, reorder, or rewrite existing locked tokens. The server enforces order preservation regardless.
+`
+ : "";
+
+ const structureContext = hasStructure
+ ? `
+ORIGINAL CATEGORIES (current draft — items flagged [LOCKED] must round-trip unchanged):
+${renderCategoriesForPrompt(categories) || " (none)"}
+
+ORIGINAL COMPOSITE SHEETS (current draft):
+${renderCompositesForPrompt(compositeSheets) || " (none)"}
+`
+ : "";
+
+ const structureSchema = hasStructure
+ ? `,
+ "categories": { "<category_key>": { "variations": [ { "label": "<short label>", "prompt": "<full prompt fragment>", "locked": true } ] } },
+ "compositeSheets": [ { "kind": "reference_sheet" | "world_pitch_poster", "label": "<short label>", "prompt": "<full board prompt>", "locked": true } ]`
+ : "";
+
return `You are a senior world-building editor for a Stable-Diffusion-style image-generation pipeline AND a story-bible drafter for a comic/TV production pipeline.
The user has seven top-level fields that define a "world":
@@ -185,7 +258,7 @@ ${lockedSection}Return ONLY valid JSON in this schema (replace every <…> with
"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>", "..."] },
+ "influences": { "embrace": ["<short reference label>", "..."], "avoid": ["<short reference label>", "..."] }${structureSchema},
"rationale": "<one concise sentence explaining the overall edit>",
"changes": ["<short bullet of what changed and why>"]
}
@@ -199,7 +272,7 @@ Rules:
- 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" : ""}
+${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" : ""}${structureRules}
ORIGINAL STARTER IDEA:
${starterPrompt || "(empty)"}
@@ -221,11 +294,67 @@ ${styleNotes || "(empty)"}
ORIGINAL INFLUENCES:
Embrace: ${embrace.length ? embrace.join(", ") : "(none)"}
Avoid: ${avoid.length ? avoid.join(", ") : "(none)"}
-
+${structureContext}
USER FEEDBACK:
${feedback}`;
}
+// Lock semantics for categories + composites are the same: locked items
+// round-trip verbatim from the originals; LLM output is taken for everything
+// else, but any LLM entry whose label collides with a locked one is dropped
+// (we never let the LLM "rewrite" a locked item by re-using its label).
+const mergeCategoriesWithLocks = (originalCategories, llmCategories) => {
+ const orig = originalCategories || {};
+ const fresh = (llmCategories && typeof llmCategories === "object") ? llmCategories : {};
+ const merged = {};
+
+ for (const [rawKey, origCat] of Object.entries(orig)) {
+ const key = normalizeCategoryKey(rawKey) || rawKey;
+ const origVars = Array.isArray(origCat?.variations) ? origCat.variations : [];
+ const llmVars = Array.isArray(fresh?.[key]?.variations) ? fresh[key].variations : [];
+ const lockedOrig = origVars.filter((v) => v?.locked === true);
+ const lockedLabels = new Set(lockedOrig.map((v) => normalizeLabelKey(v.label)));
+
+ const out = [...lockedOrig];
+ for (const v of llmVars) {
+ if (!v || typeof v !== "object") continue;
+ const label = typeof v.label === "string" ? v.label.trim() : "";
+ if (!label || lockedLabels.has(normalizeLabelKey(label))) continue;
+ out.push({ label, prompt: typeof v.prompt === "string" ? v.prompt : "" });
+ }
+ merged[key] = { variations: out };
+ }
+
+ for (const [rawKey, cat] of Object.entries(fresh)) {
+ const key = normalizeCategoryKey(rawKey) || rawKey;
+ if (merged[key]) continue;
+ if (!cat || typeof cat !== "object") continue;
+ merged[key] = { variations: Array.isArray(cat.variations) ? cat.variations : [] };
+ }
+
+ return sanitizeCategories(merged);
+};
+
+const mergeCompositesWithLocks = (originalSheets, llmSheets) => {
+ const orig = Array.isArray(originalSheets) ? originalSheets : [];
+ const fresh = Array.isArray(llmSheets) ? llmSheets : [];
+ const lockedOrig = orig.filter((s) => s?.locked === true);
+ const lockedLabels = new Set(lockedOrig.map((s) => normalizeLabelKey(s.label)));
+
+ const merged = [...lockedOrig];
+ for (const s of fresh) {
+ if (!s || typeof s !== "object") continue;
+ const label = typeof s.label === "string" ? s.label.trim() : "";
+ if (!label || lockedLabels.has(normalizeLabelKey(label))) continue;
+ merged.push({
+ kind: COMPOSITE_SHEET_KINDS.includes(s.kind) ? s.kind : "reference_sheet",
+ label,
+ prompt: typeof s.prompt === "string" ? s.prompt : "",
+ });
+ }
+ return sanitizeCompositeSheets(merged);
+};
+
// CLI providers (codex/claude-code/gemini-cli) need provider-specific arg
// shapes that the toolkit runner already knows about — going through the
// runner avoids the "stdin is not a terminal" failure mode that hits when
@@ -289,7 +418,15 @@ async function runRefine(provider, model, prompt) {
}
/**
- * Refine the 6 top-level world fields (starter, style, negative + bible).
+ * Refine world fields. Operates in two modes:
+ * - Bible-only (pre-Expand): categories + compositeSheets omitted; behavior
+ * matches the original refine — rewrite the seven scalar/influence fields
+ * per feedback.
+ * - Holistic (post-Expand): caller passes `categories` and/or `compositeSheets`
+ * and the LLM may edit/replace/remove unlocked variations + composites, add
+ * new ones, and propose new categories. Locked items (per-field, per-list,
+ * per-variation, per-composite) round-trip verbatim. Locked influence lists
+ * become APPEND-ONLY in this path (preserve order, may add new tokens).
*
* @param {object} args
* @param {string} args.starterPrompt — original
@@ -298,6 +435,9 @@ async function runRefine(provider, model, prompt) {
* @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.influences] — { embrace, avoid }
+ * @param {object} [args.categories] — full categories map from the draft (with per-item locks)
+ * @param {Array} [args.compositeSheets] — composite sheets from the draft (with per-item locks)
* @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
@@ -311,6 +451,8 @@ export async function refineWorldPrompts({
premise = "",
styleNotes = "",
influences,
+ categories,
+ compositeSheets,
locked = {},
feedback,
providerId,
@@ -370,6 +512,10 @@ export async function refineWorldPrompts({
// Trim originals up front so we can pass them to both the LLM AND use them
// verbatim as the lock fallback below.
+ const hasStructure =
+ (categories && typeof categories === "object" && Object.keys(categories).length > 0) ||
+ (Array.isArray(compositeSheets) && compositeSheets.length > 0);
+
const originals = {
starterPrompt: trimTo(starterPrompt, STARTER_PROMPT_MAX),
stylePrompt: trimTo(stylePrompt, PROMPT_FRAGMENT_MAX),
@@ -378,6 +524,8 @@ export async function refineWorldPrompts({
premise: trimTo(premise, PREMISE_MAX),
styleNotes: trimTo(styleNotes, STYLE_NOTES_MAX),
influences: sanitizeInfluences(influences),
+ categories: hasStructure ? sanitizeCategories(categories || {}) : null,
+ compositeSheets: hasStructure ? sanitizeCompositeSheets(compositeSheets || []) : null,
};
const llmPrompt = buildWorldRefinePrompt({
@@ -424,7 +572,14 @@ export async function refineWorldPrompts({
const llmValue = trimTo(parsed[key], FIELD_CAPS[key]);
refined[key] = llmValue || originals[key];
}
- refined.influences = mergeInfluencesWithLocks(safeLocked, parsed.influences, originals.influences);
+ // Refine path uses APPEND-ONLY semantics for locked influence lists — the
+ // user wants "lock = don't rebuild, but you may append". Expand still calls
+ // the strict variant.
+ refined.influences = mergeInfluencesWithLocksAdditive(
+ safeLocked,
+ parsed.influences,
+ originals.influences,
+ );
// Legacy cleanup: prior refinements may have stuffed a "Style direction:"
// paragraph into the starter. Now that influences carries the direction
@@ -442,7 +597,10 @@ export async function refineWorldPrompts({
});
}
- return {
+ // Structure merge — only when the caller passed categories/composites.
+ // Empty / pre-Expand calls return without these keys so the response shape
+ // stays identical to the bible-only contract.
+ const result = {
...refined,
locked: safeLocked,
rationale: trimTo(parsed.rationale, MAX_RATIONALE),
@@ -450,10 +608,25 @@ export async function refineWorldPrompts({
providerId: provider.id,
model: selectedModel,
};
+
+ if (hasStructure) {
+ result.categories = mergeCategoriesWithLocks(
+ originals.categories || {},
+ parsed.categories,
+ );
+ result.compositeSheets = mergeCompositesWithLocks(
+ originals.compositeSheets || [],
+ parsed.compositeSheets,
+ );
+ }
+
+ return result;
}
export const __testing = {
extractRefinementJson,
buildWorldRefinePrompt,
collapseStyleDirectionDupes,
+ mergeCategoriesWithLocks,
+ mergeCompositesWithLocks,
};
diff --git a/server/services/worldBuilderRefine.test.js b/server/services/worldBuilderRefine.test.js
index 86ead441cc..548a1f4f90 100644
--- a/server/services/worldBuilderRefine.test.js
+++ b/server/services/worldBuilderRefine.test.js
@@ -1,10 +1,13 @@
import { describe, it, expect } from "vitest";
import { __testing } from "./worldBuilderRefine.js";
+import { mergeInfluencesWithLocksAdditive } from "./worldBuilder.js";
const {
extractRefinementJson,
buildWorldRefinePrompt,
collapseStyleDirectionDupes,
+ mergeCategoriesWithLocks,
+ mergeCompositesWithLocks,
} = __testing;
describe("worldBuilderRefine.extractRefinementJson", () => {
@@ -243,3 +246,203 @@ describe("worldBuilderRefine.collapseStyleDirectionDupes", () => {
expect(out).toContain("Style Direction: upper");
});
});
+
+describe("worldBuilderRefine.buildWorldRefinePrompt — structure-aware path", () => {
+ it("emits an ORIGINAL CATEGORIES block + structure schema when categories are passed", () => {
+ const out = buildWorldRefinePrompt({
+ starterPrompt: "seed",
+ stylePrompt: "",
+ negativePrompt: "",
+ categories: {
+ factions: {
+ variations: [
+ { label: "The Velvet Null", prompt: "ink-noir cabal", locked: true },
+ { label: "The Lollipop Bureau", prompt: "pastel agency" },
+ ],
+ },
+ },
+ feedback: "replace lollipop bureau",
+ });
+ expect(out).toContain("ORIGINAL CATEGORIES");
+ expect(out).toContain('"The Velvet Null" [LOCKED]');
+ expect(out).toContain('"The Lollipop Bureau"');
+ expect(out).not.toMatch(/"The Lollipop Bureau" \[LOCKED\]/);
+ expect(out).toContain('"categories"');
+ expect(out).toContain("STRUCTURE RULES");
+ expect(out).toMatch(/APPEND new tokens/);
+ });
+
+ it("emits an ORIGINAL COMPOSITE SHEETS block when sheets are passed", () => {
+ const out = buildWorldRefinePrompt({
+ starterPrompt: "seed",
+ stylePrompt: "",
+ negativePrompt: "",
+ compositeSheets: [
+ { kind: "world_pitch_poster", label: "Pitch poster", prompt: "city skyline", locked: true },
+ { kind: "reference_sheet", label: "Uniforms sheet", prompt: "rival branding" },
+ ],
+ feedback: "x",
+ });
+ expect(out).toContain("ORIGINAL COMPOSITE SHEETS");
+ expect(out).toContain('"Pitch poster" [LOCKED]');
+ expect(out).toContain('"Uniforms sheet"');
+ expect(out).toContain('"compositeSheets"');
+ });
+
+ it("omits structure sections entirely when no categories/composites are passed (pre-Expand)", () => {
+ const out = buildWorldRefinePrompt({
+ starterPrompt: "seed",
+ stylePrompt: "",
+ negativePrompt: "",
+ feedback: "x",
+ });
+ expect(out).not.toContain("ORIGINAL CATEGORIES");
+ expect(out).not.toContain("ORIGINAL COMPOSITE SHEETS");
+ expect(out).not.toContain("STRUCTURE RULES");
+ expect(out).not.toContain('"categories"');
+ expect(out).not.toContain('"compositeSheets"');
+ });
+});
+
+describe("worldBuilderRefine.mergeCategoriesWithLocks", () => {
+ it("preserves locked variations and replaces unlocked ones from LLM output", () => {
+ const original = {
+ factions: {
+ variations: [
+ { label: "Velvet Null", prompt: "ink-noir", locked: true },
+ { label: "Lollipop Bureau", prompt: "pastel agency" },
+ ],
+ },
+ };
+ const fromLlm = {
+ factions: {
+ variations: [
+ // LLM trying to overwrite a locked label should be ignored.
+ { label: "Velvet Null", prompt: "REWRITTEN BY MISTAKE" },
+ // Unlocked item gets rewritten.
+ { label: "Lollipop Bureau", prompt: "umbrella-academy-coded misfits in pastel" },
+ ],
+ },
+ };
+ const merged = mergeCategoriesWithLocks(original, fromLlm);
+ const labels = merged.factions.variations.map((v) => v.label);
+ expect(labels).toEqual(["Velvet Null", "Lollipop Bureau"]);
+ const velvet = merged.factions.variations.find((v) => v.label === "Velvet Null");
+ expect(velvet.prompt).toBe("ink-noir");
+ expect(velvet.locked).toBe(true);
+ const lollipop = merged.factions.variations.find((v) => v.label === "Lollipop Bureau");
+ expect(lollipop.prompt).toBe("umbrella-academy-coded misfits in pastel");
+ });
+
+ it("appends entirely new variations the LLM proposes", () => {
+ const original = {
+ factions: {
+ variations: [
+ { label: "Velvet Null", prompt: "ink-noir", locked: true },
+ ],
+ },
+ };
+ const fromLlm = {
+ factions: {
+ variations: [
+ { label: "Velvet Null", prompt: "x" },
+ { label: "The Hollow Choir", prompt: "monastic survivors with bone instruments" },
+ ],
+ },
+ };
+ const merged = mergeCategoriesWithLocks(original, fromLlm);
+ const labels = merged.factions.variations.map((v) => v.label);
+ expect(labels).toContain("The Hollow Choir");
+ });
+
+ it("accepts entirely new categories the LLM proposes", () => {
+ const original = { factions: { variations: [] } };
+ const fromLlm = {
+ factions: { variations: [] },
+ secret_rituals: {
+ variations: [{ label: "Solstice Mask", prompt: "midnight procession with bone masks" }],
+ },
+ };
+ const merged = mergeCategoriesWithLocks(original, fromLlm);
+ expect(merged.secret_rituals).toBeDefined();
+ expect(merged.secret_rituals.variations[0].label).toBe("Solstice Mask");
+ });
+
+ it("drops unlocked items the LLM omits (effectively removed)", () => {
+ const original = {
+ factions: {
+ variations: [
+ { label: "Locked Faction", prompt: "stays", locked: true },
+ { label: "Doomed Faction", prompt: "goes" },
+ ],
+ },
+ };
+ const fromLlm = {
+ factions: { variations: [{ label: "Locked Faction", prompt: "ignored" }] },
+ };
+ const merged = mergeCategoriesWithLocks(original, fromLlm);
+ const labels = merged.factions.variations.map((v) => v.label);
+ expect(labels).toContain("Locked Faction");
+ expect(labels).not.toContain("Doomed Faction");
+ });
+});
+
+describe("worldBuilderRefine.mergeCompositesWithLocks", () => {
+ it("preserves locked composites verbatim and rewrites unlocked ones", () => {
+ const original = [
+ { kind: "world_pitch_poster", label: "Pitch", prompt: "original pitch", locked: true },
+ { kind: "reference_sheet", label: "Uniforms", prompt: "old uniforms" },
+ ];
+ const fromLlm = [
+ { kind: "world_pitch_poster", label: "Pitch", prompt: "REWRITTEN" }, // ignored
+ { kind: "reference_sheet", label: "Uniforms", prompt: "umbrella-academy uniforms" },
+ { kind: "reference_sheet", label: "Vehicles", prompt: "new vehicle board" },
+ ];
+ const merged = mergeCompositesWithLocks(original, fromLlm);
+ const labels = merged.map((c) => c.label);
+ expect(labels).toEqual(["Pitch", "Uniforms", "Vehicles"]);
+ expect(merged.find((c) => c.label === "Pitch").prompt).toBe("original pitch");
+ expect(merged.find((c) => c.label === "Uniforms").prompt).toBe("umbrella-academy uniforms");
+ });
+});
+
+describe("worldBuilder.mergeInfluencesWithLocksAdditive (refine-time)", () => {
+ it("preserves locked tokens in order and APPENDS new tokens from LLM", () => {
+ const merged = mergeInfluencesWithLocksAdditive(
+ { influencesEmbrace: true, influencesAvoid: true },
+ { embrace: ["Moebius", "Umbrella Academy"], avoid: ["kid-comic"] },
+ { embrace: ["Moebius", "Brandon Graham"], avoid: ["grimdark"] },
+ );
+ // Original Moebius + Brandon Graham preserved in order, plus new Umbrella Academy appended.
+ expect(merged.embrace).toEqual(["Moebius", "Brandon Graham", "Umbrella Academy"]);
+ expect(merged.avoid).toEqual(["grimdark", "kid-comic"]);
+ });
+
+ it("does not duplicate when LLM repeats existing locked tokens", () => {
+ const merged = mergeInfluencesWithLocksAdditive(
+ { influencesEmbrace: true },
+ { embrace: ["moebius", "MOEBIUS", "Saga"] }, // case-insensitive dedup
+ { embrace: ["Moebius"] },
+ );
+ expect(merged.embrace).toEqual(["Moebius", "Saga"]);
+ });
+
+ it("ignores LLM removals when the list is locked", () => {
+ const merged = mergeInfluencesWithLocksAdditive(
+ { influencesEmbrace: true },
+ { embrace: [] }, // LLM tried to wipe the list
+ { embrace: ["Moebius", "Brandon Graham"] },
+ );
+ expect(merged.embrace).toEqual(["Moebius", "Brandon Graham"]);
+ });
+
+ it("falls through to LLM output entirely when list is NOT locked", () => {
+ const merged = mergeInfluencesWithLocksAdditive(
+ {}, // nothing locked
+ { embrace: ["Umbrella Academy"], avoid: ["candy colored"] },
+ { embrace: ["Moebius"], avoid: ["grimdark"] },
+ );
+ expect(merged.embrace).toEqual(["Umbrella Academy"]);
+ expect(merged.avoid).toEqual(["candy colored"]);
+ });
+});