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(universe-builder): per-category "Generate N more" variations

[._.]/ Adam Eivye4c0cbedb228
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2ece76b81c..cab0009a87 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Universe Builder — per-category "Generate N more" variations.** Each category card now has a Generate dropdown (3 / 5 / 10 / custom up to 50) next to the existing Render / + Add buttons. The LLM is given the universe's bible context (logline, premise, style notes, influences, stylePrompt) plus the list of existing labels to skip, and returns N additional variations that get appended to the category. Locked items are unaffected — Generate is purely additive. Auto-saves when the universe is already persisted; otherwise hands you a "review then Save" toast. New endpoint: `POST /api/universe-builder/generate-variations`.
+
## Changed
- **Pipeline series arc — inline theme editing.** Theme pills on the Series Arc card are now directly editable: click a pill to rename, hover for the × to remove, click the dashed "+ Add theme" chip to append (up to 20 themes, 100 chars each — matching `ARC_LIMITS` on the server). Writes are optimistic with a single-flight save gate so a blur-then-click sequence can't double-persist against stale state. The redundant comma-separated themes input was removed from the "Edit arc" form; logline / summary / protagonist arc / shape still live there.
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 29944426b6..b371c99911 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -48,6 +48,24 @@ export const expandUniverse = ({
}),
});
+// Caller should dedupe the returned variations against its local list before
+// appending — the local list may have changed during the request.
+export const generateCategoryVariations = ({
+ category, count, existingLabels,
+ influences,
+ logline, premise, styleNotes, stylePrompt, negativePrompt,
+ providerId, model,
+} = {}, options = {}) => request('/universe-builder/generate-variations', {
+ method: 'POST',
+ body: JSON.stringify({
+ category, count, existingLabels,
+ influences,
+ logline, premise, styleNotes, stylePrompt, negativePrompt,
+ providerId, model,
+ }),
+ ...options,
+});
+
export const refineWorldPrompts = ({
starterPrompt, stylePrompt, negativePrompt,
logline, premise, styleNotes,
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 9aa9a20565..67ffb1364f 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -20,7 +20,7 @@ import * as svc from '../services/universeBuilder.js';
import * as canonSvc from '../services/universeCanon.js';
import { BIBLE_KINDS } from '../lib/storyBible.js';
import { getUniverseCanonUsage } from '../services/canonUsage.js';
-import { expandWorldTemplate } from '../services/universeBuilderExpand.js';
+import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';
import { refineWorldPrompts } from '../services/universeBuilderRefine.js';
import { enqueueJob } from '../services/mediaJobQueue/index.js';
import { getSettings } from '../services/settings.js';
@@ -164,6 +164,21 @@ const expandSchema = z.object({
model: z.string().trim().max(200).optional(),
});
+const generateVariationsSchema = z.object({
+ category: z.string().trim().min(1).max(svc.WORLD_CATEGORY_KEY_MAX),
+ count: z.number().int().min(1).max(svc.VARIATIONS_PER_CATEGORY_MAX),
+ existingLabels: z.array(z.string().trim().min(1).max(svc.VARIATION_LABEL_MAX))
+ .max(svc.VARIATIONS_PER_CATEGORY_MAX).optional().default([]),
+ influences: influencesSchema.optional(),
+ 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(''),
+ stylePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),
+ negativePrompt: z.string().trim().max(svc.PROMPT_FRAGMENT_MAX).optional().default(''),
+ providerId: z.string().trim().max(80).optional(),
+ model: z.string().trim().max(200).optional(),
+});
+
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(''),
@@ -243,6 +258,12 @@ router.post('/expand', asyncHandler(async (req, res) => {
res.json(result);
}));
+router.post('/generate-variations', asyncHandler(async (req, res) => {
+ const body = validateRequest(generateVariationsSchema, req.body ?? {});
+ const result = await generateCategoryVariations(body);
+ res.json(result);
+}));
+
// Refines the 3 top-level prompts (starter / style / negative) based on
// user feedback. Stateless — the caller decides whether to write the
// result back to a saved universe. Keep ahead of `/:id`.
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index dbb7c9f63a..025c5fd71e 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -413,10 +413,167 @@ export async function expandWorldTemplate({
};
}
+function buildCategoryGeneratePrompt({
+ category,
+ count,
+ existingLabels,
+ influences,
+ logline,
+ premise,
+ styleNotes,
+ stylePrompt,
+ negativePrompt,
+}) {
+ 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\nEmbrace: ${embrace.join(", ") || "(none)"}\nAvoid: ${avoid.join(", ") || "(none)"}\n`
+ : "";
+
+ const stateLines = [
+ logline && `LOGLINE: ${logline}`,
+ premise && `PREMISE: ${premise}`,
+ styleNotes && `STYLE NOTES: ${styleNotes}`,
+ stylePrompt && `STYLE PROMPT: ${stylePrompt}`,
+ negativePrompt && `NEGATIVE PROMPT: ${negativePrompt}`,
+ ].filter(Boolean);
+ const stateSection = stateLines.length
+ ? `\n# Universe context — keep new variations consistent with this established setting\n${stateLines.join('\n\n')}\n`
+ : "";
+
+ const existingSection = existingLabels.length
+ ? `\n# Existing "${category}" variations — DO NOT regenerate these labels or close paraphrases\n${existingLabels.map((l) => `- "${l}"`).join('\n')}\n`
+ : "";
+
+ return `You are a universe-building prompt engineer for a Stable-Diffusion-style image generation pipeline. The user has an existing universe and wants ${count} MORE variations added to the "${category}" category.
+${stateSection}${influencesSection}${existingSection}
+# Output contract
+Return a SINGLE JSON object with one key: "variations" — an array of EXACTLY ${count} objects. Each object has the shape:
+ { "label": string (max ${LABEL_MAX} chars), "prompt": string (max ${PROMPT_FRAGMENT_MAX} chars, comma-separated tokens describing ONE specific subject in this category) }
+
+# Rules
+- Generate ${count} variations — no more, no less.
+- Each variation must be visually distinct from the others AND from the existing labels listed above.
+- "label" is a short human-recognizable name (e.g. "Crystalline canyon basin", "Scavenger walker mech").
+- "prompt" describes the SUBJECT only — the universe's stylePrompt is automatically prepended at render time, so do NOT repeat style tokens.
+- Do not include camera/aspect tokens; the renderer adds those.
+- Stay consistent with the universe context and influences. Lean into the embrace list; avoid the avoid list.
+- Output JUST the JSON object. NO markdown, NO commentary.`;
+}
+
+const isVariationsShape = (o) =>
+ o && typeof o === "object" && Array.isArray(o.variations);
+
+const extractVariationsJson = (raw) => {
+ if (!raw || typeof raw !== "string") throw new Error("Empty LLM response");
+ const { value, lastError, lastPreview } = extractJsonShared(raw, {
+ shapePredicate: isVariationsShape,
+ });
+ if (value !== undefined) return value;
+ throw new ServerError(
+ "LLM returned invalid JSON for variation generation. Try a different model or rerun.",
+ {
+ status: 502,
+ code: "LLM_INVALID_JSON",
+ context: {
+ details: {
+ reason: lastError?.message || "no JSON object with variations found",
+ preview: lastPreview || "",
+ },
+ },
+ },
+ );
+};
+
+/**
+ * Generate N additional variations for one category. Returns
+ * `{ variations: [{label, prompt}], llm: { provider, model } }`. Caller is
+ * responsible for merging the result into the universe (dedupe + append).
+ */
+export async function generateCategoryVariations({
+ category,
+ count,
+ existingLabels = [],
+ influences,
+ logline = '',
+ premise = '',
+ styleNotes = '',
+ stylePrompt = '',
+ negativePrompt = '',
+ providerId,
+ model,
+} = {}) {
+ const n = Math.max(1, Math.min(VARIATIONS_PER_CATEGORY_MAX, Number(count) || 0));
+
+ const safeInfluences = sanitizeInfluences(influences);
+ const safeExisting = Array.isArray(existingLabels)
+ ? existingLabels.filter((l) => typeof l === "string" && l.trim()).map((l) => l.trim())
+ : [];
+
+ let provider = providerId ? await getProviderById(providerId).catch(() => null) : null;
+ if (!provider) provider = await getActiveProvider();
+ if (!provider) throw new Error("No AI provider available for variation generation");
+ const selectedModel = resolveEffectiveModel(provider, model);
+
+ const fullPrompt = buildCategoryGeneratePrompt({
+ category: category.trim(),
+ count: n,
+ existingLabels: safeExisting,
+ influences: safeInfluences,
+ logline,
+ premise,
+ styleNotes,
+ stylePrompt,
+ negativePrompt,
+ });
+
+ console.log(
+ `🌍 Universe Builder generating ${n} variations for "${category}" via ${provider.name}/${selectedModel || "default"} — skip-list size=${safeExisting.length}`,
+ );
+
+ const { text: raw, runId } = await runPromptThroughProvider({
+ provider,
+ model: selectedModel,
+ prompt: fullPrompt,
+ source: "universe-builder-generate-variations",
+ });
+ console.log(
+ `🌍 Universe Builder generate raw response — runId=${runId} length=${raw?.length || 0}`,
+ );
+ const parsed = extractVariationsJson(raw);
+
+ const normalized = normalizeCategories({ [category]: { variations: parsed.variations } });
+ const variations = normalized[category]?.variations || [];
+
+ const seen = new Set(safeExisting.map((l) => l.toLowerCase()));
+ const deduped = variations.filter((v) => {
+ const key = v.label.toLowerCase();
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+
+ console.log(
+ `🌍 Universe Builder generate complete — runId=${runId} requested=${n} returned=${variations.length} kept-after-dedupe=${deduped.length}`,
+ );
+ if (deduped.length === 0) {
+ console.warn(
+ `⚠️ Universe Builder generate produced 0 new variations — inspect data/runs/${runId}/output.txt`,
+ );
+ }
+
+ return {
+ variations: deduped,
+ llm: { provider: provider.id, model: selectedModel || null },
+ };
+}
+
// Export for tests.
export const __testing = {
extractJson,
+ extractVariationsJson,
normalizeCategories,
normalizeCompositeSheets,
buildExpansionPrompt,
+ buildCategoryGeneratePrompt,
};